Skip to content

feat(airc_core): handshake response parser → airc_core.handshake (#152 Phase 1) - #168

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

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

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Continuing the Python truth-layer migration. Four heredocs that parse the host's handshake response (`ssh_pub`, `airc_home`, `identity`, `reminder`) now route through `airc_core.handshake`.

What

  • New `lib/airc_core/handshake.py` — `get_field` reads JSON from stdin, prints field value or default.
  • Bash callsites: `echo "$response" | "$AIRC_PYTHON" -m airc_core.handshake get_field [default]`.

Why

Pre-migration each callsite was an inline python heredoc with bash variable substitution (`'FIELD'` substituted in). Same silent-fail class continuum found in the write-side (PR #165). Now python source is fixed bytes; field name + default come via argv.

Test posture

scenario result
identity 19/19
whois 5/5
part_persists 8/8
list 4/4
general_sidecar_default 12/12
kick 12/12

Plus CLI unit tests covering valid response, missing field with default, nested object round-trip, empty/garbage stdin.

Phase 1 progress

…Phase 1)

Four field-extract sites for the host's handshake response (ssh_pub,
airc_home, identity, reminder) were inline `python3 -c "import sys,
json; print(json.load(sys.stdin).get('FIELD',''))"` heredocs. Same
class as get_config_val pre-PR #167 — bash variable substitution
into python source is a per-callsite silent-fail vector if the
embedded value drifts.

Now: response JSON via stdin; field name + default via argv.
Python source is fixed bytes.

## CLI shape

```
echo "$response" | "$AIRC_PYTHON" -m airc_core.handshake get_field <name> [default]
```

Handles dict / list values via json.dumps so callers can re-parse
(needed for the identity field, which is a nested object).

## Test posture

- identity: 19/19
- whois: 5/5
- part_persists: 8/8
- list: 4/4
- general_sidecar_default: 12/12
- kick: 12/12

Plus direct CLI unit tests (valid response, missing field with
default, nested object round-trip, empty stdin → default, garbage
input → default).

## What's left in handshake-related code

- Host's response BUILDER (line 3236, builds the JSON payload the
  joiner reads). Bash-substitutes name + airc_home + identity into
  python source. Same class. Migrate next.
- Joiner's payload BUILDER (line 2580, sends payload TO host).
  Same pattern; same class.

Both are smaller migrations following the same shape.
Copilot AI review requested due to automatic review settings April 27, 2026 21:57
@joelteply
joelteply merged commit db89174 into canary Apr 27, 2026
2 checks passed
@joelteply
joelteply deleted the feat/airc-core-handshake-parse branch April 27, 2026 21:57

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 joiner-side handshake response field extraction (ssh_pub, airc_home, identity, reminder) from inline python -c heredocs to a dedicated airc_core.handshake module, continuing the Python truth-layer migration.

Changes:

  • Added lib/airc_core/handshake.py with a get_field CLI that reads JSON from stdin and prints a requested field with an optional default.
  • Updated airc join flow to call python -m airc_core.handshake get_field ... for the four handshake-parsed fields.
  • Switched the bash plumbing to use printf '%s' for piping the JSON response into Python (instead of echo).

Reviewed changes

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

File Description
lib/airc_core/handshake.py New CLI module for extracting fields from handshake JSON read from stdin.
airc Replaces four inline Python heredocs with airc_core.handshake get_field calls.

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

Comment on lines +18 to +19
Empty stdout on parse failure (matches the bash `|| true` fallback
pattern). Exit always 0 — caller checks the value.

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 module docstring says the CLI has "Empty stdout on parse failure" and that the "Exit always 0", but _cli() returns exit code 2 for missing/unknown subcommands and prints the provided default (which may be non-empty) when JSON parsing fails. Please update the docstring to match actual stdout/exit-code behavior (or adjust _cli() to meet the documented contract).

Suggested change
Empty stdout on parse failure (matches the bash `|| true` fallback
pattern). Exit always 0 — caller checks the value.
For `get_field`, invalid or non-object JSON behaves like an empty
object: the command prints the provided default, or an empty string
if no default was given. Successful `get_field` execution exits 0.
CLI usage errors (missing/unknown subcommands or missing field name)
exit 2; unknown subcommands also write a message to stderr.

Copilot uses AI. Check for mistakes.
Comment on lines +54 to +61
v = obj.get(field, default)
# Numbers (e.g. reminder=300) round-trip cleanly through str();
# nested objects (e.g. identity={}) need json.dumps so callers
# get a parseable string back rather than Python repr.
if isinstance(v, (dict, list)):
print(json.dumps(v))
else:
print(v if v != "" else default)

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.

v = obj.get(field, default) can yield None when the JSON explicitly contains null, and the current code will print None rather than falling back to default. To match the surrounding convention in airc_core.config.get() (treat None as missing), consider mapping None to default before printing.

Copilot uses AI. Check for mistakes.
Comment on lines +14 to +20
CLI:

echo "$response" | python -m airc_core.handshake get_field <name> [default]

Empty stdout on parse failure (matches the bash `|| true` fallback
pattern). Exit always 0 — caller checks the value.
"""

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.

PR description mentions adding "CLI unit tests" for this module, but this change set only adds the new module + bash callsite updates (no new/updated test files). If the tests are intended to be part of this PR, please include them; otherwise consider updating the PR description to avoid implying new committed test coverage.

Copilot uses AI. Check for mistakes.
joelteply added a commit that referenced this pull request Apr 27, 2026
… heredocs (#152 Phase 1 cleanup) (#169)

feat(airc_core): collapse _whois_in_scope + resolve_name + cmd_rename heredocs into get_config_val[_in] (#152 Phase 1)

Cleanup pass following PR #167/#168. Eight more inline `python -c`
heredocs collapsed into one-line calls now that airc_core.config
handles the read pattern.

## Sites migrated

1. **resolve_name** (line 1228) — was duplicating the get_config_val
   logic inline. Now calls get_config_val.
2. **cmd_rename** (line 3369) — same.
3. **_whois_in_scope** (six sites) — host_name, host_identity,
   host_target (×2), host_airc_home, peer-file's identity, peer-file's
   host. All collapsed to get_config_val_in or airc_core.handshake
   get_field.

## New: get_config_val_in

Like get_config_val but reads from an arbitrary config.json path.
Used by _whois_in_scope's cross-scope walk (#134) which inspects
sibling scope state without changing $CONFIG. Same module, same CLI;
just different env var per call.

## airc_core.config: dict round-trip

Extended `get` to JSON-encode dict/list values (matches
handshake.get_field shape). Lets _whois_in_scope read host_identity
+ peer identity blobs as JSON-encoded strings that callers can
re-parse.

## Test posture

- whois: 5/5
- whois_cross_scope: 6/6  ← hottest path through _whois_in_scope
- identity: 19/19
- kick: 12/12
- part_persists: 8/8
- list: 4/4
- general_sidecar_default: 12/12

## Code reduction

~70 lines of inline python heredoc → ~10 lines of bash function
calls. Each removed heredoc was a separate silent-fail vector
(bash-substituted env var into python source code).

## Phase 1 progress

- ✓ iso_to_epoch (Phase 0a)
- ✓ config CRUD core (PR #167)
- ✓ handshake response parse (PR #168)
- ✓ _whois_in_scope + resolve_name + cmd_rename cleanup (this PR)
- next: handshake/gist envelope BUILD sites, identity show/set, monitor_formatter
joelteply added a commit that referenced this pull request Apr 27, 2026
… Phase 1) (#170)

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