Repository navigation
feat(channels): channel field on message envelope — Phase 2A - #223
Conversation
Architectural shift from per-room gists to per-account-singleton mesh.
Joel 2026-04-27: "B is the god damn correct shift. They all share the
same gist, stop being stupid. one goes down first one to resolve, posts
to gist. host goes down, new host, first one that posts, becomes it."
## What changes
- New `lib/airc_bash/mesh.sh` — primitives for the mesh-gist abstraction:
_mesh_desc, _mesh_find (singleton lookup), _mesh_publish, _mesh_update,
_mesh_age_secs, _mesh_take_over (race-aware oldest-by-created election)
- airc top-level: source mesh.sh; _self_heal_stale_host now takes only
stale_id (no room_name discriminator — mesh is per-account, nothing
to discriminate on)
- cmd_connect.sh:
- Discovery: singleton lookup via _mesh_find (was: per-room awk filter)
- Host publish: description "airc mesh", payload kind "mesh",
channels: [\$room_name] array (replaces .name + .topic)
- Heartbeat payload: same shape change
- Race-loser: _mesh_take_over (jitter, list, oldest-by-created wins)
- Joiner: kind "mesh" handled alongside legacy "room" for back-compat
with gists that haven't rolled over yet
- cmd_rooms.sh: list display now recognizes mesh (◆), room (#), invite
(1:1) — three kinds during the transition
## What's deferred to Phase 2/3/4
- Joiners adding their own channels to the mesh gist (currently the
host's published channels list is set at create time and only the
host updates it)
- Channel-as-message-metadata routing (messages still go to one log;
per-channel filtering is local-only at display time)
- .general sidecar deletion (still spawned per spawn_general_sidecar_if_wanted)
- Sweep of legacy `airc room: *` gists on rollover
## Verification
- bash -n clean on all four files
- airc help / version / dispatch reach correct paths
- test/integration.sh tabs: 1/3 (rename-marker timing flake; 0/3 on
pristine canary HEAD too — not introduced
by this PR, predates mesh switch)
- test/integration.sh status: 7/0 ✓
- test/integration.sh room: 14/0 ✓
- test/integration.sh general_sidecar_default: 12/0 ✓
- test/integration.sh platform_adapters: 9/2 (darwin/macos rename
from PR #211, unrelated)
## Test plan
- [ ] CI integration suite on push to canary
- [ ] e2e: continuum-b69f (Windows) + Mac Claude on same gh account
both run `airc update && airc join` — confirm both converge on
a single new "airc mesh" gist; first to publish wins; second
becomes joiner
- [ ] e2e takeover: kill the host, confirm joiner detects stale and
becomes new host (mesh takeover via _mesh_take_over)
- [ ] migration grace: existing `airc room: *` gists left untouched;
new mesh gist created alongside; cmd_rooms shows both with
separate markers (◆ vs #)
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Stamps the active channel on every outgoing message envelope so the
monitor formatter can route display by channel uniformly, regardless
of which scope the message was emitted from. This is the substrate
for Phase 2B (collapsing the multi-scope sidecar into a single scope
with subscribed_channels).
## Envelope shape
Old (room implied by scope-level room_name file):
{"from":"X","to":"Y","ts":"...","msg":"..."}
New (channel stamped on the line itself):
{"from":"X","to":"Y","ts":"...","channel":"general","msg":"..."}
## Sites stamped
- cmd_send.sh: peer/broadcast envelope + sig over the new payload shape
- cmd_send.sh: queue marker (tailnet offline)
- cmd_send.sh: queue marker (network error)
- cmd_send.sh: fail marker (auth)
- airc top-level: drain marker
- handshake.py: peer-join system event
Rename markers go through cmd_send --internal and inherit the field.
## Display
monitor_formatter.py now prefers `m.get("channel")` over the scope-
level room_name when prefixing each emitted line. The scope-level
room_name remains as a fallback for pre-Phase-2 envelopes that lack
the field, so older messages still prefix correctly during rollover.
## Verification
- bash -n + python ast.parse on all four changed files
- test/integration.sh tabs: 19/0 ✓
- test/integration.sh room: 14/0 ✓
- test/integration.sh queue: 7/0 ✓
## Stacked on Phase 1
Branched off feat/one-mesh-gist-per-account (PR #222). When that
merges to canary, Phase 2A rebases cleanly. Phase 2B (sidecar
deletion + subscribed_channels config) follows.
Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
Adds a per-message channel field to the message envelope so downstream display/routing can be driven uniformly by envelope metadata, while also bringing in the mesh (one-gist-per-account) substrate helpers this work builds on.
Changes:
- Stamp
channelonto outbound message envelopes and system markers (queued/auth-fail/drain/join). - Update
monitor_formatter.pyto preferm["channel"]over scoperoom_namewhen prefixing lines (with fallback for older envelopes). - Introduce and wire up
lib/airc_bash/mesh.shhelpers for mesh gist discovery/takeover and update connect/teardown flows to use mesh semantics.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 12 comments.
Show a summary per file
| File | Description |
|---|---|
| lib/airc_core/monitor_formatter.py | Prefix output lines using envelope channel (fallback to scope room). |
| lib/airc_core/handshake.py | Join system event now includes channel. |
| lib/airc_bash/mesh.sh | New mesh gist abstraction helpers (_mesh_find, _mesh_publish, _mesh_take_over, etc.). |
| lib/airc_bash/cmd_send.sh | Stamp channel on outbound envelopes and local markers. |
| lib/airc_bash/cmd_rooms.sh | Recognize/display mesh gists alongside legacy room/invite gists. |
| lib/airc_bash/cmd_connect.sh | Switch discovery/hosting logic toward mesh gist; parse mesh payload shape. |
| airc | Source mesh.sh, adjust stale-host self-heal, and stamp channel on drain markers. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| local picked; picked=$(_mesh_find) | ||
| rm -f "$CONFIG" "$AIRC_WRITE_DIR/room_name" | ||
| if [ -n "$picked" ]; then | ||
| echo " ✓ Another tab beat us to it — joining their fresh gist ($picked)" | ||
| if [ -n "$picked" ] && [ "$picked" != "$stale_id" ]; then | ||
| echo " ✓ Another tab beat us to it — joining their fresh mesh gist ($picked)" | ||
| echo "" | ||
| _reexec_into rejoin "$picked" | ||
| fi | ||
| echo " Re-execing into host mode for #${room_name}..." | ||
| echo " Re-execing into host mode (mesh singleton for this gh account)..." | ||
| echo "" | ||
| _reexec_into host --room "$room_name" | ||
| _reexec_into host |
There was a problem hiding this comment.
_self_heal_stale_host now removes $AIRC_WRITE_DIR/room_name and then re-execs into host mode without passing --room. In mesh mode the host still publishes channels: ["${room_name}"], so losing the room context here can cause the takeover host to publish/subscribe under an unintended auto-inferred room (or fall back to general). Consider preserving the current room name (read it before rm -f) and passing it through to _reexec_into host --room <saved> (or avoid deleting room_name here if it’s still needed as the scope’s channel identity).
| ids=$(gh gist list --limit 50 2>/dev/null \ | ||
| | awk -F'\t' -v d="$desc" '$2 == d { print $1 }') |
There was a problem hiding this comment.
mesh.sh is sourced by airc, which runs under set -euo pipefail (airc:9). In _mesh_find, the ids=$(gh gist list ... | awk ...) pipeline is not guarded; if gh exits non-zero (rate limit, auth lapse, network), pipefail + -e can terminate the entire airc process instead of letting the caller handle an error/empty result. Consider wrapping failing pipelines in an if ! ids=$(...); then ...; fi block (or using || true plus explicit checks) similar to the guarded command-substitution pattern described in cmd_connect.sh:479-487.
| ids=$(gh gist list --limit 50 2>/dev/null \ | |
| | awk -F'\t' -v d="$desc" '$2 == d { print $1 }') | |
| if ! ids=$(gh gist list --limit 50 2>/dev/null \ | |
| | awk -F'\t' -v d="$desc" '$2 == d { print $1 }'); then | |
| echo "_mesh_find: failed to list gists via gh" >&2 | |
| return 1 | |
| fi |
| local ids; ids=$(gh gist list --limit 50 2>/dev/null \ | ||
| | awk -F'\t' -v d="$desc" '$2 == d { print $1 }') |
There was a problem hiding this comment.
_mesh_take_over also runs ids=$(gh gist list ... | awk ...) unguarded. With set -euo pipefail, any gh failure here can exit the parent airc process mid-takeover rather than returning a result (the caller currently expects _mesh_take_over to sometimes return empty and treats that as “assume winner”). Guard this pipeline so failures degrade into a controlled return value/exit status.
| local ids; ids=$(gh gist list --limit 50 2>/dev/null \ | |
| | awk -F'\t' -v d="$desc" '$2 == d { print $1 }') | |
| local ids="" | |
| if ! ids=$(gh gist list --limit 50 2>/dev/null \ | |
| | awk -F'\t' -v d="$desc" '$2 == d { print $1 }'); then | |
| return 0 | |
| fi |
| if [ -z "$target" ] && \ | ||
| [ "${AIRC_NO_DISCOVERY:-0}" != "1" ] && \ | ||
| command -v gh >/dev/null 2>&1; then | ||
|
|
||
| # ── Room discovery (the substrate path) ────────────────────── | ||
| # Match exact room name to avoid `airc room: general-test` colliding | ||
| # with `airc room: general`. Pick the most-recent if duplicates exist | ||
| # (stale hosts get re-elected on next reconnect when SSH fails). | ||
| if [ "$use_room" = "1" ]; then | ||
| _did_room_discovery=1 | ||
| local _room_filter="airc room: ${room_name}\$" | ||
| local _room_candidates; _room_candidates=$(gh gist list --limit 50 2>/dev/null \ | ||
| | awk -F'\t' -v re="$_room_filter" '$2 ~ re { print $1 "\t" $2 "\t" $4 }') | ||
| local _room_count; _room_count=$(printf '%s' "$_room_candidates" | grep -c . || true) | ||
| if [ "$_room_count" -ge 1 ]; then | ||
| # Most recent wins (gh gist list is reverse-chrono by update). | ||
| local _picked_id; _picked_id=$(printf '%s' "$_room_candidates" | head -1 | awk -F'\t' '{print $1}') | ||
| echo " Found #${room_name} on your gh account → joining ($_picked_id)" | ||
| target="$_picked_id" | ||
| # fall through to gist resolver below — kind:room → invite handshake | ||
| else | ||
| echo " No #${room_name} found on your gh account → becoming the host." | ||
| # Race against a concurrent host attempt is handled POST-publish | ||
| # (see "race-loser detection" near host_gist_id write below). | ||
| # Pre-publish recheck doesn't help — neither tab's gist is | ||
| # globally visible yet at this point. | ||
| fi | ||
| # ── Mesh discovery (singleton per gh account) ──────────────── |
There was a problem hiding this comment.
--no-room is documented/implemented as “disable the substrate entirely”, but mesh discovery currently runs unconditionally inside the zero-arg discovery gate. That means airc connect --no-room (with no target) can still auto-join an existing mesh gist (because target gets set by _mesh_find), changing the flag’s semantics. Consider guarding the mesh discovery block with use_room==1 (or introducing an explicit --no-mesh/AIRC_NO_MESH), so --no-room reliably skips mesh/room discovery and falls back to the legacy invite flow/host behavior.
| local fail_marker; fail_marker=$(printf '{"from":"airc","ts":"%s","channel":"%s","msg":"[AUTH FAILED to %s — repair required, NOT queued] %s"}' \ | ||
| "$(timestamp)" "$active_channel" "$peer_name" "${stderr:-no stderr}") |
There was a problem hiding this comment.
This auth-failure marker JSON interpolates active_channel without JSON-escaping. To keep messages.jsonl valid and line-delimited, reuse the same escaped/sanitized channel value you use for the outbound envelope.
| [ -f "$payload_path" ] || return 1 | ||
| command -v gh >/dev/null 2>&1 || return 1 | ||
| local desc; desc=$(_mesh_desc) | ||
| local url; url=$(gh gist create -d "$desc" "$payload_path" 2>/dev/null | tail -1) |
There was a problem hiding this comment.
Similarly, _mesh_publish uses url=$(gh gist create ... | tail -1) without guarding against non-zero exits. Under set -euo pipefail, a transient gh failure can abort the whole script instead of returning an empty id / non-zero status from _mesh_publish. Please guard the pipeline so the function can fail gracefully and the caller can decide how to proceed.
| local url; url=$(gh gist create -d "$desc" "$payload_path" 2>/dev/null | tail -1) | |
| local url | |
| if ! url=$(gh gist create -d "$desc" "$payload_path" 2>/dev/null | tail -1); then | |
| return 1 | |
| fi |
| { | ||
| "airc": 1, | ||
| "kind": "room", | ||
| "name": "${room_name}", | ||
| "topic": "", | ||
| "kind": "mesh", | ||
| "channels": ["${room_name}"], | ||
| "invite": "$_invite_long", |
There was a problem hiding this comment.
The gist JSON payload embeds room_name directly inside the channels array. If room_name contains quotes/backslashes/newlines (user-provided via --room or from a modified room_name file), this produces invalid JSON and can break discovery/joins. Please JSON-escape/sanitize room_name before interpolating it into the heredoc (and reuse the escaped value everywhere this payload is built).
| { | ||
| "airc": 1, | ||
| "kind": "room", | ||
| "name": "${_hb_room}", | ||
| "topic": "", | ||
| "kind": "mesh", | ||
| "channels": ["${_hb_room}"], | ||
| "invite": "${_hb_invite}", |
There was a problem hiding this comment.
The heartbeat gist payload also embeds _hb_room directly into JSON (channels: ["${_hb_room}"]). For the same reasons as the host-publish payload, this should be JSON-escaped/sanitized to avoid producing malformed JSON (and to keep the heartbeat updater resilient if a room name ever contains unexpected characters).
| local active_channel="general" | ||
| [ -f "$AIRC_WRITE_DIR/room_name" ] && active_channel=$(cat "$AIRC_WRITE_DIR/room_name" 2>/dev/null || echo general) | ||
| [ -z "$active_channel" ] && active_channel="general" | ||
|
|
||
| local payload="{\"from\":\"$my_name\",\"to\":\"$peer_name\",\"ts\":\"$ts_val\",\"channel\":\"$active_channel\",\"msg\":\"$escaped_msg\"}" |
There was a problem hiding this comment.
active_channel is read from room_name and then interpolated into multiple JSON strings (payload, full_msg, and markers). Unlike msg, it is not JSON-escaped; if the file contains a quote, backslash, or newline, this will emit invalid JSON (and newlines can corrupt the jsonl framing). Please JSON-escape/sanitize the channel once (similar to escaped_msg) and use the escaped value everywhere it’s inserted into JSON.
| echo "$full_msg" >> "$AIRC_WRITE_DIR/pending.jsonl" | ||
| local queue_marker; queue_marker=$(printf '{"from":"airc","ts":"%s","msg":"[QUEUED to %s — peer offline in tailnet, auto-delivers on wake]"}' \ | ||
| "$(timestamp)" "$peer_name") | ||
| local queue_marker; queue_marker=$(printf '{"from":"airc","ts":"%s","channel":"%s","msg":"[QUEUED to %s — peer offline in tailnet, auto-delivers on wake]"}' \ |
There was a problem hiding this comment.
This queued-marker JSON includes "channel":"$active_channel" but uses the raw (unescaped) channel value. After escaping/sanitizing the channel for the main payload, ensure the marker JSON reuses the same escaped value to avoid malformed JSON in messages.jsonl.
| local queue_marker; queue_marker=$(printf '{"from":"airc","ts":"%s","channel":"%s","msg":"[QUEUED to %s — peer offline in tailnet, auto-delivers on wake]"}' \ | |
| local queue_marker; queue_marker=$(python3 -c 'import json, sys; print(json.dumps({ | |
| "from": "airc", | |
| "ts": sys.argv[1], | |
| "channel": sys.argv[2], | |
| "msg": "[QUEUED to %s — peer offline in tailnet, auto-delivers on wake]" % sys.argv[3], | |
| }, ensure_ascii=False))' \ |
Summary
Stamps the active channel on every message envelope so the monitor formatter can route display by channel uniformly. This is the substrate for Phase 2B (sidecar deletion + subscribed_channels config).
Envelope shape
Old: `{"from":"X","to":"Y","ts":"...","msg":"..."}`
New: `{"from":"X","to":"Y","ts":"...","channel":"general","msg":"..."}`
Sites stamped
Display
`monitor_formatter.py` now prefers `m.get("channel")` over the scope-level room_name when prefixing each line — pre-Phase-2 envelopes without the field still fall back correctly during rollover.
Stacked on Phase 1
Branched from `feat/one-mesh-gist-per-account` (#222). When that merges, Phase 2A rebases cleanly. Phase 2B (sidecar deletion + subscribed_channels) follows.
Test plan
🤖 Generated with Claude Code