Skip to content

docs(README): add 'Built with itself' hero — Codex + Claude Code together - #378

Merged
joelteply merged 1 commit into
canaryfrom
docs/readme-built-with-itself-hero
Apr 30, 2026
Merged

joelteply merged 1 commit into
canaryfrom
docs/readme-built-with-itself-hero

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Joel's framing: "you could say something similar to that at the top of airc, of how it was used to create itself / and codex and claude together."

Adds a callout block right after the existing intro line, before the default-room blockquote. Lead with the cross-vendor angle — Anthropic's Claude Code AND OpenAI's Codex, on the same mesh — because that's the unique-narrative wedge.

Concrete proof points from day one (2026-04-29):

  • 21 commits across 3 main bundles
  • Multiple Claude Code instances on two Macs
  • OpenAI Codex agent peer-to-peer with them
  • Fresh-Mac install QA pass from true first-encounter perspective
  • Cross-vendor agent-to-agent comms validated end-to-end
  • Between human checkpoints, human delegating the seam

Closes with: "The mesh isn't a thought experiment — it's how this README got here."

🤖 Generated with Claude Code

…e together

Joel's framing: "you could say something similar to that at the top of
airc, of how it was used to create itself / and codex and claude
together."

Adds a callout block right after the existing intro line, before the
default-room blockquote. Lead with the cross-vendor angle — Anthropic's
Claude Code AND OpenAI's Codex, on the same mesh — because that's the
unique-narrative wedge no other agent-substrate has shipped yet.

Concrete proof points from day one (2026-04-29):
- 21 commits across 3 main bundles
- Multiple Claude Code instances on two Macs
- OpenAI Codex agent peer-to-peer with them
- Fresh-Mac install QA pass from true first-encounter perspective
- Cross-vendor agent-to-agent comms validated end-to-end
- Between human checkpoints, human delegating the seam

Closes with the substrate-size line ("200-line bash + thin Python core")
to ground the magic — it's not enterprise-federation; it's IRC over a
private gist, and that's the entire point.

