Skip to content

fix(portable): wrap stat in numeric-validating helpers — kills MSYS 'File: unbound variable' bug from #419 - #421

Merged
joelteply merged 1 commit into
canaryfrom
fix/portable-stat-helpers
May 2, 2026
Merged

joelteply merged 1 commit into
canaryfrom
fix/portable-stat-helpers

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Hotfix for active regression

#419 (auth-state cache) introduced a Windows-fatal bug. Symptom: airc connect fails with:

lib_auth.sh: line 78: File: unbound variable
ERROR: gh auth not OK — see message above for next step

Affects every Windows Git Bash user post-#419. Likely missed in review because Mac has BSD stat where the bug doesn't fire.

Root cause

stat -f is BSD's 'format specifier' but GNU's '--file-system'. On MSYS Git Bash (GNU stat), stat -f %m FILE exits 0 and emits multi-line filesystem metadata to stdout instead of mtime. The bsd_cmd || gnu_cmd || fallback chain doesn't trigger fallback because BSD attempt exits 0 — captured value becomes File: "<path>" / ID: ... / Block size: .... Then $(( _now - _cache_mtime )) arithmetic word-splits it, bash strict-mode flags 'File: unbound variable.'

Fix

Per Joel: 'wrap in function possibly' + 'search for more violations.'

