Skip to content

feat(airc_core): monitor_formatter → airc_core.monitor_formatter (250-line migration, biggest single heredoc) - #171

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

joelteply merged 1 commit into
canaryfrom
feat/airc-core-monitor-formatter

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

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`). Migrated to a proper Python module.

Impact

airc shrinks by 250 lines (5897 → 5647). The migrated logic includes:

  • Cross-platform inactivity watchdog (SIGALRM / threading.Timer)
  • [rename] handler with chain-repair
  • Ping/pong control message handling
  • Own-send filtering with mid-session rename support
  • Inbound mirror-to-local for joiners
  • Per-line error handling

All preserved verbatim. CLI:

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

Bash function shrinks from 268 lines to 4.

Why a real .py file matters here

  • No more `'\''` shell-escape gymnastics — natural apostrophes in comments
  • Editor syntax highlighting works (was just a bash string before)
  • Unit-testable in isolation (_rename_files, _find_peer_by_host)
  • Importable from other airc_core modules when needed

Test posture

84 assertions across 8 monitor_formatter-touching scenarios:

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

Phase 1 cumulative

6 migrations merged today. airc bash down ~300+ lines (foundation + small migrations + this big one). The pattern continues: each migration removes a silent-fail vector, makes Python logic testable, and shrinks the bash file.

…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
Copilot AI review requested due to automatic review settings April 27, 2026 22:28
@joelteply
joelteply merged commit 0354658 into canary Apr 27, 2026
2 checks passed
@joelteply
joelteply deleted the feat/airc-core-monitor-formatter branch April 27, 2026 22:28

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 large embedded Python heredoc used by airc’s monitor formatter into a proper airc_core.monitor_formatter module, keeping the same stdin/stdout + exit-code contract while shrinking the bash entrypoint and making the formatter logic importable/testable.

Changes:

  • Added lib/airc_core/monitor_formatter.py to host the formatter loop (rename handling, ping/pong control traffic, joiner mirroring, watchdog exit=2).
  • Replaced the inline "$AIRC_PYTHON" -u -c '...' heredoc in airc with a thin wrapper that runs "$AIRC_PYTHON" -u -m airc_core.monitor_formatter.
  • Updated the surrounding bash comments to describe the migration.

Reviewed changes

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

File Description
lib/airc_core/monitor_formatter.py New Python module containing the migrated formatter implementation and watchdog logic.
airc Drops the large inline Python heredoc and invokes the new airc_core.monitor_formatter module instead.

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

Comment thread airc

# Read JSONL from stdin, emit one human-readable line per message.
# Handles [rename] protocol by updating peer records on disk.
# Read JSONL from stdin, emit one human-readable line per message.

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 header comment is duplicated (the same "Read JSONL from stdin..." line appears twice). Consider removing the redundant copy to keep this section concise.

Suggested change
# Read JSONL from stdin, emit one human-readable line per message.

Copilot uses AI. Check for mistakes.
Comment on lines +60 to +84
# Cross-platform watchdog. POSIX (mac/linux/WSL) gets signal.SIGALRM
# which is cheaper (single-thread, kernel-armed). Windows Python has
# no SIGALRM so we fall back to threading.Timer — same exit semantics,
# slight overhead from the timer thread. Either way the fmt_exit=2
# contract is preserved.
try:
signal.signal(signal.SIGALRM, _watchdog_exit)
signal.alarm(WATCHDOG_SEC)

def _arm_watchdog():
signal.alarm(WATCHDOG_SEC)
except (AttributeError, ValueError):
import threading

_wd_timer_holder = [None]

def _arm_watchdog():
if _wd_timer_holder[0] is not None:
_wd_timer_holder[0].cancel()
t = threading.Timer(WATCHDOG_SEC, _watchdog_exit)
t.daemon = True
t.start()
_wd_timer_holder[0] = t

_arm_watchdog()

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 watchdog is armed and the SIGALRM handler is installed at import time. That makes airc_core.monitor_formatter unsafe to import (e.g., for unit tests or reuse from other modules): simply importing it starts an alarm/timer and can terminate the entire process via os._exit(2) ~150s later, and it also overwrites any existing SIGALRM handler in the host process. Move watchdog setup/arming into run() (or _cli()), and keep module import side-effect free (e.g., create an _arm_watchdog inside run() and no-op it when watchdog is disabled).

Copilot uses AI. Check for mistakes.
Comment on lines +100 to +110
d = json.load(open(new_json))
d["name"] = new
json.dump(d, open(new_json, "w"), indent=2)
except Exception:
pass
old_pub = os.path.join(peers_dir, f"{old}.pub")
new_pub = os.path.join(peers_dir, f"{new}.pub")
if os.path.isfile(old_pub):
try:
os.rename(old_pub, new_pub)
except Exception:

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.

_rename_files returns True even if os.rename(old_json, new_json) raises (the exception is swallowed and the function falls through to return True). On Windows os.rename fails if the destination exists; in that case the formatter will print a successful nick change even though the peer record wasn't updated. Consider returning False when the json rename fails (and only returning True once the rename succeeded), and narrow the exception handling to expected OSError/ValueError cases so unexpected errors are surfaced to stderr for diagnosis.

Suggested change
d = json.load(open(new_json))
d["name"] = new
json.dump(d, open(new_json, "w"), indent=2)
except Exception:
pass
old_pub = os.path.join(peers_dir, f"{old}.pub")
new_pub = os.path.join(peers_dir, f"{new}.pub")
if os.path.isfile(old_pub):
try:
os.rename(old_pub, new_pub)
except Exception:
except (OSError, ValueError):
return False
try:
with open(new_json) as f:
d = json.load(f)
d["name"] = new
with open(new_json, "w") as f:
json.dump(d, f, indent=2)
except (OSError, ValueError, json.JSONDecodeError):
return False
old_pub = os.path.join(peers_dir, f"{old}.pub")
new_pub = os.path.join(peers_dir, f"{new}.pub")
if os.path.isfile(old_pub):
try:
os.rename(old_pub, new_pub)
except (OSError, ValueError):

Copilot uses AI. Check for mistakes.
Comment on lines +177 to +186
def current_name():
"""Read identity name fresh from config.json each time so a rename
during the session immediately takes effect for own-send filtering.
Without this the monitor keeps the name it saw at startup and fails
to filter our own outbound rename markers, which can trigger the
host-fallback chain-repair against other peers sharing our host."""
try:
return json.load(open(config_path)).get("name", "")
except Exception:
return ""

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.

This uses json.load(open(...)) / json.dump(..., open(...)) without context managers. In a long-running monitor process (and especially if this module is ever run on non-refcounting Python implementations), that risks delayed file descriptor close and delayed flushes to disk. Prefer with open(...) as f: for these reads/writes (including current_name() and _find_peer_by_host).

Copilot uses AI. Check for mistakes.
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