Skip to content

refactor(adapters): iso_to_epoch dedupes BSD/GNU date split (Windows iteration step 1) - #151

Merged
joelteply merged 1 commit into
canaryfrom
feat/windows-portability-audit
Apr 27, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/windows-portability-audit

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

First step of the Windows portability iteration. Each step finds a pattern of repetition and unifies it behind an adapter, verified on Mac so we know macOS/Linux didn't break.

What

`iso_to_epoch` adapter near the existing platform adapters block. Replaces the BSD-vs-GNU `date` fork that lived inline at three callsites (heartbeat parse in cmd_connect, `_format_relative_time`, `_is_stale`).

Why

Joel 2026-04-27: "look for ways to keep these consistent, permanently."

Three callsites of the same fallback pattern means a future fix (e.g. WSL date drift, Cygwin coreutils gaps) has to land at every site. Three places to update is two too many.

The adapter also adds a python3 datetime fallback that didn't exist at any callsite before — useful on minimal MSYS/Cygwin installs where neither `date` flavor parses.

Tests

scenario_platform_adapters extended with 3 new assertions (known timestamp → expected epoch, empty input → empty output, garbage input → empty). Adjacent scenarios using iso_to_epoch downstream (list, part_persists, part_keeps_sidecar) all green.

scenario result
platform_adapters 11/11 (was 8/8)
list / rooms / ls 4/4
part_persists 8/8
part_keeps_sidecar 6/6

Out of scope (next iteration)

The deeper consistency question — bash and PowerShell ports drifting feature-for-feature — is an architectural conversation. PS port is currently behind canary by ~20 commits (last touched at #114). Filing as a separate issue so this surgical dedupe can ship now and the architectural piece gets dedicated discussion.

…tes)

Pre-fix: the BSD-vs-GNU 'date' fork had its own \`-j -u -f ... ||
date -u -d ...\` fallback chain at three callsites (heartbeat parse
in cmd_connect, _format_relative_time, _is_stale). Each chain had
slightly different error handling — heartbeat returned empty on
parse-fail and skipped the staleness check; _format_relative_time
echoed the raw ts; _is_stale returned 1. Three places, three slight
variations of "the same idea." Future fixes (e.g. WSL date drift,
Cygwin coreutils gaps) had to land at every site.

Post-fix: single iso_to_epoch helper near the platform adapters block.
Tries BSD → GNU → python3 datetime fallback. All three callsites
route through it. Each callsite kept its OWN error handling (their
semantics differ, that's fine — the parse layer is what was duplicated).

Adds python3 fallback that didn't exist anywhere before — useful on
minimal MSYS/Cygwin where neither date flavor parses. Unit-tested in
scenario_platform_adapters with a known timestamp + empty + garbage
inputs.

Joel's directive 2026-04-27: "look for ways to keep these consistent,
permanently." This is one pattern; the deeper bash↔PowerShell drift
question is a separate architectural conversation (Python truth-layer
candidate). Filing the architectural piece separately so the immediate
adapter dedupe can ship without blocking on the bigger discussion.

Test posture:
- platform_adapters: 11/11 (was 8/8; +3 for iso_to_epoch)
- list / rooms / ls: 4/4 (downstream consumer via _format_relative_time)
- part_persists, part_keeps_sidecar: 8/8 + 6/6 (heartbeat path,
  unchanged behavior)
Copilot AI review requested due to automatic review settings April 27, 2026 17:31
@joelteply
joelteply merged commit 51df415 into canary Apr 27, 2026
3 checks passed
@joelteply
joelteply deleted the feat/windows-portability-audit branch April 27, 2026 17:32

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

Refactors airc timestamp parsing by introducing a dedicated iso_to_epoch platform adapter to unify BSD/GNU (and now python) parsing behavior as part of the Windows-portability iteration, and updates integration tests to cover the new adapter.

Changes:

  • Add iso_to_epoch adapter in the Platform adapters block with BSD/GNU date parsing plus python fallback.
  • Replace three duplicated inline ISO→epoch parsing chains with calls to iso_to_epoch (cmd_connect heartbeat, _format_relative_time, _is_stale).
  • Extend scenario_platform_adapters integration coverage with known/empty/garbage input assertions for iso_to_epoch.

Reviewed changes

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

File Description
airc Adds iso_to_epoch adapter and routes existing ISO timestamp consumers through it.
test/integration.sh Adds adapter-level assertions for iso_to_epoch behavior.

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

Comment thread airc
Comment on lines +933 to +954
iso_to_epoch() {
local ts="${1:-}"
[ -z "$ts" ] && return 0
local epoch=""
if epoch=$(date -j -u -f "%Y-%m-%dT%H:%M:%SZ" "$ts" +%s 2>/dev/null); then
echo "$epoch"; return 0
fi
if epoch=$(date -u -d "$ts" +%s 2>/dev/null); then
echo "$epoch"; return 0
fi
if command -v python3 >/dev/null 2>&1; then
python3 -c "
import datetime, sys
try:
dt = datetime.datetime.strptime('$ts', '%Y-%m-%dT%H:%M:%SZ')
dt = dt.replace(tzinfo=datetime.timezone.utc)
print(int(dt.timestamp()))
except Exception:
sys.exit(1)
" 2>/dev/null
fi
}

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.

iso_to_epoch can return a non-zero exit status when the python fallback fails to parse (it sys.exit(1) and the function returns that status). Because airc runs with set -euo pipefail, callsites like _hb_ts=$(iso_to_epoch ...) / epoch=$(iso_to_epoch ...) will cause the whole command to abort on any unexpected timestamp. Make the adapter always succeed from the shell’s perspective (return 0) and signal failure only via empty stdout (e.g., swallow python’s non-zero and ensure the function ends with return 0).

Copilot uses AI. Check for mistakes.
Comment thread airc
Comment on lines +944 to +952
python3 -c "
import datetime, sys
try:
dt = datetime.datetime.strptime('$ts', '%Y-%m-%dT%H:%M:%SZ')
dt = dt.replace(tzinfo=datetime.timezone.utc)
print(int(dt.timestamp()))
except Exception:
sys.exit(1)
" 2>/dev/null

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 fallback embeds $ts directly inside a double-quoted python3 -c string. If the timestamp ever contains quotes (it comes from remote gist JSON), this can break quoting and allow shell/python code injection. Pass the timestamp as data (e.g., via argv or an env var) and parse sys.argv[1] / os.environ[...] in python, or validate it strictly before use, instead of interpolating it into the python source string.

Suggested change
python3 -c "
import datetime, sys
try:
dt = datetime.datetime.strptime('$ts', '%Y-%m-%dT%H:%M:%SZ')
dt = dt.replace(tzinfo=datetime.timezone.utc)
print(int(dt.timestamp()))
except Exception:
sys.exit(1)
" 2>/dev/null
python3 -c '
import datetime, sys
try:
dt = datetime.datetime.strptime(sys.argv[1], "%Y-%m-%dT%H:%M:%SZ")
dt = dt.replace(tzinfo=datetime.timezone.utc)
print(int(dt.timestamp()))
except Exception:
sys.exit(1)
' "$ts" 2>/dev/null

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.
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