Repository navigation
feat(airc_core): Python truth-layer foundation + first migration (#152 Phase 0) - #166
Conversation
…Phase 0) Joel 2026-04-27: "3000 lines of code dear god" → "yes" (start the architectural pivot to airc_core). Today's session shipped 17 PRs, ~half fighting bash → python heredoc fragility (silent SyntaxErrors, function-export leaks, missed sed patterns, swallowed stderr). The pattern is the problem: bash substituting variables INTO python source code is a per-site silent fail. PR #164 fixed the export -f leak via AIRC_PYTHON; PR #165 hardened ONE heredoc with env-var pass; ~30 more heredocs remain. This PR pivots: business logic moves to a Python truth-layer package (airc_core/), bash + ps1 become thin shells that invoke the Python via -m. Same input → same output → same testable code, no more bash-into-python escaping. ## Phase 0: foundation - `lib/airc_core/__init__.py` — package marker. v0.1.0. - airc bash resolves the lib dir at startup (4 candidates, first hit wins; canonicalizes to absolute via cd+pwd so PYTHONPATH stays valid across cwd changes). Sets PYTHONPATH unconditionally. - New debug command `airc debug-pythonpath` echoes the resolved path + tests `import airc_core` end-to-end. - install.sh changes: none needed — the existing clone-everything shape already pulls lib/ along. ## Phase 0a: first function migrated - `lib/airc_core/datetime.py` exposes `iso_to_epoch()` with a CLI entry: `python -m airc_core.datetime iso_to_epoch <ts>`. - Bash `iso_to_epoch` shrinks from 22 lines (3-fallback adapter chain) to 4 lines (single Python module call). - Test harness in scenario_platform_adapters updated to set AIRC_PYTHON + PYTHONPATH for the extracted-adapter shell so the test sees the Python module. ## Why iso_to_epoch as the first migration - Pure logic, no I/O — easiest to verify identical behavior. - Already adapter-fied in PR #151 (clean callsite contract). - Three callsites downstream — proves the pattern works for both the function definition AND its consumers. - Smallest possible blast radius if the pattern flubs. ## Test posture - platform_adapters: 11/11 (was 11/11; iso_to_epoch trio still green through the migrated code path) - part_persists: 8/8 (downstream consumer via heartbeat parse) - list: 4/4 (downstream consumer via _format_relative_time) - general_sidecar_default: 12/12 (sidecar spawn touches the path) ## Pattern for follow-up phases Phase 0a establishes the shape. For each subsequent migration: 1. Identify a heredoc-heavy function in airc bash. 2. Re-implement the logic in airc_core/<module>.py with a CLI entry. 3. Bash function becomes a 1-line `"$AIRC_PYTHON" -m airc_core.<module> <subcommand> "$@"` call. 4. Run integration tests; verify identical bash-side behavior. 5. Same module is callable from airc.ps1 (Phase 2 — drift between bash and ps1 ports goes away mechanically). Priority order for Phase 1 (high-fragility first): - pair handshake JSON build/parse (~80 lines, env-var pass already partially done in #165) - gist envelope build (host's response payload) - gist envelope resolve (joiner's parse — the JSON-key-leak class) - monitor_formatter (the long-running -u -c heredoc; missed by sed in #164, fixed in #165) - host_address_set (network enumeration) - config CRUD (45+ callsites; biggest dedupe but most plumbing) ## Out of scope for this PR - No Phase 1 migrations land here. Joel reviews the SHAPE first. - airc.ps1 still uses its own duplicate logic; that's Phase 2. - The 30+ remaining heredocs in airc bash still exist; they'll migrate one at a time per the Phase 1 priority order.
…1) (#167) feat(airc_core): migrate config CRUD (get_name, get_config_val) to airc_core.config (#152 Phase 1) Continuing the Python truth-layer migration started in PR #166. Phase 1: convert high-risk bash heredocs to airc_core modules incrementally. ## What - New `lib/airc_core/config.py` with `get(config_path, key, default)` + `get_name(config_path)` + CLI entry point. - Bash `get_name` and `get_config_val` shrink from inline python heredocs (with bash-variable substitution INTO the python source) to one-line `"$AIRC_PYTHON" -m airc_core.config get <key> <default>` calls. ## Why 45+ callsites across airc bash use these two helpers. Pre-migration each was an inline `"$AIRC_PYTHON" -c "import json; ...$1...$2..."` heredoc — bash $1 / $2 substituted INTO the python source. If the key or default contained quotes, special chars, etc., python parsing broke silently and the value fell back via `2>/dev/null || echo $2`. Continuum-b69f 2026-04-27 traced one symptom (host_target reading empty even when config.json had it) to this class. Now: CONFIG env var holds the file path; key + default come from argv. Python source is fixed bytes; bash never touches it. ## Test posture - identity: 19/19 (heaviest config-read scenario — name, identity fields, integrations all read via the migrated path) - whois: 5/5 - part_persists: 8/8 - list: 4/4 - general_sidecar_default: 12/12 - platform_adapters: 11/11 Direct unit-test of the CLI: - valid config → returns name correctly - missing config → returns default - get_name on valid config → name - both subcommands respond as expected ## Next migrations Per the Phase 1 priority queue (high-fragility first): pair handshake JSON build/parse → gist envelope build → gist envelope resolve → monitor_formatter → host_address_set. Each lands as a separate PR; integration tests verify identical bash-side behavior.
There was a problem hiding this comment.
Pull request overview
Introduces a new lib/airc_core/ Python package intended to become the shared “truth-layer” for business logic across airc (bash) and airc.ps1 (PowerShell), and migrates the first function (iso_to_epoch) from bash into that Python layer with supporting diagnostics and test harness updates.
Changes:
- Add
lib/airc_corePython package (v0.1.0) andairc_core.datetime:iso_to_epoch()with apython -m airc_core.datetime iso_to_epoch <ts>CLI entry. - Update
aircto resolvelib/at startup, prepend it toPYTHONPATH, and replace the bashiso_to_epochimplementation with a one-line module call; addairc debug-pythonpath. - Update
test/integration.shplatform-adapter extraction harness to setAIRC_PYTHONandPYTHONPATHso extracted adapters can callairc_core.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 8 comments.
| File | Description |
|---|---|
airc |
Adds lib/ resolution + PYTHONPATH wiring; migrates iso_to_epoch to Python module; adds debug command. |
lib/airc_core/__init__.py |
Introduces the Python truth-layer package and version. |
lib/airc_core/datetime.py |
Implements iso_to_epoch() and a small -m CLI dispatcher. |
test/integration.sh |
Ensures adapter tests run with AIRC_PYTHON + PYTHONPATH set for airc_core imports. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
|
||
|
|
||
| def iso_to_epoch(ts: str) -> int | None: |
There was a problem hiding this comment.
The return annotation int | None requires Python 3.10+ (PEP 604). The repo currently only checks for “a working python3 (or python)” without enforcing a minimum minor version, so this will SyntaxError on common distros with Python 3.8/3.9. Consider using Optional[int] (or int | None only if you also add a runtime version check / documented minimum version).
| def iso_to_epoch(ts: str) -> int | None: | |
| from typing import Optional | |
| def iso_to_epoch(ts: str) -> Optional[int]: |
| # Resolve the airc install dir's lib/ path and prepend to PYTHONPATH so | ||
| # Python heredocs + module invocations can import airc_core (the | ||
| # Python truth-layer #152). Three resolution paths, first hit wins: | ||
| # 1. $AIRC_DIR (explicit override / install.sh's working dir) | ||
| # 2. dirname of this script (dev checkout — running from repo) | ||
| # 3. $HOME/.airc-src (install.sh default) | ||
| # When the lib/ dir doesn't exist (e.g. older install before this PR | ||
| # landed), PYTHONPATH stays unmodified — heredocs still work. | ||
| _airc_resolve_lib_dir() { | ||
| local _candidate _abs | ||
| for _candidate in \ | ||
| "${AIRC_DIR:-}/lib" \ | ||
| "$(dirname "$(readlink "$0" 2>/dev/null || echo "$0")")/lib" \ | ||
| "$(dirname "$0")/lib" \ | ||
| "$HOME/.airc-src/lib"; do |
There was a problem hiding this comment.
Comment says “Three resolution paths” but _airc_resolve_lib_dir currently checks four candidates (including both readlink-based and plain dirname "$0"). Consider updating the comment to match the actual resolution order to avoid confusion when debugging installs.
| if [ -n "${_airc_lib_dir:-}" ]; then | ||
| if [ -n "${PYTHONPATH:-}" ]; then | ||
| export PYTHONPATH="$_airc_lib_dir:$PYTHONPATH" | ||
| else | ||
| export PYTHONPATH="$_airc_lib_dir" | ||
| fi | ||
| fi |
There was a problem hiding this comment.
PYTHONPATH is being concatenated with :. That works on POSIX, but if this script is run under Git Bash with a native Windows Python, Python uses os.pathsep == ';' and will treat the whole value as a single entry, breaking import airc_core. Consider determining the separator via Python (or uname/platform detection) and joining with the correct os.pathsep so airc_core imports reliably across macOS/Linux/Windows-bash.
| for _candidate in \ | ||
| "${AIRC_DIR:-}/lib" \ |
There was a problem hiding this comment.
The first lib-dir candidate is built as "${AIRC_DIR:-}/lib". When AIRC_DIR is unset/empty this expands to /lib, which is unrelated to airc and could lead to surprising resolution behavior. Consider only including the $AIRC_DIR/lib candidate when AIRC_DIR is non-empty.
| for _candidate in \ | |
| "${AIRC_DIR:-}/lib" \ | |
| if [ -n "${AIRC_DIR:-}" ]; then | |
| _candidate="$AIRC_DIR/lib" | |
| if [ -d "$_candidate/airc_core" ]; then | |
| # Canonicalize to absolute path so PYTHONPATH stays valid even | |
| # if cwd changes mid-script (heredocs that cd elsewhere). cd + | |
| # pwd is the portable canonicalize idiom — `realpath` and | |
| # `readlink -f` are not available everywhere (BSD readlink | |
| # lacks -f, busybox lacks realpath). | |
| _abs=$(cd "$_candidate" 2>/dev/null && pwd) || _abs="$_candidate" | |
| printf '%s' "$_abs" | |
| return 0 | |
| fi | |
| fi | |
| for _candidate in \ |
| sys.exit(1) | ||
| " 2>/dev/null | ||
| fi | ||
| "$AIRC_PYTHON" -m airc_core.datetime iso_to_epoch "$ts" 2>/dev/null |
There was a problem hiding this comment.
iso_to_epoch is called in command substitutions in several places (e.g. epoch=$(iso_to_epoch ...)). Under set -e, if the Python module invocation fails (missing PYTHONPATH, import error, etc.) this command will return non-zero and can terminate the whole script, while 2>/dev/null hides the root cause. To preserve the documented contract (“empty output on failure”), ensure this call cannot propagate a non-zero exit status (e.g., swallow failures and return 0 while emitting no output).
| "$AIRC_PYTHON" -m airc_core.datetime iso_to_epoch "$ts" 2>/dev/null | |
| "$AIRC_PYTHON" -m airc_core.datetime iso_to_epoch "$ts" 2>/dev/null || true |
| bash -c "source '$_adapters_extract'; $*" | ||
| AIRC_PYTHON="${AIRC_PYTHON:-python3}" \ | ||
| PYTHONPATH="${_airc_lib_dir}${PYTHONPATH:+:$PYTHONPATH}" \ | ||
| bash -c "source '$_adapters_extract'; export AIRC_PYTHON='${AIRC_PYTHON:-python3}'; $*" |
There was a problem hiding this comment.
The bash -c string embeds an expanded AIRC_PYTHON value (export AIRC_PYTHON='${AIRC_PYTHON:-python3}'). If AIRC_PYTHON ever contains backslashes or other characters meaningful to the double-quoted outer string (common on Windows paths), this can break quoting. Since AIRC_PYTHON=... bash -c ... already passes it in the environment, consider dropping the inner export ... (or otherwise avoid interpolating the value into the bash -c command string).
| bash -c "source '$_adapters_extract'; export AIRC_PYTHON='${AIRC_PYTHON:-python3}'; $*" | |
| bash -c "source '$_adapters_extract'; $*" |
| AIRC_PYTHON="${AIRC_PYTHON:-python3}" \ | ||
| PYTHONPATH="${_airc_lib_dir}${PYTHONPATH:+:$PYTHONPATH}" \ |
There was a problem hiding this comment.
_adapter_call defaults AIRC_PYTHON to python3. The main airc script explicitly supports Git Bash environments where only python exists (no python3 alias). To keep adapter tests portable, mirror the same interpreter resolution logic here (prefer python3 if available, else python) rather than hard-coding python3.
| AIRC_PYTHON="${AIRC_PYTHON:-python3}" \ | ||
| PYTHONPATH="${_airc_lib_dir}${PYTHONPATH:+:$PYTHONPATH}" \ |
There was a problem hiding this comment.
PYTHONPATH is being joined using : here as well. If these adapter tests ever run under Git Bash with a native Windows Python, Python expects PYTHONPATH to be ;-separated (os.pathsep). Consider using the same path-separator logic as the runtime script to avoid Windows-only import failures.
… 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
…-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
…#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)
…nd-to-end (#177) fix(msys): export MSYS2_ARG_CONV_EXCL at airc startup — last layer of cross-machine fix (continuum's catch + verify) continuum-b69f's diagnosis 2026-04-27: even with PR #174 + #176's argparse `--flags`, MSYS Git Bash on Windows translates argv VALUES that look like Unix-rooted paths when bash invokes a Windows-native binary. So `--host-airc-home /Users/joelteply/.airc` arrived at python.exe as `--host-airc-home C:/Program Files/Git/Users/joelteply/.airc`, the joiner cached the corrupted path, the SSH command later sent it to a real Unix host that had no such file. Silent broadcast failure. ## Fix ```bash export MSYS2_ARG_CONV_EXCL="${MSYS2_ARG_CONV_EXCL:-/Users/;/home/;/root/}" ``` Set once at airc startup, exported, every airc_core invocation inherits the same translation policy. Targeted prefix list covers macOS / Linux / root home prefixes without breaking `/tmp/` or `/c/` paths (which DO need translation for `--config "$CONFIG"` where $CONFIG is on the local Windows filesystem). Honors a user override via the `${...:-...}` default-fallback. ## End-to-end verification continuum-b69f shipped a test broadcast from Windows after their local patch: > WORKING TEST: Windows-Mac airc msg via continuum-msyspatch with > targeted MSYS exclude. should land! Verified live in MY host's messages.jsonl on Mac: ``` {"from":"continuum-msyspatch","to":"all","ts":"2026-04-27T23:30:13Z", "msg":"WORKING TEST: Windows-Mac airc msg via continuum-msyspatch with targeted MSYS exclude. should land!","sig":"..."} ``` **Cross-machine Mac↔Windows airc end-to-end working.** This was the last bug in the chain that started at PR #153 (Microsoft Store python3 stub). ## Test posture (Mac, where the env var is a no-op) - tabs 19/19, identity 19/19, whois 5/5, part_persists 8/8, list 4/4, general_sidecar_default 12/12, kick 12/12, events 5/5, platform_adapters 11/11, whois_cross_scope 6/6 ## Today's full chain of cross-machine fixes #153 → #154 → #155 → #156 → #157 → #158 → #159 → #160 → #162 → #164 → #165 → #166 → ... → #176 → this. 27+ PRs to ship a working cross-machine airc on Windows. Every step revealed a new layer.
Architectural pivot per Joel 2026-04-27 ("3000 lines of code dear god" → "yes" start #152).
Phase 0: foundation
Phase 0a: first function migrated
Why iso_to_epoch first
Pure logic, no I/O, smallest blast radius, three downstream callsites prove the contract holds end-to-end.
Test posture
Pattern for Phase 1
For each future migration: re-implement logic in airc_core/.py, bash function becomes 1-line `"$AIRC_PYTHON" -m` call, integration tests verify identical behavior. Phase 1 priority queue (high-fragility first): pair handshake JSON, gist envelope build/resolve, monitor_formatter, host_address_set, config CRUD.
Why this shape
The 17 PRs today fixing bash-into-python heredoc fragility (silent SyntaxErrors, export-f leaks, missed sed patterns, swallowed stderr) are symptoms of mixing bash variable substitution with embedded python source. Each migration eliminates one site's worth of those silent-fail vectors permanently.
Joel reviews shape before scaling
This PR establishes the pattern. If the shape is right, Phase 1 scales to the remaining ~30 heredocs in priority order. If the shape needs adjustment, we adjust before scaling.