Skip to content

fix(airc): two PR #164 followups — sed missed line 1372 + harden host_* config write (continuum's retest) - #165

Merged
joelteply merged 1 commit into
canaryfrom
fix/airc-python-sed-miss-line-1372
Apr 27, 2026
Merged

joelteply merged 1 commit into
canaryfrom
fix/airc-python-sed-miss-line-1372

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

continuum-b69f's PR #164 retest 2026-04-27 found two remaining issues.

Bug A — line 1372 missed by PR #164's sed

`python3 -u -c '` (the unbuffered monitor_formatter launch) didn't match the `python3 -c` regex. On Windows with Store stub, monitor_formatter crashed silently — joiner monitor went dark, no inbound stream visible. One-line fix.

Bug B — host_* config write silently no-op'd

continuum's joiner config had `name`, `host`, `host_target`, `created` but missing `host_airc_home`, `host_name`, `host_port`, `host_ssh_pub`, `host_identity` — all five written by ONE python heredoc whose body had five bash-substituted variables. If any substitution broke python parsing (special char, empty value, etc.), the heredoc errored, `2>/dev/null || true` swallowed it, all five fields stayed empty. Specifically host_airc_home empty meant cmd_send's SSH push targeted a wrong remote path → another silent-no-op direction even after PR #164.

Fix: pass values as env vars; python reads via `os.environ.get(...)`. Bash never touches python source. Stderr surfaces (warn line, not /dev/null). `int(host_port)` wrapped in try/except.

Pattern note

`"$AIRC_PYTHON" -c "..."` heredocs with bash-var substitutions are fragile by class. Filing follow-up to sweep all ~30 sites.

Mac regression

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

Win→Mac e2e validation pending continuum's retest.

…_* config write

continuum-b69f's PR #164 retest 2026-04-27 found two remaining bugs:

## Bug A: sed missed `python3 -u -c '` at line 1372

PR #164's sed pattern was `python3 -c` — didn't match the `-u` flag
sandwiched between python3 and -c at line 1372 (monitor_formatter
unbuffered launch). On Windows Git Bash with the Microsoft Store
stub, this site silent-failed too: monitor_formatter crashed at
launch, the inbound stream went dark, joiner couldn't see anything
the host wrote. One-line fix: `python3 -u -c '` →
`"$AIRC_PYTHON" -u -c '`.

## Bug B: host_* config write silently no-op'd if ANY bash subst broke

continuum's joiner config showed `name`, `host`, `host_target`,
`created` but NOT `host_airc_home`, `host_name`, `host_port`,
`host_ssh_pub`, `host_identity` — all five fields written together
by the heredoc at line 2768.

Pre-fix:
```bash
HOST_IDENTITY="$host_identity_json" "$AIRC_PYTHON" -c "
import json, os
c = json.load(open('$CONFIG'))
c['host_airc_home'] = '$host_airc_home'
c['host_name']      = '$peer_name'
c['host_port']      = ${peer_port:-7547}
c['host_ssh_pub']   = '''$host_ssh_pub'''
...
" 2>/dev/null || true
```

Five bash substitutions into python source. If ANY substitution
breaks python parsing (newline in host_ssh_pub, special char in
host_airc_home, empty/non-numeric peer_port, etc.) the whole heredoc
crashes at parse time. `2>/dev/null || true` swallows the SyntaxError
and zero fields land. Five silently-empty config fields downstream:
- host_airc_home empty → cmd_send computes wrong remote path
- host_name empty → "Connected to ''" banner
- host_port wrong → SSH targets wrong port (or 7547 fallback)
- host_ssh_pub empty → host's SSH key not in authorized_keys
- host_identity empty → airc whois <host> shows (unset)

Post-fix: pass everything as env vars; python reads from os.environ.
Bash never touches the python source. Also emit stderr to a warn line
(not /dev/null) so the future debugger can see it. Also catch
ValueError on int(host_port) so a non-numeric value falls back to
7547 instead of dying.

## Pattern lesson

bash → python heredoc with bash variable substitution into the
python SOURCE is fragile. Any unusual byte in the variable can
break python parsing. Same shape as the resolver heredoc that
broke pre-PR #155 with set -e + pipefail.

Repeat-offender pattern. Consider a sweep: every `"$AIRC_PYTHON" -c
"..."` heredoc that contains `$bash_var` substitutions — convert to
env-var pass + os.environ. Out of scope for this PR (would touch
~30 sites); file as a separate canary follow-up.

## Test posture

Mac regression (5 scenarios, all green):
- identity 19/19
- whois 5/5
- part_persists 8/8
- list 4/4
- general_sidecar_default 12/12