Hero kicker: "The mesh isn't a thought experiment — it's how this
README got here." If you can read this README, the mesh works.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@joelteply
joelteply merged commit aef5313 into canary Apr 30, 2026
6 checks passed
@joelteply
joelteply deleted the docs/readme-built-with-itself-hero branch April 30, 2026 04:26
joelteply added a commit that referenced this pull request May 2, 2026
…, bus stability, rate-limit, design docs) (#422)

* docs(README): correct the encryption claims (broadcasts plaintext; DMs require pairing) + update day-one numbers

Joel caught the misleading 'How it stays safe' block: it claimed
'every cross-network message is sealed with X25519 + ChaCha20-Poly1305
... GitHub stores ciphertext only' — but reality (and the rest of the
README, line 13) is:
  - broadcasts are PLAINTEXT on the gist (group encryption is roadmap)
  - DMs between PAIRED peers are encrypted
  - DMs to UNPAIRED peers silently fall back to plaintext (#358 — confirmed
    live during today's QA pass)

A user reading the original wording reasonably believes 'all my mesh
traffic is private to recipients.' That's a security misrepresentation.

Honest version distinguishes the three cases + cross-references #358
(the active fix-track) so readers know the asymmetry exists, the
constraint is documented, and the planned mitigations are tracked.

Also updates the 'Built with itself' hero (added in #378) from
'21 commits across 3 main bundles' to '23+ commits across 4 main
bundles' — the day finished with the late-evening bundles 3 and 4
(Codex parity + README hero) which the prior numbers missed.

Signed-claim ("Every envelope Ed25519-signed; tampering observable")
stays + tightens to note sigs verify even on plaintext bodies — that
distinguishes integrity from confidentiality, which the original
block conflated.

The default-room blockquote (line 13) was already accurate ("paired
peers" + "broadcasts plaintext") so no change there.

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

* fix(#381 layer B): host-side queue/drain symmetry for transient gist failures (#385)

Pre-fix the host-side cmd_send branch had no queue path: on bearer_cli
'transient_failure' the warning printed and the message was dropped on
the floor with exit 0. Joiners polling the gist saw nothing; the user's
own audit log showed the message (because the local-mirror echo happened
BEFORE the publish attempt) so the chat widget read 'sent successfully'
even when zero peers received it. Classic silent-success-is-failure.

This change mirrors the joiner-side queue + drain pattern across to host
mode:

cmd_send.sh:
  - Move the unconditional `echo $full_msg >> $MESSAGES` into the
    `delivered)` case only. The user no longer sees their own message
    echoed back unless delivery actually completed.
  - On `transient_failure`/empty kind, append $full_msg to pending.jsonl
    and emit a [QUEUED] system marker to messages.jsonl. The user sees
    'queued for retry' in their log, not a phantom successful send.
  - On `auth_failure`, mirror the joiner branch: emit [GH AUTH FAILED]
    marker and die() with re-auth instructions. Don't queue (every
    retry hits the same dead token).
  - Unknown bearer kinds queue defensively + log loudly.

airc top-level:
  - Add flush_pending_host_loop() — symmetric to flush_pending_loop but
    drains via bearer_cli send (gist publish) instead of SSH push.
    Runs the same 5s tick, parent-liveness gate, snapshot/unsent flow.
    Per-line: extracts channel from the queued JSON, looks up the
    channel's gist, re-resolves recipient pubkey for DM wrap (so a
    pubkey paired post-queue gets used at retry time), publishes via
    bearer_cli, on `delivered` appends to local audit log + emits
    [DRAINED N] marker.
  - monitor() spawn site: when host_target is empty AND we have a
    publishable route (channel_gists OR room_gist_id), spawn the host
    flush loop. Same pidfile-honesty gate as the joiner branch — skip
    the spawn when standalone (--no-gist) so airc.pid doesn't list a
    PID that exited two seconds ago.

Composes with #381 layer A (bearer_gh.py 404/transient classification)
once that lands: layer A makes outcomes accurate, layer B makes
non-`delivered` outcomes recoverable. Layer A retries the initial
gh-api GET; layer B holds the message across longer outages (gh API
secondary rate-limit, network partitions, sandbox flake) until a tick
of the drain loop sees the gist alive again.

Edge case (documented, not addressed here): drain re-runs the wrap
step. If the original cmd_send used --plaintext to a peer with a known
X25519 pubkey, the queued $full_msg is re-wrapped at drain time. This
mirrors the asymmetry already present in the joiner-side flow (which
SSHes plaintext over) and is rare enough to leave to a follow-up.

Issue: airc#381 (Joel's tentative split: layer A → continuum-b741,
layer B → continuum-2c54)

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process) (#389)

* fix(install,connect): surface 'airc daemon install' earlier (#382)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process)

Joel observed (twice on M5 in 48h, "FREQUENT" in practice): gh's
keyring token silently invalidates — token revoked, 2FA flow expired,
brew upgrade replaced gh, OS keychain rotation, sleep across an OAuth
boundary. Pre-fix, every airc command path that touched the gist
substrate would `die "run gh auth login -h github.com"` and stop.

The user then had to manually re-auth. Two problems with that:

1. The next user (Carl, Toby, anyone) hits the same wall on first
   use after a token expires. Manual fix per user = unfixed bug.
2. Joel's "no manual fixes" / "script must self-heal" rule is
   universal: "airc MUST BE THE INSTIGATOR" — when airc detects the
   failure, IT runs the auth flow. The user's only step is clicking
   "Authorize" in the browser airc opened.

This change adds two helpers to a new `lib/airc_bash/lib_auth.sh`:

- airc_detect_gh_auth_state → echoes one of {ok, invalid,
  rate_limited, not_installed}. Distinguishes a real keyring-invalid
  state (BOTH /user and /rate_limit fail) from secondary rate limit
  (only /user fails — token is fine, just wait).

- airc_self_heal_gh_auth → runs `gh auth login --web --hostname
  github.com --git-protocol https -s gist` IN-PROCESS. gh prints the
  device code, opens the browser via the OS opener, blocks until the
  user pastes the code + clicks Authorize. Refuses to run in
  non-interactive contexts (background flush loops have no human at
  the keyboard).

- airc_ensure_gh_auth_or_heal → high-level wrapper: detect → react.
  Single-line call site for command surfaces. ok → return 0;
  rate_limited → emit explanation + return 1; invalid → trigger
  self-heal + re-detect to confirm + return 0/1; not_installed →
  emit install hint + return 1.

Wired into:

- cmd_connect.sh (~30 lines collapsed to 1 wrapper call): pre-flight
  before the join flow now self-heals on invalid token.

- cmd_send.sh (auth_failure path): on bearer-reported auth failure,
  detect + self-heal, then RETRY the send ONCE post-heal. We don't
  loop — if the retry fails too, something else is going on (scope
  missing? gist deleted?) and the user should see it.

Out of scope for this PR (separate follow-ups):
- Wire into cmd_status.sh + cmd_doctor.sh for clearer surfacing
  (today they print "RATE-LIMITED (secondary)" even when the keyring
  is genuinely dead — the new detect helper would fix that).
- Background flush loop (monitor) doesn't self-heal — by design,
  refuses non-TTY. Caller must run an interactive airc cmd to
  re-auth, then queued sends drain.

Tested:
- bash -n on all 4 touched files: clean
- airc_detect_gh_auth_state against real `ok` keyring: returns "ok"
- against bogus GH_TOKEN: returns "invalid"
- against PATH without gh: returns "not_installed"
- (Live self-heal flow tested manually previously when M5's token
  invalidated; this PR formalizes that path so users don't need to
  remember the command.)

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

---------

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

* fix(install,connect): surface 'airc daemon install' earlier (#382) (#388)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text (#390)

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text

PR #388 landed with 4 Copilot review concerns. This PR addresses all 4 +
extracts the cross-platform "is the daemon installed?" detect into a
shared helper so install.sh + cmd_connect.sh + cmd_daemon.sh all use ONE
implementation. Per Joel "if you code modularly like we require": three
near-identical case statements collapse to one detector.

NEW: lib/airc_bash/lib_daemon_detect.sh
  airc_daemon_is_installed() — covers darwin (LaunchAgents plist),
  linux+wsl (systemd user unit), windows (HKCU\...\Run\airc-monitor).
  Sourced from top-level airc + install.sh.

CHANGED:
  - install.sh: drops local _daemon_already_installed (Darwin/Linux only),
    sources lib_daemon_detect.sh from $CLONE_DIR, calls the shared
    helper. Fixes Copilot concern #2 (Windows/WSL gap).
  - install.sh: AIRC_INSTALL_YES=1 check now runs BEFORE the !-t 0
    non-TTY check, so `curl … | AIRC_INSTALL_YES=1 bash` actually
    installs the daemon instead of falling into the non-TTY tip
    branch. Fixes Copilot concern #3 (ordering bug).
  - install.sh: prompt text drops the bogus `--no-daemon-prompt` flag
    reference (the flag was never implemented anywhere); keeps only
    the AIRC_INSTALL_NO_DAEMON=1 env-var hint that DOES work. Fixes
    Copilot concern #1 (lying-to-user copy).
  - install.sh: launchd/systemd → "launchd / systemd / HKCU-Run" in
    the prompt body so Windows users see their platform mentioned.
  - cmd_connect.sh: first-host daemon-tip block (line ~1707) replaces
    its Darwin-only/Linux-only case statement with a single call to
    airc_daemon_is_installed. Fires correctly on Windows now where
    the previous code never fired (HKCU Run-key wasn't checked).
    Fixes Copilot concern #4.
  - cmd_daemon.sh::_daemon_installed becomes a thin wrapper around
    the shared detector. Preserves the local-private-helper API
    used by callers in this file; cross-platform logic now lives in
    one place. Detection guaranteed consistent across all sites.

Branch ordering rationale (install.sh, top→bottom):
  1. AIRC_INSTALL_NO_DAEMON=1   — explicit opt-out trumps everything
  2. AIRC_INSTALL_YES=1         — explicit auto-install (now BEFORE non-TTY)
  3. airc_daemon_is_installed   — idempotent re-run no-op
  4. !-t 0 || !-t 1             — non-TTY tip
  5. interactive [Y/n]          — default

TEST:
  - bash -n on all 5 touched files: clean
  - airc_daemon_is_installed against real Mac (daemon installed): returns 0 ✓
  - against mocked-windows (reg query mocked to succeed): returns 0 ✓
  - cmd_daemon.sh::_daemon_installed wrapper: still returns same value
    as direct airc_daemon_is_installed call (delegation works)
  - install.sh ordering: verified YES check (line 909) precedes !-t 0
    check (line 920+) by inspection

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

* docs: address Copilot nits on PR #390 — comment-only fixes

Three pure comment fixes from Copilot review:
1. lib_daemon_detect.sh: 'users-experience bugs' → 'user experience bugs'
   (grammar)
2. install.sh: 'Three NON-prompt branches' → 'Four NON-prompt branches'
   (the list below the comment has 4 branches: NO_DAEMON, YES,
   already-installed, non-TTY)
3. lib_daemon_detect.sh: HKCU\...\Run\airc-monitor reads as a subkey
   path; airc-monitor is actually the VALUE NAME under the Run key.
   Reworded to clarify.

No code changes.

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

---------

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

* fix: distinguish env_token_invalid (GH_TOKEN poisoned) from keyring-invalid (#391)

Discovered live on canary 73ab85e while testing PR #389's self-heal flow:
when GH_TOKEN env var is set + invalid, gh REFUSES to run `gh auth login`
("The value of the GH_TOKEN environment variable is being used for
authentication. To have GitHub CLI store credentials instead, first clear
the value from the environment").

Pre-fix the wrapper would still trigger self-heal in this case, gh would
bounce immediately, and the user got the misleading "auth flow did not
complete (cancelled? no network?)" fallback message. No path forward
visible to them.

Fix: detect this case as a NEW state, `env_token_invalid`, distinct from
keyring-`invalid`. The wrapper handles it with a precise message:

  ✗ GH_TOKEN environment variable is set + invalid.
    airc can't auto-heal this — gh refuses to run 'gh auth login' while
    GH_TOKEN is set. Self-heal would just bounce.

    Two paths to fix:
    1. Stale dotfile / leftover export → just unset it:
         unset GH_TOKEN
       Then re-run your airc command. airc will detect the keyring
       auth + self-heal it via the browser flow.
    2. Real CI token (Actions, Codespace, dotfile sourcing a managed
       token) → fix the source. Don't run gh auth login; refresh
       whichever system writes GH_TOKEN.

    What gh sees right now:
      [verbatim gh auth status output]

Detection logic:
  if gh auth status passes:           → ok           (unchanged)
  elif gh api rate_limit passes:      → rate_limited (unchanged)
  elif [ -n "${GH_TOKEN:-}" ]:        → env_token_invalid  (NEW)
  else:                               → invalid      (unchanged)

GH_TOKEN takes precedence over keyring in gh's auth resolution. If we
got past gh auth status + gh api rate_limit both failing AND GH_TOKEN
is set, then GH_TOKEN is what gh's using and it's dead. Self-heal can't
fix that — only user-side action can.

Tested:
  - real ok keyring (no GH_TOKEN):           detect → "ok"             ✓
  - bogus GH_TOKEN, real keyring fine:        detect → "env_token_invalid" ✓
  - mocked auth+rate fails, no GH_TOKEN:      detect → "invalid"        ✓
  - wrapper with env_token_invalid: emits two-path message + returns 1 ✓

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

* fix: detect_scope walks up to enclosing .airc/ ancestor (no more .airc/.airc) (#392)

When a user `cd`'d into the scope dir for forensic inspection (or any
descendant), `detect_scope()` returned `$pwd/.airc` — producing wrong
nested paths like `/repo/.airc/.airc`. Every subsequent airc command
then died with "Not initialized" against a directory that didn't exist.
Discovered live on M5 2026-05-01 while diagnosing a different airc
issue: the very act of `cd .airc; airc status` to inspect state broke
airc.

Fix: walk up from cwd looking for an ancestor whose basename is .airc.
If found, that's the scope. If not found, fall through to the
documented `$pwd/.airc` per-cwd default (unchanged behaviour for the
common fresh-cwd case).

Test cases:

  cwd                              | pre-fix              | post-fix
  ---------------------------------|----------------------|------------
  /repo (no .airc anywhere)        | /repo/.airc          | /repo/.airc (same)
  /repo (has child .airc)          | /repo/.airc          | /repo/.airc (same)
  /repo/.airc        (BUG TRIGGER) | /repo/.airc/.airc    | /repo/.airc ✓ FIXED
  /repo/.airc/identity             | /repo/.airc/identity/.airc | /repo/.airc ✓ FIXED
  AIRC_HOME=/x set                 | /x                   | /x (override unchanged)

Carve-out narrowly addresses the bug. Doesn't change behaviour for
"cwd is parallel to a sibling .airc/" (e.g. cwd=/repo/src with /repo/.airc
existing — that still creates /repo/src/.airc the way it always has).
A broader "find enclosing scope from any subdir" change would shift the
documented per-cwd identity contract; deserves its own design discussion.

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

* hotfix(host_address_set): restore Tailscale entry when daemon signed in (#394)

* canary → main: bearer rewrite + post-3c substrate (#306)

* 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-loss class — host broadcasts
returned 'delivered' but the gist was never written; joiners polling
the gist saw nothing; user surface lied success.

## Bug 1: cmd_send.sh host-path was local-append-only
The else-branch (host case, line ~363 pre-fix) ended with:

    echo "\$full_msg" >> "\$MESSAGES"

with a comment "Joiners' SSH tails will pick it up" — relic of pre-3c
when SSH bearer's tail -F over SSH was the wire. Phase 3c (#281) deleted
SSH wholesale; joiners now poll the gist via GhBearer; a local-only
append disappears.

Fix: after the local audit append, ALSO call bearer_cli send with the
host's --room-gist-id so GhBearer publishes to the gist. Same wrap-if-
recipient-known logic as the joiner branch, so DMs to peers with
stored x25519_pub get encrypted and broadcasts go plaintext.

## Bug 2: GhBearer._gh_gist_write_file silent no-op on first send
\`gh gist edit GIST_ID file\` (no flag) returns exit 0 BUT silently does
nothing when the target filename doesn't exist in the gist. The
fallback chain ('try plain edit; on non-zero, retry with -a') never
fires because the first call returns 0 without writing. Production
gists start with only an airc-invite seed (no messages.jsonl), so
EVERY first host send hit this trap.

Fix: read the gist's file list FIRST, choose the correct subcommand:
  - file already in gist  → \`gh gist edit GIST file\`        (replace)
  - file NOT in gist      → \`gh gist edit GIST -a file\`     (add)

One extra GET, but eliminates the silent-no-op trap. Defense-in-depth:
if the existence check disagrees with reality (concurrent peer added
the file between our GET and our edit), retry the OTHER subcommand
once before giving up.

## Why the existing 123 integration tests didn't catch this
- All scenarios that exercise multi-peer messaging used \`--no-room
  --no-gist\` for speed. That flag bypasses gh entirely; the test rig
  rode on the SSH-bearer TCP-handshake path. After Phase 3c moved
  production to GhBearer, the test rig kept exercising a stripped-down
  path that doesn't match production architecture.
- scenario_bearer_gh DOES use a real gh gist BUT pre-seeds it with
  messages.jsonl (the 'happy path' shape). Production gists start with
  airc-invite seed (NOT messages.jsonl), so the first send is a CREATE
  not a REPLACE — exactly the bug. The seed shape masked it.

Two new TDD scenarios cover both paths post-fix:

- \`gh_send_creates_messages_jsonl\` (unit-of-bearer): seeds gist with
  airc-invite (matching production), runs bearer_cli send directly,
  asserts gist now contains messages.jsonl with the marker. Pre-fix:
  bearer reports 'delivered', gist unchanged. Post-fix: green.
- \`host_msg_publishes_to_gist\` (end-to-end cmd_send→bearer): spawns a
  real host with --room (no --no-gist), runs \`airc msg <marker>\`,
  asserts gist's messages.jsonl contains the marker. Pre-fix: cmd_send
  never invoked bearer_cli on host path. Post-fix: green.

Verified locally:
- gh_send_creates_messages_jsonl: 5/5 (was 3/2 before fix)
- host_msg_publishes_to_gist: 2/2 (was 1/1 before fix)

Closes #285. #283 (sidecar) and #284 (cross-room DM) are tracked
separately and will get their own TDD + fix.

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

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

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]>

* docs(skills): update /join skill for post-3c architecture (#289)

The /join skill is what every AI peer reads at startup — its content
shapes how peers behave + troubleshoot. Tonight's QA pass surfaced
that the skill still referenced Tailscale, SSH transport, and the
sidecar-process model — all gone in Phase 3c (#281).

Updates:
- Transport section: gist IS the wire; LocalBearer for same-machine,
  GhBearer for cross-network; envelope-encrypted at the X25519+
  ChaCha20-Poly1305 layer. GitHub stores ciphertext only.
- Boot outcomes: removed Tailscale-up nudges + multi-address pick
  references; added the new #general gist resolution surface.
- Multi-room: ONE monitor per scope polls all subscribed channels'
  gists in parallel. No separate sidecar process.
- Troubleshooting: replaced SSH/Tailscale failure modes with the
  actual post-3c surfaces — gh auth, gist content verification,
  cross-room routing via --room flag.

Skills/doctor and skills/invite still have similar stale refs;
follow-up PR.

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

* fix(#290): channel_gist prefers single-channel gists (substrate convergence) (#291)

* docs(skills): update /join skill for post-3c architecture

The /join skill is what every AI peer reads at startup — its content
shapes how peers behave + troubleshoot. Tonight's QA pass surfaced
that the skill still referenced Tailscale, SSH transport, and the
sidecar-process model — all gone in Phase 3c (#281).

Updates:
- Transport section: gist IS the wire; LocalBearer for same-machine,
  GhBearer for cross-network; envelope-encrypted at the X25519+
  ChaCha20-Poly1305 layer. GitHub stores ciphertext only.
- Boot outcomes: removed Tailscale-up nudges + multi-address pick
  references; added the new #general gist resolution surface.
- Multi-room: ONE monitor per scope polls all subscribed ch…
joelteply added a commit that referenced this pull request May 17, 2026
* canary → main: 35-commit airc bios-hardening (silence beacons, daemon, bus stability, rate-limit, design docs) (#422)

* docs(README): correct the encryption claims (broadcasts plaintext; DMs require pairing) + update day-one numbers

Joel caught the misleading 'How it stays safe' block: it claimed
'every cross-network message is sealed with X25519 + ChaCha20-Poly1305
... GitHub stores ciphertext only' — but reality (and the rest of the
README, line 13) is:
  - broadcasts are PLAINTEXT on the gist (group encryption is roadmap)
  - DMs between PAIRED peers are encrypted
  - DMs to UNPAIRED peers silently fall back to plaintext (#358 — confirmed
    live during today's QA pass)

A user reading the original wording reasonably believes 'all my mesh
traffic is private to recipients.' That's a security misrepresentation.

Honest version distinguishes the three cases + cross-references #358
(the active fix-track) so readers know the asymmetry exists, the
constraint is documented, and the planned mitigations are tracked.

Also updates the 'Built with itself' hero (added in #378) from
'21 commits across 3 main bundles' to '23+ commits across 4 main
bundles' — the day finished with the late-evening bundles 3 and 4
(Codex parity + README hero) which the prior numbers missed.

Signed-claim ("Every envelope Ed25519-signed; tampering observable")
stays + tightens to note sigs verify even on plaintext bodies — that
distinguishes integrity from confidentiality, which the original
block conflated.

The default-room blockquote (line 13) was already accurate ("paired
peers" + "broadcasts plaintext") so no change there.

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

* fix(#381 layer B): host-side queue/drain symmetry for transient gist failures (#385)

Pre-fix the host-side cmd_send branch had no queue path: on bearer_cli
'transient_failure' the warning printed and the message was dropped on
the floor with exit 0. Joiners polling the gist saw nothing; the user's
own audit log showed the message (because the local-mirror echo happened
BEFORE the publish attempt) so the chat widget read 'sent successfully'
even when zero peers received it. Classic silent-success-is-failure.

This change mirrors the joiner-side queue + drain pattern across to host
mode:

cmd_send.sh:
  - Move the unconditional `echo $full_msg >> $MESSAGES` into the
    `delivered)` case only. The user no longer sees their own message
    echoed back unless delivery actually completed.
  - On `transient_failure`/empty kind, append $full_msg to pending.jsonl
    and emit a [QUEUED] system marker to messages.jsonl. The user sees
    'queued for retry' in their log, not a phantom successful send.
  - On `auth_failure`, mirror the joiner branch: emit [GH AUTH FAILED]
    marker and die() with re-auth instructions. Don't queue (every
    retry hits the same dead token).
  - Unknown bearer kinds queue defensively + log loudly.

airc top-level:
  - Add flush_pending_host_loop() — symmetric to flush_pending_loop but
    drains via bearer_cli send (gist publish) instead of SSH push.
    Runs the same 5s tick, parent-liveness gate, snapshot/unsent flow.
    Per-line: extracts channel from the queued JSON, looks up the
    channel's gist, re-resolves recipient pubkey for DM wrap (so a
    pubkey paired post-queue gets used at retry time), publishes via
    bearer_cli, on `delivered` appends to local audit log + emits
    [DRAINED N] marker.
  - monitor() spawn site: when host_target is empty AND we have a
    publishable route (channel_gists OR room_gist_id), spawn the host
    flush loop. Same pidfile-honesty gate as the joiner branch — skip
    the spawn when standalone (--no-gist) so airc.pid doesn't list a
    PID that exited two seconds ago.

Composes with #381 layer A (bearer_gh.py 404/transient classification)
once that lands: layer A makes outcomes accurate, layer B makes
non-`delivered` outcomes recoverable. Layer A retries the initial
gh-api GET; layer B holds the message across longer outages (gh API
secondary rate-limit, network partitions, sandbox flake) until a tick
of the drain loop sees the gist alive again.

Edge case (documented, not addressed here): drain re-runs the wrap
step. If the original cmd_send used --plaintext to a peer with a known
X25519 pubkey, the queued $full_msg is re-wrapped at drain time. This
mirrors the asymmetry already present in the joiner-side flow (which
SSHes plaintext over) and is rare enough to leave to a follow-up.

Issue: airc#381 (Joel's tentative split: layer A → continuum-b741,
layer B → continuum-2c54)

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process) (#389)

* fix(install,connect): surface 'airc daemon install' earlier (#382)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process)

Joel observed (twice on M5 in 48h, "FREQUENT" in practice): gh's
keyring token silently invalidates — token revoked, 2FA flow expired,
brew upgrade replaced gh, OS keychain rotation, sleep across an OAuth
boundary. Pre-fix, every airc command path that touched the gist
substrate would `die "run gh auth login -h github.com"` and stop.

The user then had to manually re-auth. Two problems with that:

1. The next user (Carl, Toby, anyone) hits the same wall on first
   use after a token expires. Manual fix per user = unfixed bug.
2. Joel's "no manual fixes" / "script must self-heal" rule is
   universal: "airc MUST BE THE INSTIGATOR" — when airc detects the
   failure, IT runs the auth flow. The user's only step is clicking
   "Authorize" in the browser airc opened.

This change adds two helpers to a new `lib/airc_bash/lib_auth.sh`:

- airc_detect_gh_auth_state → echoes one of {ok, invalid,
  rate_limited, not_installed}. Distinguishes a real keyring-invalid
  state (BOTH /user and /rate_limit fail) from secondary rate limit
  (only /user fails — token is fine, just wait).

- airc_self_heal_gh_auth → runs `gh auth login --web --hostname
  github.com --git-protocol https -s gist` IN-PROCESS. gh prints the
  device code, opens the browser via the OS opener, blocks until the
  user pastes the code + clicks Authorize. Refuses to run in
  non-interactive contexts (background flush loops have no human at
  the keyboard).

- airc_ensure_gh_auth_or_heal → high-level wrapper: detect → react.
  Single-line call site for command surfaces. ok → return 0;
  rate_limited → emit explanation + return 1; invalid → trigger
  self-heal + re-detect to confirm + return 0/1; not_installed →
  emit install hint + return 1.

Wired into:

- cmd_connect.sh (~30 lines collapsed to 1 wrapper call): pre-flight
  before the join flow now self-heals on invalid token.

- cmd_send.sh (auth_failure path): on bearer-reported auth failure,
  detect + self-heal, then RETRY the send ONCE post-heal. We don't
  loop — if the retry fails too, something else is going on (scope
  missing? gist deleted?) and the user should see it.

Out of scope for this PR (separate follow-ups):
- Wire into cmd_status.sh + cmd_doctor.sh for clearer surfacing
  (today they print "RATE-LIMITED (secondary)" even when the keyring
  is genuinely dead — the new detect helper would fix that).
- Background flush loop (monitor) doesn't self-heal — by design,
  refuses non-TTY. Caller must run an interactive airc cmd to
  re-auth, then queued sends drain.

Tested:
- bash -n on all 4 touched files: clean
- airc_detect_gh_auth_state against real `ok` keyring: returns "ok"
- against bogus GH_TOKEN: returns "invalid"
- against PATH without gh: returns "not_installed"
- (Live self-heal flow tested manually previously when M5's token
  invalidated; this PR formalizes that path so users don't need to
  remember the command.)

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

---------

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

* fix(install,connect): surface 'airc daemon install' earlier (#382) (#388)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text (#390)

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text

PR #388 landed with 4 Copilot review concerns. This PR addresses all 4 +
extracts the cross-platform "is the daemon installed?" detect into a
shared helper so install.sh + cmd_connect.sh + cmd_daemon.sh all use ONE
implementation. Per Joel "if you code modularly like we require": three
near-identical case statements collapse to one detector.

NEW: lib/airc_bash/lib_daemon_detect.sh
  airc_daemon_is_installed() — covers darwin (LaunchAgents plist),
  linux+wsl (systemd user unit), windows (HKCU\...\Run\airc-monitor).
  Sourced from top-level airc + install.sh.

CHANGED:
  - install.sh: drops local _daemon_already_installed (Darwin/Linux only),
    sources lib_daemon_detect.sh from $CLONE_DIR, calls the shared
    helper. Fixes Copilot concern #2 (Windows/WSL gap).
  - install.sh: AIRC_INSTALL_YES=1 check now runs BEFORE the !-t 0
    non-TTY check, so `curl … | AIRC_INSTALL_YES=1 bash` actually
    installs the daemon instead of falling into the non-TTY tip
    branch. Fixes Copilot concern #3 (ordering bug).
  - install.sh: prompt text drops the bogus `--no-daemon-prompt` flag
    reference (the flag was never implemented anywhere); keeps only
    the AIRC_INSTALL_NO_DAEMON=1 env-var hint that DOES work. Fixes
    Copilot concern #1 (lying-to-user copy).
  - install.sh: launchd/systemd → "launchd / systemd / HKCU-Run" in
    the prompt body so Windows users see their platform mentioned.
  - cmd_connect.sh: first-host daemon-tip block (line ~1707) replaces
    its Darwin-only/Linux-only case statement with a single call to
    airc_daemon_is_installed. Fires correctly on Windows now where
    the previous code never fired (HKCU Run-key wasn't checked).
    Fixes Copilot concern #4.
  - cmd_daemon.sh::_daemon_installed becomes a thin wrapper around
    the shared detector. Preserves the local-private-helper API
    used by callers in this file; cross-platform logic now lives in
    one place. Detection guaranteed consistent across all sites.

Branch ordering rationale (install.sh, top→bottom):
  1. AIRC_INSTALL_NO_DAEMON=1   — explicit opt-out trumps everything
  2. AIRC_INSTALL_YES=1         — explicit auto-install (now BEFORE non-TTY)
  3. airc_daemon_is_installed   — idempotent re-run no-op
  4. !-t 0 || !-t 1             — non-TTY tip
  5. interactive [Y/n]          — default

TEST:
  - bash -n on all 5 touched files: clean
  - airc_daemon_is_installed against real Mac (daemon installed): returns 0 ✓
  - against mocked-windows (reg query mocked to succeed): returns 0 ✓
  - cmd_daemon.sh::_daemon_installed wrapper: still returns same value
    as direct airc_daemon_is_installed call (delegation works)
  - install.sh ordering: verified YES check (line 909) precedes !-t 0
    check (line 920+) by inspection

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

* docs: address Copilot nits on PR #390 — comment-only fixes

Three pure comment fixes from Copilot review:
1. lib_daemon_detect.sh: 'users-experience bugs' → 'user experience bugs'
   (grammar)
2. install.sh: 'Three NON-prompt branches' → 'Four NON-prompt branches'
   (the list below the comment has 4 branches: NO_DAEMON, YES,
   already-installed, non-TTY)
3. lib_daemon_detect.sh: HKCU\...\Run\airc-monitor reads as a subkey
   path; airc-monitor is actually the VALUE NAME under the Run key.
   Reworded to clarify.

No code changes.

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

---------

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

* fix: distinguish env_token_invalid (GH_TOKEN poisoned) from keyring-invalid (#391)

Discovered live on canary 73ab85e while testing PR #389's self-heal flow:
when GH_TOKEN env var is set + invalid, gh REFUSES to run `gh auth login`
("The value of the GH_TOKEN environment variable is being used for
authentication. To have GitHub CLI store credentials instead, first clear
the value from the environment").

Pre-fix the wrapper would still trigger self-heal in this case, gh would
bounce immediately, and the user got the misleading "auth flow did not
complete (cancelled? no network?)" fallback message. No path forward
visible to them.

Fix: detect this case as a NEW state, `env_token_invalid`, distinct from
keyring-`invalid`. The wrapper handles it with a precise message:

  ✗ GH_TOKEN environment variable is set + invalid.
    airc can't auto-heal this — gh refuses to run 'gh auth login' while
    GH_TOKEN is set. Self-heal would just bounce.

    Two paths to fix:
    1. Stale dotfile / leftover export → just unset it:
         unset GH_TOKEN
       Then re-run your airc command. airc will detect the keyring
       auth + self-heal it via the browser flow.
    2. Real CI token (Actions, Codespace, dotfile sourcing a managed
       token) → fix the source. Don't run gh auth login; refresh
       whichever system writes GH_TOKEN.

    What gh sees right now:
      [verbatim gh auth status output]

Detection logic:
  if gh auth status passes:           → ok           (unchanged)
  elif gh api rate_limit passes:      → rate_limited (unchanged)
  elif [ -n "${GH_TOKEN:-}" ]:        → env_token_invalid  (NEW)
  else:                               → invalid      (unchanged)

GH_TOKEN takes precedence over keyring in gh's auth resolution. If we
got past gh auth status + gh api rate_limit both failing AND GH_TOKEN
is set, then GH_TOKEN is what gh's using and it's dead. Self-heal can't
fix that — only user-side action can.

Tested:
  - real ok keyring (no GH_TOKEN):           detect → "ok"             ✓
  - bogus GH_TOKEN, real keyring fine:        detect → "env_token_invalid" ✓
  - mocked auth+rate fails, no GH_TOKEN:      detect → "invalid"        ✓
  - wrapper with env_token_invalid: emits two-path message + returns 1 ✓

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

* fix: detect_scope walks up to enclosing .airc/ ancestor (no more .airc/.airc) (#392)

When a user `cd`'d into the scope dir for forensic inspection (or any
descendant), `detect_scope()` returned `$pwd/.airc` — producing wrong
nested paths like `/repo/.airc/.airc`. Every subsequent airc command
then died with "Not initialized" against a directory that didn't exist.
Discovered live on M5 2026-05-01 while diagnosing a different airc
issue: the very act of `cd .airc; airc status` to inspect state broke
airc.

Fix: walk up from cwd looking for an ancestor whose basename is .airc.
If found, that's the scope. If not found, fall through to the
documented `$pwd/.airc` per-cwd default (unchanged behaviour for the
common fresh-cwd case).

Test cases:

  cwd                              | pre-fix              | post-fix
  ---------------------------------|----------------------|------------
  /repo (no .airc anywhere)        | /repo/.airc          | /repo/.airc (same)
  /repo (has child .airc)          | /repo/.airc          | /repo/.airc (same)
  /repo/.airc        (BUG TRIGGER) | /repo/.airc/.airc    | /repo/.airc ✓ FIXED
  /repo/.airc/identity             | /repo/.airc/identity/.airc | /repo/.airc ✓ FIXED
  AIRC_HOME=/x set                 | /x                   | /x (override unchanged)

Carve-out narrowly addresses the bug. Doesn't change behaviour for
"cwd is parallel to a sibling .airc/" (e.g. cwd=/repo/src with /repo/.airc
existing — that still creates /repo/src/.airc the way it always has).
A broader "find enclosing scope from any subdir" change would shift the
documented per-cwd identity contract; deserves its own design discussion.

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

* hotfix(host_address_set): restore Tailscale entry when daemon signed in (#394)

* canary → main: bearer rewrite + post-3c substrate (#306)

* 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-loss class — host broadcasts
returned 'delivered' but the gist was never written; joiners polling
the gist saw nothing; user surface lied success.

## Bug 1: cmd_send.sh host-path was local-append-only
The else-branch (host case, line ~363 pre-fix) ended with:

    echo "\$full_msg" >> "\$MESSAGES"

with a comment "Joiners' SSH tails will pick it up" — relic of pre-3c
when SSH bearer's tail -F over SSH was the wire. Phase 3c (#281) deleted
SSH wholesale; joiners now poll the gist via GhBearer; a local-only
append disappears.

Fix: after the local audit append, ALSO call bearer_cli send with the
host's --room-gist-id so GhBearer publishes to the gist. Same wrap-if-
recipient-known logic as the joiner branch, so DMs to peers with
stored x25519_pub get encrypted and broadcasts go plaintext.

## Bug 2: GhBearer._gh_gist_write_file silent no-op on first send
\`gh gist edit GIST_ID file\` (no flag) returns exit 0 BUT silently does
nothing when the target filename doesn't exist in the gist. The
fallback chain ('try plain edit; on non-zero, retry with -a') never
fires because the first call returns 0 without writing. Production
gists start with only an airc-invite seed (no messages.jsonl), so
EVERY first host send hit this trap.

Fix: read the gist's file list FIRST, choose the correct subcommand:
  - file already in gist  → \`gh gist edit GIST file\`        (replace)
  - file NOT in gist      → \`gh gist edit GIST -a file\`     (add)

One extra GET, but eliminates the silent-no-op trap. Defense-in-depth:
if the existence check disagrees with reality (concurrent peer added
the file between our GET and our edit), retry the OTHER subcommand
once before giving up.

## Why the existing 123 integration tests didn't catch this
- All scenarios that exercise multi-peer messaging used \`--no-room
  --no-gist\` for speed. That flag bypasses gh entirely; the test rig
  rode on the SSH-bearer TCP-handshake path. After Phase 3c moved
  production to GhBearer, the test rig kept exercising a stripped-down
  path that doesn't match production architecture.
- scenario_bearer_gh DOES use a real gh gist BUT pre-seeds it with
  messages.jsonl (the 'happy path' shape). Production gists start with
  airc-invite seed (NOT messages.jsonl), so the first send is a CREATE
  not a REPLACE — exactly the bug. The seed shape masked it.

Two new TDD scenarios cover both paths post-fix:

- \`gh_send_creates_messages_jsonl\` (unit-of-bearer): seeds gist with
  airc-invite (matching production), runs bearer_cli send directly,
  asserts gist now contains messages.jsonl with the marker. Pre-fix:
  bearer reports 'delivered', gist unchanged. Post-fix: green.
- \`host_msg_publishes_to_gist\` (end-to-end cmd_send→bearer): spawns a
  real host with --room (no --no-gist), runs \`airc msg <marker>\`,
  asserts gist's messages.jsonl contains the marker. Pre-fix: cmd_send
  never invoked bearer_cli on host path. Post-fix: green.

Verified locally:
- gh_send_creates_messages_jsonl: 5/5 (was 3/2 before fix)
- host_msg_publishes_to_gist: 2/2 (was 1/1 before fix)

Closes #285. #283 (sidecar) and #284 (cross-room DM) are tracked
separately and will get their own TDD + fix.

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

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

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]>

* docs(skills): update /join skill for post-3c architecture (#289)

The /join skill is what every AI peer reads at startup — its content
shapes how peers behave + troubleshoot. Tonight's QA pass surfaced
that the skill still referenced Tailscale, SSH transport, and the
sidecar-process model — all gone in Phase 3c (#281).

Updates:
- Transport section: gist IS the wire; LocalBearer for same-machine,
  GhBearer for cross-network; envelope-encrypted at the X25519+
  ChaCha20-Poly1305 layer. GitHub stores ciphertext only.
- Boot outcomes: removed Tailscale-up nudges + multi-address pick
  references; added the new #general gist resolution surface.
- Multi-room: ONE monitor per scope polls all subscribed channels'
  gists in parallel. No separate sidecar process.
- Troubleshooting: replaced SSH/Tailscale failure modes with the
  actual post-3c surfaces — gh auth, gist content verification,
  cross-room routing via --room flag.

Skills/doctor and skills/invite still have similar stale refs;
follow-up PR.

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

* fix(#290): channel_gist prefers single-channel gists (substrate convergence) (#291)

* docs(skills): update /join skill for post-3c architecture

The /join skill is what every AI peer reads at startup — its content
shapes how peers behave + troubleshoot. Tonight's QA pass surfaced
that the skill still referenced Tailscale, SSH transport, and the
sidecar-process model — all gone in Phase 3c (#281).

Updates:
- Transport section: gist IS the wire; LocalBearer for same-machine,
  GhBearer for cross-network; envelope-encrypted at the X25519+
  ChaCha20-Poly1305 layer. GitHub stores ciphertext only.
- Boot outcomes: removed Tailscale-up nudges + multi-address pick
  references; added the new #general gist resolution surfa…
joelteply added a commit that referenced this pull request May 17, 2026
…ate (#643)

* canary → main: 35-commit airc bios-hardening (silence beacons, daemon, bus stability, rate-limit, design docs) (#422)

* docs(README): correct the encryption claims (broadcasts plaintext; DMs require pairing) + update day-one numbers

Joel caught the misleading 'How it stays safe' block: it claimed
'every cross-network message is sealed with X25519 + ChaCha20-Poly1305
... GitHub stores ciphertext only' — but reality (and the rest of the
README, line 13) is:
  - broadcasts are PLAINTEXT on the gist (group encryption is roadmap)
  - DMs between PAIRED peers are encrypted
  - DMs to UNPAIRED peers silently fall back to plaintext (#358 — confirmed
    live during today's QA pass)

A user reading the original wording reasonably believes 'all my mesh
traffic is private to recipients.' That's a security misrepresentation.

Honest version distinguishes the three cases + cross-references #358
(the active fix-track) so readers know the asymmetry exists, the
constraint is documented, and the planned mitigations are tracked.

Also updates the 'Built with itself' hero (added in #378) from
'21 commits across 3 main bundles' to '23+ commits across 4 main
bundles' — the day finished with the late-evening bundles 3 and 4
(Codex parity + README hero) which the prior numbers missed.

Signed-claim ("Every envelope Ed25519-signed; tampering observable")
stays + tightens to note sigs verify even on plaintext bodies — that
distinguishes integrity from confidentiality, which the original
block conflated.

The default-room blockquote (line 13) was already accurate ("paired
peers" + "broadcasts plaintext") so no change there.

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

* fix(#381 layer B): host-side queue/drain symmetry for transient gist failures (#385)

Pre-fix the host-side cmd_send branch had no queue path: on bearer_cli
'transient_failure' the warning printed and the message was dropped on
the floor with exit 0. Joiners polling the gist saw nothing; the user's
own audit log showed the message (because the local-mirror echo happened
BEFORE the publish attempt) so the chat widget read 'sent successfully'
even when zero peers received it. Classic silent-success-is-failure.

This change mirrors the joiner-side queue + drain pattern across to host
mode:

cmd_send.sh:
  - Move the unconditional `echo $full_msg >> $MESSAGES` into the
    `delivered)` case only. The user no longer sees their own message
    echoed back unless delivery actually completed.
  - On `transient_failure`/empty kind, append $full_msg to pending.jsonl
    and emit a [QUEUED] system marker to messages.jsonl. The user sees
    'queued for retry' in their log, not a phantom successful send.
  - On `auth_failure`, mirror the joiner branch: emit [GH AUTH FAILED]
    marker and die() with re-auth instructions. Don't queue (every
    retry hits the same dead token).
  - Unknown bearer kinds queue defensively + log loudly.

airc top-level:
  - Add flush_pending_host_loop() — symmetric to flush_pending_loop but
    drains via bearer_cli send (gist publish) instead of SSH push.
    Runs the same 5s tick, parent-liveness gate, snapshot/unsent flow.
    Per-line: extracts channel from the queued JSON, looks up the
    channel's gist, re-resolves recipient pubkey for DM wrap (so a
    pubkey paired post-queue gets used at retry time), publishes via
    bearer_cli, on `delivered` appends to local audit log + emits
    [DRAINED N] marker.
  - monitor() spawn site: when host_target is empty AND we have a
    publishable route (channel_gists OR room_gist_id), spawn the host
    flush loop. Same pidfile-honesty gate as the joiner branch — skip
    the spawn when standalone (--no-gist) so airc.pid doesn't list a
    PID that exited two seconds ago.

Composes with #381 layer A (bearer_gh.py 404/transient classification)
once that lands: layer A makes outcomes accurate, layer B makes
non-`delivered` outcomes recoverable. Layer A retries the initial
gh-api GET; layer B holds the message across longer outages (gh API
secondary rate-limit, network partitions, sandbox flake) until a tick
of the drain loop sees the gist alive again.

Edge case (documented, not addressed here): drain re-runs the wrap
step. If the original cmd_send used --plaintext to a peer with a known
X25519 pubkey, the queued $full_msg is re-wrapped at drain time. This
mirrors the asymmetry already present in the joiner-side flow (which
SSHes plaintext over) and is rare enough to leave to a follow-up.

Issue: airc#381 (Joel's tentative split: layer A → continuum-b741,
layer B → continuum-2c54)

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process) (#389)

* fix(install,connect): surface 'airc daemon install' earlier (#382)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process)

Joel observed (twice on M5 in 48h, "FREQUENT" in practice): gh's
keyring token silently invalidates — token revoked, 2FA flow expired,
brew upgrade replaced gh, OS keychain rotation, sleep across an OAuth
boundary. Pre-fix, every airc command path that touched the gist
substrate would `die "run gh auth login -h github.com"` and stop.

The user then had to manually re-auth. Two problems with that:

1. The next user (Carl, Toby, anyone) hits the same wall on first
   use after a token expires. Manual fix per user = unfixed bug.
2. Joel's "no manual fixes" / "script must self-heal" rule is
   universal: "airc MUST BE THE INSTIGATOR" — when airc detects the
   failure, IT runs the auth flow. The user's only step is clicking
   "Authorize" in the browser airc opened.

This change adds two helpers to a new `lib/airc_bash/lib_auth.sh`:

- airc_detect_gh_auth_state → echoes one of {ok, invalid,
  rate_limited, not_installed}. Distinguishes a real keyring-invalid
  state (BOTH /user and /rate_limit fail) from secondary rate limit
  (only /user fails — token is fine, just wait).

- airc_self_heal_gh_auth → runs `gh auth login --web --hostname
  github.com --git-protocol https -s gist` IN-PROCESS. gh prints the
  device code, opens the browser via the OS opener, blocks until the
  user pastes the code + clicks Authorize. Refuses to run in
  non-interactive contexts (background flush loops have no human at
  the keyboard).

- airc_ensure_gh_auth_or_heal → high-level wrapper: detect → react.
  Single-line call site for command surfaces. ok → return 0;
  rate_limited → emit explanation + return 1; invalid → trigger
  self-heal + re-detect to confirm + return 0/1; not_installed →
  emit install hint + return 1.

Wired into:

- cmd_connect.sh (~30 lines collapsed to 1 wrapper call): pre-flight
  before the join flow now self-heals on invalid token.

- cmd_send.sh (auth_failure path): on bearer-reported auth failure,
  detect + self-heal, then RETRY the send ONCE post-heal. We don't
  loop — if the retry fails too, something else is going on (scope
  missing? gist deleted?) and the user should see it.

Out of scope for this PR (separate follow-ups):
- Wire into cmd_status.sh + cmd_doctor.sh for clearer surfacing
  (today they print "RATE-LIMITED (secondary)" even when the keyring
  is genuinely dead — the new detect helper would fix that).
- Background flush loop (monitor) doesn't self-heal — by design,
  refuses non-TTY. Caller must run an interactive airc cmd to
  re-auth, then queued sends drain.

Tested:
- bash -n on all 4 touched files: clean
- airc_detect_gh_auth_state against real `ok` keyring: returns "ok"
- against bogus GH_TOKEN: returns "invalid"
- against PATH without gh: returns "not_installed"
- (Live self-heal flow tested manually previously when M5's token
  invalidated; this PR formalizes that path so users don't need to
  remember the command.)

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

---------

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

* fix(install,connect): surface 'airc daemon install' earlier (#382) (#388)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text (#390)

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text

PR #388 landed with 4 Copilot review concerns. This PR addresses all 4 +
extracts the cross-platform "is the daemon installed?" detect into a
shared helper so install.sh + cmd_connect.sh + cmd_daemon.sh all use ONE
implementation. Per Joel "if you code modularly like we require": three
near-identical case statements collapse to one detector.

NEW: lib/airc_bash/lib_daemon_detect.sh
  airc_daemon_is_installed() — covers darwin (LaunchAgents plist),
  linux+wsl (systemd user unit), windows (HKCU\...\Run\airc-monitor).
  Sourced from top-level airc + install.sh.

CHANGED:
  - install.sh: drops local _daemon_already_installed (Darwin/Linux only),
    sources lib_daemon_detect.sh from $CLONE_DIR, calls the shared
    helper. Fixes Copilot concern #2 (Windows/WSL gap).
  - install.sh: AIRC_INSTALL_YES=1 check now runs BEFORE the !-t 0
    non-TTY check, so `curl … | AIRC_INSTALL_YES=1 bash` actually
    installs the daemon instead of falling into the non-TTY tip
    branch. Fixes Copilot concern #3 (ordering bug).
  - install.sh: prompt text drops the bogus `--no-daemon-prompt` flag
    reference (the flag was never implemented anywhere); keeps only
    the AIRC_INSTALL_NO_DAEMON=1 env-var hint that DOES work. Fixes
    Copilot concern #1 (lying-to-user copy).
  - install.sh: launchd/systemd → "launchd / systemd / HKCU-Run" in
    the prompt body so Windows users see their platform mentioned.
  - cmd_connect.sh: first-host daemon-tip block (line ~1707) replaces
    its Darwin-only/Linux-only case statement with a single call to
    airc_daemon_is_installed. Fires correctly on Windows now where
    the previous code never fired (HKCU Run-key wasn't checked).
    Fixes Copilot concern #4.
  - cmd_daemon.sh::_daemon_installed becomes a thin wrapper around
    the shared detector. Preserves the local-private-helper API
    used by callers in this file; cross-platform logic now lives in
    one place. Detection guaranteed consistent across all sites.

Branch ordering rationale (install.sh, top→bottom):
  1. AIRC_INSTALL_NO_DAEMON=1   — explicit opt-out trumps everything
  2. AIRC_INSTALL_YES=1         — explicit auto-install (now BEFORE non-TTY)
  3. airc_daemon_is_installed   — idempotent re-run no-op
  4. !-t 0 || !-t 1             — non-TTY tip
  5. interactive [Y/n]          — default

TEST:
  - bash -n on all 5 touched files: clean
  - airc_daemon_is_installed against real Mac (daemon installed): returns 0 ✓
  - against mocked-windows (reg query mocked to succeed): returns 0 ✓
  - cmd_daemon.sh::_daemon_installed wrapper: still returns same value
    as direct airc_daemon_is_installed call (delegation works)
  - install.sh ordering: verified YES check (line 909) precedes !-t 0
    check (line 920+) by inspection

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

* docs: address Copilot nits on PR #390 — comment-only fixes

Three pure comment fixes from Copilot review:
1. lib_daemon_detect.sh: 'users-experience bugs' → 'user experience bugs'
   (grammar)
2. install.sh: 'Three NON-prompt branches' → 'Four NON-prompt branches'
   (the list below the comment has 4 branches: NO_DAEMON, YES,
   already-installed, non-TTY)
3. lib_daemon_detect.sh: HKCU\...\Run\airc-monitor reads as a subkey
   path; airc-monitor is actually the VALUE NAME under the Run key.
   Reworded to clarify.

No code changes.

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

---------

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

* fix: distinguish env_token_invalid (GH_TOKEN poisoned) from keyring-invalid (#391)

Discovered live on canary 73ab85e while testing PR #389's self-heal flow:
when GH_TOKEN env var is set + invalid, gh REFUSES to run `gh auth login`
("The value of the GH_TOKEN environment variable is being used for
authentication. To have GitHub CLI store credentials instead, first clear
the value from the environment").

Pre-fix the wrapper would still trigger self-heal in this case, gh would
bounce immediately, and the user got the misleading "auth flow did not
complete (cancelled? no network?)" fallback message. No path forward
visible to them.

Fix: detect this case as a NEW state, `env_token_invalid`, distinct from
keyring-`invalid`. The wrapper handles it with a precise message:

  ✗ GH_TOKEN environment variable is set + invalid.
    airc can't auto-heal this — gh refuses to run 'gh auth login' while
    GH_TOKEN is set. Self-heal would just bounce.

    Two paths to fix:
    1. Stale dotfile / leftover export → just unset it:
         unset GH_TOKEN
       Then re-run your airc command. airc will detect the keyring
       auth + self-heal it via the browser flow.
    2. Real CI token (Actions, Codespace, dotfile sourcing a managed
       token) → fix the source. Don't run gh auth login; refresh
       whichever system writes GH_TOKEN.

    What gh sees right now:
      [verbatim gh auth status output]

Detection logic:
  if gh auth status passes:           → ok           (unchanged)
  elif gh api rate_limit passes:      → rate_limited (unchanged)
  elif [ -n "${GH_TOKEN:-}" ]:        → env_token_invalid  (NEW)
  else:                               → invalid      (unchanged)

GH_TOKEN takes precedence over keyring in gh's auth resolution. If we
got past gh auth status + gh api rate_limit both failing AND GH_TOKEN
is set, then GH_TOKEN is what gh's using and it's dead. Self-heal can't
fix that — only user-side action can.

Tested:
  - real ok keyring (no GH_TOKEN):           detect → "ok"             ✓
  - bogus GH_TOKEN, real keyring fine:        detect → "env_token_invalid" ✓
  - mocked auth+rate fails, no GH_TOKEN:      detect → "invalid"        ✓
  - wrapper with env_token_invalid: emits two-path message + returns 1 ✓

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

* fix: detect_scope walks up to enclosing .airc/ ancestor (no more .airc/.airc) (#392)

When a user `cd`'d into the scope dir for forensic inspection (or any
descendant), `detect_scope()` returned `$pwd/.airc` — producing wrong
nested paths like `/repo/.airc/.airc`. Every subsequent airc command
then died with "Not initialized" against a directory that didn't exist.
Discovered live on M5 2026-05-01 while diagnosing a different airc
issue: the very act of `cd .airc; airc status` to inspect state broke
airc.

Fix: walk up from cwd looking for an ancestor whose basename is .airc.
If found, that's the scope. If not found, fall through to the
documented `$pwd/.airc` per-cwd default (unchanged behaviour for the
common fresh-cwd case).

Test cases:

  cwd                              | pre-fix              | post-fix
  ---------------------------------|----------------------|------------
  /repo (no .airc anywhere)        | /repo/.airc          | /repo/.airc (same)
  /repo (has child .airc)          | /repo/.airc          | /repo/.airc (same)
  /repo/.airc        (BUG TRIGGER) | /repo/.airc/.airc    | /repo/.airc ✓ FIXED
  /repo/.airc/identity             | /repo/.airc/identity/.airc | /repo/.airc ✓ FIXED
  AIRC_HOME=/x set                 | /x                   | /x (override unchanged)

Carve-out narrowly addresses the bug. Doesn't change behaviour for
"cwd is parallel to a sibling .airc/" (e.g. cwd=/repo/src with /repo/.airc
existing — that still creates /repo/src/.airc the way it always has).
A broader "find enclosing scope from any subdir" change would shift the
documented per-cwd identity contract; deserves its own design discussion.

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

* hotfix(host_address_set): restore Tailscale entry when daemon signed in (#394)

* canary → main: bearer rewrite + post-3c substrate (#306)

* 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-loss class — host broadcasts
returned 'delivered' but the gist was never written; joiners polling
the gist saw nothing; user surface lied success.

## Bug 1: cmd_send.sh host-path was local-append-only
The else-branch (host case, line ~363 pre-fix) ended with:

    echo "\$full_msg" >> "\$MESSAGES"

with a comment "Joiners' SSH tails will pick it up" — relic of pre-3c
when SSH bearer's tail -F over SSH was the wire. Phase 3c (#281) deleted
SSH wholesale; joiners now poll the gist via GhBearer; a local-only
append disappears.

Fix: after the local audit append, ALSO call bearer_cli send with the
host's --room-gist-id so GhBearer publishes to the gist. Same wrap-if-
recipient-known logic as the joiner branch, so DMs to peers with
stored x25519_pub get encrypted and broadcasts go plaintext.

## Bug 2: GhBearer._gh_gist_write_file silent no-op on first send
\`gh gist edit GIST_ID file\` (no flag) returns exit 0 BUT silently does
nothing when the target filename doesn't exist in the gist. The
fallback chain ('try plain edit; on non-zero, retry with -a') never
fires because the first call returns 0 without writing. Production
gists start with only an airc-invite seed (no messages.jsonl), so
EVERY first host send hit this trap.

Fix: read the gist's file list FIRST, choose the correct subcommand:
  - file already in gist  → \`gh gist edit GIST file\`        (replace)
  - file NOT in gist      → \`gh gist edit GIST -a file\`     (add)

One extra GET, but eliminates the silent-no-op trap. Defense-in-depth:
if the existence check disagrees with reality (concurrent peer added
the file between our GET and our edit), retry the OTHER subcommand
once before giving up.

## Why the existing 123 integration tests didn't catch this
- All scenarios that exercise multi-peer messaging used \`--no-room
  --no-gist\` for speed. That flag bypasses gh entirely; the test rig
  rode on the SSH-bearer TCP-handshake path. After Phase 3c moved
  production to GhBearer, the test rig kept exercising a stripped-down
  path that doesn't match production architecture.
- scenario_bearer_gh DOES use a real gh gist BUT pre-seeds it with
  messages.jsonl (the 'happy path' shape). Production gists start with
  airc-invite seed (NOT messages.jsonl), so the first send is a CREATE
  not a REPLACE — exactly the bug. The seed shape masked it.

Two new TDD scenarios cover both paths post-fix:

- \`gh_send_creates_messages_jsonl\` (unit-of-bearer): seeds gist with
  airc-invite (matching production), runs bearer_cli send directly,
  asserts gist now contains messages.jsonl with the marker. Pre-fix:
  bearer reports 'delivered', gist unchanged. Post-fix: green.
- \`host_msg_publishes_to_gist\` (end-to-end cmd_send→bearer): spawns a
  real host with --room (no --no-gist), runs \`airc msg <marker>\`,
  asserts gist's messages.jsonl contains the marker. Pre-fix: cmd_send
  never invoked bearer_cli on host path. Post-fix: green.

Verified locally:
- gh_send_creates_messages_jsonl: 5/5 (was 3/2 before fix)
- host_msg_publishes_to_gist: 2/2 (was 1/1 before fix)

Closes #285. #283 (sidecar) and #284 (cross-room DM) are tracked
separately and will get their own TDD + fix.

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

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

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]>

* docs(skills): update /join skill for post-3c architecture (#289)

The /join skill is what every AI peer reads at startup — its content
shapes how peers behave + troubleshoot. Tonight's QA pass surfaced
that the skill still referenced Tailscale, SSH transport, and the
sidecar-process model — all gone in Phase 3c (#281).

Updates:
- Transport section: gist IS the wire; LocalBearer for same-machine,
  GhBearer for cross-network; envelope-encrypted at the X25519+
  ChaCha20-Poly1305 layer. GitHub stores ciphertext only.
- Boot outcomes: removed Tailscale-up nudges + multi-address pick
  references; added the new #general gist resolution surface.
- Multi-room: ONE monitor per scope polls all subscribed channels'
  gists in parallel. No separate sidecar process.
- Troubleshooting: replaced SSH/Tailscale failure modes with the
  actual post-3c surfaces — gh auth, gist content verification,
  cross-room routing via --room flag.

Skills/doctor and skills/invite still have similar stale refs;
follow-up PR.

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

* fix(#290): channel_gist prefers single-channel gists (substrate convergence) (#291)

* docs(skills): update /join skill for post-3c architecture

The /join skill is what every AI peer reads at startup — its content
shapes how peers behave + troubleshoot. Tonight's QA pass surfaced
that the skill still referenced Tailscale, SSH transport, and the
sidecar-process model — all gone in Phase 3c (#281).

Updates:
- Transport section: gist IS the wire; LocalBearer for same-machine,
  GhBearer for cross-network; envelope-encrypted at the X25519+
  ChaCha20-Poly1305 layer. GitHub stores ciphertext only.
- Boot outcomes: removed Tailscale-up nudges + multi-address pick
  references; added the new #general…
joelteply added a commit that referenced this pull request May 17, 2026
…rc#644 PR-1) (#645)

* canary → main: 35-commit airc bios-hardening (silence beacons, daemon, bus stability, rate-limit, design docs) (#422)

* docs(README): correct the encryption claims (broadcasts plaintext; DMs require pairing) + update day-one numbers

Joel caught the misleading 'How it stays safe' block: it claimed
'every cross-network message is sealed with X25519 + ChaCha20-Poly1305
... GitHub stores ciphertext only' — but reality (and the rest of the
README, line 13) is:
  - broadcasts are PLAINTEXT on the gist (group encryption is roadmap)
  - DMs between PAIRED peers are encrypted
  - DMs to UNPAIRED peers silently fall back to plaintext (#358 — confirmed
    live during today's QA pass)

A user reading the original wording reasonably believes 'all my mesh
traffic is private to recipients.' That's a security misrepresentation.

Honest version distinguishes the three cases + cross-references #358
(the active fix-track) so readers know the asymmetry exists, the
constraint is documented, and the planned mitigations are tracked.

Also updates the 'Built with itself' hero (added in #378) from
'21 commits across 3 main bundles' to '23+ commits across 4 main
bundles' — the day finished with the late-evening bundles 3 and 4
(Codex parity + README hero) which the prior numbers missed.

Signed-claim ("Every envelope Ed25519-signed; tampering observable")
stays + tightens to note sigs verify even on plaintext bodies — that
distinguishes integrity from confidentiality, which the original
block conflated.

The default-room blockquote (line 13) was already accurate ("paired
peers" + "broadcasts plaintext") so no change there.

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

* fix(#381 layer B): host-side queue/drain symmetry for transient gist failures (#385)

Pre-fix the host-side cmd_send branch had no queue path: on bearer_cli
'transient_failure' the warning printed and the message was dropped on
the floor with exit 0. Joiners polling the gist saw nothing; the user's
own audit log showed the message (because the local-mirror echo happened
BEFORE the publish attempt) so the chat widget read 'sent successfully'
even when zero peers received it. Classic silent-success-is-failure.

This change mirrors the joiner-side queue + drain pattern across to host
mode:

cmd_send.sh:
  - Move the unconditional `echo $full_msg >> $MESSAGES` into the
    `delivered)` case only. The user no longer sees their own message
    echoed back unless delivery actually completed.
  - On `transient_failure`/empty kind, append $full_msg to pending.jsonl
    and emit a [QUEUED] system marker to messages.jsonl. The user sees
    'queued for retry' in their log, not a phantom successful send.
  - On `auth_failure`, mirror the joiner branch: emit [GH AUTH FAILED]
    marker and die() with re-auth instructions. Don't queue (every
    retry hits the same dead token).
  - Unknown bearer kinds queue defensively + log loudly.

airc top-level:
  - Add flush_pending_host_loop() — symmetric to flush_pending_loop but
    drains via bearer_cli send (gist publish) instead of SSH push.
    Runs the same 5s tick, parent-liveness gate, snapshot/unsent flow.
    Per-line: extracts channel from the queued JSON, looks up the
    channel's gist, re-resolves recipient pubkey for DM wrap (so a
    pubkey paired post-queue gets used at retry time), publishes via
    bearer_cli, on `delivered` appends to local audit log + emits
    [DRAINED N] marker.
  - monitor() spawn site: when host_target is empty AND we have a
    publishable route (channel_gists OR room_gist_id), spawn the host
    flush loop. Same pidfile-honesty gate as the joiner branch — skip
    the spawn when standalone (--no-gist) so airc.pid doesn't list a
    PID that exited two seconds ago.

Composes with #381 layer A (bearer_gh.py 404/transient classification)
once that lands: layer A makes outcomes accurate, layer B makes
non-`delivered` outcomes recoverable. Layer A retries the initial
gh-api GET; layer B holds the message across longer outages (gh API
secondary rate-limit, network partitions, sandbox flake) until a tick
of the drain loop sees the gist alive again.

Edge case (documented, not addressed here): drain re-runs the wrap
step. If the original cmd_send used --plaintext to a peer with a known
X25519 pubkey, the queued $full_msg is re-wrapped at drain time. This
mirrors the asymmetry already present in the joiner-side flow (which
SSHes plaintext over) and is rare enough to leave to a follow-up.

Issue: airc#381 (Joel's tentative split: layer A → continuum-b741,
layer B → continuum-2c54)

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process) (#389)

* fix(install,connect): surface 'airc daemon install' earlier (#382)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process)

Joel observed (twice on M5 in 48h, "FREQUENT" in practice): gh's
keyring token silently invalidates — token revoked, 2FA flow expired,
brew upgrade replaced gh, OS keychain rotation, sleep across an OAuth
boundary. Pre-fix, every airc command path that touched the gist
substrate would `die "run gh auth login -h github.com"` and stop.

The user then had to manually re-auth. Two problems with that:

1. The next user (Carl, Toby, anyone) hits the same wall on first
   use after a token expires. Manual fix per user = unfixed bug.
2. Joel's "no manual fixes" / "script must self-heal" rule is
   universal: "airc MUST BE THE INSTIGATOR" — when airc detects the
   failure, IT runs the auth flow. The user's only step is clicking
   "Authorize" in the browser airc opened.

This change adds two helpers to a new `lib/airc_bash/lib_auth.sh`:

- airc_detect_gh_auth_state → echoes one of {ok, invalid,
  rate_limited, not_installed}. Distinguishes a real keyring-invalid
  state (BOTH /user and /rate_limit fail) from secondary rate limit
  (only /user fails — token is fine, just wait).

- airc_self_heal_gh_auth → runs `gh auth login --web --hostname
  github.com --git-protocol https -s gist` IN-PROCESS. gh prints the
  device code, opens the browser via the OS opener, blocks until the
  user pastes the code + clicks Authorize. Refuses to run in
  non-interactive contexts (background flush loops have no human at
  the keyboard).

- airc_ensure_gh_auth_or_heal → high-level wrapper: detect → react.
  Single-line call site for command surfaces. ok → return 0;
  rate_limited → emit explanation + return 1; invalid → trigger
  self-heal + re-detect to confirm + return 0/1; not_installed →
  emit install hint + return 1.

Wired into:

- cmd_connect.sh (~30 lines collapsed to 1 wrapper call): pre-flight
  before the join flow now self-heals on invalid token.

- cmd_send.sh (auth_failure path): on bearer-reported auth failure,
  detect + self-heal, then RETRY the send ONCE post-heal. We don't
  loop — if the retry fails too, something else is going on (scope
  missing? gist deleted?) and the user should see it.

Out of scope for this PR (separate follow-ups):
- Wire into cmd_status.sh + cmd_doctor.sh for clearer surfacing
  (today they print "RATE-LIMITED (secondary)" even when the keyring
  is genuinely dead — the new detect helper would fix that).
- Background flush loop (monitor) doesn't self-heal — by design,
  refuses non-TTY. Caller must run an interactive airc cmd to
  re-auth, then queued sends drain.

Tested:
- bash -n on all 4 touched files: clean
- airc_detect_gh_auth_state against real `ok` keyring: returns "ok"
- against bogus GH_TOKEN: returns "invalid"
- against PATH without gh: returns "not_installed"
- (Live self-heal flow tested manually previously when M5's token
  invalidated; this PR formalizes that path so users don't need to
  remember the command.)

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

---------

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

* fix(install,connect): surface 'airc daemon install' earlier (#382) (#388)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text (#390)

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text

PR #388 landed with 4 Copilot review concerns. This PR addresses all 4 +
extracts the cross-platform "is the daemon installed?" detect into a
shared helper so install.sh + cmd_connect.sh + cmd_daemon.sh all use ONE
implementation. Per Joel "if you code modularly like we require": three
near-identical case statements collapse to one detector.

NEW: lib/airc_bash/lib_daemon_detect.sh
  airc_daemon_is_installed() — covers darwin (LaunchAgents plist),
  linux+wsl (systemd user unit), windows (HKCU\...\Run\airc-monitor).
  Sourced from top-level airc + install.sh.

CHANGED:
  - install.sh: drops local _daemon_already_installed (Darwin/Linux only),
    sources lib_daemon_detect.sh from $CLONE_DIR, calls the shared
    helper. Fixes Copilot concern #2 (Windows/WSL gap).
  - install.sh: AIRC_INSTALL_YES=1 check now runs BEFORE the !-t 0
    non-TTY check, so `curl … | AIRC_INSTALL_YES=1 bash` actually
    installs the daemon instead of falling into the non-TTY tip
    branch. Fixes Copilot concern #3 (ordering bug).
  - install.sh: prompt text drops the bogus `--no-daemon-prompt` flag
    reference (the flag was never implemented anywhere); keeps only
    the AIRC_INSTALL_NO_DAEMON=1 env-var hint that DOES work. Fixes
    Copilot concern #1 (lying-to-user copy).
  - install.sh: launchd/systemd → "launchd / systemd / HKCU-Run" in
    the prompt body so Windows users see their platform mentioned.
  - cmd_connect.sh: first-host daemon-tip block (line ~1707) replaces
    its Darwin-only/Linux-only case statement with a single call to
    airc_daemon_is_installed. Fires correctly on Windows now where
    the previous code never fired (HKCU Run-key wasn't checked).
    Fixes Copilot concern #4.
  - cmd_daemon.sh::_daemon_installed becomes a thin wrapper around
    the shared detector. Preserves the local-private-helper API
    used by callers in this file; cross-platform logic now lives in
    one place. Detection guaranteed consistent across all sites.

Branch ordering rationale (install.sh, top→bottom):
  1. AIRC_INSTALL_NO_DAEMON=1   — explicit opt-out trumps everything
  2. AIRC_INSTALL_YES=1         — explicit auto-install (now BEFORE non-TTY)
  3. airc_daemon_is_installed   — idempotent re-run no-op
  4. !-t 0 || !-t 1             — non-TTY tip
  5. interactive [Y/n]          — default

TEST:
  - bash -n on all 5 touched files: clean
  - airc_daemon_is_installed against real Mac (daemon installed): returns 0 ✓
  - against mocked-windows (reg query mocked to succeed): returns 0 ✓
  - cmd_daemon.sh::_daemon_installed wrapper: still returns same value
    as direct airc_daemon_is_installed call (delegation works)
  - install.sh ordering: verified YES check (line 909) precedes !-t 0
    check (line 920+) by inspection

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

* docs: address Copilot nits on PR #390 — comment-only fixes

Three pure comment fixes from Copilot review:
1. lib_daemon_detect.sh: 'users-experience bugs' → 'user experience bugs'
   (grammar)
2. install.sh: 'Three NON-prompt branches' → 'Four NON-prompt branches'
   (the list below the comment has 4 branches: NO_DAEMON, YES,
   already-installed, non-TTY)
3. lib_daemon_detect.sh: HKCU\...\Run\airc-monitor reads as a subkey
   path; airc-monitor is actually the VALUE NAME under the Run key.
   Reworded to clarify.

No code changes.

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

---------

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

* fix: distinguish env_token_invalid (GH_TOKEN poisoned) from keyring-invalid (#391)

Discovered live on canary 73ab85e while testing PR #389's self-heal flow:
when GH_TOKEN env var is set + invalid, gh REFUSES to run `gh auth login`
("The value of the GH_TOKEN environment variable is being used for
authentication. To have GitHub CLI store credentials instead, first clear
the value from the environment").

Pre-fix the wrapper would still trigger self-heal in this case, gh would
bounce immediately, and the user got the misleading "auth flow did not
complete (cancelled? no network?)" fallback message. No path forward
visible to them.

Fix: detect this case as a NEW state, `env_token_invalid`, distinct from
keyring-`invalid`. The wrapper handles it with a precise message:

  ✗ GH_TOKEN environment variable is set + invalid.
    airc can't auto-heal this — gh refuses to run 'gh auth login' while
    GH_TOKEN is set. Self-heal would just bounce.

    Two paths to fix:
    1. Stale dotfile / leftover export → just unset it:
         unset GH_TOKEN
       Then re-run your airc command. airc will detect the keyring
       auth + self-heal it via the browser flow.
    2. Real CI token (Actions, Codespace, dotfile sourcing a managed
       token) → fix the source. Don't run gh auth login; refresh
       whichever system writes GH_TOKEN.

    What gh sees right now:
      [verbatim gh auth status output]

Detection logic:
  if gh auth status passes:           → ok           (unchanged)
  elif gh api rate_limit passes:      → rate_limited (unchanged)
  elif [ -n "${GH_TOKEN:-}" ]:        → env_token_invalid  (NEW)
  else:                               → invalid      (unchanged)

GH_TOKEN takes precedence over keyring in gh's auth resolution. If we
got past gh auth status + gh api rate_limit both failing AND GH_TOKEN
is set, then GH_TOKEN is what gh's using and it's dead. Self-heal can't
fix that — only user-side action can.

Tested:
  - real ok keyring (no GH_TOKEN):           detect → "ok"             ✓
  - bogus GH_TOKEN, real keyring fine:        detect → "env_token_invalid" ✓
  - mocked auth+rate fails, no GH_TOKEN:      detect → "invalid"        ✓
  - wrapper with env_token_invalid: emits two-path message + returns 1 ✓

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

* fix: detect_scope walks up to enclosing .airc/ ancestor (no more .airc/.airc) (#392)

When a user `cd`'d into the scope dir for forensic inspection (or any
descendant), `detect_scope()` returned `$pwd/.airc` — producing wrong
nested paths like `/repo/.airc/.airc`. Every subsequent airc command
then died with "Not initialized" against a directory that didn't exist.
Discovered live on M5 2026-05-01 while diagnosing a different airc
issue: the very act of `cd .airc; airc status` to inspect state broke
airc.

Fix: walk up from cwd looking for an ancestor whose basename is .airc.
If found, that's the scope. If not found, fall through to the
documented `$pwd/.airc` per-cwd default (unchanged behaviour for the
common fresh-cwd case).

Test cases:

  cwd                              | pre-fix              | post-fix
  ---------------------------------|----------------------|------------
  /repo (no .airc anywhere)        | /repo/.airc          | /repo/.airc (same)
  /repo (has child .airc)          | /repo/.airc          | /repo/.airc (same)
  /repo/.airc        (BUG TRIGGER) | /repo/.airc/.airc    | /repo/.airc ✓ FIXED
  /repo/.airc/identity             | /repo/.airc/identity/.airc | /repo/.airc ✓ FIXED
  AIRC_HOME=/x set                 | /x                   | /x (override unchanged)

Carve-out narrowly addresses the bug. Doesn't change behaviour for
"cwd is parallel to a sibling .airc/" (e.g. cwd=/repo/src with /repo/.airc
existing — that still creates /repo/src/.airc the way it always has).
A broader "find enclosing scope from any subdir" change would shift the
documented per-cwd identity contract; deserves its own design discussion.

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

* hotfix(host_address_set): restore Tailscale entry when daemon signed in (#394)

* canary → main: bearer rewrite + post-3c substrate (#306)

* 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-loss class — host broadcasts
returned 'delivered' but the gist was never written; joiners polling
the gist saw nothing; user surface lied success.

## Bug 1: cmd_send.sh host-path was local-append-only
The else-branch (host case, line ~363 pre-fix) ended with:

    echo "\$full_msg" >> "\$MESSAGES"

with a comment "Joiners' SSH tails will pick it up" — relic of pre-3c
when SSH bearer's tail -F over SSH was the wire. Phase 3c (#281) deleted
SSH wholesale; joiners now poll the gist via GhBearer; a local-only
append disappears.

Fix: after the local audit append, ALSO call bearer_cli send with the
host's --room-gist-id so GhBearer publishes to the gist. Same wrap-if-
recipient-known logic as the joiner branch, so DMs to peers with
stored x25519_pub get encrypted and broadcasts go plaintext.

## Bug 2: GhBearer._gh_gist_write_file silent no-op on first send
\`gh gist edit GIST_ID file\` (no flag) returns exit 0 BUT silently does
nothing when the target filename doesn't exist in the gist. The
fallback chain ('try plain edit; on non-zero, retry with -a') never
fires because the first call returns 0 without writing. Production
gists start with only an airc-invite seed (no messages.jsonl), so
EVERY first host send hit this trap.

Fix: read the gist's file list FIRST, choose the correct subcommand:
  - file already in gist  → \`gh gist edit GIST file\`        (replace)
  - file NOT in gist      → \`gh gist edit GIST -a file\`     (add)

One extra GET, but eliminates the silent-no-op trap. Defense-in-depth:
if the existence check disagrees with reality (concurrent peer added
the file between our GET and our edit), retry the OTHER subcommand
once before giving up.

## Why the existing 123 integration tests didn't catch this
- All scenarios that exercise multi-peer messaging used \`--no-room
  --no-gist\` for speed. That flag bypasses gh entirely; the test rig
  rode on the SSH-bearer TCP-handshake path. After Phase 3c moved
  production to GhBearer, the test rig kept exercising a stripped-down
  path that doesn't match production architecture.
- scenario_bearer_gh DOES use a real gh gist BUT pre-seeds it with
  messages.jsonl (the 'happy path' shape). Production gists start with
  airc-invite seed (NOT messages.jsonl), so the first send is a CREATE
  not a REPLACE — exactly the bug. The seed shape masked it.

Two new TDD scenarios cover both paths post-fix:

- \`gh_send_creates_messages_jsonl\` (unit-of-bearer): seeds gist with
  airc-invite (matching production), runs bearer_cli send directly,
  asserts gist now contains messages.jsonl with the marker. Pre-fix:
  bearer reports 'delivered', gist unchanged. Post-fix: green.
- \`host_msg_publishes_to_gist\` (end-to-end cmd_send→bearer): spawns a
  real host with --room (no --no-gist), runs \`airc msg <marker>\`,
  asserts gist's messages.jsonl contains the marker. Pre-fix: cmd_send
  never invoked bearer_cli on host path. Post-fix: green.

Verified locally:
- gh_send_creates_messages_jsonl: 5/5 (was 3/2 before fix)
- host_msg_publishes_to_gist: 2/2 (was 1/1 before fix)

Closes #285. #283 (sidecar) and #284 (cross-room DM) are tracked
separately and will get their own TDD + fix.

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

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

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]>

* docs(skills): update /join skill for post-3c architecture (#289)

The /join skill is what every AI peer reads at startup — its content
shapes how peers behave + troubleshoot. Tonight's QA pass surfaced
that the skill still referenced Tailscale, SSH transport, and the
sidecar-process model — all gone in Phase 3c (#281).

Updates:
- Transport section: gist IS the wire; LocalBearer for same-machine,
  GhBearer for cross-network; envelope-encrypted at the X25519+
  ChaCha20-Poly1305 layer. GitHub stores ciphertext only.
- Boot outcomes: removed Tailscale-up nudges + multi-address pick
  references; added the new #general gist resolution surface.
- Multi-room: ONE monitor per scope polls all subscribed channels'
  gists in parallel. No separate sidecar process.
- Troubleshooting: replaced SSH/Tailscale failure modes with the
  actual post-3c surfaces — gh auth, gist content verification,
  cross-room routing via --room flag.

Skills/doctor and skills/invite still have similar stale refs;
follow-up PR.

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

* fix(#290): channel_gist prefers single-channel gists (substrate convergence) (#291)

* docs(skills): update /join skill for post-3c architecture

The /join skill is what every AI peer reads at startup — its content
shapes how peers behave + troubleshoot. Tonight's QA pass surfaced
that the skill still referenced Tailscale, SSH transport, and the
sidecar-process model — all gone in Phase 3c (#281).

Updates:
- Transport section: gist IS the wire; LocalBearer for same-machine,
  GhBearer for cross-network; envelope-encrypted at the X25519+
  ChaCha20-Poly1305 layer. GitHub stores ciphertext only.
- Boot outcomes: removed Tailscale-up nudges + multi-address pick
  references; added the new #…
joelteply added a commit that referenced this pull request Jun 27, 2026
* fix(codex): poll inbox after sending airc messages (#556)

* feat(knock): public collaboration knock entrypoint (airc#559 PR-1) (#560)

feat(knock): add public collaboration knock entrypoint (airc#559 PR-1)

Smallest cohesive first slice of airc#559 — the public-facing collaboration
front door. Future PRs add the approval flow, private-room handoff/rotation,
and shared sprint/kanban queue primitives.

Why this shape:

  - Uses `gh issue create` on the target repo with title prefix
    "airc-knock: <message>" and a structured envelope body. Repo owners
    get GitHub-native moderation (labels, close, spam, block) out of the
    box; no new abuse surface to defend.
  - Envelope body contains a JSON identity block (name/pronouns/role/bio/
    gh_login) inside a fenced ```json``` block plus human-readable
    markdown. Future tooling (`airc approve <peer>`, sprint queue) parses
    the JSON; humans read the markdown.
  - Auto-applies the `airc-knock` label when it exists; falls back to no
    label with an operator hint when the repo hasn't created it yet.
  - No `ensure_init`: knock is intentionally usable BEFORE the knocker
    has a paired airc scope. The whole point is "outsider asks to join."
    `resolve_name` falls back to derive_name → hostname when no scope
    exists, so identity is still well-defined.
  - `--dry-run` prints the envelope that WOULD be posted without calling
    gh. Lets operators preview before posting + lets tests verify the
    envelope shape without a real GitHub repo.
  - Title slice capped at 180 chars (well below GitHub's 256-char limit)
    with `...` ellipsis on overflow so long messages still produce
    moderation-readable titles.

What this PR does NOT do (deferred to airc#559 PR-2/PR-3):

  - Approval flow (`airc approve <peer>` → sends private-room invite via DM)
  - Private-room rotation when a peer becomes abusive
  - Shared sprint/kanban queue primitives
  - Repo-local `.airc/` discovery manifest (continuum#1109 pilots that)

Validation:

  - python3 test/test_knock.py — 7/7 PASS (dispatch, validation, dry-run,
    JSON envelope shape, title slicing)
  - python3 test/test_inbox.py — 4/4 still PASS (no regression)
  - python3 test/test_codex_hook.py — 7/7 still PASS (no regression)
  - bash -n airc lib/airc_bash/cmd_knock.sh — clean

Closes part 1 of airc#559.

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

* feat(approve): forward-secret room-invite handoff (airc#559 PR-2) (#561)

* feat(approve): forward-secret room-invite handoff to knockers (airc#559 PR-2)

Closes part 2 of airc#559. Builds on PR-1 (#560) to complete the knock
→ approve → join handoff with forward-secret per-message ECDH so the
invite ciphertext on a durable public GitHub comment cannot be retro-
actively recovered even if either party's long-term key leaks later.

What lands

  - `airc knock` now generates a per-knock ephemeral X25519 keypair and
    embeds the pubkey in a new "Approval crypto" envelope block in the
    issue body. Private half prints to stdout for the operator to save
    (state management deferred to PR-2c).
  - `airc approve <issue-url>` reads the knocker_pub from the issue,
    generates a per-approval ephemeral, runs X25519 ECDH + HKDF-SHA256
    (info=`airc-knock-approve-v1`), AEAD-encrypts the invite string
    with ChaCha20-Poly1305, posts the {approver_pub, nonce, ciphertext}
    envelope as a comment on the issue. Default invite = current
    scope's invite; --invite overrides.
  - `airc decrypt-approval <issue-url> --knocker-priv <hex>` fetches
    the approval comment, derives the shared key, decrypts. Prints the
    join string to stdout.
  - `airc_core.knock_crypto` python module wraps the airc crypto stack
    (gen-knock-keys / encrypt-for-knocker / decrypt-from-approver) so
    the bash shell layer stays thin.
  - Both ephemerals are per-message — Joel's WebAuthn/MPC background
    expectation. Long-term key compromise YEARS later cannot recover
    any prior approval. The ephemerals are NEVER written to disk past
    one-shot use.

Why forward secrecy specifically

  GitHub comments are durable; even after issue close, the ciphertext
  stays in the history. Sibling claude tab #1 (continuum#1109 author)
  flagged this on AIRC: raw "encrypt to ephemeral pubkey" without
  forward secrecy means a leaked long-term static key retroactively
  decrypts every prior approval. Per-knock + per-approval ephemerals
  fix it. PR-3 will add room-rotation hooks so even fresh decryption
  of an old invite can't reopen access.

Identity binding via airc whois, not gh login

  Per Joel's design note: one gh account maps to many agents; trust
  must key on AIRC peer/session/whois identity. The knocker_pub IS the
  AIRC identity binding — each agent generates its own ephemeral, so a
  single gh login can knock from N agents without conflating identity.

Out of scope (future PRs under airc#559)

  - Knocker-side state management: $AIRC_WRITE_DIR/knock-state/ to
    save priv keys automatically instead of operator-copy-paste. PR-2c.
  - Room-rotation hooks so leaked-old-comment ciphertext can't reopen
    access. PR-3.
  - Sprint/kanban queue primitives (sibling tab #1's 7-item design
    spec logged for that PR). PR-4.

Validation

  - python3 test/test_approve.py — 10/10 PASS (dispatch + validation +
    crypto roundtrip + tamper-resistance + wrong-knocker-priv-fails +
    knock envelope embeds pubkey)
  - python3 test/test_knock.py — 7/7 still PASS (no regression on PR-1)
  - python3 test/test_inbox.py — 4/4 still PASS (no regression)
  - python3 test/test_codex_hook.py — 7/7 still PASS (no regression)
  - bash -n airc lib/airc_bash/cmd_knock.sh lib/airc_bash/cmd_approve.sh
    — clean

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

* fix(approve): parse gh payloads through heredocs

---------

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

* feat(queue): add issue-backed queue add/list

Adds AIRC queue add/list primitives for issue-backed work coordination. Includes review fixes for queue list parsing, now_utc time anchoring, and hermetic gh testing.

* feat(queue): claim/release/set-status verbs (airc#562 PR-2) (#568)

* feat(queue): claim/release/set-status verbs (airc#562 PR-2)

Builds on PR-1 (airc#566) to add the in-place mutation verbs that turn
queue cards into a real coordination substrate. Future PRs add nudge
broadcasts (PR-3) and heartbeat + stall detection (PR-4).

Verbs added

  airc queue claim <issue-url> [--owner X] [--status Y]
      Set owner field + status (default in-progress) on an existing
      card. Default owner = current scope's resolve_name (sub-tab
      disambiguation is the operator's job; airc handle alone can't
      tell which agent is claiming when one gh user runs many).
      Status enum enforced with the canonical 5 named on typo.

  airc queue release <issue-url> [--reason "..."] [--status claimed|blocked]
      Clear owner field, revert status to claimed (default) or blocked.
      For non-release status changes (in-progress / review / merged),
      operator must use set-status — the error names this so they don't
      guess. --reason logged with the release.

  airc queue set-status <issue-url> <state>
      Pure status-field change. Does NOT close the issue when state =
      merged — operators close manually so the queue tracks closure as
      an explicit event (vs implicit-when-status-changes).

How it works

  All three verbs share _airc_queue_mutate_card which:
    1. Resolves <issue-url> to (repo, issue_num); accepts both full
       https://github.com/.../issues/N and short-form owner/repo#N.
    2. Fetches body via `gh issue view ... --json body --jq .body`.
    3. Hands body + mutations to a python helper that parses the
       kind=airc-queue-card-v1 envelope, applies --set/--clear, and
       appends a "## Status log" entry (newest-first; section auto-
       created if missing).
    4. Writes back via `gh issue edit ... --body <new-body>`.

  Body + mutations passed via temp files to the python heredoc to avoid
  the stdin contention bug Codex caught in PR-1's list path (and PR-2
  approve flow's parser).

  All verbs support --dry-run that prints the new body without calling
  gh — what every test exercises.

Validation

  - python3 test/test_queue_claim.py — 16/16 PASS
    (dispatch + validation + body shape + status log + claim/release/
     set-status semantics + body-without-status-log creates-section)
  - python3 test/test_queue.py — 16/16 still PASS (no PR-1 regression)
  - python3 test/test_knock.py — 7/7 still PASS
  - python3 test/test_approve.py — 12/12 still PASS
  - python3 test/test_inbox.py — 4/4 still PASS
  - python3 test/test_codex_hook.py — 7/7 still PASS
  - bash -n airc lib/airc_bash/cmd_queue.sh — clean

Pairs with: airc#566 (queue PR-1) + continuum#1110 (.airc QUEUE.md
spec) + sibling claude tab #1's continuum#1119 forge-alloy proof
contracts (settlement-event metadata stays compat with this card shape).

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

* fix(queue): support mac bash in issue ref parser

---------

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

* feat(queue): nudge verb — surface card to peers (airc#562 PR-3) (#573)

* feat(queue): nudge verb — surface card to peers (airc#562 PR-3)

Adds `airc queue nudge <issue-url> [--peer @handle] [--message "..."]`
to the queue verb set. Continues claude tab #2's airc#562 series after
PR-1 (#566 add/list, merged) and PR-2 (#568 claim/release/set-status,
merged).

Claude tab #2 explicitly yielded this PR-3 to me on AIRC after
shipping the prior two slices in the same session.

WHAT IT DOES
- Verifies the issue is a real airc-queue-card-v1 envelope (rejects
  random non-card issues before any send — prevents spam vector)
- Composes a one-line "nudge: <repo>#<N> [→ @peer] — <title>
  (status=...) — claim with: airc queue claim <repo>#<N>" broadcast
- Sends via cmd_send (broadcast OR DM if --peer set)
- Annotates the card body status log with "<actor> nudged @peer" or
  "<actor> nudged (broadcast)" via the same _airc_queue_mutate_card
  path used by claim/release/set-status — no new wire format
- NOTHING ELSE: no status change, no ownership change, no
  heartbeat/stall logic. Nudge is the action; recipients filter +
  decide whether to claim.

WHY OUT OF SCOPE
- Idle detection: WHO-is-idle is a separate concern; nudge is fire-
  and-forget. Heartbeat/stall-driven auto-pickup stays as PR-4
  (claude tab #1's 7-req design from earlier today + the 30min
  cadence in continuum/.airc/ASSEMBLY-LINE.md).
- Routing intelligence: nudge is dumb broadcast/DM. Cognition-aware
  routing (airc#572) layers on top later as advisory, not central.

DESIGN NOTES
- --peer accepts handle with or without leading '@'; both normalized
  to bare handle. Empty after strip ('@' alone) fails fast.
- Per Joel's protocol-not-client + handle-not-gh-login conventions:
  --peer addresses AIRC whois identity (claude-tab-1, codex,
  continuum-8e97), NOT a github account.
- Status-log entry shape mirrors PR-2 idiom: "<timestamp> — <actor>
  <verb> <target>: <optional message>".
- Empty mutations (just log_msg, no --set/--clear) is a supported
  use of _airc_queue_mutate_card — empty mutations_raw loop is a
  no-op, log entry still appends.
- Top-level help updated: nudge listed in USAGE + VERB SCOPE
  section now shows PR-1/PR-2 merged, PR-3 (this PR), PR-4
  (heartbeat/stall) deferred.

VALIDATION
- New test/test_queue_nudge.py: 14/14 PASS
  - Dispatch: nudge --help + top-level help lists nudge
  - Validation: missing URL / malformed URL / non-card body rejected
    BEFORE send / empty --peer after @ strip rejected
  - Dry-run: broadcast text contains card title + status + claim
    hint + owner; --peer renders DM-style with → arrow + targeted
    log entry; no --peer renders broadcast log entry; --message
    appends; @ prefix optional on --peer; bash 3 macOS regression
    on issue-url parser
  - Crucially: nudge does NOT mutate card status (no "set:status="
    tokens in dry-run output)
- test_queue.py: 16/16 PASS (no regression on PR-1)
- test_queue_claim.py: 17/17 PASS (no regression on PR-2)
- bash -n airc + lib/airc_bash/cmd_queue.sh: clean

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

* docs(queue): expose nudge in global help

---------

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

* fix(#571): route every gh body write through --body-file (lib_gh.sh) (#574)

GitHub issue/PR/comment bodies are Markdown — they routinely contain
backticks, fenced code blocks, $-vars, and single quotes. Two failure
modes have bitten Codex on canary:

1. Heredoc-construction at variable-build time. If a body is built via
   $(cat <<EOF ... EOF) where the EOF terminator isn't single-quoted,
   embedded backticks/$(...) execute as command substitution AT BUILD
   TIME, mangling the body before it ever reaches gh.

2. argv-length limit on `--body "$x"`. ARG_MAX is ~256KB on macOS/Linux;
   a queue card with a long status log + cross-references can approach
   that. argv overflow is silent — gh runs but with truncated body.

Fix is API-shaped: every gh invocation that takes a body goes through
`_airc_gh_safe_body`, which writes to a temp file and passes via
--body-file. Eliminates both classes in one place — callers can't
accidentally use --body and miss the protection because the helper
hides the flag entirely.

Changes
- lib/airc_bash/lib_gh.sh (new): _airc_gh_safe_body helper. Documented
  why temp-file beats stdin (callers compose with $(...) — pipe-stdin
  + capture-stdout is exactly the contention pattern Codex caught in
  cmd_approve.sh / cmd_queue.sh review). Bash 3.2 compatible (mktemp
  fallback for BusyBox). 2>&1-equivalent contract preserved so callers
  keep `if out=$(_airc_gh_safe_body ...)` patterns unchanged.
- airc: source lib_gh.sh unconditionally near lib_auth.sh / lib_daemon.
- lib/airc_bash/cmd_knock.sh: 2 sites (label + fallback) → helper.
- lib/airc_bash/cmd_approve.sh: 1 site (issue comment with AEAD
  envelope) → helper.
- lib/airc_bash/cmd_queue.sh: 3 sites (issue create label + fallback +
  issue edit on every mutate) → helper.
- test/test_gh_safe_body.py (new): 10 tests covering helper roundtrip
  (plain / backticks-inert / fenced ```bash``` block with $vars + $()
  + backticks / no-trailing-newline-added), --body-file flag discipline
  (argv asserted), gh-failure propagation, missing-arg rejection (rc=2),
  and a greppable invariant: each cmd module must call
  _airc_gh_safe_body and must NOT use raw `--body` (catches future
  regressions).

Tests
- 10/10 new test_gh_safe_body.
- 7/7 test_knock + 12/12 test_approve + 16/16 test_queue + 17/17
  test_queue_claim still green (no behavior change for callers).
- Full python suite (21 modules) clean.
- Live dry-run: `airc queue claim CambrianTech/airc#571 --dry-run`
  produces the expected card body, going through the new helper path.

Companion guidance for future authors lives in lib_gh.sh's doc-comment.

* feat(queue): repo-scoped nudge status sweep (#578)

feat(queue): add repo-scoped nudge status sweep

* fix(gh): safely close issues with markdown comments (#582)

* feat(queue): adopt existing issues into queue cards (#583)

* feat(lane): add worktree lanes for agents (#585)

* feat(queue): summarize repo nudge pongs (#586)

* feat(#576): auto-close queue cards when PRs merge into canary (#581)

GitHub's native "Closes #N" only triggers an issue auto-close when the
PR merges into the DEFAULT branch (main). Our protected workflow
(enforce-canary-staging.yml) requires PRs land in canary FIRST, then
canary→main is promoted as a single integration commit later. That
gap leaves queue cards open for days — they look idle, get nudged,
accumulate noise. Codex called this out as the litter pattern: airc#571,
airc#567, continuum#1125 all sat open after their PR merged into canary
and required manual `gh issue close` cleanup.

Changes
-------

- lib/airc_bash/cmd_queue.sh: new `_cmd_queue_close_merged` verb +
  `_airc_queue_close_merged_help`. Scans a merged PR's body for
  queue-card refs (same-repo: `#N`, `Closes #N`; cross-repo: `owner/repo#N`),
  verifies each is an `airc-queue-card-v1` envelope, sets status=merged
  with a status-log line citing PR URL + merge SHA + actor, then closes
  the issue. Idempotent (skips already-merged); silent on non-card refs;
  cross-repo refs detected + reported but NOT closed (workflow token is
  repo-scoped). Uses `_airc_gh_safe_body` from airc#571 for the mutate
  path, so backticks in body refs don't trip shell substitution.

- .github/workflows/auto-close-queue-cards.yml: triggers on
  `pull_request.closed` filtered on `merged=true` + `base=canary`,
  runs `./airc queue close-merged` from the checkout. Uses workflow
  GITHUB_TOKEN with issues:write granted via the permissions block.
  Concurrency-grouped so multiple simultaneous PR merges serialize
  status-log writes defensively.

- test/test_queue_close_merged.py: 19 tests covering dispatch + help,
  validation (missing/malformed PR url, unknown flags), unmerged-PR
  guard, missing-merge-sha guard, ref parsing (Closes-keyword + bare
  `#N` + cross-repo + dedup + no-false-positive), envelope verification
  (skips non-cards silently), idempotency (skips already-merged),
  cross-repo detection-without-close, dry-run behavior, actor flag
  propagation to status-log. End-to-end test with a fake-gh stub
  asserts the body sent to `gh issue edit` shows `status: merged` +
  status-log entry with PR URL + SHA prefix + actor, AND that
  `gh issue close` was called. Plus the greppable invariant: no raw
  `--body` flag in cmd_queue.sh (the airc#571 enforcement extends here).

Tests + verification
--------------------

- 19/19 new test_queue_close_merged.
- 7/7 test_knock + 12/12 test_approve + 16/16 test_queue + 17/17
  test_queue_claim + 14/14 test_queue_nudge + 10/10 test_gh_safe_body
  still green (no behavior change for callers).
- bash -n clean on cmd_queue.sh + airc dispatcher.
- Live dry-run against the just-merged airc#574 (this PR's grandparent):
  3 refs scanned (airc#571 already-merged + airc#561 + airc#566),
  airc#571 idempotent-skip, airc#561+#566 silent-skip (PR refs, no
  envelope), 0 errored. Exact behavior we want.

Out of scope (follow-ups)
-------------------------

- Cross-repo close (airc PR closing continuum#NNN) needs an org-scoped
  token; deferred to a separate card.
- Adding a closing-comment on the issue (in addition to the status-log
  entry) for human visibility — status log is sufficient for v1.
- Adopting the workflow into the continuum repo — same file template,
  separate PR there.

* fix(#576): detect queue refs in PR titles (#587)

fix queue close-merged title refs

* feat(#572): queue heartbeat and stale scan (#588)

feat queue heartbeat and stale scan

* feat(#570): embeddable queue and room widgets (#589)

feat add embeddable queue widgets

* feat(#591): summarize queue availability (#592)

* fix(#593): ignore repo-nudge templates in pongs (#594)

* fix(#596): honor per-agent queue owner (#597)

* fix: add session work identity for queue ownership (#598)

Add session work identity for queue ownership

* fix(queue): close already-merged queue cards (#599)

fix(queue): close already-merged cards

* fix(queue): require closing keywords for close-merged

Closes #600

* fix(queue): preserve issue titles

Closes #602

* feat(queue): recommend next work for idle agents

Adds airc queue next/pick for actionable idle-agent work selection.

* feat(queue): allow cross-repo close-merged

PR-1 for continuum#1174. Adds opt-in --allow-cross-repo for close-merged.

* feat(queue): add metronome idle pulse

Closes #606

* fix(queue): prevent accidental claim takeovers

Closes #611

* docs(readme): document AI work queue workflow (#614)

* feat(queue): warn on stale PR branches (#617)

* refactor(queue): split command helpers (#618)

* fix(queue): default planning view and unclaimed-owner semantics (#620)

* fix(queue): treat --owner unclaimed as no-owner sentinel (#613)

`airc queue adopt --owner unclaimed` was writing the literal string
"unclaimed" into the card envelope's owner field. That defeats airc#612
collision protection on the subsequent `airc queue claim`: the claim
command sees owner=unclaimed as an *active* owner and refuses to
overwrite it without --force.

The intent of `--owner unclaimed` (which surfaced during bulk adoption
of legacy backlog) is "this card is available — someone will claim it
later." That maps to absence-of-owner, not a literal "unclaimed" handle.

This change normalizes the sentinel during adopt arg parsing, and
simultaneously makes the default-owner fallback explicit: it only fires
when --owner wasn't passed at all. So --owner "" and --owner unclaimed
both produce a card with NO owner field, while plain `airc queue adopt`
still auto-fills with the running agent's resolve_name.

Tests:
  - test_adopt_with_owner_unclaimed_omits_owner_field
  - test_adopt_with_empty_owner_omits_owner_field
  - test_adopt_default_owner_falls_back_to_resolve_name (regression guard)

Surfaced by claude-tab-2 hitting the friction during bulk adoption of
their own placeholder claims.

* fix(queue): add default plan view and normalize unclaimed owners

* Fix collaboration health for same-nick peers (#625)

fix collaboration health for same-nick peers

* fix(lane): hydrate submodules after worktree add (continuum#1252) (#624)

`airc lane create` runs `git worktree add` to make the lane, but git
worktree add does NOT init submodules in the new working tree. For repos
that have submodule deps (continuum has `vendor/llama.cpp` ~500MB CMake
project), this leaves every submodule directory empty. The first Rust
commit attempt in the lane then fails:

    CMake Error: The source directory "<lane>/src/workers/vendor/llama.cpp"
                 does not appear to contain CMakeLists.txt.
    ❌ Rust compilation FAILED
    ❌ PRE-PUSH FAILED

Surfaced when claude-tab-1 hit it on first work in a freshly-created
lane (continuum#1252). Workaround was `git submodule update --init`
manually — fine once you know it, friction every time you forget.

Fix: run `git submodule update --init --recursive` in the new lane dir
right after worktree add succeeds. Repos with no submodules: no-op,
exits 0. Repos with broken submodules: fails LOUD (no `2>/dev/null`,
no `|| true`) so the user sees the real error instead of hitting it
later via a confusing CMake/Rust failure.

Test:
- `test_lane_create_hydrates_submodules_in_new_worktree` — outer repo
  with a sentinel-file inner submodule; asserts the sentinel exists in
  the lane's submodule path after `airc lane create`. Pre-fix this
  would fail; post-fix it passes.

Full lane suite: 5 passed (4 existing + 1 new), 0 failed.

Closes continuum#1252.

* feat(queue): personalized dispatch verb (closes continuum#1192 broadcast→idle gap) (#623)

feat(queue): personalized dispatch verb to close metronome→idle-agent gap

Closes continuum#1192.

## Problem

`airc queue metronome` already broadcasts a "queue is open" pulse to
the room every N minutes. But a broadcast ≠ "for me" — agents see the
pulse and stay idle because nothing names them. Joel called this out
2026-05-14 16:55Z: "whole point of kanban/airc is you can get another
issue ... needs to hand it out automatically on interval or something."

## Fix

New verb `airc queue dispatch <agent> [<owner/repo>]` that:

1. Runs the same ranker `queue next --owner <agent>` exposes (so the
   choice respects per-agent affinity, claimed cards, etc.)
2. Picks the TOP candidate (`--limit 1 --json`)
3. Formats a one-line DM containing the card title, URL, AND the exact
   `airc queue claim` + `airc lane create` commands ready to copy
4. Sends via `cmd_send "@<agent>"` so the recipient sees a directly-
   addressed hand-out, not a broadcast pulse

`--dry-run` previews without sending. `--message TEXT` appends extra
context (e.g. "you've been idle 5min, pickup?").

## Why a tempfile not a stdin pipe

The python parser needs:
- argv: target_agent, extra_message, json_path
- script source via heredoc

A `printf '%s' "$next_json" | python3 - <<'PYEOF' ... PYEOF` would
fight over fd 0 (heredoc and pipe both redirect stdin). Tempfile +
argv path is the cleanest way to pass the JSON without losing the
heredoc-script.

## Smoke test

```
$ airc queue dispatch claude-tab-2 CambrianTech/continuum --dry-run
[dry-run] would DM @claude-tab-2:
📋 hand-out for @claude-tab-2: #1253 — Replace Continuum chat/Postgres dependency with AIRC Rust SQLite substrate
   https://github.com/CambrianTech/continuum/issues/1253
   claim: airc queue claim 'CambrianTech/continuum#1253' --owner 'claude-tab-2'
   lane:  airc lane create 'CambrianTech/continuum#1253' --base 'canary'
```

## Future flywheel

This is the per-call hand-out primitive. The metronome can grow a
`--dispatch-mode` flag to walk the staleness/availability list every
tick and auto-fan-out to idle agents. That keeps the substrate side
to "pull list of idle peers + dispatch each" instead of every agent
needing to remember to run their own `queue next`.

Refs continuum#1192 (auto-handout idle-agent dispatch).

* fix(queue): dispatch metronome hand-outs (#627)

* feat: add hygiene policy command (#632)

add airc hygiene policy command

* fix: fail closed on update conflicts (#633)

fix update conflict recovery

* docs: design rust sqlite substrate (#634)

design rust sqlite substrate

* docs: design realtime event bus (#635)

design realtime event bus

* feat(queue): add steward dry-run digest (#636)

add queue steward dry run

* feat(core): add Rust transcript primitives (#637)

add rust transcript core

* feat(logs): add json transcript pages (#638)

* fix(logs): avoid strict-mode crash without json flag (#639)

* refactor(logs): use one render path for human and json modes (#640)

* feat(queue): metronome fan-out across active roster (airc#607, continuum#1192) (#641)

feat(queue): metronome fan-out across active roster (#607, continuum#1192)

Closes the gap where a single-owner queue metronome could only ever DM
one agent, leaving the rest of the channel idle even though their next
claimable card was sitting right there. Operators opt in with --all;
the monitor consumer then enumerates recent senders in this scope's
messages.jsonl and dispatches per agent with per-recipient dedup so a
tight pulse can't double-DM the same agent.

Why bash and not Rust: this is the bridge while airc#628 (Rust queue-
dispatch substrate) lands. The embedded python roster extractor and
the bash dispatcher are intentionally minimal so the Rust port can
delete them wholesale rather than re-implement a TS-shaped API.

Changes
- airc: reminder_timer_loop reads owner=*roster* sentinel, builds the
  recipient list from messages.jsonl (filters self + 'airc' system
  sender + outside-window), dispatches per agent via cmd_queue.
  Per-recipient last-pinged stamp under queue_metronome_recent/ so
  the dedup window matches the configured interval.
- lib/airc_bash/cmd_queue.sh: --all / --roster flag, --roster-window
  flag (default 86400s, minimum 60s), mutex against --owner so the
  config file can't land in a contradictory state the monitor would
  silently resolve one way. off path now also clears recent dedup.
- lib/airc_bash/cmd_queue_help.sh: usage + options for the new flags.
- test/test_queue_metronome_fanout.py: 3 CLI tests against the real
  binary + 9 unit tests of the roster extraction logic (recent-only,
  filter self/airc, window enforcement, ISO + epoch + epoch-ms ts,
  dedup by latest, empty/missing/malformed log).

Validation
- 12/12 new tests pass.
- 102/102 existing queue tests (test_queue*) still pass.
- bash -n clean on all three modified shell files.
- Smoke: airc queue metronome ... --all writes correct sentinel,
  --all+--owner refused up-front, off clears state.

* docs: propose manager-role + lane substrate for airc (#642)

* canary → main: 35-commit airc bios-hardening (silence beacons, daemon, bus stability, rate-limit, design docs) (#422)

* docs(README): correct the encryption claims (broadcasts plaintext; DMs require pairing) + update day-one numbers

Joel caught the misleading 'How it stays safe' block: it claimed
'every cross-network message is sealed with X25519 + ChaCha20-Poly1305
... GitHub stores ciphertext only' — but reality (and the rest of the
README, line 13) is:
  - broadcasts are PLAINTEXT on the gist (group encryption is roadmap)
  - DMs between PAIRED peers are encrypted
  - DMs to UNPAIRED peers silently fall back to plaintext (#358 — confirmed
    live during today's QA pass)

A user reading the original wording reasonably believes 'all my mesh
traffic is private to recipients.' That's a security misrepresentation.

Honest version distinguishes the three cases + cross-references #358
(the active fix-track) so readers know the asymmetry exists, the
constraint is documented, and the planned mitigations are tracked.

Also updates the 'Built with itself' hero (added in #378) from
'21 commits across 3 main bundles' to '23+ commits across 4 main
bundles' — the day finished with the late-evening bundles 3 and 4
(Codex parity + README hero) which the prior numbers missed.

Signed-claim ("Every envelope Ed25519-signed; tampering observable")
stays + tightens to note sigs verify even on plaintext bodies — that
distinguishes integrity from confidentiality, which the original
block conflated.

The default-room blockquote (line 13) was already accurate ("paired
peers" + "broadcasts plaintext") so no change there.

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

* fix(#381 layer B): host-side queue/drain symmetry for transient gist failures (#385)

Pre-fix the host-side cmd_send branch had no queue path: on bearer_cli
'transient_failure' the warning printed and the message was dropped on
the floor with exit 0. Joiners polling the gist saw nothing; the user's
own audit log showed the message (because the local-mirror echo happened
BEFORE the publish attempt) so the chat widget read 'sent successfully'
even when zero peers received it. Classic silent-success-is-failure.

This change mirrors the joiner-side queue + drain pattern across to host
mode:

cmd_send.sh:
  - Move the unconditional `echo $full_msg >> $MESSAGES` into the
    `delivered)` case only. The user no longer sees their own message
    echoed back unless delivery actually completed.
  - On `transient_failure`/empty kind, append $full_msg to pending.jsonl
    and emit a [QUEUED] system marker to messages.jsonl. The user sees
    'queued for retry' in their log, not a phantom successful send.
  - On `auth_failure`, mirror the joiner branch: emit [GH AUTH FAILED]
    marker and die() with re-auth instructions. Don't queue (every
    retry hits the same dead token).
  - Unknown bearer kinds queue defensively + log loudly.

airc top-level:
  - Add flush_pending_host_loop() — symmetric to flush_pending_loop but
    drains via bearer_cli send (gist publish) instead of SSH push.
    Runs the same 5s tick, parent-liveness gate, snapshot/unsent flow.
    Per-line: extracts channel from the queued JSON, looks up the
    channel's gist, re-resolves recipient pubkey for DM wrap (so a
    pubkey paired post-queue gets used at retry time), publishes via
    bearer_cli, on `delivered` appends to local audit log + emits
    [DRAINED N] marker.
  - monitor() spawn site: when host_target is empty AND we have a
    publishable route (channel_gists OR room_gist_id), spawn the host
    flush loop. Same pidfile-honesty gate as the joiner branch — skip
    the spawn when standalone (--no-gist) so airc.pid doesn't list a
    PID that exited two seconds ago.

Composes with #381 layer A (bearer_gh.py 404/transient classification)
once that lands: layer A makes outcomes accurate, layer B makes
non-`delivered` outcomes recoverable. Layer A retries the initial
gh-api GET; layer B holds the message across longer outages (gh API
secondary rate-limit, network partitions, sandbox flake) until a tick
of the drain loop sees the gist alive again.

Edge case (documented, not addressed here): drain re-runs the wrap
step. If the original cmd_send used --plaintext to a peer with a known
X25519 pubkey, the queued $full_msg is re-wrapped at drain time. This
mirrors the asymmetry already present in the joiner-side flow (which
SSHes plaintext over) and is rare enough to leave to a follow-up.

Issue: airc#381 (Joel's tentative split: layer A → continuum-b741,
layer B → continuum-2c54)

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process) (#389)

* fix(install,connect): surface 'airc daemon install' earlier (#382)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process)

Joel observed (twice on M5 in 48h, "FREQUENT" in practice): gh's
keyring token silently invalidates — token revoked, 2FA flow expired,
brew upgrade replaced gh, OS keychain rotation, sleep across an OAuth
boundary. Pre-fix, every airc command path that touched the gist
substrate would `die "run gh auth login -h github.com"` and stop.

The user then had to manually re-auth. Two problems with that:

1. The next user (Carl, Toby, anyone) hits the same wall on first
   use after a token expires. Manual fix per user = unfixed bug.
2. Joel's "no manual fixes" / "script must self-heal" rule is
   universal: "airc MUST BE THE INSTIGATOR" — when airc detects the
   failure, IT runs the auth flow. The user's only step is clicking
   "Authorize" in the browser airc opened.

This change adds two helpers to a new `lib/airc_bash/lib_auth.sh`:

- airc_detect_gh_auth_state → echoes one of {ok, invalid,
  rate_limited, not_installed}. Distinguishes a real keyring-invalid
  state (BOTH /user and /rate_limit fail) from secondary rate limit
  (only /user fails — token is fine, just wait).

- airc_self_heal_gh_auth → runs `gh auth login --web --hostname
  github.com --git-protocol https -s gist` IN-PROCESS. gh prints the
  device code, opens the browser via the OS opener, blocks until the
  user pastes the code + clicks Authorize. Refuses to run in
  non-interactive contexts (background flush loops have no human at
  the keyboard).

- airc_ensure_gh_auth_or_heal → high-level wrapper: detect → react.
  Single-line call site for command surfaces. ok → return 0;
  rate_limited → emit explanation + return 1; invalid → trigger
  self-heal + re-detect to confirm + return 0/1; not_installed →
  emit install hint + return 1.

Wired into:

- cmd_connect.sh (~30 lines collapsed to 1 wrapper call): pre-flight
  before the join flow now self-heals on invalid token.

- cmd_send.sh (auth_failure path): on bearer-reported auth failure,
  detect + self-heal, then RETRY the send ONCE post-heal. We don't
  loop — if the retry fails too, something else is going on (scope
  missing? gist deleted?) and the user should see it.

Out of scope for this PR (separate follow-ups):
- Wire into cmd_status.sh + cmd_doctor.sh for clearer surfacing
  (today they print "RATE-LIMITED (secondary)" even when the keyring
  is genuinely dead — the new detect helper would fix that).
- Background flush loop (monitor) doesn't self-heal — by design,
  refuses non-TTY. Caller must run an interactive airc cmd to
  re-auth, then queued sends drain.

Tested:
- bash -n on all 4 touched files: clean
- airc_detect_gh_auth_state against real `ok` keyring: returns "ok"
- against bogus GH_TOKEN: returns "invalid"
- against PATH without gh: returns "not_installed"
- (Live self-heal flow tested manually previously when M5's token
  invalidated; this PR formalizes that path so users don't need to
  remember the command.)

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

---------

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

* fix(install,connect): surface 'airc daemon install' earlier (#382) (#388)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text (#390)

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text

PR #388 landed with 4 Copilot review concerns. This PR addresses all 4 +
extracts the cross-platform "is the daemon installed?" detect into a
shared helper so install.sh + cmd_connect.sh + cmd_daemon.sh all use ONE
implementation. Per Joel "if you code modularly like we require": three
near-identical case statements collapse to one detector.

NEW: lib/airc_bash/lib_daemon_detect.sh
  airc_daemon_is_installed() — covers darwin (LaunchAgents plist),
  linux+wsl (systemd user unit), windows (HKCU\...\Run\airc-monitor).
  Sourced from top-level airc + install.sh.

CHANGED:
  - install.sh: drops local _daemon_already_installed (Darwin/Linux only),
    sources lib_daemon_detect.sh from $CLONE_DIR, calls the shared
    helper. Fixes Copilot concern #2 (Windows/WSL gap).
  - install.sh: AIRC_INSTALL_YES=1 check now runs BEFORE the !-t 0
    non-TTY check, so `curl … | AIRC_INSTALL_YES=1 bash` actually
    installs the daemon instead of falling into the non-TTY tip
    branch. Fixes Copilot concern #3 (ordering bug).
  - install.sh: prompt text drops the bogus `--no-daemon-prompt` flag
    reference (the flag was never implemented anywhere); keeps only
    the AIRC_INSTALL_NO_DAEMON=1 env-var hint that DOES work. Fixes
    Copilot concern #1 (lying-to-user copy).
  - install.sh: launchd/systemd → "launchd / systemd / HKCU-Run" in
    the prompt body so Windows users see their platform mentioned.
  - cmd_connect.sh: first-host daemon-tip block (line ~1707) replaces
    its Darwin-only/Linux-only case statement with a single call to
    airc_daemon_is_installed. Fires correctly on Windows now where
    the previous code never fired (HKCU Run-key wasn't checked).
    Fixes Copilot concern #4.
  - cmd_daemon.sh::_daemon_installed becomes a thin wrapper around
    the shared detector. Preserves the local-private-helper API
    used by callers in this file; cross-platform logic now lives in
    one place. Detection guaranteed consistent across all sites.

Branch ordering rationale (install.sh, top→bottom):
  1. AIRC_INSTALL_NO_DAEMON=1   — explicit opt-out trumps everything
  2. AIRC_INSTALL_YES=1         — explicit auto-install (now BEFORE non-TTY)
  3. airc_daemon_is_installed   — idempotent re-run no-op
  4. !-t 0 || !-t 1             — non-TTY tip
  5. interactive [Y/n]          — default

TEST:
  - bash -n on all 5 touched files: clean
  - airc_daemon_is_installed against real Mac (daemon installed): returns 0 ✓
  - against mocked-windows (reg query mocked to succeed): returns 0 ✓
  - cmd_daemon.sh::_daemon_installed wrapper: still returns same value
    as direct airc_daemon_is_installed call (delegation works)
  - install.sh ordering: verified YES check (line 909) precedes !-t 0
    check (line 920+) by inspection

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

* docs: address Copilot nits on PR #390 — comment-only fixes

Three pure comment fixes from Copilot review:
1. lib_daemon_detect.sh: 'users-experience bugs' → 'user experience bugs'
   (grammar)
2. install.sh: 'Three NON-prompt branches' → 'Four NON-prompt branches'
   (the list below the comment has 4 branches: NO_DAEMON, YES,
   already-installed, non-TTY)
3. lib_daemon_detect.sh: HKCU\...\Run\airc-monitor reads as a subkey
   path; airc-monitor is actually the VALUE NAME under the Run key.
   Reworded to clarify.

No code changes.

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

---------

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

* fix: distinguish env_token_invalid (GH_TOKEN poisoned) from keyring-invalid (#391)

Discovered live on canary 73ab85e while testing PR #389's self-heal flow:
when GH_TOKEN env var is set + invalid, gh REFUSES to run `gh auth login`
("The value of the GH_TOKEN environment variable is being used for
authentication. To have GitHub CLI store credentials instead, first clear
the value from the environment").

Pre-fix the wrapper would still trigger self-heal in this case, gh would
bounce immediately, and the user got the misleading "auth flow did not
complete (cancelled? no network?)" fallback message. No path forward
visible to them.

Fix: detect this case as a NEW state, `env_token_invalid`, distinct from
keyring-`invalid`. The wrapper handles it with a precise message:

  ✗ GH_TOKEN environment variable is set + invalid.
    airc can't auto-heal this — gh refuses to run 'gh auth login' while
    GH_TOKEN is set. Self-heal would just bounce.

    Two paths to fix:
    1. Stale dotfile / leftover export → just unset it:
         unset GH_TOKEN
       Then re-run your airc command. airc will detect the keyring
       auth + self-heal it via the browser flow.
    2. Real CI token (Actions, Codespace, dotfile sourcing a managed
       token) → fix the source. Don't run gh auth login; refresh
       whichever system writes GH_TOKEN.

    What gh sees right now:
      [verbatim gh auth status output]

Detection logic:
  if gh auth status passes:           → ok           (unchanged)
  elif gh api rate_limit passes:      → rate_limited (unchanged)
  elif [ -n "${GH_TOKEN:-}" ]:        → env_token_invalid  (NEW)
  else:                               → invalid      (unchanged)

GH_TOKEN takes precedence over keyring in gh's auth resolution. If we
got past gh auth status + gh api rate_limit both failing AND GH_TOKEN
is set, then GH_TOKEN is what gh's using and it's dead. Self-heal can't
fix that — only user-side action can.

Tested:
  - real ok keyring (no GH_TOKEN):           detect → "ok"             ✓
  - bogus GH_TOKEN, real keyring fine:        detect → "env_token_invalid" ✓
  - mocked auth+rate fails, no GH_TOKEN:      detect → "invalid"        ✓
  - wrapper with env_token_invalid: emits two-path message + returns 1 ✓

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

* fix: detect_scope walks up to enclosing .airc/ ancestor (no more .airc/.airc) (#392)

When a user `cd`'d into the scope dir for forensic inspection (or any
descendant), `detect_scope()` returned `$pwd/.airc` — producing wrong
nested paths like `/repo/.airc/.airc`. Every subsequent airc command
then died with "Not initialized" against a directory that didn't exist.
Discovered live on M5 2026-05-01 while diagnosing a different airc
issue: the very act of `cd .airc; airc status` to inspect state broke
airc.

Fix: walk up from cwd looking for an ancestor whose basename is .airc.
If found, that's the scope. If not found, fall through to the
documented `$pwd/.airc` per-cwd default (unchanged behaviour for the
common fresh-cwd case).

Test cases:

  cwd                              | pre-fix              | post-fix
  ---------------------------------|----------------------|------------
  /repo (no .airc anywhere)        | /repo/.airc          | /repo/.airc (same)
  /repo (has child .airc)          | /repo/.airc          | /repo/.airc (same)
  /repo/.airc        (BUG TRIGGER) | /repo/.airc/.airc    | /repo/.airc ✓ FIXED
  /repo/.airc/identity             | /repo/.airc/identity/.airc | /repo/.airc ✓ FIXED
  AIRC_HOME=/x set                 | /x                   | /x (override unchanged)

Carve-out narrowly addresses the bug. Doesn't change behaviour for
"cwd is parallel to a sibling .airc/" (e.g. cwd=/repo/src with /repo/.airc
existing — that still creates /repo/src/.airc the way it always has).
A broader "find enclosing scope from any subdir" change would shift the
documented per-cwd identity contract; deserves its own design discussion.

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

* hotfix(host_address_set): restore Tailscale entry when daemon signed in (#394)

* canary → main: bearer rewrite + post-3c substrate (#306)

* 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…
joelteply added a commit that referenced this pull request Aug 9, 2026
…in release (#1313) (#1336)

* canary → main: 35-commit airc bios-hardening (silence beacons, daemon, bus stability, rate-limit, design docs) (#422)

* docs(README): correct the encryption claims (broadcasts plaintext; DMs require pairing) + update day-one numbers

Joel caught the misleading 'How it stays safe' block: it claimed
'every cross-network message is sealed with X25519 + ChaCha20-Poly1305
... GitHub stores ciphertext only' — but reality (and the rest of the
README, line 13) is:
  - broadcasts are PLAINTEXT on the gist (group encryption is roadmap)
  - DMs between PAIRED peers are encrypted
  - DMs to UNPAIRED peers silently fall back to plaintext (#358 — confirmed
    live during today's QA pass)

A user reading the original wording reasonably believes 'all my mesh
traffic is private to recipients.' That's a security misrepresentation.

Honest version distinguishes the three cases + cross-references #358
(the active fix-track) so readers know the asymmetry exists, the
constraint is documented, and the planned mitigations are tracked.

Also updates the 'Built with itself' hero (added in #378) from
'21 commits across 3 main bundles' to '23+ commits across 4 main
bundles' — the day finished with the late-evening bundles 3 and 4
(Codex parity + README hero) which the prior numbers missed.

Signed-claim ("Every envelope Ed25519-signed; tampering observable")
stays + tightens to note sigs verify even on plaintext bodies — that
distinguishes integrity from confidentiality, which the original
block conflated.

The default-room blockquote (line 13) was already accurate ("paired
peers" + "broadcasts plaintext") so no change there.

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

* fix(#381 layer B): host-side queue/drain symmetry for transient gist failures (#385)

Pre-fix the host-side cmd_send branch had no queue path: on bearer_cli
'transient_failure' the warning printed and the message was dropped on
the floor with exit 0. Joiners polling the gist saw nothing; the user's
own audit log showed the message (because the local-mirror echo happened
BEFORE the publish attempt) so the chat widget read 'sent successfully'
even when zero peers received it. Classic silent-success-is-failure.

This change mirrors the joiner-side queue + drain pattern across to host
mode:

cmd_send.sh:
  - Move the unconditional `echo $full_msg >> $MESSAGES` into the
    `delivered)` case only. The user no longer sees their own message
    echoed back unless delivery actually completed.
  - On `transient_failure`/empty kind, append $full_msg to pending.jsonl
    and emit a [QUEUED] system marker to messages.jsonl. The user sees
    'queued for retry' in their log, not a phantom successful send.
  - On `auth_failure`, mirror the joiner branch: emit [GH AUTH FAILED]
    marker and die() with re-auth instructions. Don't queue (every
    retry hits the same dead token).
  - Unknown bearer kinds queue defensively + log loudly.

airc top-level:
  - Add flush_pending_host_loop() — symmetric to flush_pending_loop but
    drains via bearer_cli send (gist publish) instead of SSH push.
    Runs the same 5s tick, parent-liveness gate, snapshot/unsent flow.
    Per-line: extracts channel from the queued JSON, looks up the
    channel's gist, re-resolves recipient pubkey for DM wrap (so a
    pubkey paired post-queue gets used at retry time), publishes via
    bearer_cli, on `delivered` appends to local audit log + emits
    [DRAINED N] marker.
  - monitor() spawn site: when host_target is empty AND we have a
    publishable route (channel_gists OR room_gist_id), spawn the host
    flush loop. Same pidfile-honesty gate as the joiner branch — skip
    the spawn when standalone (--no-gist) so airc.pid doesn't list a
    PID that exited two seconds ago.

Composes with #381 layer A (bearer_gh.py 404/transient classification)
once that lands: layer A makes outcomes accurate, layer B makes
non-`delivered` outcomes recoverable. Layer A retries the initial
gh-api GET; layer B holds the message across longer outages (gh API
secondary rate-limit, network partitions, sandbox flake) until a tick
of the drain loop sees the gist alive again.

Edge case (documented, not addressed here): drain re-runs the wrap
step. If the original cmd_send used --plaintext to a peer with a known
X25519 pubkey, the queued $full_msg is re-wrapped at drain time. This
mirrors the asymmetry already present in the joiner-side flow (which
SSHes plaintext over) and is rare enough to leave to a follow-up.

Issue: airc#381 (Joel's tentative split: layer A → continuum-b741,
layer B → continuum-2c54)

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process) (#389)

* fix(install,connect): surface 'airc daemon install' earlier (#382)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process)

Joel observed (twice on M5 in 48h, "FREQUENT" in practice): gh's
keyring token silently invalidates — token revoked, 2FA flow expired,
brew upgrade replaced gh, OS keychain rotation, sleep across an OAuth
boundary. Pre-fix, every airc command path that touched the gist
substrate would `die "run gh auth login -h github.com"` and stop.

The user then had to manually re-auth. Two problems with that:

1. The next user (Carl, Toby, anyone) hits the same wall on first
   use after a token expires. Manual fix per user = unfixed bug.
2. Joel's "no manual fixes" / "script must self-heal" rule is
   universal: "airc MUST BE THE INSTIGATOR" — when airc detects the
   failure, IT runs the auth flow. The user's only step is clicking
   "Authorize" in the browser airc opened.

This change adds two helpers to a new `lib/airc_bash/lib_auth.sh`:

- airc_detect_gh_auth_state → echoes one of {ok, invalid,
  rate_limited, not_installed}. Distinguishes a real keyring-invalid
  state (BOTH /user and /rate_limit fail) from secondary rate limit
  (only /user fails — token is fine, just wait).

- airc_self_heal_gh_auth → runs `gh auth login --web --hostname
  github.com --git-protocol https -s gist` IN-PROCESS. gh prints the
  device code, opens the browser via the OS opener, blocks until the
  user pastes the code + clicks Authorize. Refuses to run in
  non-interactive contexts (background flush loops have no human at
  the keyboard).

- airc_ensure_gh_auth_or_heal → high-level wrapper: detect → react.
  Single-line call site for command surfaces. ok → return 0;
  rate_limited → emit explanation + return 1; invalid → trigger
  self-heal + re-detect to confirm + return 0/1; not_installed →
  emit install hint + return 1.

Wired into:

- cmd_connect.sh (~30 lines collapsed to 1 wrapper call): pre-flight
  before the join flow now self-heals on invalid token.

- cmd_send.sh (auth_failure path): on bearer-reported auth failure,
  detect + self-heal, then RETRY the send ONCE post-heal. We don't
  loop — if the retry fails too, something else is going on (scope
  missing? gist deleted?) and the user should see it.

Out of scope for this PR (separate follow-ups):
- Wire into cmd_status.sh + cmd_doctor.sh for clearer surfacing
  (today they print "RATE-LIMITED (secondary)" even when the keyring
  is genuinely dead — the new detect helper would fix that).
- Background flush loop (monitor) doesn't self-heal — by design,
  refuses non-TTY. Caller must run an interactive airc cmd to
  re-auth, then queued sends drain.

Tested:
- bash -n on all 4 touched files: clean
- airc_detect_gh_auth_state against real `ok` keyring: returns "ok"
- against bogus GH_TOKEN: returns "invalid"
- against PATH without gh: returns "not_installed"
- (Live self-heal flow tested manually previously when M5's token
  invalidated; this PR formalizes that path so users don't need to
  remember the command.)

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

---------

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

* fix(install,connect): surface 'airc daemon install' earlier (#382) (#388)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text (#390)

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text

PR #388 landed with 4 Copilot review concerns. This PR addresses all 4 +
extracts the cross-platform "is the daemon installed?" detect into a
shared helper so install.sh + cmd_connect.sh + cmd_daemon.sh all use ONE
implementation. Per Joel "if you code modularly like we require": three
near-identical case statements collapse to one detector.

NEW: lib/airc_bash/lib_daemon_detect.sh
  airc_daemon_is_installed() — covers darwin (LaunchAgents plist),
  linux+wsl (systemd user unit), windows (HKCU\...\Run\airc-monitor).
  Sourced from top-level airc + install.sh.

CHANGED:
  - install.sh: drops local _daemon_already_installed (Darwin/Linux only),
    sources lib_daemon_detect.sh from $CLONE_DIR, calls the shared
    helper. Fixes Copilot concern #2 (Windows/WSL gap).
  - install.sh: AIRC_INSTALL_YES=1 check now runs BEFORE the !-t 0
    non-TTY check, so `curl … | AIRC_INSTALL_YES=1 bash` actually
    installs the daemon instead of falling into the non-TTY tip
    branch. Fixes Copilot concern #3 (ordering bug).
  - install.sh: prompt text drops the bogus `--no-daemon-prompt` flag
    reference (the flag was never implemented anywhere); keeps only
    the AIRC_INSTALL_NO_DAEMON=1 env-var hint that DOES work. Fixes
    Copilot concern #1 (lying-to-user copy).
  - install.sh: launchd/systemd → "launchd / systemd / HKCU-Run" in
    the prompt body so Windows users see their platform mentioned.
  - cmd_connect.sh: first-host daemon-tip block (line ~1707) replaces
    its Darwin-only/Linux-only case statement with a single call to
    airc_daemon_is_installed. Fires correctly on Windows now where
    the previous code never fired (HKCU Run-key wasn't checked).
    Fixes Copilot concern #4.
  - cmd_daemon.sh::_daemon_installed becomes a thin wrapper around
    the shared detector. Preserves the local-private-helper API
    used by callers in this file; cross-platform logic now lives in
    one place. Detection guaranteed consistent across all sites.

Branch ordering rationale (install.sh, top→bottom):
  1. AIRC_INSTALL_NO_DAEMON=1   — explicit opt-out trumps everything
  2. AIRC_INSTALL_YES=1         — explicit auto-install (now BEFORE non-TTY)
  3. airc_daemon_is_installed   — idempotent re-run no-op
  4. !-t 0 || !-t 1             — non-TTY tip
  5. interactive [Y/n]          — default

TEST:
  - bash -n on all 5 touched files: clean
  - airc_daemon_is_installed against real Mac (daemon installed): returns 0 ✓
  - against mocked-windows (reg query mocked to succeed): returns 0 ✓
  - cmd_daemon.sh::_daemon_installed wrapper: still returns same value
    as direct airc_daemon_is_installed call (delegation works)
  - install.sh ordering: verified YES check (line 909) precedes !-t 0
    check (line 920+) by inspection

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

* docs: address Copilot nits on PR #390 — comment-only fixes

Three pure comment fixes from Copilot review:
1. lib_daemon_detect.sh: 'users-experience bugs' → 'user experience bugs'
   (grammar)
2. install.sh: 'Three NON-prompt branches' → 'Four NON-prompt branches'
   (the list below the comment has 4 branches: NO_DAEMON, YES,
   already-installed, non-TTY)
3. lib_daemon_detect.sh: HKCU\...\Run\airc-monitor reads as a subkey
   path; airc-monitor is actually the VALUE NAME under the Run key.
   Reworded to clarify.

No code changes.

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

---------

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

* fix: distinguish env_token_invalid (GH_TOKEN poisoned) from keyring-invalid (#391)

Discovered live on canary 73ab85e while testing PR #389's self-heal flow:
when GH_TOKEN env var is set + invalid, gh REFUSES to run `gh auth login`
("The value of the GH_TOKEN environment variable is being used for
authentication. To have GitHub CLI store credentials instead, first clear
the value from the environment").

Pre-fix the wrapper would still trigger self-heal in this case, gh would
bounce immediately, and the user got the misleading "auth flow did not
complete (cancelled? no network?)" fallback message. No path forward
visible to them.

Fix: detect this case as a NEW state, `env_token_invalid`, distinct from
keyring-`invalid`. The wrapper handles it with a precise message:

  ✗ GH_TOKEN environment variable is set + invalid.
    airc can't auto-heal this — gh refuses to run 'gh auth login' while
    GH_TOKEN is set. Self-heal would just bounce.

    Two paths to fix:
    1. Stale dotfile / leftover export → just unset it:
         unset GH_TOKEN
       Then re-run your airc command. airc will detect the keyring
       auth + self-heal it via the browser flow.
    2. Real CI token (Actions, Codespace, dotfile sourcing a managed
       token) → fix the source. Don't run gh auth login; refresh
       whichever system writes GH_TOKEN.

    What gh sees right now:
      [verbatim gh auth status output]

Detection logic:
  if gh auth status passes:           → ok           (unchanged)
  elif gh api rate_limit passes:      → rate_limited (unchanged)
  elif [ -n "${GH_TOKEN:-}" ]:        → env_token_invalid  (NEW)
  else:                               → invalid      (unchanged)

GH_TOKEN takes precedence over keyring in gh's auth resolution. If we
got past gh auth status + gh api rate_limit both failing AND GH_TOKEN
is set, then GH_TOKEN is what gh's using and it's dead. Self-heal can't
fix that — only user-side action can.

Tested:
  - real ok keyring (no GH_TOKEN):           detect → "ok"             ✓
  - bogus GH_TOKEN, real keyring fine:        detect → "env_token_invalid" ✓
  - mocked auth+rate fails, no GH_TOKEN:      detect → "invalid"        ✓
  - wrapper with env_token_invalid: emits two-path message + returns 1 ✓

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

* fix: detect_scope walks up to enclosing .airc/ ancestor (no more .airc/.airc) (#392)

When a user `cd`'d into the scope dir for forensic inspection (or any
descendant), `detect_scope()` returned `$pwd/.airc` — producing wrong
nested paths like `/repo/.airc/.airc`. Every subsequent airc command
then died with "Not initialized" against a directory that didn't exist.
Discovered live on M5 2026-05-01 while diagnosing a different airc
issue: the very act of `cd .airc; airc status` to inspect state broke
airc.

Fix: walk up from cwd looking for an ancestor whose basename is .airc.
If found, that's the scope. If not found, fall through to the
documented `$pwd/.airc` per-cwd default (unchanged behaviour for the
common fresh-cwd case).

Test cases:

  cwd                              | pre-fix              | post-fix
  ---------------------------------|----------------------|------------
  /repo (no .airc anywhere)        | /repo/.airc          | /repo/.airc (same)
  /repo (has child .airc)          | /repo/.airc          | /repo/.airc (same)
  /repo/.airc        (BUG TRIGGER) | /repo/.airc/.airc    | /repo/.airc ✓ FIXED
  /repo/.airc/identity             | /repo/.airc/identity/.airc | /repo/.airc ✓ FIXED
  AIRC_HOME=/x set                 | /x                   | /x (override unchanged)

Carve-out narrowly addresses the bug. Doesn't change behaviour for
"cwd is parallel to a sibling .airc/" (e.g. cwd=/repo/src with /repo/.airc
existing — that still creates /repo/src/.airc the way it always has).
A broader "find enclosing scope from any subdir" change would shift the
documented per-cwd identity contract; deserves its own design discussion.

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

* hotfix(host_address_set): restore Tailscale entry when daemon signed in (#394)

* canary → main: bearer rewrite + post-3c substrate (#306)

* 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-loss class — host broadcasts
returned 'delivered' but the gist was never written; joiners polling
the gist saw nothing; user surface lied success.

## Bug 1: cmd_send.sh host-path was local-append-only
The else-branch (host case, line ~363 pre-fix) ended with:

    echo "\$full_msg" >> "\$MESSAGES"

with a comment "Joiners' SSH tails will pick it up" — relic of pre-3c
when SSH bearer's tail -F over SSH was the wire. Phase 3c (#281) deleted
SSH wholesale; joiners now poll the gist via GhBearer; a local-only
append disappears.

Fix: after the local audit append, ALSO call bearer_cli send with the
host's --room-gist-id so GhBearer publishes to the gist. Same wrap-if-
recipient-known logic as the joiner branch, so DMs to peers with
stored x25519_pub get encrypted and broadcasts go plaintext.

## Bug 2: GhBearer._gh_gist_write_file silent no-op on first send
\`gh gist edit GIST_ID file\` (no flag) returns exit 0 BUT silently does
nothing when the target filename doesn't exist in the gist. The
fallback chain ('try plain edit; on non-zero, retry with -a') never
fires because the first call returns 0 without writing. Production
gists start with only an airc-invite seed (no messages.jsonl), so
EVERY first host send hit this trap.

Fix: read the gist's file list FIRST, choose the correct subcommand:
  - file already in gist  → \`gh gist edit GIST file\`        (replace)
  - file NOT in gist      → \`gh gist edit GIST -a file\`     (add)

One extra GET, but eliminates the silent-no-op trap. Defense-in-depth:
if the existence check disagrees with reality (concurrent peer added
the file between our GET and our edit), retry the OTHER subcommand
once before giving up.

## Why the existing 123 integration tests didn't catch this
- All scenarios that exercise multi-peer messaging used \`--no-room
  --no-gist\` for speed. That flag bypasses gh entirely; the test rig
  rode on the SSH-bearer TCP-handshake path. After Phase 3c moved
  production to GhBearer, the test rig kept exercising a stripped-down
  path that doesn't match production architecture.
- scenario_bearer_gh DOES use a real gh gist BUT pre-seeds it with
  messages.jsonl (the 'happy path' shape). Production gists start with
  airc-invite seed (NOT messages.jsonl), so the first send is a CREATE
  not a REPLACE — exactly the bug. The seed shape masked it.

Two new TDD scenarios cover both paths post-fix:

- \`gh_send_creates_messages_jsonl\` (unit-of-bearer): seeds gist with
  airc-invite (matching production), runs bearer_cli send directly,
  asserts gist now contains messages.jsonl with the marker. Pre-fix:
  bearer reports 'delivered', gist unchanged. Post-fix: green.
- \`host_msg_publishes_to_gist\` (end-to-end cmd_send→bearer): spawns a
  real host with --room (no --no-gist), runs \`airc msg <marker>\`,
  asserts gist's messages.jsonl contains the marker. Pre-fix: cmd_send
  never invoked bearer_cli on host path. Post-fix: green.

Verified locally:
- gh_send_creates_messages_jsonl: 5/5 (was 3/2 before fix)
- host_msg_publishes_to_gist: 2/2 (was 1/1 before fix)

Closes #285. #283 (sidecar) and #284 (cross-room DM) are tracked
separately and will get their own TDD + fix.

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

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

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]>

* docs(skills): update /join skill for post-3c architecture (#289)

The /join skill is what every AI peer reads at startup — its content
shapes how peers behave + troubleshoot. Tonight's QA pass surfaced
that the skill still referenced Tailscale, SSH transport, and the
sidecar-process model — all gone in Phase 3c (#281).

Updates:
- Transport section: gist IS the wire; LocalBearer for same-machine,
  GhBearer for cross-network; envelope-encrypted at the X25519+
  ChaCha20-Poly1305 layer. GitHub stores ciphertext only.
- Boot outcomes: removed Tailscale-up nudges + multi-address pick
  references; added the new #general gist resolution surface.
- Multi-room: ONE monitor per scope polls all subscribed channels'
  gists in parallel. No separate sidecar process.
- Troubleshooting: replaced SSH/Tailscale failure modes with the
  actual post-3c surfaces — gh auth, gist content verification,
  cross-room routing via --room flag.

Skills/doctor and skills/invite still have similar stale refs;
follow-up PR.

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

* fix(#290): channel_gist prefers single-channel gists (substrate convergence) (#291)

* docs(skills): update /join skill for post-3c architecture

The /join skill is what every AI peer reads at startup — its content
shapes how peers behave + troubleshoot. Tonight's QA pass surfaced
that the skill still referenced Tailscale, SSH transport, and the
sidecar-process model — all gone in Phase 3c (#281).

Updates:
- Transport section: gist IS the wire; LocalBearer for same-machine,
  GhBearer for cross-network; envelope-encrypted at the X25519+
  ChaCha20-Poly1305 layer. GitHub stores ciphertext only.
- Boot outcomes: removed Tailscale-up nudges + multi-address pick
  references; adde…
joelteply added a commit that referenced this pull request Sep 20, 2026
…en on ci / rust / runtime-guards (#1443)

* docs: design rust sqlite substrate (#634)

design rust sqlite substrate

* docs: design realtime event bus (#635)

design realtime event bus

* feat(queue): add steward dry-run digest (#636)

add queue steward dry run

* feat(core): add Rust transcript primitives (#637)

add rust transcript core

* feat(logs): add json transcript pages (#638)

* fix(logs): avoid strict-mode crash without json flag (#639)

* refactor(logs): use one render path for human and json modes (#640)

* feat(queue): metronome fan-out across active roster (airc#607, continuum#1192) (#641)

feat(queue): metronome fan-out across active roster (#607, continuum#1192)

Closes the gap where a single-owner queue metronome could only ever DM
one agent, leaving the rest of the channel idle even though their next
claimable card was sitting right there. Operators opt in with --all;
the monitor consumer then enumerates recent senders in this scope's
messages.jsonl and dispatches per agent with per-recipient dedup so a
tight pulse can't double-DM the same agent.

Why bash and not Rust: this is the bridge while airc#628 (Rust queue-
dispatch substrate) lands. The embedded python roster extractor and
the bash dispatcher are intentionally minimal so the Rust port can
delete them wholesale rather than re-implement a TS-shaped API.

Changes
- airc: reminder_timer_loop reads owner=*roster* sentinel, builds the
  recipient list from messages.jsonl (filters self + 'airc' system
  sender + outside-window), dispatches per agent via cmd_queue.
  Per-recipient last-pinged stamp under queue_metronome_recent/ so
  the dedup window matches the configured interval.
- lib/airc_bash/cmd_queue.sh: --all / --roster flag, --roster-window
  flag (default 86400s, minimum 60s), mutex against --owner so the
  config file can't land in a contradictory state the monitor would
  silently resolve one way. off path now also clears recent dedup.
- lib/airc_bash/cmd_queue_help.sh: usage + options for the new flags.
- test/test_queue_metronome_fanout.py: 3 CLI tests against the real
  binary + 9 unit tests of the roster extraction logic (recent-only,
  filter self/airc, window enforcement, ISO + epoch + epoch-ms ts,
  dedup by latest, empty/missing/malformed log).

Validation
- 12/12 new tests pass.
- 102/102 existing queue tests (test_queue*) still pass.
- bash -n clean on all three modified shell files.
- Smoke: airc queue metronome ... --all writes correct sentinel,
  --all+--owner refused up-front, off clears state.

* docs: propose manager-role + lane substrate for airc (#642)

* canary → main: 35-commit airc bios-hardening (silence beacons, daemon, bus stability, rate-limit, design docs) (#422)

* docs(README): correct the encryption claims (broadcasts plaintext; DMs require pairing) + update day-one numbers

Joel caught the misleading 'How it stays safe' block: it claimed
'every cross-network message is sealed with X25519 + ChaCha20-Poly1305
... GitHub stores ciphertext only' — but reality (and the rest of the
README, line 13) is:
  - broadcasts are PLAINTEXT on the gist (group encryption is roadmap)
  - DMs between PAIRED peers are encrypted
  - DMs to UNPAIRED peers silently fall back to plaintext (#358 — confirmed
    live during today's QA pass)

A user reading the original wording reasonably believes 'all my mesh
traffic is private to recipients.' That's a security misrepresentation.

Honest version distinguishes the three cases + cross-references #358
(the active fix-track) so readers know the asymmetry exists, the
constraint is documented, and the planned mitigations are tracked.

Also updates the 'Built with itself' hero (added in #378) from
'21 commits across 3 main bundles' to '23+ commits across 4 main
bundles' — the day finished with the late-evening bundles 3 and 4
(Codex parity + README hero) which the prior numbers missed.

Signed-claim ("Every envelope Ed25519-signed; tampering observable")
stays + tightens to note sigs verify even on plaintext bodies — that
distinguishes integrity from confidentiality, which the original
block conflated.

The default-room blockquote (line 13) was already accurate ("paired
peers" + "broadcasts plaintext") so no change there.

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

* fix(#381 layer B): host-side queue/drain symmetry for transient gist failures (#385)

Pre-fix the host-side cmd_send branch had no queue path: on bearer_cli
'transient_failure' the warning printed and the message was dropped on
the floor with exit 0. Joiners polling the gist saw nothing; the user's
own audit log showed the message (because the local-mirror echo happened
BEFORE the publish attempt) so the chat widget read 'sent successfully'
even when zero peers received it. Classic silent-success-is-failure.

This change mirrors the joiner-side queue + drain pattern across to host
mode:

cmd_send.sh:
  - Move the unconditional `echo $full_msg >> $MESSAGES` into the
    `delivered)` case only. The user no longer sees their own message
    echoed back unless delivery actually completed.
  - On `transient_failure`/empty kind, append $full_msg to pending.jsonl
    and emit a [QUEUED] system marker to messages.jsonl. The user sees
    'queued for retry' in their log, not a phantom successful send.
  - On `auth_failure`, mirror the joiner branch: emit [GH AUTH FAILED]
    marker and die() with re-auth instructions. Don't queue (every
    retry hits the same dead token).
  - Unknown bearer kinds queue defensively + log loudly.

airc top-level:
  - Add flush_pending_host_loop() — symmetric to flush_pending_loop but
    drains via bearer_cli send (gist publish) instead of SSH push.
    Runs the same 5s tick, parent-liveness gate, snapshot/unsent flow.
    Per-line: extracts channel from the queued JSON, looks up the
    channel's gist, re-resolves recipient pubkey for DM wrap (so a
    pubkey paired post-queue gets used at retry time), publishes via
    bearer_cli, on `delivered` appends to local audit log + emits
    [DRAINED N] marker.
  - monitor() spawn site: when host_target is empty AND we have a
    publishable route (channel_gists OR room_gist_id), spawn the host
    flush loop. Same pidfile-honesty gate as the joiner branch — skip
    the spawn when standalone (--no-gist) so airc.pid doesn't list a
    PID that exited two seconds ago.

Composes with #381 layer A (bearer_gh.py 404/transient classification)
once that lands: layer A makes outcomes accurate, layer B makes
non-`delivered` outcomes recoverable. Layer A retries the initial
gh-api GET; layer B holds the message across longer outages (gh API
secondary rate-limit, network partitions, sandbox flake) until a tick
of the drain loop sees the gist alive again.

Edge case (documented, not addressed here): drain re-runs the wrap
step. If the original cmd_send used --plaintext to a peer with a known
X25519 pubkey, the queued $full_msg is re-wrapped at drain time. This
mirrors the asymmetry already present in the joiner-side flow (which
SSHes plaintext over) and is rare enough to leave to a follow-up.

Issue: airc#381 (Joel's tentative split: layer A → continuum-b741,
layer B → continuum-2c54)

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process) (#389)

* fix(install,connect): surface 'airc daemon install' earlier (#382)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix: airc self-heals invalid gh keyring tokens (browser flow in-process)

Joel observed (twice on M5 in 48h, "FREQUENT" in practice): gh's
keyring token silently invalidates — token revoked, 2FA flow expired,
brew upgrade replaced gh, OS keychain rotation, sleep across an OAuth
boundary. Pre-fix, every airc command path that touched the gist
substrate would `die "run gh auth login -h github.com"` and stop.

The user then had to manually re-auth. Two problems with that:

1. The next user (Carl, Toby, anyone) hits the same wall on first
   use after a token expires. Manual fix per user = unfixed bug.
2. Joel's "no manual fixes" / "script must self-heal" rule is
   universal: "airc MUST BE THE INSTIGATOR" — when airc detects the
   failure, IT runs the auth flow. The user's only step is clicking
   "Authorize" in the browser airc opened.

This change adds two helpers to a new `lib/airc_bash/lib_auth.sh`:

- airc_detect_gh_auth_state → echoes one of {ok, invalid,
  rate_limited, not_installed}. Distinguishes a real keyring-invalid
  state (BOTH /user and /rate_limit fail) from secondary rate limit
  (only /user fails — token is fine, just wait).

- airc_self_heal_gh_auth → runs `gh auth login --web --hostname
  github.com --git-protocol https -s gist` IN-PROCESS. gh prints the
  device code, opens the browser via the OS opener, blocks until the
  user pastes the code + clicks Authorize. Refuses to run in
  non-interactive contexts (background flush loops have no human at
  the keyboard).

- airc_ensure_gh_auth_or_heal → high-level wrapper: detect → react.
  Single-line call site for command surfaces. ok → return 0;
  rate_limited → emit explanation + return 1; invalid → trigger
  self-heal + re-detect to confirm + return 0/1; not_installed →
  emit install hint + return 1.

Wired into:

- cmd_connect.sh (~30 lines collapsed to 1 wrapper call): pre-flight
  before the join flow now self-heals on invalid token.

- cmd_send.sh (auth_failure path): on bearer-reported auth failure,
  detect + self-heal, then RETRY the send ONCE post-heal. We don't
  loop — if the retry fails too, something else is going on (scope
  missing? gist deleted?) and the user should see it.

Out of scope for this PR (separate follow-ups):
- Wire into cmd_status.sh + cmd_doctor.sh for clearer surfacing
  (today they print "RATE-LIMITED (secondary)" even when the keyring
  is genuinely dead — the new detect helper would fix that).
- Background flush loop (monitor) doesn't self-heal — by design,
  refuses non-TTY. Caller must run an interactive airc cmd to
  re-auth, then queued sends drain.

Tested:
- bash -n on all 4 touched files: clean
- airc_detect_gh_auth_state against real `ok` keyring: returns "ok"
- against bogus GH_TOKEN: returns "invalid"
- against PATH without gh: returns "not_installed"
- (Live self-heal flow tested manually previously when M5's token
  invalidated; this PR formalizes that path so users don't need to
  remember the command.)

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

---------

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

* fix(install,connect): surface 'airc daemon install' earlier (#382) (#388)

The airc daemon (lib/airc_bash/cmd_daemon.sh) already exists end-to-end
on launchd / systemd / schtasks. But its discoverability was wrong:
the tip only fired AFTER the mesh had gone down ("daemon restart will
self-heal" / "airc daemon install" hint in the reconnect-loop). By
that time peers have missed however many hours of mesh activity.

Push discoverability earlier on two surfaces:

1. install.sh — at the end of first install (after Codex pre-approve,
   before the 'Done' summary), prompt Y/n for daemon install. Skip
   conditions cover the cases that shouldn't see a prompt:
   - daemon already installed (idempotent re-run)
   - non-TTY install (curl-bash piped without terminal — surface as a
     visible tip line so the option lands in the install transcript)
   - AIRC_INSTALL_NO_DAEMON=1 (headless / config-managed environments)
   - AIRC_INSTALL_YES=1 (power-user one-liner — install daemon w/o ask)
   When prompted, default to Y (the user already opted in by running
   the installer).

2. lib/airc_bash/cmd_connect.sh — when this scope first becomes a
   host (publishes a new room gist on gh-account substrate), print
   one extra line: "Tip: 'airc daemon install' keeps this mesh alive
   across machine sleep." Only fires when daemon isn't already
   installed (idempotent re-hosts stay silent).

The two surfaces compose: (1) catches every fresh install, (2) catches
every host-mode-first-time even for users who installed before #382
landed or skipped the prompt then. Together they replace the
post-disconnect-only tip with a pre-disconnect hint at the moments
the user is most likely to act.

Cross-refs:
  #381 layer A (#387) — initial-GET retry composes with daemon being
                         alive to actually drain the queue
  #381 layer B (#385) — host-side queue/drain symmetry; daemon is
                         what keeps the host process alive long
                         enough to drain
  #383 (#384)         — host-mode watchdog; without that fix the
                         daemon thrashes; together they make the
                         daemon-install offer worth taking

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

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text (#390)

* fix(#388): address Copilot review — Windows/WSL daemon detect + ordering + stale text

PR #388 landed with 4 Copilot review concerns. This PR addresses all 4 +
extracts the cross-platform "is the daemon installed?" detect into a
shared helper so install.sh + cmd_connect.sh + cmd_daemon.sh all use ONE
implementation. Per Joel "if you code modularly like we require": three
near-identical case statements collapse to one detector.

NEW: lib/airc_bash/lib_daemon_detect.sh
  airc_daemon_is_installed() — covers darwin (LaunchAgents plist),
  linux+wsl (systemd user unit), windows (HKCU\...\Run\airc-monitor).
  Sourced from top-level airc + install.sh.

CHANGED:
  - install.sh: drops local _daemon_already_installed (Darwin/Linux only),
    sources lib_daemon_detect.sh from $CLONE_DIR, calls the shared
    helper. Fixes Copilot concern #2 (Windows/WSL gap).
  - install.sh: AIRC_INSTALL_YES=1 check now runs BEFORE the !-t 0
    non-TTY check, so `curl … | AIRC_INSTALL_YES=1 bash` actually
    installs the daemon instead of falling into the non-TTY tip
    branch. Fixes Copilot concern #3 (ordering bug).
  - install.sh: prompt text drops the bogus `--no-daemon-prompt` flag
    reference (the flag was never implemented anywhere); keeps only
    the AIRC_INSTALL_NO_DAEMON=1 env-var hint that DOES work. Fixes
    Copilot concern #1 (lying-to-user copy).
  - install.sh: launchd/systemd → "launchd / systemd / HKCU-Run" in
    the prompt body so Windows users see their platform mentioned.
  - cmd_connect.sh: first-host daemon-tip block (line ~1707) replaces
    its Darwin-only/Linux-only case statement with a single call to
    airc_daemon_is_installed. Fires correctly on Windows now where
    the previous code never fired (HKCU Run-key wasn't checked).
    Fixes Copilot concern #4.
  - cmd_daemon.sh::_daemon_installed becomes a thin wrapper around
    the shared detector. Preserves the local-private-helper API
    used by callers in this file; cross-platform logic now lives in
    one place. Detection guaranteed consistent across all sites.

Branch ordering rationale (install.sh, top→bottom):
  1. AIRC_INSTALL_NO_DAEMON=1   — explicit opt-out trumps everything
  2. AIRC_INSTALL_YES=1         — explicit auto-install (now BEFORE non-TTY)
  3. airc_daemon_is_installed   — idempotent re-run no-op
  4. !-t 0 || !-t 1             — non-TTY tip
  5. interactive [Y/n]          — default

TEST:
  - bash -n on all 5 touched files: clean
  - airc_daemon_is_installed against real Mac (daemon installed): returns 0 ✓
  - against mocked-windows (reg query mocked to succeed): returns 0 ✓
  - cmd_daemon.sh::_daemon_installed wrapper: still returns same value
    as direct airc_daemon_is_installed call (delegation works)
  - install.sh ordering: verified YES check (line 909) precedes !-t 0
    check (line 920+) by inspection

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

* docs: address Copilot nits on PR #390 — comment-only fixes

Three pure comment fixes from Copilot review:
1. lib_daemon_detect.sh: 'users-experience bugs' → 'user experience bugs'
   (grammar)
2. install.sh: 'Three NON-prompt branches' → 'Four NON-prompt branches'
   (the list below the comment has 4 branches: NO_DAEMON, YES,
   already-installed, non-TTY)
3. lib_daemon_detect.sh: HKCU\...\Run\airc-monitor reads as a subkey
   path; airc-monitor is actually the VALUE NAME under the Run key.
   Reworded to clarify.

No code changes.

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

---------

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

* fix: distinguish env_token_invalid (GH_TOKEN poisoned) from keyring-invalid (#391)

Discovered live on canary 73ab85e while testing PR #389's self-heal flow:
when GH_TOKEN env var is set + invalid, gh REFUSES to run `gh auth login`
("The value of the GH_TOKEN environment variable is being used for
authentication. To have GitHub CLI store credentials instead, first clear
the value from the environment").

Pre-fix the wrapper would still trigger self-heal in this case, gh would
bounce immediately, and the user got the misleading "auth flow did not
complete (cancelled? no network?)" fallback message. No path forward
visible to them.

Fix: detect this case as a NEW state, `env_token_invalid`, distinct from
keyring-`invalid`. The wrapper handles it with a precise message:

  ✗ GH_TOKEN environment variable is set + invalid.
    airc can't auto-heal this — gh refuses to run 'gh auth login' while
    GH_TOKEN is set. Self-heal would just bounce.

    Two paths to fix:
    1. Stale dotfile / leftover export → just unset it:
         unset GH_TOKEN
       Then re-run your airc command. airc will detect the keyring
       auth + self-heal it via the browser flow.
    2. Real CI token (Actions, Codespace, dotfile sourcing a managed
       token) → fix the source. Don't run gh auth login; refresh
       whichever system writes GH_TOKEN.

    What gh sees right now:
      [verbatim gh auth status output]

Detection logic:
  if gh auth status passes:           → ok           (unchanged)
  elif gh api rate_limit passes:      → rate_limited (unchanged)
  elif [ -n "${GH_TOKEN:-}" ]:        → env_token_invalid  (NEW)
  else:                               → invalid      (unchanged)

GH_TOKEN takes precedence over keyring in gh's auth resolution. If we
got past gh auth status + gh api rate_limit both failing AND GH_TOKEN
is set, then GH_TOKEN is what gh's using and it's dead. Self-heal can't
fix that — only user-side action can.

Tested:
  - real ok keyring (no GH_TOKEN):           detect → "ok"             ✓
  - bogus GH_TOKEN, real keyring fine:        detect → "env_token_invalid" ✓
  - mocked auth+rate fails, no GH_TOKEN:      detect → "invalid"        ✓
  - wrapper with env_token_invalid: emits two-path message + returns 1 ✓

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

* fix: detect_scope walks up to enclosing .airc/ ancestor (no more .airc/.airc) (#392)

When a user `cd`'d into the scope dir for forensic inspection (or any
descendant), `detect_scope()` returned `$pwd/.airc` — producing wrong
nested paths like `/repo/.airc/.airc`. Every subsequent airc command
then died with "Not initialized" against a directory that didn't exist.
Discovered live on M5 2026-05-01 while diagnosing a different airc
issue: the very act of `cd .airc; airc status` to inspect state broke
airc.

Fix: walk up from cwd looking for an ancestor whose basename is .airc.
If found, that's the scope. If not found, fall through to the
documented `$pwd/.airc` per-cwd default (unchanged behaviour for the
common fresh-cwd case).

Test cases:

  cwd                              | pre-fix              | post-fix
  ---------------------------------|----------------------|------------
  /repo (no .airc anywhere)        | /repo/.airc          | /repo/.airc (same)
  /repo (has child .airc)          | /repo/.airc          | /repo/.airc (same)
  /repo/.airc        (BUG TRIGGER) | /repo/.airc/.airc    | /repo/.airc ✓ FIXED
  /repo/.airc/identity             | /repo/.airc/identity/.airc | /repo/.airc ✓ FIXED
  AIRC_HOME=/x set                 | /x                   | /x (override unchanged)

Carve-out narrowly addresses the bug. Doesn't change behaviour for
"cwd is parallel to a sibling .airc/" (e.g. cwd=/repo/src with /repo/.airc
existing — that still creates /repo/src/.airc the way it always has).
A broader "find enclosing scope from any subdir" change would shift the
documented per-cwd identity contract; deserves its own design discussion.

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

* hotfix(host_address_set): restore Tailscale entry when daemon signed in (#394)

* canary → main: bearer rewrite + post-3c substrate (#306)

* 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-loss class — host broadcasts
returned 'delivered' but the gist was never written; joiners polling
the gist saw nothing; user surface lied success.

## Bug 1: cmd_send.sh host-path was local-append-only
The else-branch (host case, line ~363 pre-fix) ended with:

    echo "\$full_msg" >> "\$MESSAGES"

with a comment "Joiners' SSH tails will pick it up" — relic of pre-3c
when SSH bearer's tail -F over SSH was the wire. Phase 3c (#281) deleted
SSH wholesale; joiners now poll the gist via GhBearer; a local-only
append disappears.

Fix: after the local audit append, ALSO call bearer_cli send with the
host's --room-gist-id so GhBearer publishes to the gist. Same wrap-if-
recipient-known logic as the joiner branch, so DMs to peers with
stored x25519_pub get encrypted and broadcasts go plaintext.

## Bug 2: GhBearer._gh_gist_write_file silent no-op on first send
\`gh gist edit GIST_ID file\` (no flag) returns exit 0 BUT silently does
nothing when the target filename doesn't exist in the gist. The
fallback chain ('try plain edit; on non-zero, retry with -a') never
fires because the first call returns 0 without writing. Production
gists start with only an airc-invite seed (no messages.jsonl), so
EVERY first host send hit this trap.

Fix: read the gist's file list FIRST, choose the correct subcommand:
  - file already in gist  → \`gh gist edit GIST file\`        (replace)
  - file NOT in gist      → \`gh gist edit GIST -a file\`     (add)

One extra GET, but eliminates the silent-no-op trap. Defense-in-depth:
if the existence check disagrees with reality (concurrent peer added
the file between our GET and our edit), retry the OTHER subcommand
once before giving up.

## Why the existing 123 integration tests didn't catch this
- All scenarios that exercise multi-peer messaging used \`--no-room
  --no-gist\` for speed. That flag bypasses gh entirely; the test rig
  rode on the SSH-bearer TCP-handshake path. After Phase 3c moved
  production to GhBearer, the test rig kept exercising a stripped-down
  path that doesn't match production architecture.
- scenario_bearer_gh DOES use a real gh gist BUT pre-seeds it with
  messages.jsonl (the 'happy path' shape). Production gists start with
  airc-invite seed (NOT messages.jsonl), so the first send is a CREATE
  not a REPLACE — exactly the bug. The seed shape masked it.

Two new TDD scenarios cover both paths post-fix:

- \`gh_send_creates_messages_jsonl\` (unit-of-bearer): seeds gist with
  airc-invite (matching production), runs bearer_cli send directly,
  asserts gist now contains messages.jsonl with the marker. Pre-fix:
  bearer reports 'delivered', gist unchanged. Post-fix: green.
- \`host_msg_publishes_to_gist\` (end-to-end cmd_send→bearer): spawns a
  real host with --room (no --no-gist), runs \`airc msg <marker>\`,
  asserts gist's messages.jsonl contains the marker. Pre-fix: cmd_send
  never invoked bearer_cli on host path. Post-fix: green.

Verified locally:
- gh_send_creates_messages_jsonl: 5/5 (was 3/2 before fix)
- host_msg_publishes_to_gist: 2/2 (was 1/1 before fix)

Closes #285. #283 (sidecar) and #284 (cross-room DM) are tracked
separately and will get their own TDD + fix.

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

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

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. …
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