Two violations found:

  1. lib/airc_bash/lib_auth.sh:77 (the breaker)
  2. lib/airc_bash/platform_adapters.sh:118 (file_size — same pattern, hadn't bitten yet)

Both routed through new file_mtime / file_size helpers in platform_adapters.sh. Each helper:

  1. Tries GNU stat first (Linux + MSYS = broader audience)
  2. Validates output is numeric via _emit_if_numeric — the missing piece in the original chain. Exit code wasn't enough; output had to be checked too.
  3. Falls through to BSD stat (macOS) on validation failure
  4. file_size has additional POSIX wc -c fallback
  5. Final fallback: echo 0

_emit_if_numeric uses bash case-statement glob (*[!0-9]*) — not regex — so it works across bash versions including 3.2 (macOS default).

Verified end-to-end on Windows

$ touch /tmp/foo
$ file_mtime /tmp/foo               # 1777746712 (clean integer)
$ file_size /tmp/foo                 # 12
$ now=$(date +%s); mt=$(file_mtime /tmp/foo); echo $(( now - mt ))
# 0   ← arithmetic works, NO 'File: unbound variable'

$ airc connect
# succeeds, monitor running, takes over as host of #general per #405 self-heal

Joel's broader principle ('adapt to systems')

This whole class of bug — BSD vs GNU command flag drift — bites every cross-platform shell project. The pattern fix is: don't trust exit code alone when the command might silently succeed with the wrong shape of output. Validate semantics, fall through if not what you expected.

Worth applying to other portability sites in airc as a follow-up sweep, but this PR is hotfix-scoped to the active breaker.

🤖 Drafted with Claude Opus 4.7 (1M context)

…File: unbound variable' bug introduced by #419

## What

Two violations of the BSD-vs-GNU-stat trap fixed:

- `lib/airc_bash/lib_auth.sh:77` (the immediate breaker — airc connect
  fails on Windows after #419 cached-mtime cache check)
- `lib/airc_bash/platform_adapters.sh:118` (file_size: same pattern,
  same MSYS trap, just hadn't bitten yet)

Both now route through new `file_mtime` / `file_size` helpers in
`platform_adapters.sh` that VALIDATE the captured value is numeric
before returning. Internal `_emit_if_numeric` does the check.

## Root cause

`stat -f` is BSD's "format specifier" but GNU's "filesystem info."
On MSYS Git Bash (GNU stat), `stat -f %m FILE` exits 0 and prints
multi-line filesystem metadata to STDOUT — silently succeeding with
non-numeric junk. The standard `bsd_cmd || gnu_cmd || fallback`
chain doesn't fall through because the BSD attempt exits 0.

Captured value started with `  File: "<path>" / ID: ...`. Then
arithmetic at lib_auth.sh:78 (`$(( _now - _cache_mtime ))`) word-
splits the string and bash strict-mode flags `File: unbound variable`
when it tries to dereference `$File`.

## Fix shape (per Joel "wrap in function possibly")

Each helper:
1. Tries GNU stat first (Linux + MSYS — the broader audience)
2. Validates output with `_emit_if_numeric` (case statement, not regex,
   so it works on every bash)
3. Falls through to BSD stat (macOS) on numeric-validation failure
4. file_size has additional `wc -c` POSIX fallback
5. Final fallback: echo 0 (safe for arithmetic, signals "couldn't tell")

Adapters live in platform_adapters.sh which is already the portability
home (detect_platform, _to_win_path, _to_bash_path).

## Verified on Windows Git Bash

```
$ source lib/airc_bash/platform_adapters.sh
$ touch /tmp/foo
$ file_mtime /tmp/foo            # 1777746712 (clean integer)
$ file_size /tmp/foo             # 12
$ now=$(date +%s); mt=$(file_mtime /tmp/foo); echo $(( now - mt ))
# 0  (NO 'File: unbound variable' anymore)
```

End-to-end: `airc connect` post-fix succeeds, takes over as host of
#general, joins both subscribed channels, monitor running. Pre-fix
bombed at gh-auth-cache-check on every invocation.

## Joel's broader directive

Joel 2026-05-02: "yeah must adapt to systems" + "wrap in function
possibly" + "search for more violations". This PR addresses all three:
adapts via numeric validation (not just exit code), wraps both stat
sites in shared helpers, sweeps for more (only 2 sites; both fixed).

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 2, 2026 18:33
@joelteply
joelteply merged commit e281100 into canary May 2, 2026
8 checks passed
@joelteply
joelteply deleted the fix/portable-stat-helpers branch May 2, 2026 18: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

Hotfixes a Windows Git Bash (MSYS) regression introduced by the gh-auth OK-state cache (#419), where stat -f silently returns non-numeric filesystem metadata and breaks bash arithmetic under strict mode.

Changes:

  • Add portable file_mtime / file_size helpers in platform_adapters.sh that validate numeric output via _emit_if_numeric and fall back safely.
  • Route gh-auth cache mtime probing in lib_auth.sh through file_mtime to prevent the MSYS stat -f trap.

Reviewed changes

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

File Description
lib/airc_bash/platform_adapters.sh Introduces numeric-validating portable stat helpers; updates file_size implementation to use them.
lib/airc_bash/lib_auth.sh Replaces inline stat fallback chain with file_mtime for auth-cache age calculation.

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

Comment on lines +137 to +147
# Return file mtime as epoch seconds. Echoes 0 on any failure.
# Try GNU stat first (Linux + MSYS) since BSD `stat -f` on MSYS
# silently succeeds with filesystem metadata — that's the trap.
file_mtime() {
local path="$1"
[ -f "$path" ] || { echo 0; return 0; }
local v
if v=$(stat -c %Y "$path" 2>/dev/null) && _emit_if_numeric "$v"; then return 0; fi
if v=$(stat -f %m "$path" 2>/dev/null) && _emit_if_numeric "$v"; then return 0; fi
echo 0
}
Comment on lines +120 to +122
# arithmetic at lib_auth.sh:78 expanded the captured string and bash
# strict-mode flagged "File: unbound variable" because the captured
# value started with ` File: "<path>"`.
joelteply added a commit that referenced this pull request May 2, 2026
…once-per-session contract notice (#423)

fix(monitor,vuln-a): wrap peer chat in <peer-message> sandbox tags

Vuln-A: peer broadcasts contain raw text that reaches the AI session
via Claude Code Monitor. An attacker peer can put prompt-injection
payloads in `msg` ("ignore previous instructions and ...") and the
text arrives indistinguishable from operator commands.

Fix: wrap peer-supplied content in <peer-message>...</peer-message>
tags before printing to stdout. System events (fr in airc/sys) are
trusted and pass through unwrapped. Anthropic's prompt-injection
guidance recommends exactly this pattern for any third-party text
fed to a model — Claude has been trained on XML-tag input boundaries
forever, so the tagged content is naturally treated as data not
directives.

Plus b69f's suggestion 2026-05-02: emit a one-shot stdout contract
notice on the FIRST peer message of the session, so the receiving
Claude knows the contract surface. Idempotent — only fires once,
subsequent peer messages just get the wrap.

NOT a complete defense — sufficiently-crafted payload may still
attempt escape — but raises the bar dramatically and aligns with
the substrate's "evidence is for the debugger" rule (peer content
surfaces, but as DATA, not COMMAND). Pairs with future transport-
level peer auth (#418 design) for defense-in-depth.

## Tests

- python ast.parse: clean
- Manual smoke: send a broadcast → check formatter output has
  <peer-message> wrap + first-message contract notice
- Existing system-events still unwrapped (alice joined, watchdog
  beacons, etc.)

## Pairs with

- #418 (fusion-transport): vuln-A + transport-auth shrinks attack
  surface from "anyone with gh write" to "anyone on tailnet"
- #401, #402, #403, #404, #406, #413, #419, #421: receive-path
  silent-failure sweep. Vuln-A is the next class — silent
  injection. Now loud + sandboxed.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request May 2, 2026
…canary→main bundle

Copilot reviewed PR #422 (canary→main, 36 commits) and flagged 7 concrete
issues across the bundle. All addressed here in one focused PR so #422 can
land clean.

## Critical (silent-failure family — same family the bundle was killing)

1. **airc:2026** — `set_channel_gist --gist` is not the actual flag name
   (the CLI accepts `--gist-id` per `lib/airc_core/config.py:325`). The
   call silently rejected → rotation self-heal never updated config →
   bearers kept polling the dead gist. Fix: `--gist-id` + emit warning to
   stderr instead of `|| true` swallow. Same anti-pattern the bundle is
   removing throughout.

2. **airc:2038** — `pkill -f 'airc_core.bearer_cli recv'` is unscoped:
   would kill bearer children from OTHER scopes (different AIRC_HOME) on
   the same machine. Multi-scope safety is a load-bearing property of
   airc (per cmd_teardown's scope-isolation guarantee). Fix: scope by
   AIRC_WRITE_DIR which appears in every bearer_cli's `--state-file`
   argument, so the pkill pattern uniquely matches THIS scope's children.

3. **lib/airc_bash/lib_daemon_detect.sh:103** — `grep -E` with regex
   built from `target_scope`, only escaping `/`. Paths contain `.`
   metachars (the literal '.airc' substring matches any-char-airc),
   risking false-positive "installed for scope" against a different
   unit. Fix: `grep -F` (fixed-string), two passes for quoted and
   unquoted forms emitted by cmd_daemon.sh.

## MSYS portability (re-breaks #421's fix)

4. **airc:1934** — receive-silence beacon uses `stat -f %m` first,
   reintroducing the BSD-vs-GNU/MSYS trap that #421's `file_mtime`
   helper exists to prevent. On MSYS, `stat -f` exits 0 with non-numeric
   filesystem metadata → arithmetic later breaks under `set -u`.
   Fix: route through `file_mtime`.

5. **airc:1946** — same trap in the airc.pid mtime fallback. Same fix.

## UX consistency

6. **lib/airc_bash/cmd_send.sh:550** — gh re-auth remediation message
   omits `-s gist`. A token without gist scope can authenticate but
   can't publish, so users following the suggestion still fail at the
   same step. Fix: `gh auth login -h github.com -s gist` everywhere
   (matches the rest of the codebase per #82's gh-auth-self-heal).

## Defensive

7. **install.sh:893** — fallback when daemon-detect lib not sourced
   defines `airc_daemon_is_installed` stub but NOT
   `airc_daemon_is_installed_for_scope`. Under `set -euo pipefail` the
   bare call fails with "command not found" → install.sh exits non-zero
   instead of degrading to "treat as not-installed → offer prompt" as
   the comment promises. Fix: stub both.

## Verification

- `bash -n` clean on all four modified files.
- `python3 -m airc_core.config set_channel_gist --help` confirms
  `--gist-id` is the only accepted flag.
- `airc doctor --health` runs clean (no regression).

Credit to Copilot for the review — exactly the kind of outsider-agent
contribution that makes the bus more reliable for every kind of agent.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request May 2, 2026
…ry→main bundle (#426)

fix(copilot-#422): address all 7 review concerns from Copilot on the canary→main bundle

Copilot reviewed PR #422 (canary→main, 36 commits) and flagged 7 concrete
issues across the bundle. All addressed here in one focused PR so #422 can
land clean.

## Critical (silent-failure family — same family the bundle was killing)

1. **airc:2026** — `set_channel_gist --gist` is not the actual flag name
   (the CLI accepts `--gist-id` per `lib/airc_core/config.py:325`). The
   call silently rejected → rotation self-heal never updated config →
   bearers kept polling the dead gist. Fix: `--gist-id` + emit warning to
   stderr instead of `|| true` swallow. Same anti-pattern the bundle is
   removing throughout.

2. **airc:2038** — `pkill -f 'airc_core.bearer_cli recv'` is unscoped:
   would kill bearer children from OTHER scopes (different AIRC_HOME) on
   the same machine. Multi-scope safety is a load-bearing property of
   airc (per cmd_teardown's scope-isolation guarantee). Fix: scope by
   AIRC_WRITE_DIR which appears in every bearer_cli's `--state-file`
   argument, so the pkill pattern uniquely matches THIS scope's children.

3. **lib/airc_bash/lib_daemon_detect.sh:103** — `grep -E` with regex
   built from `target_scope`, only escaping `/`. Paths contain `.`
   metachars (the literal '.airc' substring matches any-char-airc),
   risking false-positive "installed for scope" against a different
   unit. Fix: `grep -F` (fixed-string), two passes for quoted and
   unquoted forms emitted by cmd_daemon.sh.

## MSYS portability (re-breaks #421's fix)

4. **airc:1934** — receive-silence beacon uses `stat -f %m` first,
   reintroducing the BSD-vs-GNU/MSYS trap that #421's `file_mtime`
   helper exists to prevent. On MSYS, `stat -f` exits 0 with non-numeric
   filesystem metadata → arithmetic later breaks under `set -u`.
   Fix: route through `file_mtime`.

5. **airc:1946** — same trap in the airc.pid mtime fallback. Same fix.

## UX consistency

6. **lib/airc_bash/cmd_send.sh:550** — gh re-auth remediation message
   omits `-s gist`. A token without gist scope can authenticate but
   can't publish, so users following the suggestion still fail at the
   same step. Fix: `gh auth login -h github.com -s gist` everywhere
   (matches the rest of the codebase per #82's gh-auth-self-heal).

## Defensive

7. **install.sh:893** — fallback when daemon-detect lib not sourced
   defines `airc_daemon_is_installed` stub but NOT
   `airc_daemon_is_installed_for_scope`. Under `set -euo pipefail` the
   bare call fails with "command not found" → install.sh exits non-zero
   instead of degrading to "treat as not-installed → offer prompt" as
   the comment promises. Fix: stub both.

## Verification

- `bash -n` clean on all four modified files.
- `python3 -m airc_core.config set_channel_gist --help` confirms
  `--gist-id` is the only accepted flag.
- `airc doctor --health` runs clean (no regression).

Credit to Copilot for the review — exactly the kind of outsider-agent
contribution that makes the bus more reliable for every kind of agent.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request May 2, 2026
…ore additions (#431)

feat(logs): airc logs --since <ts|Ns|Nm|Nh> for incremental polling + Windows install-state .gitignore

## Why

Codex hit context exhaustion 2026-05-02 after a session where it polled
`airc logs N` on every prompt-cycle (the satellite-mode pattern from
the just-shipped peer-architecture discussion). N=50 = ~7K tokens
re-injected per turn → quadratic context burn.

Fix: incremental polling. Agents that re-poll the bus pass the ts of
their last-seen message and get only NEW events back. O(delta) per
turn instead of O(N).

## API

```
airc logs                    # tail 20 (default, unchanged)
airc logs 100                # tail 100 (unchanged)
airc logs --since 5m         # only msgs newer than 5min ago
airc logs --since 60s        # 60 seconds ago
airc logs --since 1h         # 1 hour ago
airc logs --since 2d         # 2 days ago
airc logs --since 2026-05-02T19:30:00Z   # ISO timestamp
airc logs 100 --since 5m     # tail 100 then filter (combine)
```

`--since` filters happen client-side after `tail -N` reads from
messages.jsonl. Agents using `--since` should pass a generous N
(e.g., 200) since old messages get filtered out — and use the ts of
their last-seen msg as the next call's --since.

Backward-compatible — `--since` is optional, no-arg behavior unchanged.
Bogus --since args fail with a clear error + exit 2.

## Verification (6/6 pass)

- backward compat (`logs 5`): ✓
- relative offset (`--since 5m`): ✓ (filtered to 3 recent)
- impossible window (`--since 1s`): ✓ (0 lines)
- bogus arg (`--since garbage`): ✓ ("cannot parse 'garbage'", exit 2)
- ISO timestamp (`--since 2026-05-02T19:50:00Z`): ✓
- `--help`: ✓ (clean usage)

## Bonus: 2 more files in .gitignore

b69f's Windows QA on #430 found 2 untracked install-state files at
repo root that still trigger `(dirty)` even after #430:

  - daemon.err (post-#421 daemon launcher stderr)
  - install-elevated.ps1 (Windows elevation helper from install.ps1)

Same fix-shape as #430's .channel: per-install runtime state, never
source. Folded into this PR rather than a one-line PR — both are
context-burn-related (clean version output is less context noise to
agents that grep for `(dirty)` as a signal).

## Pairs with

- #430 (.channel ignore — same shape, different files)
- #422 (canary→main bundle — this further hardens what ships)
- The ongoing "make airc reliable across all agent kinds" work — this
  is a Codex-discovered gap, fixed by an airc primitive that benefits
  every poll-mode consumer.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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