Skip to content

feat(airc_core): joiner handshake send → airc_core.handshake.send (#152 Phase 1) - #170

Merged
joelteply merged 1 commit into
canaryfrom
feat/airc-core-handshake-build
Apr 27, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/airc-core-handshake-build

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

The joiner's pair-handshake send was a 23-line inline `python -c` heredoc with five bash-variable substitutions into the python source. Migrated to airc_core.handshake.send via env vars.

What

`airc_core.handshake.send(host, port)` reads MY_NAME / MY_HOST / MY_SSH_PUB / MY_SIGN_PUB / MY_AIRC_HOME / MY_IDENTITY from env. Bash callsite is a 8-line env-var-pass + module call.

Why

  • ssh_pub may have trailing newline (openssh-keygen quirk)
  • identity is JSON-encoded user text (apostrophes, etc.)
  • All five values previously substituted INTO python source code

Same silent-fail class continuum traced today.

Test posture

scenario result
tabs 19/19
identity 19/19
whois 5/5
kick 12/12
part_persists 8/8

Phase 1 progress

5 migrations merged today: foundation (#166) + config CRUD (#167) + handshake parse (#168) + scope cleanup (#169) + this PR. Next targets: host's response BUILDER (line ~3236), self-heal heredocs, then monitor_formatter (the big one).

… Phase 1)

The pair-handshake send was an inline `python -c` heredoc with FIVE
bash-variable substitutions into the python source — name, host,
ssh_pub, sign_pub, airc_home — plus the connect target as `('$peer_host_only', $peer_port)`.
Any unusual character in any field could silently break python parsing.
Specifically host_ssh_pub may contain a trailing newline (depending on
how openssh-keygen wrote the .pub file); host_target may contain
characters that need quoting; identity is a JSON-encoded blob of
arbitrary user-set text. Each was a per-callsite silent-fail.

## Migration

`airc_core.handshake.send(host, port)` reads all six fields from env:
MY_NAME, MY_HOST, MY_SSH_PUB, MY_SIGN_PUB, MY_AIRC_HOME, MY_IDENTITY.
Builds the JSON payload, opens TCP socket, sends, reads response,
returns it as a string. Exceptions surface to stderr (matches the
never-swallow-errors rule); bash captures stderr via `2>&1`.

Bash callsite shrinks from 23 lines (inline python heredoc) to 8
lines (env-var pass + module call):

    response=$(MY_NAME="$my_name" \
               MY_HOST="$(whoami)@$(get_host)" \
               MY_SSH_PUB="$my_ssh_pub" \
               MY_SIGN_PUB="$my_sign_pub" \
               MY_AIRC_HOME="$AIRC_WRITE_DIR" \
               MY_IDENTITY="$my_identity_json" \
               "$AIRC_PYTHON" -m airc_core.handshake send "$peer_host_only" "$peer_port" 2>&1) || _pair_ok=0

## Test posture

Pair-handshake exercising scenarios all green:
- tabs: 19/19 (two-tab pair on localhost — exercises send + receive)
- identity: 19/19 (exchange identity at handshake)
- whois: 5/5 (read identity from response)
- kick: 12/12 (multi-peer pairing)
- part_persists: 8/8 (sidecar + primary spawning)

## Phase 1 progress

- ✓ iso_to_epoch (Phase 0a, PR #166)
- ✓ config CRUD core (PR #167)
- ✓ handshake response parse (PR #168)
- ✓ _whois_in_scope cleanup (PR #169)
- ✓ joiner handshake send (this PR)
- next: host's response builder (line ~3236), self-heal/discovery
        heredocs, monitor_formatter
Copilot AI review requested due to automatic review settings April 27, 2026 22:22
@joelteply
joelteply merged commit 100dd00 into canary Apr 27, 2026
2 checks passed
@joelteply
joelteply deleted the feat/airc-core-handshake-build branch April 27, 2026 22:23

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Migrates the joiner-side pair-handshake “send” logic out of an inline bash python -c heredoc and into the Python truth-layer (airc_core.handshake.send), reducing fragility from bash string substitution and improving handling of special characters/newlines in payload fields.

Changes:

  • Adds airc_core.handshake.send(host, port) to build the joiner payload from env vars, perform the TCP exchange, and return the host response as a string.
  • Updates the joiner handshake callsite in airc to pass payload fields via MY_* env vars and invoke "$AIRC_PYTHON" -m airc_core.handshake send ....

Reviewed changes

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

File Description
lib/airc_core/handshake.py Introduces send() and a new send CLI subcommand to perform the joiner-side TCP handshake using env-provided payload fields.
airc Replaces the inline Python heredoc for joiner handshake send with a module call to airc_core.handshake send, passing data via env vars.

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

Comment on lines +65 to +76
s = sock_mod.socket(sock_mod.AF_INET, sock_mod.SOCK_STREAM)
s.settimeout(30)
s.connect((host, int(port)))
s.sendall((payload + "\n").encode())
s.shutdown(sock_mod.SHUT_WR)
data = b""
while True:
chunk = s.recv(4096)
if not chunk:
break
data += chunk
s.close()

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

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

send() opens a TCP socket but doesn’t guarantee it gets closed if any step raises (connect/send/shutdown/recv/timeout/JSON errors). This can leak file descriptors and leave half-open sockets during repeated connect attempts. Please wrap the socket in a context manager or try/finally so it is always closed (and consider socket.create_connection(..., timeout=30) for simpler setup).

Suggested change
s = sock_mod.socket(sock_mod.AF_INET, sock_mod.SOCK_STREAM)
s.settimeout(30)
s.connect((host, int(port)))
s.sendall((payload + "\n").encode())
s.shutdown(sock_mod.SHUT_WR)
data = b""
while True:
chunk = s.recv(4096)
if not chunk:
break
data += chunk
s.close()
data = b""
with sock_mod.create_connection((host, int(port)), timeout=30) as s:
s.sendall((payload + "\n").encode())
s.shutdown(sock_mod.SHUT_WR)
while True:
chunk = s.recv(4096)
if not chunk:
break
data += chunk

Copilot uses AI. Check for mistakes.
Comment on lines +115 to +116
# rule.
print(f"airc-handshake-send-error: {e}", file=sys.stderr)

Copilot AI Apr 27, 2026

Copy link

Choose a reason for hiding this comment

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

The CLI error emitted for send only prints str(e), which can lose useful debugging context (exception type, host/port). Since this output is surfaced to users via the bash 2>&1 capture, consider including the exception class and the target host:port to make failures actionable (e.g., distinguish timeout vs. DNS vs. refused).

Suggested change
# rule.
print(f"airc-handshake-send-error: {e}", file=sys.stderr)
# rule. Include endpoint + exception class so failures are
# actionable (for example: timeout vs DNS vs refused).
print(
f"airc-handshake-send-error: {host}:{port} "
f"{type(e).__name__}: {e}",
file=sys.stderr,
)

Copilot uses AI. Check for mistakes.
joelteply added a commit that referenced this pull request Apr 27, 2026
…-line migration, biggest single heredoc) (#171)

feat(airc_core): monitor_formatter → airc_core.monitor_formatter (#152 Phase 1, biggest single migration)

The biggest single heredoc in airc bash. ~250 lines of Python embedded
in a `"$AIRC_PYTHON" -u -c '...'` block, complete with apostrophe-
escape gymnastics like `caller'\''s` and `Joel'\''s` because bash
single-quoting required them. Migrated to a proper Python module.

## Impact

airc bash file: **5897 → 5647 lines** (−250 lines, ~4.2% reduction
of the entire script).

The migrated function had:
- Inactivity watchdog (cross-platform: SIGALRM on POSIX,
  threading.Timer on Windows)
- [rename] handler with chain-repair via stable host id
- Ping/pong control message handling with auto-pong subprocess.Popen
- Own-send filtering with mid-session rename support
- Inbound mirror-to-local-log for joiners (avoids feedback loop on
  hosts)
- Belt-and-suspenders error handling per line so one bad message
  doesn't kill the formatter

All preserved verbatim — same logic, same stdin/stdout contract.
The CLI shape:

    PEERS_DIR=<peers-dir> "$AIRC_PYTHON" -u -m airc_core.monitor_formatter <my_name>

Bash function shrinks to 4 lines (was 268).

## Why a real .py file matters here

The bash heredoc had:
- `'\''` shell-escape sequences scattered through comments (caller's
  → caller'\''s) — readable Python source now restores natural
  apostrophes.
- No editor syntax highlighting for python (it was inside a bash
  string).
- No way to unit-test individual functions (_rename_files,
  _find_peer_by_host) without invoking the whole bash + airc stack.

Now the module is a regular Python file: lints, syntax-highlights,
unit-testable, importable from other airc_core modules if needed.

## Test posture

84 assertions pass across 8 scenarios touching monitor_formatter
(every scenario that pairs + sends/receives):

- tabs: 19/19 (two-tab message exchange)
- identity: 19/19 (identity round-trip + rename)
- whois: 5/5 (host_identity propagation)
- part_persists: 8/8 (sidecar + primary monitor active)
- list: 4/4
- general_sidecar_default: 12/12
- kick: 12/12 (multi-peer monitor traffic)
- events: 5/5 (system-event formatting)

## Phase 1 progress

- ✓ iso_to_epoch (Phase 0a, PR #166)
- ✓ config CRUD core (PR #167)
- ✓ handshake response parse (PR #168)
- ✓ _whois_in_scope cleanup (PR #169)
- ✓ joiner handshake send (PR #170)
- ✓ monitor_formatter (this PR — biggest single migration)
- next: host's pair-handshake handler heredocs, smaller cleanups
joelteply added a commit that referenced this pull request Apr 27, 2026
…#152 Phase 1) (#172)

feat(airc_core): host pair-handshake accept_one → airc_core.handshake.accept_one (#152 Phase 1)

Symmetric counterpart of PR #170 (joiner send) — the HOST'S accept-
and-respond heredoc, biggest remaining bash-into-python heredoc with
substituted variables. 127 lines of Python with EIGHT bash variable
substitutions migrated to a clean Python module.

## Substitutions previously inline

- $host_port — the listen port (numeric, but bare-substituted)
- $PEERS_DIR — joiner's peer file path
- $(timestamp) — bash command-substitution INTO python (highest risk)
- $IDENTITY_DIR — host's ssh_key.pub source
- $CONFIG — host's identity load path
- $name — host's identity name
- $reminder_interval — numeric reminder interval
- $AIRC_WRITE_DIR — host's airc_home (sent in response)
- $MESSAGES — system-event log path

Each was a per-callsite silent-fail vector. Continuum traced the
write-side variant (#165) earlier today.

## Migration

`airc_core.handshake.accept_one()` reads all from env vars (HOST_PORT,
PEERS_DIR, IDENTITY_DIR, CONFIG, HOST_NAME, REMINDER_INTERVAL,
AIRC_WRITE_DIR, MESSAGES). Bash callsite shrinks from 127 lines
(heredoc body) to a 9-line env-var-pass + module call.

Same logic preserved verbatim — accept-with-timeout, parent-death
detection (`os.getppid() == 1`), authorize joiner SSH key, write peer
record (with stable-host stale cleanup), build response, write
peer-joined system event. The outer `while true; do ... done &`
bash loop unchanged.

## Impact

- airc bash: 5647 → 5529 (-118 lines)
- Cumulative today (Phase 1): ~370 lines moved out of bash to
  testable Python modules.

## Test posture (Mac, 89 assertions / 9 scenarios)

- tabs: 19/19 (two-tab pair on localhost — exercises full accept
  loop end-to-end)
- scope: 5/5 (multi-cwd pairing across scopes)
- identity: 19/19 (identity exchange at handshake)
- whois: 5/5
- kick: 12/12 (multi-peer, multiple accepts)
- part_persists: 8/8
- list: 4/4
- general_sidecar_default: 12/12
- events: 5/5 (peer-joined system event emission)

## Phase 1 progress

- ✓ iso_to_epoch, config CRUD, handshake parse, _whois cleanup,
  joiner send, monitor_formatter (PRs #166-#171)
- ✓ host accept_one (this PR)
- next: smaller cleanups (lan_ip resolver, identity/peer config writes,
  remaining gist-envelope bash heredocs)
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.

2 participants