Repository navigation
feat(bearer): Phase 1 — cmd_send through bearer seam, SSH knowledge consolidated - #272
Conversation
…owledge 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]>
There was a problem hiding this comment.
Pull request overview
Phase 1 of the bearer rewrite: routes cmd_send through a Python bearer seam, consolidating SSH delivery logic (including __APPENDED__ confirmation and tailscale-offline fast-path) into lib/airc_core/bearer_ssh.py, and introducing a bash-callable bearer_cli that returns structured SendOutcome JSON.
Changes:
- Adds
SendOutcometo the bearer contract and updates the Bearersend()API to return structured outcomes instead of relying on exceptions for normal failure modes. - Implements
SshBearer.send()with SSH argv construction,__APPENDED__confirmation, offline fast-path, and auth-vs-transient failure classification. - Updates
cmd_send.shto callairc_core.bearer_cli sendand branch onSendOutcome.kindinstead of inlining SSH logic.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
lib/airc_core/bearer.py |
Introduces SendOutcome and updates bearer send() to return it. |
lib/airc_core/bearer_ssh.py |
Moves SSH send primitive + tailscale offline fast-path and failure classification into SshBearer.send(). |
lib/airc_core/bearer_resolver.py |
Threads peer_meta into bearer constructors. |
lib/airc_core/bearer_cli.py |
New CLI bridge for bash → bearer send, emitting outcome JSON. |
lib/airc_bash/cmd_send.sh |
Replaces direct relay_ssh send path with bearer_cli + outcome branching. |
airc |
Removes is_peer_offline_in_tailnet bash helper (relocated to Python). |
test/test_bearer.py |
Expands unit tests for SshBearer.send() behavior and CGNAT matching. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| --remote-home "$rhome" 2>/dev/null) | ||
| local kind detail | ||
| kind=$(printf '%s' "$outcome" | "$AIRC_PYTHON" -c 'import json,sys; print(json.load(sys.stdin).get("kind",""))' 2>/dev/null) | ||
| detail=$(printf '%s' "$outcome" | "$AIRC_PYTHON" -c 'import json,sys; print(json.load(sys.stdin).get("detail",""))' 2>/dev/null) |
There was a problem hiding this comment.
This bearer_cli invocation runs inside a command substitution with set -euo pipefail in effect. If the Python process exits non-zero (module import error, uncaught exception, etc.), bash will abort before reaching the case that defensively treats empty/malformed outcomes as transient. To make the "queue rather than disappear" defense real, guard the pipeline (e.g., append || true) and/or ensure bearer_cli never exits non-zero for send failures.
| --remote-home "$rhome" 2>/dev/null) | |
| local kind detail | |
| kind=$(printf '%s' "$outcome" | "$AIRC_PYTHON" -c 'import json,sys; print(json.load(sys.stdin).get("kind",""))' 2>/dev/null) | |
| detail=$(printf '%s' "$outcome" | "$AIRC_PYTHON" -c 'import json,sys; print(json.load(sys.stdin).get("detail",""))' 2>/dev/null) | |
| --remote-home "$rhome" 2>/dev/null || true) | |
| local kind detail | |
| kind=$(printf '%s' "$outcome" | "$AIRC_PYTHON" -c 'import json,sys; print(json.load(sys.stdin).get("kind",""))' 2>/dev/null || true) | |
| detail=$(printf '%s' "$outcome" | "$AIRC_PYTHON" -c 'import json,sys; print(json.load(sys.stdin).get("detail",""))' 2>/dev/null || true) |
| auth_markers = [ | ||
| "Permission denied", | ||
| "Authentication failed", | ||
| "publickey", | ||
| ] | ||
| if any(m in stderr for m in auth_markers): | ||
| return ("auth_failure", "host refused our SSH identity; re-pair required") | ||
| return ("transient_failure", stderr.strip().splitlines()[-1] if stderr.strip() else "ssh failed") |
There was a problem hiding this comment.
_classify_ssh_failure()'s auth markers are a strict subset of the prior bash classification (cmd_send.sh previously treated host key verification failures, key-changed warnings, and "no supported authentication" as auth-class failures). As written, those cases will now be misclassified as transient and get queued/retried, which is a behavior change and hides the "re-pair required" signal. Consider porting the full marker set from the removed bash grep to preserve behavior.
| provided we pass `-i`; otherwise ssh uses its default key search. | ||
|
|
||
| Splits user@host:port into user@host plus a separate -p port | ||
| argument (ssh's CLI doesn't accept :port in the host arg).""" | ||
| ssh_bin = _resolve_ssh_bin() | ||
| argv = [ssh_bin] | ||
| if identity_key: |
There was a problem hiding this comment.
_build_ssh_argv() always adds -i <identity_key> whenever identity_key is non-empty, even if the file doesn't exist. The old relay_ssh only used -i when the key file existed, otherwise it let ssh fall back to default key search. If you want behavior preservation, check the path exists before adding -i (and treat missing keys as either fallback or a structured auth/transient outcome rather than letting ssh fail with a confusing "Identity file ... not accessible").
| provided we pass `-i`; otherwise ssh uses its default key search. | |
| Splits user@host:port into user@host plus a separate -p port | |
| argument (ssh's CLI doesn't accept :port in the host arg).""" | |
| ssh_bin = _resolve_ssh_bin() | |
| argv = [ssh_bin] | |
| if identity_key: | |
| provided and the file exists we pass `-i`; otherwise ssh uses its | |
| default key search. | |
| Splits user@host:port into user@host plus a separate -p port | |
| argument (ssh's CLI doesn't accept :port in the host arg).""" | |
| ssh_bin = _resolve_ssh_bin() | |
| argv = [ssh_bin] | |
| if identity_key and os.path.exists(identity_key): |
| stdout = result.stdout.decode("utf-8", errors="replace") | ||
| stderr = result.stderr.decode("utf-8", errors="replace") | ||
|
|
||
| if "__APPENDED__" in stdout: |
There was a problem hiding this comment.
send() treats delivery as successful when "APPENDED" appears anywhere in stdout. Previously cmd_send.sh required an exact marker line (^__APPENDED__$), which is safer against banners/MOTD or other stdout noise. To preserve the old confirmation protocol, consider checking for a full-line marker in stdout (e.g., via splitlines) rather than substring matching.
| if "__APPENDED__" in stdout: | |
| if any(line == "__APPENDED__" for line in stdout.splitlines()): |
| local queue_marker; queue_marker=$(printf '{"from":"airc","ts":"%s","channel":"%s","msg":"[QUEUED to %s — %s]"}' \ | ||
| "$(timestamp)" "$active_channel" "$peer_name" "${detail:-peer offline}") | ||
| echo "$queue_marker" >> "$MESSAGES" | ||
| date +%s > "$AIRC_WRITE_DIR/last_sent" 2>/dev/null | ||
| rm -f "$AIRC_WRITE_DIR/reminded" 2>/dev/null | ||
| return 0 | ||
| ;; | ||
| auth_failure) | ||
| # Hard failure. Don't queue — every retry will fail identically. | ||
| # Surface loudly + die so the user re-pairs instead of sending | ||
| # into the void. | ||
| local fail_marker; fail_marker=$(printf '{"from":"airc","ts":"%s","channel":"%s","msg":"[AUTH FAILED to %s — repair required, NOT queued] %s"}' \ | ||
| "$(timestamp)" "$active_channel" "$peer_name" "${stderr:-no stderr}") | ||
| "$(timestamp)" "$active_channel" "$peer_name" "${detail:-no detail}") | ||
| echo "$fail_marker" >> "$MESSAGES" | ||
| echo " SSH auth to host FAILED. Message NOT queued — every retry would fail identically." >&2 | ||
| echo " SSH stderr: ${stderr}" >&2 | ||
| echo " Bearer: ${detail}" >&2 | ||
| echo " Fix: airc teardown --flush && airc connect <invite-string>" >&2 | ||
| die "Authentication failure — re-pair required" | ||
| fi | ||
|
|
||
| # Network-class wire failure: legitimately transient, queue for retry. | ||
| echo "$full_msg" >> "$AIRC_WRITE_DIR/pending.jsonl" | ||
| local queue_marker; queue_marker=$(printf '{"from":"airc","ts":"%s","channel":"%s","msg":"[QUEUED to %s — network error, will retry] %s"}' \ | ||
| "$(timestamp)" "$active_channel" "$peer_name" "${stderr:-no stderr}") | ||
| echo "$queue_marker" >> "$MESSAGES" | ||
| echo " Network error reaching host — message queued for retry. Monitor will flush when host returns." >&2 | ||
| # Surface the actual stderr so the user understands WHY — the old | ||
| # generic "host unreachable" was hiding real errors. | ||
| echo " SSH stderr: ${stderr:-<none>}" >&2 | ||
| else | ||
| rm -f "$err" | ||
| fi | ||
| ;; | ||
| transient_failure|"") | ||
| # Network-class failure or empty/malformed outcome → treat as | ||
| # transient + queue. Empty kind defends against bearer_cli | ||
| # crashing or outputting nothing — the message goes to pending | ||
| # rather than disappearing silently. | ||
| echo "$full_msg" >> "$AIRC_WRITE_DIR/pending.jsonl" | ||
| local queue_marker; queue_marker=$(printf '{"from":"airc","ts":"%s","channel":"%s","msg":"[QUEUED to %s — network error, will retry] %s"}' \ | ||
| "$(timestamp)" "$active_channel" "$peer_name" "${detail:-no detail}") | ||
| echo "$queue_marker" >> "$MESSAGES" |
There was a problem hiding this comment.
detail is interpolated directly into JSON strings via printf (e.g. [QUEUED ...] %s), but detail can contain quotes/backslashes/control chars (especially for resolver errors or raw ssh stderr). Without escaping, this can produce invalid JSON lines in messages.jsonl/pending markers and break downstream log parsing. Before embedding, JSON-escape and (optionally) truncate/sanitize detail similarly to the previous stderr-sanitization block that was removed.
| try: | ||
| bearer = resolve(peer_meta) | ||
| except Exception as e: # PeerUnreachable + any resolver-side error | ||
| # Surface as a transient failure outcome rather than crashing the | ||
| # caller. The caller's queue+retry path handles it. | ||
| print(json.dumps({"kind": "transient_failure", "detail": f"resolver error: {e}"})) | ||
| return 0 | ||
|
|
||
| bearer.open(args.peer_id) | ||
| payload = sys.stdin.buffer.read() | ||
| try: | ||
| outcome = bearer.send(args.peer_id, args.channel, payload) | ||
| finally: | ||
| bearer.close() |
There was a problem hiding this comment.
bearer_cli currently only wraps resolver errors; exceptions from bearer.open()/send() (e.g., missing ssh binary, missing host_target, unexpected subprocess errors) will raise and exit non-zero, which undermines the documented contract that callers should branch on the JSON outcome and can cause bash set -e aborts. Consider catching BearerError/Exception around open+send and printing a structured outcome (auth_failure/transient_failure) while still returning 0, reserving non-zero exit only for truly malformed CLI invocation.
| # No tailscale = always False. Just verify no crash on user@host form. | ||
| self.assertFalse(bearer_ssh._is_peer_offline_in_tailnet("[email protected]")) | ||
| self.assertFalse(bearer_ssh._is_peer_offline_in_tailnet("[email protected]")) |
There was a problem hiding this comment.
The offline-fast-path tests only cover [email protected] without a :port, but real host_target values are often user@ip:7547. Adding a test that includes the port suffix would catch the current mismatch between tailscale-status IPs and the host_target string (and prevent regressions in the fast-path behavior).
| # No tailscale = always False. Just verify no crash on user@host form. | |
| self.assertFalse(bearer_ssh._is_peer_offline_in_tailnet("[email protected]")) | |
| self.assertFalse(bearer_ssh._is_peer_offline_in_tailnet("[email protected]")) | |
| # No tailscale = always False. Just verify no crash on | |
| # user@host and user@host:port forms. | |
| self.assertFalse(bearer_ssh._is_peer_offline_in_tailnet("[email protected]")) | |
| self.assertFalse(bearer_ssh._is_peer_offline_in_tailnet("[email protected]:7547")) | |
| self.assertFalse(bearer_ssh._is_peer_offline_in_tailnet("[email protected]")) | |
| self.assertFalse(bearer_ssh._is_peer_offline_in_tailnet("[email protected]:7547")) |
| ALL SSH-specific knowledge lives in this module: ssh binary location, key | ||
| selection, host/port resolution, MSYS path translation, the | ||
| selection, host/port resolution, MSYS path handling on Windows, the | ||
| `__APPENDED__` confirmation protocol, error classification (auth vs | ||
| network), pending-queue semantics for offline peers. Code outside this | ||
| file does not mention SSH. | ||
| network), Tailscale-CGNAT offline-detection fast-path. Code outside this | ||
| file does not mention SSH or Tailscale. |
There was a problem hiding this comment.
The module docstring claims "Code outside this file does not mention SSH or Tailscale", but the repo still has non-bearer Tailscale/SSH references (e.g. airc's advise_tailscale_if_down() and install scripts). Consider narrowing/rephrasing this statement (e.g. "cmd_send path does not mention..."), otherwise it's misleading for future maintainers grepping for these terms.
| # Strip user@ prefix if present. | ||
| host = host_target.split("@", 1)[-1] | ||
| if not _CGNAT_RE.match(host): | ||
| return False | ||
| ts_bin = _resolve_tailscale_bin() | ||
| if not ts_bin: | ||
| return False | ||
| try: | ||
| result = subprocess.run( | ||
| [ts_bin, "status"], | ||
| capture_output=True, | ||
| text=True, | ||
| timeout=5, | ||
| ) | ||
| except (subprocess.TimeoutExpired, OSError): | ||
| return False | ||
| if result.returncode != 0: | ||
| return False | ||
| # tailscale status format: "<IP> <hostname> <owner> <os> <state...>" | ||
| # Match target IP at column 1 + the literal word "offline" anywhere on | ||
| # the same line. | ||
| for line in result.stdout.splitlines(): | ||
| cols = line.split() | ||
| if not cols: | ||
| continue | ||
| if cols[0] == host and "offline" in line: | ||
| return True |
There was a problem hiding this comment.
_is_peer_offline_in_tailnet() compares tailscale-status column 1 (an IP) against host, but host may still include the SSH port suffix (e.g. 100.64.0.1:7547 after stripping user@). In that common case this can never match, so the offline fast-path will never engage. Strip a trailing :port from the host before the status-line comparison (while keeping the existing user@ stripping and CGNAT gate).
…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]>
Summary
Phase 1 of the bearer rewrite. `cmd_send.sh`'s SSH delivery primitive is now in `lib/airc_core/bearer_ssh.py` — `relay_ssh` invocation, `APPENDED` confirmation, Tailscale-CGNAT offline fast-path, and auth-vs-transient classification all live in one module. `cmd_send.sh` shrinks to "build envelope, hand to bearer, branch on SendOutcome.kind."
What this proves
The seam carries weight. Adding a new transport (gh, Reticulum, anything) to the send path no longer touches `cmd_send.sh` — only the resolver registers it. This is the modularity property #270 root-caused as missing.
What moved
CGNAT regex, ssh option set, identity-key handling, `user@` prefix strip (issue #78 defense) all preserved literally.
How cmd_send invokes the bearer
```bash
outcome=$(printf '%s' "$full_msg" | "$AIRC_PYTHON" -m airc_core.bearer_cli send \
"$peer_name" "$active_channel" \
--host-target "$host_target" \
--identity-key "$IDENTITY_DIR/ssh_key" \
--remote-home "$rhome")
kind=$(echo "$outcome" | python3 -c '...json.load...kind...')
case "$kind" in
delivered) ;;
queued_unreachable) # write [QUEUED ... peer offline ...]
auth_failure) # write [AUTH FAILED ...] + die loudly
transient_failure) # write [QUEUED ... network error ...]
esac
```
SendOutcome contract
Added to `bearer.py`. Bearers return a structured `SendOutcome` (kind + detail) instead of raising on normal failure modes. Kinds are enumerated + bearer-agnostic — any future bearer populates the same set so callers never branch on transport.
```python
@DataClass(frozen=True)
class SendOutcome:
kind: str # "delivered" | "queued_unreachable" | "auth_failure" | "transient_failure"
detail: str = ""
```
Tests
25 unit tests (10 new). All green locally.
Behavior preservation
All cmd_send paths produce identical user-visible output:
The integration suite (runs on canary push) will exercise these end-to-end.
Phase plan
Test plan
🤖 Generated with Claude Code