Repository navigation
Conversation
refactor(platform): extract proc/port/file/platform adapters; route all callsites through them Joel, 2026-04-26: 'we mess each other up if we dont abstract.' / 'fixing one [platform] can degrade the other.' Multiple AIs working on the same codebase across Mac/Linux/WSL/Windows-Git-Bash repeatedly retouched the same inline pgrep/lsof/stat patterns; each tweak risked diverging from the others. The fix is to consolidate all platform-specific shell calls behind named adapters so business logic stays platform-agnostic and porting work happens in one place per capability. ## New adapters (top of file, just before relay_ssh) - `proc_children <pid>` — direct children of PID, one per line. pgrep -P primary; ps -axo pid,ppid + awk fallback for envs without pgrep (Git Bash for Windows ships only msys coreutils). - `proc_parent <pid>` — PPID. ps -p X -o ppid= cross-platform. - `proc_cmdline <pid>` — full argv. ps -p X -o command=. - `proc_airc_pids_matching <regex>` — airc-related PIDs owned by current user, used by `airc teardown --all`. pgrep -u + -f primary; ps + awk fallback. - `port_listeners <port>` — PIDs listening on a TCP port. lsof primary (mac/most linux); ss fallback (modern linux); netstat -ano fallback (Windows native + minimal containers). Empty output = nobody listening. - `file_size <path>` — bytes. stat -f%z (BSD) → stat -c%s (GNU) → wc -c fallback (POSIX-portable). - `detect_platform` — emits macos/linux/wsl/windows-bash/unknown. WSL detection unified via /proc/version content match. Reserved for the rare case where a top-level decision genuinely depends on platform (e.g. Tailscale.app launching) — most callers should use the proc_/ port_/file_ adapters which handle differences internally. ## Callsites converted - 8 inline `pgrep -P <pid>` sites → `proc_children` - 2 inline `pgrep -u $(id -u) -f <pattern>` sites → `proc_airc_pids_matching` - 4 inline `lsof -tiTCP:<port> -sTCP:LISTEN` sites → `port_listeners` - 3 inline `ps -p <pid> -o ppid= | tr -d ' '` and `ps -p <pid> -o command=` sites → `proc_parent` / `proc_cmdline` - 1 inline `stat -f%z X || stat -c%s X || echo 0` site → `file_size` Inline `case "$(uname -s)"` blocks for tailscale-down guidance and machine_id lookup were NOT converted to `detect_platform`. Those blocks do platform-specific WORK (different commands per platform), not platform-specific abstraction of one shape — converting them would be larger surface-area for marginal cleanup. detect_platform stays available for future per-platform decisions. ## Tests - scenario_platform_adapters — 8 assertions exercising each adapter with a synthetic process tree + listener. proc_children sees a spawned sleep; proc_parent returns the harness PID; proc_cmdline contains 'sleep'; port_listeners finds a python listener on a random high port; file_size returns 11 for 'hello world' and 0 for missing files; detect_platform returns a valid value matching uname. - scenario_general_sidecar_default fixed — was reading primary's airc.pid for sidecar PID, stale since #125 separated sidecar pidfiles. Now reads ${home}.general/airc.pid via awk '{print $1; exit}' to extract first PID from the multi-PID host-mode line. ## Mac/Linux regression sweep Full suite (mode=all) ran post-refactor: - 194 assertions pass - 1 flake (rename propagation in scenario_tabs — passed on retry, pre- existing intermittent timing issue, not caused by this refactor) No new platform dependencies introduced. The adapters add fallback paths that activate on platforms the inline calls didn't support (e.g. Git Bash without pgrep), so this is strictly more portable than what was on canary before, while behavior on Mac/Linux is unchanged. ## Why now Joel asked to take this on while he prepares to rebuild the Windows side. With adapters in place, each Windows fallback bug becomes a one-helper edit with a contained blast radius. Without adapters, every Windows fix risks breaking the Mac/Linux paths it touches. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
) (#131) The resume code path had its own SSH probe / stale-gist 404 self-heal / stale-auth recovery / unreachable-host takeover — all duplicated from the discovery + JOIN MODE flow. Worse, its SSH probe could "succeed" against an unreachable cached host (orphaned pair-listener answering on the cached port), printing "(SSH verified)" against a ghost. Outbound messages then vaporized; user couldn't tell paired from broken. Architectural fix: gist is the source of truth. Cached host_target / host_port / host_ssh_pub are stale snapshots of external substrate state. Every `airc connect` runs discovery and re-pairs fresh. Cost: one `gh gist list` (~200ms). Benefit: structurally impossible to print "(SSH verified)" against a host we haven't actually verified, and the entire "saved pairing diverged from gist" failure class disappears. What stays: identity (ssh keys, name, identity blob), peer records, saved room_name file (the one piece of cross-restart state worth trusting — which room you were last in). Discovery + JOIN MODE already handle stale-heartbeat takeover, TCP-unreachable self-heal, race-loser detection, and host_target overwrite on successful pair. Tests: removed five resume-specific scenarios whose assertions described code paths that no longer exist (resume_stale_auth, room_overrides_resume, stale_auth_room_selfheal, resume_404_gist_no_silent_exit, resume_prints_connected_banner). Added scenario_connect_after_kill_recovers which proves the architectural property end-to-end with real gh: pair, kill host, reconnect — assert no resume-banner ever prints, and beta lands in a working state. Net: 702 deletions, 159 insertions. Same end-state behavior under every recovery scenario the deleted resume code was trying to handle, just exercised through one path instead of two. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Promotes the canary refactors to main by (1) removing the cmd_connect resume path in favor of always running gist-backed discovery, and (2) extracting platform-specific process/port/filesystem calls into a dedicated “Platform adapters” section with a new integration scenario to validate adapter contracts.
Changes:
- Remove resume-path logic/tests and add a new architectural-property scenario (
connect_after_kill_recovers) asserting cached pairing is never trusted. - Add “Platform adapters” helpers (
proc_*,port_*,file_*,detect_platform) and convert key callsites to use them. - Update sidecar PID expectations and add an integration scenario that extracts/sources the adapter block for cross-platform validation.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
airc |
Adds platform adapter helpers and switches multiple callsites to use them; removes resume logic and adjusts auto-room behavior to honor saved room_name. |
test/integration.sh |
Deletes resume-specific scenarios, adds connect_after_kill_recovers, adjusts sidecar PID assertions, and adds scenario_platform_adapters. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | ||
| elif command -v ss >/dev/null 2>&1; then | ||
| # ss output: 'LISTEN 0 ... users:(("python",pid=12345,fd=4))' | ||
| # Awk extracts pid= number. | ||
| ss -tlnp "( sport = :$port )" 2>/dev/null \ | ||
| | awk 'NR>1 { match($0, /pid=[0-9]+/); if (RSTART) print substr($0, RSTART+4, RLENGTH-4) }' | ||
| elif command -v netstat >/dev/null 2>&1; then | ||
| # netstat -ano output (Windows + some Linux): | ||
| # TCP 0.0.0.0:7547 0.0.0.0:0 LISTENING 12345 | ||
| # Trailing column is PID. Match $port at end of local-address column. | ||
| netstat -ano 2>/dev/null \ | ||
| | awk -v p=":$port" '$2 ~ p"$" && /LISTEN/ { print $NF }' | ||
| fi |
There was a problem hiding this comment.
port_listeners calls lsof/ss/netstat without guarding their exit codes. Both lsof -t and ss commonly return non-zero when there are no matching listeners; under set -euo pipefail that can abort airc during normal “port is free” checks. Make port_listeners always exit 0 and emit empty output when there are no listeners or when no backend tool is available (e.g., add || true to the backend commands and a final return 0).
| lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | |
| elif command -v ss >/dev/null 2>&1; then | |
| # ss output: 'LISTEN 0 ... users:(("python",pid=12345,fd=4))' | |
| # Awk extracts pid= number. | |
| ss -tlnp "( sport = :$port )" 2>/dev/null \ | |
| | awk 'NR>1 { match($0, /pid=[0-9]+/); if (RSTART) print substr($0, RSTART+4, RLENGTH-4) }' | |
| elif command -v netstat >/dev/null 2>&1; then | |
| # netstat -ano output (Windows + some Linux): | |
| # TCP 0.0.0.0:7547 0.0.0.0:0 LISTENING 12345 | |
| # Trailing column is PID. Match $port at end of local-address column. | |
| netstat -ano 2>/dev/null \ | |
| | awk -v p=":$port" '$2 ~ p"$" && /LISTEN/ { print $NF }' | |
| fi | |
| lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null || true | |
| elif command -v ss >/dev/null 2>&1; then | |
| # ss output: 'LISTEN 0 ... users:(("python",pid=12345,fd=4))' | |
| # Awk extracts pid= number. | |
| ss -tlnp "( sport = :$port )" 2>/dev/null \ | |
| | awk 'NR>1 { match($0, /pid=[0-9]+/); if (RSTART) print substr($0, RSTART+4, RLENGTH-4) }' \ | |
| || true | |
| elif command -v netstat >/dev/null 2>&1; then | |
| # netstat -ano output (Windows + some Linux): | |
| # TCP 0.0.0.0:7547 0.0.0.0:0 LISTENING 12345 | |
| # Trailing column is PID. Match $port at end of local-address column. | |
| netstat -ano 2>/dev/null \ | |
| | awk -v p=":$port" '$2 ~ p"$" && /LISTEN/ { print $NF }' \ | |
| || true | |
| fi | |
| return 0 |
| # ── Kill alpha hard. SIGKILL bypasses alpha's EXIT trap, so alpha's | ||
| # gist is left STALE on gh (host process gone, gist still exists). | ||
| # This is the worst case: a cached pairing pointing at a dead host | ||
| # whose gist still resolves. | ||
| AIRC_HOME=/tmp/airc-it-cakr-h/state "$AIRC" teardown >/dev/null 2>&1 | ||
| # teardown deletes the gist gracefully — do that for round 1 to | ||
| # exercise the gist-gone case. (The TCP-unreachable-but-gist-alive | ||
| # case is exercised by scenario_two_tab_localhost's host-crash branch.) |
There was a problem hiding this comment.
This scenario’s comments say “Kill alpha hard. SIGKILL bypasses alpha's EXIT trap, so alpha's gist is left STALE on gh”, but the code actually runs airc teardown, which is the graceful path that deletes the gist. Please align the comments with the actual behavior (gist-gone case) or change the code to perform a real hard kill if that’s what you intend to test.
| # ── Kill alpha hard. SIGKILL bypasses alpha's EXIT trap, so alpha's | |
| # gist is left STALE on gh (host process gone, gist still exists). | |
| # This is the worst case: a cached pairing pointing at a dead host | |
| # whose gist still resolves. | |
| AIRC_HOME=/tmp/airc-it-cakr-h/state "$AIRC" teardown >/dev/null 2>&1 | |
| # teardown deletes the gist gracefully — do that for round 1 to | |
| # exercise the gist-gone case. (The TCP-unreachable-but-gist-alive | |
| # case is exercised by scenario_two_tab_localhost's host-crash branch.) | |
| # ── Shut alpha down gracefully. This runs `airc teardown`, which | |
| # triggers alpha's normal cleanup path and deletes its gist on gh. | |
| # For this round we want a cached pairing pointing at a dead host | |
| # whose gist is gone, so beta must recover from the gist-gone case. | |
| AIRC_HOME=/tmp/airc-it-cakr-h/state "$AIRC" teardown >/dev/null 2>&1 | |
| # The TCP-unreachable-but-gist-alive case is exercised by | |
| # scenario_two_tab_localhost's host-crash branch. |
| pgrep -P "$pid" 2>/dev/null | ||
| else | ||
| # POSIX-portable fallback. Works on Git Bash (msys ps), Linux ps, | ||
| # macOS ps. Awk filters by ppid column. | ||
| ps -axo pid,ppid 2>/dev/null | awk -v p="$pid" '$2 == p { print $1 }' |
There was a problem hiding this comment.
Under set -euo pipefail, pgrep -P exits with status 1 when there are no child processes. In proc_children, that non-zero exit will trigger errexit and can abort the entire script even though “no children” is a normal outcome. Make this adapter always succeed (exit 0) and return empty output when there are no children (e.g., guard pgrep with || true, and ensure the ps+awk pipeline can’t trip errexit).
| pgrep -P "$pid" 2>/dev/null | |
| else | |
| # POSIX-portable fallback. Works on Git Bash (msys ps), Linux ps, | |
| # macOS ps. Awk filters by ppid column. | |
| ps -axo pid,ppid 2>/dev/null | awk -v p="$pid" '$2 == p { print $1 }' | |
| pgrep -P "$pid" 2>/dev/null || true | |
| else | |
| # POSIX-portable fallback. Works on Git Bash (msys ps), Linux ps, | |
| # macOS ps. Awk filters by ppid column. | |
| ps -axo pid,ppid 2>/dev/null | awk -v p="$pid" '$2 == p { print $1 }' || true |
| proc_airc_pids_matching() { | ||
| local pattern="$1" | ||
| [ -z "$pattern" ] && return 0 | ||
| if command -v pgrep >/dev/null 2>&1; then | ||
| pgrep -u "$(id -u)" -f "$pattern" 2>/dev/null | ||
| else | ||
| # Fallback: ps + awk. Less precise than pgrep -f (no anchored regex) | ||
| # but covers the same shape. Filter by user since msys ps -u option | ||
| # may not match POSIX semantics. | ||
| local me; me=$(whoami 2>/dev/null) | ||
| ps -axo pid,user,command 2>/dev/null \ | ||
| | awk -v u="$me" -v p="$pattern" 'NR>1 && $2 == u && $0 ~ p { print $1 }' | ||
| fi |
There was a problem hiding this comment.
proc_airc_pids_matching uses pgrep, which returns exit status 1 when there are no matches. With set -e, that can terminate airc even though “no matching processes” is expected. Consider making this adapter consistently exit 0 with empty output on “no matches” (e.g., pgrep ... || true), similar to the old callsites that had || true everywhere.
Summary
Promotes two canary commits to main:
83cd508) —refactor(connect): always discover; delete resume code path (closes #130). Deletes ~250 lines of duplicated state-handling. Ghost-pairing class structurally impossible.146aea1) —refactor(platform): extract proc/port/file/platform adapters.Verified end-to-end
Three-tab mesh on canary
83cd508confirmed cross-tab interop:vhsm-d1f4hosting#useideem+#generalsidecar — took over a 45-min-stale gist via discovery+self-heal with zero resume-language ✓continuum-b741joined#general— independently verifiedsaved → not-found → fresh host, no banneron its end ✓authenticator-fd63joined#useideem+#general— third-tab interop confirmed ✓Integration suite: 181 passes against
83cd508. The 3 pre-existing failures (port still held after teardown,alpha still listening after teardown,beta did NOT see rename marker) are tracked separately in #132 — orphan-survival of pair-listener Python andairc connectbash when launching subshells exit. They predate this promotion and are independent.Test plan
bash test/integration.sh connect_after_kill_recoverspasses (7/7) — new architectural-property testbash test/integration.sh auto_scopepasses (4/4)bash test/integration.sh bouncepasses (4/4)bash test/integration.sh roompasses (14/14)bash test/integration.sh general_sidecar_defaultpasses (12/12)bash test/integration.sh send_room_flagpasses (8/8)🤖 Generated with Claude Code