End-to-end Win→Mac broadcast verification still pending continuum's
retest after pulling this fix.
Copilot AI review requested due to automatic review settings April 27, 2026 21:34
@joelteply
joelteply merged commit caa0b5e into canary Apr 27, 2026
2 checks passed
@joelteply
joelteply deleted the fix/airc-python-sed-miss-line-1372 branch April 27, 2026 21:34

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

Follow-up fixes to airc after PR #164 retesting: ensure all monitor Python invocations use the resolved AIRC_PYTHON, and harden the joiner-side host config write so special characters/newlines in values can’t break the embedded Python source.

Changes:

  • Replace the remaining python3 -u -c monitor formatter invocation with "$AIRC_PYTHON" -u -c.
  • Write host-related config fields by passing values via environment variables (avoids bash-substituted Python source), and surface failures via stderr + a warning.

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

Comment thread airc
c["host_airc_home"] = os.environ.get("HOST_AIRC_HOME", "")
c["host_name"] = os.environ.get("HOST_NAME", "")
try: c["host_port"] = int(os.environ.get("HOST_PORT", "7547"))
except: c["host_port"] = 7547

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 Python snippet uses a bare except: when parsing HOST_PORT. Bare except also catches KeyboardInterrupt/SystemExit and makes debugging harder; prefer except Exception or (better) except ValueError, TypeError for the int(...) conversion and keep other exceptions visible.

Suggested change
except: c["host_port"] = 7547
except (ValueError, TypeError): c["host_port"] = 7547

Copilot uses AI. Check for mistakes.
Comment thread airc
c["host_ssh_pub"] = os.environ.get("HOST_SSH_PUB", "")
c["host_identity"] = json.loads(os.environ.get("HOST_IDENTITY", "{}"))
json.dump(c, open(os.environ["CONFIG"], "w"), indent=2)
' || echo " ⚠ config write failed (host_airc_home/host_name/host_port/host_ssh_pub may be unset). airc may still work if subsequent retries refresh." >&2

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 warning message after the config write failure lists host_airc_home/host_name/host_port/host_ssh_pub, but this block also writes host_identity. If the write fails, host_identity will also remain stale/unset; update the message to include it (or make the message generic like “host fields may be unset”).

Suggested change
' || echo " ⚠ config write failed (host_airc_home/host_name/host_port/host_ssh_pub may be unset). airc may still work if subsequent retries refresh." >&2
' || echo " ⚠ config write failed (host_airc_home/host_name/host_port/host_ssh_pub/host_identity may be unset). airc may still work if subsequent retries refresh." >&2

Copilot uses AI. Check for mistakes.
joelteply added a commit that referenced this pull request Apr 27, 2026
…Phase 0) (#166)

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.
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)
joelteply added a commit that referenced this pull request Apr 27, 2026
…(continuum's #174 follow-up) (#176)

fix(airc_core): config set_host_block subcommand — last env-var-pass site converted to argparse (continuum's PR #174 follow-up)

continuum-b69f's #174 retest 2026-04-27 found that PR #174 missed the
host_* config WRITE site (the post-handshake "store host details"
block). It still used env vars, so MSYS path-translated $host_airc_home
on Git Bash before python read it from os.environ. Same silent-fail
class as the rest of #174.

## Fix (matches PR #174 pattern verbatim)

New subcommand: `airc_core.config set_host_block`.

```bash
"$AIRC_PYTHON" -m airc_core.config set_host_block \
    --config "$CONFIG" \
    --host-airc-home "$host_airc_home" \
    --host-name "$peer_name" \
    --host-port "${peer_port:-7547}" \
    --host-ssh-pub "$host_ssh_pub" \
    --host-identity-json "$host_identity_json"
```

Bash callsite is one airc_core invocation; no env-var pass; no python
heredoc with bash substitutions; no `2>/dev/null` swallowing errors.
The CLI errors are surfaced via stderr per the never-swallow-errors
rule.

## Why this matters per Joel's "always the right fix"

PR #174 was the right approach for the SEND/PARSE/ACCEPT sites. PR
#165 (env-var hardening) was a defensive partial fix at the WRITE
site. Today we close the loop — same architecture across all
config-mutating sites.

## Test posture

95 assertions / 9 scenarios green:
- tabs 19, identity 19, whois 5, part_persists 8, list 4,
  general_sidecar_default 12, kick 12, events 5, platform_adapters 11

Unit test:
- set_host_block writes valid JSON with all fields preserved
  uncorrupted (path / SSH pubkey / identity dict round-trip)
joelteply added a commit that referenced this pull request Apr 27, 2026
…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.
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