agentleFS
littlebearappslittlebearapps/untether/CLAUDE.md

untether

CLAUDE.md72 starsChanged 4 months agoMITView on GitHub

Telegram bridge for Claude Code, Codex, OpenCode, Pi, Gemini CLI, Amp, and other agent CLIs. Control your coding agents from anywhere — walking the dog, watching footy, at a friend's place. Repo: littlebearapps/untether Based on: banteg/takopi (upstream) Untether adds interactive permission control, plan mode support, and several UX improvements on top of upstream takopi. All interactive features are Claude Code-specific; Codex, OpenCode, and other engines use standard non-interactive mode.

  • Reads credentials
  • Commits and pushes

The file

We split this CLAUDE.md into the rules it gives an agent

10 rules. About 0 are common, 4 are distinctive, and 6 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 6

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    ALWAYS test via @untether_dev_bot: before merging/releasing. Staging (@hetz_lba1_bot) runs released wheels only.

    line 273
  2. Very specific:

    All three guard scripts use the current Claude Code PreToolUse output schema (hookSpecificOutput / permissionDecision: "deny").

    line 291
  3. Very specific:

    Create PRs to dev: gh pr create --base dev --title "..." --body "..."

    line 295
  4. Very specific:

    No further manual approval is needed.

    line 305
  5. Very specific:

    All third-party actions are pinned to commit SHAs (supply chain protection).

    line 357
  6. Distinctive:

    Every bug fix and significant change MUST have a GitHub issue:

    line 367
  7. Distinctive:

    Bugs found during debugging: create an issue before or alongside the fix

    line 368
  8. Very specific:

    Issue links: every fix/change entry must reference its GitHub issue: #N

    line 378
  9. Distinctive:

    Before tagging a release:

    line 389
  10. Distinctive:

    All related GitHub issues exist and are referenced in CHANGELOG.md

    line 390

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

Untether

Telegram bridge for Claude Code, Codex, OpenCode, Pi, Gemini CLI, Amp, and other agent CLIs. Control your coding agents from anywhere — walking the dog, watching footy, at a friend's place.

Repo: littlebearapps/untether Based on: banteg/takopi (upstream)

Untether adds interactive permission control, plan mode support, and several UX improvements on top of upstream takopi. All interactive features are Claude Code-specific; Codex, OpenCode, and other engines use standard non-interactive mode.

Features (vs upstream takopi)

  • Interactive permission control — bidirectional Telegram buttons for tool approval, plan mode, and clarifying questions
  • Pause & Outline Plan — third button on plan approval; the outline (chat text, or the ExitPlanMode plan input on plan-file CLIs, #659) is posted with Approve/Deny/Let's discuss buttons (hold-open keeps session alive while user reads); the v2.1.72-74-era progressive cooldown was retired in #570 (upstream retry loop fixed, verified on CLI 2.1.215)
  • Agent context preamble — configurable prompt preamble tells agents they're on Telegram and requests structured end-of-task summaries; [preamble] config section
  • /planmode — toggle permission mode per chat (on/off/auto)
  • /listen — set listen mode (all / mentions) per chat or topic; controls when the bot responds in groups; renamed from /trigger in v0.35.3 (#297) to disambiguate from webhook/cron triggers — /trigger still works as a deprecated alias for one release cycle
  • Ask mode — interactive AskUserQuestion with option buttons, sequential multi-question flows, and /config toggle; Claude-only
  • Early callback answering — clears button spinners immediately instead of waiting for processing
  • Approval push notifications — separate notify message when approval buttons appear
  • Ephemeral message cleanup — approval-related messages auto-delete when run finishes
  • Bold formatting — command responses use HTML bold for key values
  • /usage — shows API usage and cost for the current session
  • /export — exports session transcript as markdown or JSON
  • /browse — navigate project files via inline keyboard buttons
  • Cost tracking and budget — per-run and daily cost limits with configurable alerts
  • Subscription usage footer — configurable [footer] to show 5h/weekly subscription usage instead of/alongside API costs
  • Graceful restart — /restart command drains active runs before restarting; SIGTERM also triggers graceful drain
  • Compact startup message — version number, conditional diagnostics (only shows mode/topics/triggers/engines when they carry signal), project count instead of full list
  • Workflow mode indicator — startup message shows mode: assistant, mode: workspace, or mode: handoff; derived from session_mode + topics.enabled
  • Model/mode footer — final messages show model name + permission mode (e.g. 🏷 sonnet · plan) from StartedEvent.meta; all engines populate model info
  • /verbose — toggle verbose progress mode per chat; shows tool details (file paths, commands, patterns) in progress messages
  • /config — inline settings menu with navigable sub-pages; toggle plan mode, ask mode, verbose, engine, trigger via buttons
  • [progress] config — global verbosity and max_actions settings in untether.toml
  • Pi context compaction — AutoCompactionStart/AutoCompactionEnd events rendered as progress actions
  • Stall diagnostics & liveness watchdog — /proc process diagnostics (CPU, RSS, TCP, FDs), progressive stall warnings with Telegram notifications, liveness watchdog for alive-but-silent subprocesses, stall auto-cancel (dead process, no-PID zombie, absolute cap) with CPU-active suppression (sleeping-process aware — shows tool name when main process waiting on child), tool-active repeat suppression (first warning fires, repeats suppressed while child CPU-active), MCP tool-aware threshold (15 min for network-bound MCP calls vs 10 min for local tools) with contextual "MCP tool running: {server}" messaging, session.summary structured log; bare rate_limit_events latch a conservative 60s wait so throttled sessions aren't mistaken for hung ones (#657); [watchdog] config section with configurable tool_timeout, mcp_tool_timeout, and stream_idle_auto_retry/stream_idle_max_retries (#572 — bounded auto-resume of Type-A mid-generation API stalls, default off; Type-B never retries)
  • Auto-continue — detects Claude Code sessions that exit after receiving tool results without processing them (upstream bugs #34142, #30333) and auto-resumes; suppressed on signal deaths (rc=143/SIGTERM, rc=137/SIGKILL) to prevent death spirals under memory pressure; configurable via [auto_continue] with enabled (default true) and max_retries (default 1)
  • Empty-resume recovery (quarantine-and-fresh) (#631, #632) — a resume that returns 0 turns/$0 (upstream dangling-tool_use defect) quarantines the session in session_quarantine.json and auto-resends the message once on a fresh session; sessions SIGTERM'd after a result (forced_teardown_after_result) are quarantined proactively so the next message diverts to a fresh session before any empty result is seen; [auto_continue] flags empty_resume_fresh and quarantine_on_forced_teardown (both default true); structured events runner.empty_result → session.quarantined → session.auto_resend_fresh/session.resume_diverted_fresh; Claude runner only
  • MCP catalog observability + proactive refresh (#365) — catalog_staleness.detected structlog WARNING once per (session, server, status) tuple when Claude's system.init reports a non-connected MCP status (detect_catalog_staleness, default on); opt-in fire-and-forget mcp_status control_request after each tool_result to nudge Claude Code's catalog (notify_catalog_refresh, default off). Request IDs use the ut_catalog_refresh_<session_id>_<seq> namespace; drained via ClaudeRunner._drain_catalog_refresh. Logs catalog.refresh_sent INFO / catalog.refresh_failed WARN/ERROR. Claude runner only
  • File upload deduplication — auto-appends _1, _2, … when target file exists, instead of requiring --force; media groups without captions auto-save to incoming/
  • Agent-initiated file delivery (outbox) — agents write files to .untether-outbox/ during a run; Untether sends them as Telegram documents on completion with 📎 captions; deny-glob security, size limits, file count cap, auto-cleanup; [transports.telegram.files] config
  • Progress persistence — active progress messages persisted to active_progress.json; on restart, orphan messages edited to "⚠️ interrupted by restart" with keyboard removed
  • Resume line formatting — visual separation with blank line and ↩️ prefix in final message footer
  • /continue — cross-environment resume; pick up the most recent CLI session from Telegram using each engine's native continue flag (--continue, resume --last, --resume latest); supported for Claude, Codex, OpenCode, Pi, Gemini (not AMP)
  • Timezone-aware cron triggers — per-cron timezone or global default_timezone with IANA names (e.g. Australia/Melbourne); DST-aware via zoneinfo; invalid names rejected at config parse time
  • Hot-reload trigger configuration — editing untether.toml applies cron/webhook changes immediately without restart; TriggerManager holds mutable state that the cron scheduler and webhook server reference at runtime; handle_reload() re-parses [triggers] on config file change
  • Hot-reload Telegram bridge settings — voice_transcription (incl. the #638 voice_transcription_language ISO-639-1 hint), file transfer, allowed_user_ids, timing, and show_resume_line settings reload without restart; TelegramBridgeConfig unfrozen (slots kept) with update_from() wired into handle_reload(); restart-only keys (bot_token, chat_id, session_mode, topics, message_overflow) still warn
  • /at command — one-shot delayed runs: /at 30m <prompt> schedules a prompt to run in 60s–24h; /cancel drops pending delays before firing; lost on restart (documented) with a per-chat cap of 20 pending delays; telegram/at_scheduler.py holds task-group + run_job refs
  • run_once cron flag — [[triggers.crons]] entries can set run_once = true to fire once then auto-disable; cron stays in TOML and re-activates on config reload or restart
  • Trigger visibility (Tier 1) — /ping shows per-chat trigger summary (⏰ triggers: 1 cron (id, 9:00 AM daily (Melbourne))); run footer shows ⏰ cron:<id> / ⚡ webhook:<id> for trigger-initiated runs; new describe_cron() utility renders common patterns in plain English
  • Graceful restart improvements (Tier 1) — persists Telegram update_id to last_update_id.json so restarts don't drop/duplicate messages; Type=notify systemd integration via stdlib sd_notify (READY=1 + STOPPING=1); RestartSec=2
  • diff_preview plan bypass (#283) — after user approves a plan outline via "Pause & Outline Plan", the _discuss_approved flag short-circuits diff preview for subsequent Edit/Write tools so no second approval is needed
  • User-extensible env allowlist (#409) — [security] env_extra_allow and env_extra_prefix_allow (in untether.toml) extend the engine-subprocess env allowlist with per-deployment names so users can thread credential-manager tokens (1Password, Doppler, Vault, Infisical, …) without forking utils/env_policy.py. Names are validated against [A-Z_][A-Z0-9_]*. Honoured by the Claude and Pi runners and by the env_audit probe. BWS_ACCESS_TOKEN was promoted into the built-in defaults at the same time. One env_policy.user_extension INFO log per process
  • Master trigger pause toggle (#294) — TriggerManager.pause() / resume() / is_paused gate cron firing and webhook dispatch globally; webhook server returns 503 triggers paused (with Retry-After: 60); /health endpoint reflects paused state. Wired into /config two ways: home-page button row (only when triggers configured) and a dedicated 📡 Triggers page (config:tg) showing counts + Pause/Resume button. /ping switches to ⏸ triggers paused: … (suspended) while paused. Pause is in-memory only — restart auto-resumes (safe default)

See .claude/skills/claude-stream-json/ and .claude/rules/control-channel.md for implementation details.

Architecture

Telegram <-> TelegramPresenter <-> RunnerBridge <-> Runner (claude/codex/opencode/pi/gemini/amp)
                                       |
                                  ProgressTracker
  • Runners (src/untether/runners/) — engine-specific subprocess managers
  • RunnerBridge (src/untether/runner_bridge.py) — connects runners to Telegram presenter, manages ProgressEdits
  • TelegramPresenter (src/untether/telegram/bridge.py) — renders progress, inline keyboards, and answers
  • Commands (src/untether/telegram/commands/) — command/callback handlers

Key files

FilePurpose
runners/claude.pyClaude Code runner, interactive features
runners/gemini.pyGemini CLI runner
runners/amp.pyAMP CLI runner (Sourcegraph)
runner_bridge.pyConnects runners to Telegram presenter, injects agent preamble, auto-continue with signal death suppression, empty-resume quarantine-and-fresh recovery
session_quarantine.pyPersistent QuarantineStore (session_quarantine.json): poisoned-session markers, forced-teardown quarantine, resume divert (#631/#632)
cost_tracker.pyPer-run/daily cost tracking and budget alerts
commands/claude_control.pyApprove/Deny/Discuss callback handler
commands/dispatch.pyCallback dispatch and command routing
markdown.pyProgress/final message formatting, meta_line footer
commands/planmode.py/planmode toggle command
commands/usage.py/usage command
commands/export.py/export command
commands/browse.py/browse file browser
commands/restart.py/restart graceful restart command
commands/verbose.py/verbose toggle command
commands/config.py/config inline settings menu
commands/ask_question.pyAskUserQuestion option button handler
commands/topics.py/new, /ctx, /topic commands; _cancel_chat_tasks() helper
commands/listen.py/listen command (listen-mode toggle); /trigger deprecated alias (#297)
listen_mode.pyresolve_listen_mode() and should_trigger_run() for response gating
utils/proc_diag.py/proc process diagnostics for stall analysis (CPU, RSS, TCP, FDs, children)
shutdown.pyGraceful shutdown state and drain logic
telegram/bridge.pyTelegram message rendering
telegram/loop.pyTelegram update loop, signal handlers, drain-then-exit
telegram/files.pyFile upload helpers, deduplication, deny globs, atomic writes
telegram/outbox_delivery.pyAgent-initiated file delivery: scan, send, cleanup outbox files
commands.pyCommand result types
scripts/validate_release.pyRelease validation (changelog format, issue links, version match)
scripts/healthcheck.shPost-deploy health check (systemd, version, logs, Bot API)
triggers/manager.pyTriggerManager: mutable cron/webhook holder for hot-reload; atomic config swap on TOML change; crons_for_chat, webhooks_for_chat, remove_cron helpers
triggers/describe.pydescribe_cron(schedule, timezone) utility for human-friendly cron rendering
telegram/at_scheduler.py/at command state: pending one-shot delays with cancel scopes, install/uninstall, cancel per chat
telegram/commands/at.py/at command backend — parses Ns/Nm/Nh, schedules delayed run
telegram/offset_persistence.pyPersist Telegram update_id across restarts; DebouncedOffsetWriter
sdnotify.pyStdlib sd_notify client for READY=1/STOPPING=1 systemd signals
triggers/server.pyWebhook HTTP server (aiohttp); multipart parsing from cached body, fire-and-forget dispatch
triggers/dispatcher.pyRoutes webhooks/crons to run_job() or non-agent action handlers
triggers/cron.pyCron expression parser, timezone-aware scheduler loop
triggers/actions.pyNon-agent webhook actions: file_write (multipart short-circuit), http_forward, notify_only
triggers/fetch.pyCron data-fetch: HTTP GET/POST, file read, response parsing, prompt building
triggers/rate_limit.pyToken-bucket rate limiter (per-webhook + global)
triggers/ssrf.pySSRF protection for outbound HTTP requests (IP blocking, DNS validation, URL scheme check)
triggers/auth.pyBearer token and HMAC-SHA256/SHA1 webhook auth verification
triggers/settings.pyCronConfig/WebhookConfig/CronFetchConfig/TriggersSettings models, timezone validation
cliff.tomlgit-cliff config for changelog drafting

Reference docs

Detailed protocol specs and event cheatsheets for each integration:

DocPathCovers
Claude runner specdocs/reference/runners/claude/runner.mdCLI invocation, stream-json protocol, control channel, permission modes
Claude stream-jsondocs/reference/runners/claude/stream-json-cheatsheet.mdJSONL event shapes (system, assistant, user, result) with examples
Claude event mappingdocs/reference/runners/claude/untether-events.mdClaude JSONL → Untether event translation rules
Codex exec-jsondocs/reference/runners/codex/exec-json-cheatsheet.mdThread/item/turn JSONL event shapes with examples
Codex event mappingdocs/reference/runners/codex/untether-events.mdCodex JSONL → Untether event translation rules
OpenCode runner specdocs/reference/runners/opencode/runner.mdCLI invocation, step-based event model, session IDs
OpenCode stream-jsondocs/reference/runners/opencode/stream-json-cheatsheet.mdJSONL event shapes (StepStart, ToolUse, Text, StepFinish)
OpenCode event mappingdocs/reference/runners/opencode/untether-events.mdOpenCode JSONL → Untether event translation rules
Pi runner specdocs/reference/runners/pi/runner.mdCLI invocation, file-based sessions, provider/model selection
Pi stream-jsondocs/reference/runners/pi/stream-json-cheatsheet.mdJSONL event shapes (SessionHeader, AgentStart, ToolExecution)
Pi event mappingdocs/reference/runners/pi/untether-events.mdPi JSONL → Untether event translation rules
Gemini runner specdocs/reference/runners/gemini/runner.mdCLI invocation, stream-json, model selection
Gemini stream-jsondocs/reference/runners/gemini/stream-json-cheatsheet.mdJSONL event shapes (init, message, tool_use, tool_result, result, error)
Gemini event mappingdocs/reference/runners/gemini/untether-events.mdGemini JSONL → Untether event translation rules
AMP runner specdocs/reference/runners/amp/runner.mdCLI invocation, stream-json, mode/model selection
AMP stream-jsondocs/reference/runners/amp/stream-json-cheatsheet.mdJSONL event shapes (system, assistant, user, result)
AMP event mappingdocs/reference/runners/amp/untether-events.mdAMP JSONL → Untether event translation rules
Telegram transportdocs/reference/transports/telegram.mdBot API client, outbox/rate-limiting, voice transcription, forum topics
Workflow modesdocs/reference/modes.mdAssistant, workspace, handoff — settings, commands, mode-agnostic features

Skills (project-scoped)

Domain-specific Claude Code skills for working on Untether:

SkillPathUse when
Telegram Bot API.claude/skills/telegram-bot-api/Working on Telegram transport, inline keyboards, outbox, rate limiting, voice, topics
JSONL Subprocess Runner.claude/skills/jsonl-subprocess-runner/Working on runner base class, event translation, session locking, adding engines
Claude stream-json.claude/skills/claude-stream-json/Working on Claude runner, control channel, permission modes, auto-approve, outline gate
Codex/OpenCode/Pi.claude/skills/codex-opencode-pi/Working on non-Claude runners, comparing engine protocols
Untether Architecture.claude/skills/untether-architecture/Understanding overall data flow, config system, progress tracking, project system
Release Coordination.claude/skills/release-coordination/Preparing releases, version bumps, changelog drafting, issue audits, rollback procedures

Hooks (project-scoped)

Project hooks in .claude/hooks.json fire automatically:

HookTriggerWhat it does
release-guardBash: git push, git tag, gh pr merge, gh releaseBlocks pushes to master/main, tag creation, PR merging, releases; allows feature and dev branch pushes
release-guard-protectEdit/Write to guard scripts, hooks.json, or help-faq-protect.shPrevents modification of release guard infrastructure and the FAQ-protect hook
release-guard-mcpGitHub MCP write toolsBlocks merge_pull_request and writes to master/main; allows feature branches
help-faq-protectBash: rm, git rm, mv, > redirect targeting docs/faq/faq.mdBlocks deletion / move / truncate of the help-centre FAQ; edits via Edit/Write/append >> are allowed (#477, #483)
dev-workflow-guardsystemctl with untetherBlocks staging restarts during dev; guides to untether-dev; allows staging.sh/pipx upgrade path
runner-edit-contextEdit/Write to runners/*.py3-event contract, PTY lifecycle, test/doc reminders
schema-edit-contextEdit/Write to schemas/*.pymsgspec impact on parsing, fixture updates
telegram-edit-contextEdit/Write to telegram/*.pyOutbox model, callback_data limits, early answering
version-bump-checklistEdit/Write to pyproject.toml (version change)GitHub issues, CHANGELOG entry, uv lock, release checklist

Rules (project-scoped)

Rules in .claude/rules/ auto-load when editing matching files:

RuleApplies toKey constraints
runner-development.mdrunners/**, runner.pyEventFactory usage, session locking, entry point registration
telegram-transport.mdtelegram/**Outbox-only writes, 64-byte callback data, ephemeral cleanup
control-channel.mdrunners/claude.py, claude_control.pyPTY lifecycle, session registries, outline-gate mechanics
testing-conventions.mdtests/**pytest+anyio, stub patterns, 80% coverage threshold
release-discipline.mdCHANGELOG.md, pyproject.tomlGitHub issue linking, changelog format, semantic versioning
dev-workflow.mdsrc/untether/**Dev vs staging separation, never restart staging for testing, always use untether-dev
context-quality.mdAI context files (CLAUDE.md, AGENTS.md, etc.)Cross-file consistency, path verification, version accuracy, command accuracy
help-faq.mddocs/faq/**NEVER delete; keep FAQ current with feature changes; H2s must be question-shaped (#477)
workflow-commands.mdagentic loop commands (.claude/commands/*.md)Routing table + 7 cross-cutting rules (Untether-mode, release-guard, dev/staging, reuse, confirm-gated writes, idempotency, redaction); cited by every workflow command. See docs/LOOPS.md for the loop registry
kaizen.md/kaizen, /kaizen-reviewCapture shape (8 tags + evidence + S/C/R), read-only-except-one-comment boundary, propose-only promotion; full rubric in docs/kaizen/README.md

Tests

3021 unit tests, 80% coverage threshold. Integration testing against @untether_dev_bot is mandatory before every release — see docs/reference/integration-testing.md for the full playbook with per-release-type tier requirements (patch/minor/major). All integration test tiers are fully automated by Claude Code via Telegram MCP tools and Bash.

Key test files:

  • test_claude_control.py — 100 tests: control requests, response routing, registry lifecycle, auto-approve/auto-deny, tool auto-approve, custom deny messages, discuss action, early toast, outline gate (#570 retired the progressive cooldown), auto permission mode, diff_preview plan bypass
  • test_callback_dispatch.py — 26 tests: callback parsing, dispatch toast/ephemeral behaviour, early answering
  • test_exec_bridge.py — 270 tests: ephemeral notification cleanup, approval push notifications, progressive stall warnings, stall diagnostics, stall auto-cancel with CPU-active suppression (sleeping-process aware), tool-active repeat suppression, approval-aware stall threshold, MCP tool stall threshold, frozen ring buffer hung escalation, session summary, PID/stream threading, auto-continue detection, signal death suppression, Type-A stream-idle auto-retry (#572), empty-resume quarantine-and-fresh recovery, resume divert/clear, empty-result diagnostics
  • test_ask_user_question.py — 35 tests: AskUserQuestion control request handling, question extraction, pending request registry, answer routing, option button rendering, multi-question flows, structured answer responses, ask mode toggle auto-deny
  • test_diff_preview.py — 14 tests: Edit diff display, Write content preview, Bash command display, line/char truncation
  • test_cost_tracker.py — 12 tests: cost accumulation, per-run/daily budget thresholds, warning levels, daily reset, auto-cancel flag
  • test_export_command.py — 16 tests: session event recording, markdown/JSON export formatting, usage integration, session trimming
  • test_browse_command.py — 39 tests: path registry, directory listing, file preview, inline keyboard buttons, project-aware root resolution, security (path traversal)
  • test_meta_line.py — 54 tests: model name shortening, meta line formatting, ProgressTracker meta storage/snapshot, footer ordering (context/meta/resume)
  • test_runner_utils.py — 34 tests: error formatting helpers, drain_stderr capture, enriched error messages, stderr sanitisation
  • test_shutdown.py — 4 tests: shutdown state transitions, idempotency, reset
  • test_preamble.py — 6 tests: default preamble injection, disabled preamble, custom text override, empty text disables, settings defaults
  • test_restart_command.py — 3 tests: command triggers shutdown, idempotent response, command id
  • test_cooldown_bypass.py — 24 tests: outline gate (hold-open with outline, auto-deny without), plan-input gate on plan-file CLIs (#659), no-text auto-deny, hold-open outline flow (#570 retired the time-based cooldown escalation)
  • test_verbose_progress.py — 21 tests: format_verbose_detail() for each tool type, MarkdownFormatter verbose mode, compact regression
  • test_verbose_command.py — 7 tests: /verbose toggle on/off/clear, backend id
  • test_config_command.py — 240 tests: home page, plan mode/ask mode/verbose/engine/listen/model/reasoning sub-pages, toggle actions, callback vs command routing, button layout, engine-aware visibility, default resolution
  • test_pi_compaction.py — 6 tests: compaction start/end, aborted, no tokens, sequence
  • test_proc_diag.py — 24 tests: format_diag, is_cpu_active, collect_proc_diag (Linux /proc reads), ProcessDiag defaults
  • test_exec_runner.py — 22 tests: event tracking (event_count, recent_events ring buffer, PID in StartedEvent meta), JsonlStreamState defaults
  • test_build_args.py — 42 tests: CLI argument construction for all 6 engines, model/reasoning/permission flags
  • test_telegram_files.py — 17 tests: file helpers, deduplication, deny globs, default upload paths
  • test_telegram_file_transfer_helpers.py — 48 tests: /file put and /file get command handling, media groups, force overwrite
  • test_loop_coverage.py — 29 tests: update loop edge cases, message routing, callback dispatch, shutdown integration
  • test_telegram_topics_command.py — 16 tests: /new cancellation (cancel helper, chat/topic modes, running task cleanup), /ctx binding, /topic command
  • test_trigger_server.py — 18 tests: health, auth, event filter, multipart (file upload, form fields, size limit, filename sanitisation, auth rejection), rate limit burst 429, fire-and-forget dispatch
  • test_trigger_actions.py — 29 tests: file_write (traversal, deny globs, size, conflicts, multipart short-circuit), http_forward (SSRF, retries, headers), notify_only
  • test_trigger_cron.py — 21 tests: 5-field cron matching, timezone conversion (Melbourne, DST, per-cron/default override), step validation
  • test_trigger_settings.py — 41 tests: CronConfig/WebhookConfig/CronFetchConfig/TriggersSettings validation, action fields, multipart defaults, timezone
  • test_trigger_ssrf.py — 73 tests: IPv4/IPv6 blocking, URL validation, DNS resolution, allowlist overrides
  • test_trigger_fetch.py — 12 tests: HTTP GET/POST, file read, parse modes, failure handling, prompt building
  • test_trigger_auth.py — 12 tests: bearer token, HMAC-SHA256/SHA1, timing-safe comparison
  • test_trigger_rate_limit.py — 5 tests: token bucket fill/drain, per-key isolation, refill timing
  • test_trigger_manager.py — 23 tests: TriggerManager init/update/clear, webhook server hot-reload (add/remove/update routes, secret changes, health count), cron schedule swapping, timezone updates; rc4 helpers (crons_for_chat, webhooks_for_chat, cron_ids, webhook_ids, remove_cron, atomic iteration)
  • test_describe_cron.py — 31 tests: human-friendly cron rendering (daily, weekday ranges, weekday lists, single day, timezone suffix, fallback to raw, AM/PM boundaries)
  • test_trigger_meta_line.py — 6 tests: trigger source rendering in format_meta_line(), ordering relative to model/effort/permission
  • test_bridge_config_reload.py — 20 tests: TelegramBridgeConfig unfrozen (slots preserved), update_from() copies all 11 fields, files swap, chat_ids/voice_transcription_api_key edge cases, trigger_manager field default, RESTART_REQUIRED_FIELDS ClassVar invariants (#318), _notify_restart_required broadcast to project chats + admin DMs with per-chat failure isolation (#318 follow-up)
  • test_at_command.py — 34 tests: /at parse (valid/invalid suffixes, bounds, case-insensitive), _format_delay, schedule/cancel, per-chat cap, scheduler install/uninstall
  • test_offset_persistence.py — 15 tests: Telegram update_id round-trip, corrupt JSON handling, atomic write, DebouncedOffsetWriter interval/max-pending semantics, explicit flush
  • test_sdnotify.py — 7 tests: NOTIFY_SOCKET handling (absent/empty/filesystem/abstract-namespace), send error swallowing, UTF-8 encoding
  • test_session_quarantine.py — 7 tests: QuarantineStore round-trip persistence, engine isolation, malformed/corrupt state-file resilience, age-based pruning to disk, singleton accessor + injection (#631/#632)
  • test_noop_resume_harness.py — 3 tests: end-to-end no-op empty-resume reproduction via the fake-claude CLI (tests/fake_clis/fake_claude_noop_resume.py) — real ClaudeRunner + handle_message drive quarantine-and-fresh recovery, healthy-resume negative control, linger-scenario emission shape (#634)
  • test_attestation_marker.py — 5 tests: scripts/run-integration-tests.sh SHA-binding (#674) — head_sha auto-derived from the script repo, --head-sha + UT_INTEGRATION_HEAD_SHA overrides, dev_bot_id default + UT_DEV_BOT_ID override, tiers/notes preserved in the marker JSON

Development

Two instances run on lba-1 — staging (PyPI/TestPyPI) and dev (local editable source). See docs/reference/dev-instance.md for full quickref including the staging workflow. See docs/reference/integration-testing.md for the structured integration test playbook run against @untether_dev_bot before every release. All integration test tiers are fully automated by Claude Code via Telegram MCP tools (send_message, get_history, list_inline_buttons, press_inline_button, reply_to_message, send_voice, send_file) and Bash (journalctl, kill -TERM, FD/zombie checks).

Staging (@hetz_lba1_bot)Dev (@untether_dev_bot)
Serviceuntether.serviceuntether-dev.service
Binary~/.local/bin/untether (pipx).venv/bin/untether (editable)
Config~/.untether/untether.toml~/.untether-dev/untether.toml
SourcePyPI release or TestPyPI rcLocal /home/nathan/untether/src/

3-phase release workflow (MANDATORY)

  1. Dev — fix code, run unit tests, test via @untether_dev_bot (6 engine chats), run integration tests
  2. Fleet rollout (rc) — bump to X.Y.ZrcN, merge feature branches to dev → CI publishes to TestPyPI, attest tests via scripts/run-integration-tests.sh ${VERSION} --manual, then scripts/fleet-rollout.sh ${VERSION} rolls the rc to all 5 hosts (lba-1 staging + nsd VPS + channelo VPS + sl VPS + Mac) in parallel
  3. Release — bump to X.Y.Z, write changelog, PR from dev → master. After merge, scripts/fleet-rollout.sh ${VERSION} rolls the stable PyPI build to all 5 hosts in parallel. release.yml publishes to PyPI automatically; the master PR merge IS the approval.

Branch model: feature/* → PR → dev (TestPyPI) → PR → master (PyPI). Master always matches the latest PyPI release.

NEVER skip integration testing for minor/major releases. NEVER skip the attestation gate. fleet-rollout.sh enforces the gate — no production upgrades without a passing @untether_dev_bot test run on file.

Claude Code's role in each phase:

  • Dev: edit code, run tests, push feature branches, create PRs to dev, run integration tests via Telegram MCP
  • Staging/Release: prepare version bumps, changelog entries, and commit on feature branches — Nathan merges PRs to dev and master, creates tags, and approves PyPI deploys

Claude Code MUST NOT push to master, merge PRs, create version tags, or trigger releases. These are enforced by hooks and GitHub rulesets (see "Release guard" below).

Dev/staging separation (CRITICAL)

  • NEVER restart untether.service (staging) to test local code changes. Staging runs a PyPI/TestPyPI wheel — local edits have no effect on it. Restarting staging during development is always wrong.
  • ALWAYS use untether-dev.service for testing. It runs the local editable source.
  • ALWAYS test via @untether_dev_bot before merging/releasing. Staging (@hetz_lba1_bot) runs released wheels only.
  • Staging is restarted after scripts/staging.sh install (TestPyPI rc) or pipx upgrade untether (PyPI release).

See .claude/rules/dev-workflow.md for full rules.

Release guard (CRITICAL)

Multi-layer protection prevents accidental merges to master and PyPI publishes. Claude Code cannot circumvent these protections.

GitHub server-side (unbypassable):

  • Branch ruleset "Protect master — no direct push" — all changes to master require a PR, no admin bypass
  • CODEOWNERS — * @littlebearapps/core ensures Nathan reviews every PR to master

Local hooks (defense-in-depth):

  • release-guard.sh — blocks git push to master/main, git tag v*, gh release create, gh pr merge to non-dev; feature and dev branch pushes allowed
  • release-guard-protect.sh — blocks Edit/Write to guard scripts and .claude/hooks.json
  • release-guard-mcp.sh — blocks GitHub MCP merge_pull_request and writes to master/main; feature and dev branches allowed

All three guard scripts use the current Claude Code PreToolUse output schema (hookSpecificOutput / permissionDecision: "deny"). Earlier versions used the legacy {"decision":"block"} shape, which Claude Code silently ignored — that bug is fixed.

Claude Code MUST:

  • Push to feature branches: git push -u origin feature/<name>
  • Create PRs to dev: gh pr create --base dev --title "..." --body "..."
  • Merge PRs to dev (allowed): gh pr merge <number> --squash (TestPyPI/staging only)
  • Let Nathan merge PRs to master — that merge is now the single release gate

Claude Code MUST NOT merge PRs targeting master — only dev merges are allowed.

Single-gate release flow: Once Nathan squash-merges a PR with a stable version (e.g. 0.35.2, no rc/a/b/dev suffix) to master:

  1. auto-tag-on-master.yml detects the version bump and pushes v0.35.2
  2. release.yml fires on the tag, runs full CI (validate version, pytest, build, twine check), publishes to PyPI via OIDC trusted publishing, and creates the GitHub Release with wheel + sdist

No further manual approval is needed. The PR merge IS the release approval. Pre-release versions (e.g. 0.35.2rc1) are skipped by auto-tag-on-master.yml so staging-PR merges don't accidentally publish.

Self-guarding: the hook scripts, .claude/hooks.json, and GitHub rulesets cannot be modified by Claude Code. Only Nathan can change these by editing files manually outside Claude Code.

# Dev cycle: edit source → restart dev → test via @untether_dev_bot
systemctl --user restart untether-dev
journalctl --user -u untether-dev -f

# Single-host staging (lba-1 only — legacy single-bot path)
scripts/staging.sh install X.Y.ZrcN
systemctl --user restart untether

# Fleet rollout to all 5 hosts (lba-1 + nsd + channelo + sl + mac)
scripts/run-integration-tests.sh X.Y.ZrcN --manual    # attest via @untether_dev_bot
scripts/fleet-rollout.sh X.Y.ZrcN                     # parallel upgrade
scripts/fleet-rollout.sh X.Y.ZrcN --dry-run           # preview
scripts/fleet-rollback.sh X.Y.(Z-1) --only mac        # revert one host

# Promote to stable (only after PyPI release)
scripts/staging.sh reset && systemctl --user restart untether

# Tests / lint
uv run pytest
uv run ruff check src/

See .claude/rules/release-discipline.md ("Fleet rollout (rc and stable)") and docs/plans/2026-05-13-fleet-monitoring-and-upgrades.md for the full design.

CI Pipeline

GitHub Actions CI runs on push to master/dev and on PRs:

JobWhat it checks
formatruff format --check --diff
ruffruff check with GitHub annotations
tyType checking (Astral's ty, informational — continue-on-error)
pytestTests on Python 3.12, 3.13, 3.14 with 80% coverage threshold
builduv build + twine check + check-wheel-contents validation
lockfileuv lock --check ensures lockfile is in sync
install-testClean wheel install + smoke-test imports (catches undeclared deps)
testpypi-publishPublishes to TestPyPI on dev push (OIDC, skip-existing: true)
auto-tag-on-masterOn master push: detects stable version bump in pyproject.toml, creates and pushes vX.Y.Z tag (skips pre-releases)
release-validationPR-only: validates changelog format, issue links, date when version changes
pip-auditDependency vulnerability scanning (PyPA advisory DB)
banditPython SAST (security static analysis)
codeqlCodeQL code scanning (Python + Actions), blocks PRs on new alerts
docsZensical docs build
prerelease-depsWeekly (Monday): tests with --upgrade --prerelease=allow (informational)

All third-party actions are pinned to commit SHAs (supply chain protection). Top-level permissions: {} restricts to least-privilege.

Dependabot auto-merge (dependabot-auto-merge.yml) auto-squash-merges dependency updates after CI passes. GitHub Actions deps (CI-only, never shipped) are auto-merged for all version bumps including major. Python deps (shipped in wheel) are auto-merged for patch/minor only; major bumps get flagged for manual review.

Release pipeline (release.yml) uses PyPI trusted publishing with OIDC. The pypi GitHub Environment publishes automatically once auto-tag-on-master.yml creates a vX.Y.Z tag — the PR review on master IS the release approval, so no second reviewer prompt is needed. (Earlier versions had a manual pypi environment reviewer gate; that gate was removed in favour of the single-gate flow described under "Release guard".) The testpypi environment deploys automatically on dev push. scripts/validate_release.py enforces changelog/version consistency. CODEOWNERS (* @littlebearapps/core) requires team review on all PRs.

Issue tracking & releases

GitHub issues

Every bug fix and significant change MUST have a GitHub issue:

  • Bugs found during debugging: create an issue before or alongside the fix
  • Issue body: description, impact, affected files, fix reference
  • Labels: bug, enhancement, documentation as appropriate; severity on bugs via severity:critical|major|minor|trivial; priority: low|medium|high (note space) for human triage
  • Auto-filed sources: auto:error-report (untether-issue-watcher daemon, log-pattern errors — runs on all 5 fleet hosts (lba-1, nsd, channelo, sl, mac); each filing is host-tagged via the HOST env in the daemon's unit/plist) and auto:monitor-audit (/monitor command audit loop, bugs + enhancements — 5 per-host configs plus the untether-fleet meta-target for cross-host audits)
  • Closing: reference the fixing PR or commit in a close comment

Changelog

CHANGELOG.md must be updated with every version bump:

  • Format: ## vX.Y.Z (YYYY-MM-DD) with ### fixes, ### changes, ### breaking, ### docs, ### tests subsections
  • Issue links: every fix/change entry must reference its GitHub issue: [#N](https://github.com/littlebearapps/untether/issues/N)
  • Scope: one changelog section per release, no retroactive edits to prior sections

Version bumps (semantic versioning)

  • Patch (0.23.x → 0.23.y): bug fixes, schema additions for new upstream events, dependency updates
  • Minor (0.x.0 → 0.y.0): new features, new commands, new engine support, config additions
  • Major (x.0.0 → y.0.0): breaking changes to config format, runner protocol, or public API

Release checklist

Before tagging a release:

  1. All related GitHub issues exist and are referenced in CHANGELOG.md
  2. CHANGELOG.md has an entry for the new version with correct date
  3. pyproject.toml version matches the changelog heading
  4. Tests pass: uv run pytest
  5. Lint clean: uv run ruff check src/
  6. Lockfile synced: uv lock --check

Documentation screenshots

48 screenshots in docs/assets/screenshots/ with a tracking checklist in CAPTURES.md. README uses a composite hero collage (hero-collage.jpg) built with ImageMagick for mobile responsiveness. Doc files use HTML <img> tags with width="360" and loading="lazy" (works in both GitHub and MkDocs). 14 screenshots are still missing and commented out with <!-- TODO: capture screenshot --> markers.

Help-centre FAQ

docs/faq/faq.md (12 H2 question-shaped Q/A pairs; renamed from docs/faq/index.md in #483 so the help-centre URL becomes /help/untether/faq/) backs the marketing-site FAQPage Schema.org pipeline shipped on feature/help-seo-geo-items-1-4 in littlebearapps/littlebearapps.com. Once the docs-sync mapping in scripts/docs-sync.config.ts registers untether → docs/faq → category: faq, the marketing site emits <script type="application/ld+json"> FAQPage JSON-LD on every help-centre deploy, unlocking AI-citation surface (ChatGPT, Perplexity, Google AI Overviews) and SERP rich-snippet eligibility.

The file MUST NOT be deleted or moved — that silently breaks the docs-sync mapping and regresses the schema on the next deploy. The repo enforces this via the help-faq-protect.sh Bash hook which blocks rm, git rm, mv-away, and shell > truncation. Edits ARE encouraged: keep the FAQ in sync with new features as they land in CHANGELOG.md. See .claude/rules/help-faq.md for the full update cadence and shape rules. Tracking issues: #477 (creation), #483 (URL rename).

Conventions

  • Python 3.12+, anyio for async, msgspec for JSONL parsing, structlog for logging
  • Ruff for linting, pytest with coverage for tests
  • Runner backends registered via entry points in pyproject.toml

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.