Dicklesworthstone/repo_updater
About
Pure-bash CLI for keeping hundreds of GitHub repos in sync: parallel clone/pull, conflict detection, JSON output, and meaningful exit codes for CI
Developer ToolsWhat you can do
- Checksum verification: Installer verifies SHA256 before installation
- Release downloads: Default installation from GitHub Releases, not main
- No credential storage: Uses gh CLI's secure credential storage
- Prompted installation: Never auto-installs without user confirmation
Measured star growth
- in 24h
- 0
- in 7 days
- +1
- in 15 days
- +1
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
Original
ru
Repo Updater
A beautiful, automation-friendly CLI for synchronizing GitHub repositories
Keep dozens (or hundreds) of repos in sync with a single command.
Clone missing repos, pull updates, detect conflicts, and get actionable resolution commands.
Pure Bash with no string parsing of git output. Uses git plumbing for reliable status detection.
Meaningful exit codes for CI. JSON output for scripting. Non-interactive mode for automation.
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/repo_updater/main/install.sh?ru_cb=$(date +%s)" | bash
# You can omit the `?ru_cb=...` once installed; it's just a cache-buster for the installer fetch.
Or via Homebrew (macOS/Linux):
brew install dicklesworthstone/tap/ru
🤖 Agent Quickstart (JSON/TOON)
Use structured output in agent contexts. stdout = data, stderr = diagnostics, exit 0 = success.
# Sync all repos (machine-readable)
ru sync --json
# Preview without changes
ru sync --dry-run --json
# Status only (no fetch)
ru status --no-fetch --json
# Same envelope as TOON, which uses fewer tokens (needs toon_rust's `toon` CLI,
# or `tru` before v0.2; without one, ru warns and prints JSON)
ru status --no-fetch --format toon
# Machine-readable CLI documentation
ru robot-docs # All topics as JSON
ru robot-docs commands # Command/flag reference
ru robot-docs quickstart # Getting started guide
ru robot-docs examples # Usage examples
ru robot-docs exit-codes # Exit code reference
ru robot-docs formats # Output format details
ru robot-docs schemas # JSON schemas for command outputs
ru --schema # Shortcut for ru robot-docs schemas
🤖 Ready-made Blurb for AI Agents
[!IMPORTANT] Copy the blurb below to your project's
AGENTS.md,CLAUDE.md, or.cursorrulesfile for AI agent integration with ru.
## ru Quick Reference for AI Agents
Syncs GitHub repos to local projects directory (clone missing, pull updates, detect conflicts).
```bash
ru sync # Sync all repos
ru sync --dry-run # Preview only
ru sync -j4 --autostash # Parallel + auto-stash
ru status --no-fetch # Quick local status
ru list --paths # Repo paths (stdout)
```
**Automation:** `--non-interactive --json` (structured→stdout, human→stderr).
**Exit:** 0=ok | 1=partial | 2=conflicts | 3=system | 4=bad args | 5=interrupted (`--resume`)
**Critical:**
- Never create worktrees/clones in projects dir → use `/tmp/`
- Never parse human output → use `--json`
🎯 The Primary Use Case: Keeping Your Projects Directory in Sync
The scenario: You work across multiple machines, contribute to dozens of repositories, and your local /data/projects directory needs to stay synchronized with GitHub. Manually running git pull in each directory is tedious and error-prone.
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Your Repos │ │ repos.d/ │ │ ru │
│ on GitHub │────▶│ public.txt │────▶│ sync │
│ (47 repos) │ │ private.txt │ │ │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
┌──────────────────────────────────────────────┤
▼ ▼ ▼
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Clone Missing │ │ Pull Updates │ │ Report Status │
│ (8 new repos) │ │ (34 updated) │ │ (2 conflicts) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
│
▼
┌─────────────────┐
│ Actionable │
│ Resolution │
│ Commands │
└─────────────────┘
The workflow:
- Configure once — Add repos to
~/.config/ru/repos.d/public.txt - Run
ru sync— Everything happens automatically - Review conflicts — Get copy-paste commands to resolve issues
# On any machine, sync all 47 of your repos
ru sync
# Output:
# → Processing 1/47: mcp_agent_mail
# ├─ Path: /data/projects/mcp_agent_mail
# ├─ Status: behind (0 ahead, 3 behind)
# └─ Result: ✓ Updated (2s)
#
# ╭─────────────────────────────────────────────────────────────╮
# │ 📊 Sync Summary │
# │ ✅ Cloned: 8 repos │
# │ ✅ Updated: 34 repos │
# │ ⏭️ Current: 3 repos │
# │ ⚠️ Conflicts: 2 repos (need attention) │
# │ Total: 47 repos processed in 2m 34s │
# ╰─────────────────────────────────────────────────────────────╯
Comparison:
| Without ru | With ru |
|---|---|
cd into each of 47 directories and git pull |
One command syncs everything |
| Forget which repos exist locally vs remotely | Automatically clones missing repos |
| Wonder if your local branch diverged | Clear status: behind, ahead, diverged, conflict |
| Google the right git commands for conflicts | Copy-paste resolution commands provided |
| Manual process breaks when network fails | Meaningful exit codes for scripting |
Table of Contents
- Ready-made Blurb for AI Agents
- The Primary Use Case
- Why ru Exists
- Highlights
- Quickstart
- Commands
- Configuration
- Repo List Format
- Sync Workflow
- Git Status Detection
- Conflict Resolution
- Managing Orphan Repositories
- Output Modes
- AI-Assisted Code Review
- Agent-Driven Sweep
- AI Sync
- Dependency Updates
- Exit Codes
- Architecture
- Design Principles
- File Denylist System
- Testing
- Troubleshooting
- Environment Variables
- Dependencies
- Security & Privacy
- Uninstallation
- Contributing
- License
💡 Why ru Exists
Managing a large collection of GitHub repositories presents unique challenges:
| Problem | Why It's Hard | How ru Solves It |
|---|---|---|
| Too many repos to update manually | 47 repos × cd + git pull = wasted time |
One command syncs everything |
| New repos on GitHub not cloned locally | No way to detect missing repos automatically | Compares list to local directory, clones missing |
| Diverged branches are confusing | "Already up to date" vs actual divergence | Git plumbing detects ahead/behind/diverged states |
| Dirty working trees block pulls | Errors with uncommitted changes | Clear warnings + resolution commands |
| Different clone strategies per repo | Some need SSH, some HTTPS, some specific branches | Flexible repo spec syntax (repo@branch) |
| Need automation in CI | Interactive prompts break scripts | --non-interactive mode, JSON output, exit codes |
| Public vs private repos | Different auth requirements | Separate lists, automatic gh CLI integration |
ru brings order to your projects directory. It's the tool you wish existed every time you've thought "I should really update all my repos."
✨ Highlights
Zero-Setup InstallationOne-liner installer handles everything:
|
Automation-Grade DesignBuilt for scripting and CI from day one:
|
Git Plumbing, Not String ParsingReliable status detection:
|
Beautiful Terminal UIPowered by gum with ANSI fallbacks:
|
Subcommand ArchitectureClean CLI with focused commands:
|
Conflict Resolution HelpActionable commands for every issue:
|
Parallel & Resumable SyncsEfficient handling of large repo collections:
|
Orphan Repository ManagementKeep your projects directory clean:
|
⚡ Quickstart
Installation
Recommended: Homebrew (macOS/Linux)
brew install dicklesworthstone/tap/ru
This method provides:
- Automatic updates via
brew upgrade - Dependency management
- Easy uninstall via
brew uninstall
Windows: WSL2
ru is a bash script, so there is no native Windows package (no Scoop or winget
manifest). On Windows, install it inside WSL2 using either the Homebrew command
above or the install script below.
Alternative: Install Script
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/repo_updater/main/install.sh?ru_cb=$(date +%s)" | bash
If you suspect CDN caching (stale installer):
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/repo_updater/main/install.sh?ru_cb=$(date +%s).$$" | bash
How cache-busting works:
GitHub's raw content is served through a CDN that caches aggressively. The ?ru_cb=... query parameter ensures fresh content:
| Technique | Cache Bypass |
|---|---|
$(date +%s) |
Unix timestamp (changes every second) |
$(date +%s).$$ |
Timestamp + PID (unique per invocation) |
RU_CACHE_BUST_TOKEN=xyz |
Custom token override |
Installer self-refresh mechanism:
When the installer runs via curl | bash, it performs automatic self-refresh to ensure you always get the latest version:
┌─────────────────────────────────────────────────────────────────┐
│ Installer Self-Refresh │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────┐
│ Detect piped │◀─────── stdin is not a TTY?
│ execution │
└────────┬────────┘
│ yes
▼
┌─────────────────┐
│ Download fresh │◀─────── Fetch latest install.sh
│ installer │ to temp file
└────────┬────────┘
│
▼
┌─────────────────┐
│ Validate │◀─────── Check #!/usr/bin/env bash
│ shebang │ header is present
└────────┬────────┘
│ valid
▼
┌─────────────────┐
│ Re-exec with │◀─────── RU_INSTALLER_REFRESHED=1
│ fresh copy │ prevents infinite loop
└─────────────────┘
This ensures that even if CDN caching serves a stale version initially, the installer will fetch and execute the latest code. The RU_INSTALLER_REFRESHED=1 environment variable prevents recursion.
To disable self-refresh (for airgapped environments):
RU_INSTALLER_NO_SELF_REFRESH=1 bash install.sh
Manual installation
# Download script
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/repo_updater/main/ru -o ~/.local/bin/ru
chmod +x ~/.local/bin/ru
# Ensure ~/.local/bin is in PATH
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc # or ~/.bashrc
source ~/.zshrc
Installation options
# Custom install directory
curl -fsSL .../install.sh | DEST=/opt/bin bash
# System-wide installation (requires sudo)
curl -fsSL .../install.sh | RU_SYSTEM=1 bash
# Install specific version
curl -fsSL .../install.sh | RU_VERSION=1.0.0 bash
# Install from main branch (not recommended for production)
curl -fsSL .../install.sh | RU_UNSAFE_MAIN=1 bash
Release installation requires a matching SHA256 entry and either sha256sum
or shasum. Missing assets, checksums, or verification tools fail installation;
they never select mutable main automatically. RU_UNSAFE_MAIN=1 explicitly
opts into an unverified development script.
The curl-to-Bash bootstrap trusts the HTTPS installer download. Its optional
self-refresh also downloads the installer from mutable main; that installer
is not authenticated by the release checksum. Release checksum verification
applies to the installed ru asset. Set RU_INSTALLER_NO_SELF_REFRESH=1 to
keep the installer bytes you downloaded.
First Run
# Initialize configuration
ru init
# Add some repos
ru add Dicklesworthstone/mcp_agent_mail
ru add Dicklesworthstone/beads_viewer
# Sync everything
ru sync
🛠️ Commands
ru [command] [options]
Available Commands
| Command | Description |
|---|---|
sync |
Clone missing repos and pull updates (default) |
status |
Show repository status without making changes |
init |
Initialize configuration directory and files |
add <repo> |
Add a repository to your list |
remove <repo> |
Remove a repository from your list |
list |
Show configured repositories |
doctor |
Run system diagnostics |
self-update |
Update ru to the latest version |
config |
Show or set configuration values |
prune |
Find and manage orphan repositories |
review |
AI-assisted code review orchestration |
agent-sweep |
Orchestrate AI agents across dirty repos |
ai-sync |
Auto-commit dirty repos using AI agents (via ntm) |
dep-update |
AI-powered dependency updates across repos |
import |
Import repos from files, your GitHub stars, an org or a user |
robot-docs |
Machine-readable CLI documentation (JSON) |
Global Options
| Flag | Description |
|---|---|
--help, -h |
Show help message |
--version, -v |
Show version |
--json |
Output JSON to stdout (human output still goes to stderr) |
--quiet, -q |
Minimal output (errors only) |
--verbose |
Detailed output |
--non-interactive |
Never prompt (for CI/automation) |
Command-Specific Options
ru sync
| Flag | Description |
|---|---|
--clone-only |
Only clone missing repos, don't pull |
--pull-only |
Only pull existing repos, don't clone |
--autostash |
Stash changes before pull, pop after |
--rebase |
Replay local commits onto the fetched upstream |
--dry-run |
Show what would happen without making changes |
--dir PATH |
Override projects directory |
--parallel N, -j N |
Sync N repos concurrently (default: 4) |
--timeout SECONDS |
Network timeout for slow operations (default: 30) |
--resume |
Resume an interrupted sync from where it left off |
--restart |
Discard interrupted sync state and start fresh |
Sync checks the fetched commits before merging, rebasing, or autostashing.
If an incoming path or a replayed local commit would overwrite an ignored file,
sync leaves the local data and staging intact and keeps that repo pending.
Move the reported obstruction somewhere safe, then run ru sync --resume with
the same strategy and --autostash options. Unrelated ignored files do not block
an update.
Ad-hoc sync: You can also pass repo URLs directly without adding them to config:
ru sync owner/repo1 owner/repo2 https://github.com/owner/repo3
ru status
| Flag | Description |
|---|---|
--fetch |
Fetch remotes first (default) |
--no-fetch |
Skip fetch, use cached state |
ru add
| Flag | Description |
|---|---|
--public |
Add to public repos list (default) |
--private |
Add to private repos list |
--from-cwd |
Detect repo from current directory's git remote |
--group NAME |
Clone into a NAME/ subfolder of the layout path |
ru remove
| Flag | Description |
|---|---|
--private |
Remove from private repos list only |
--public |
Remove from public repos list only |
| (none) | Search and remove from all repo lists |
ru list
| Flag | Description |
|---|---|
--public |
Show only public repos |
--private |
Show only private repos |
--paths |
Show local paths instead of URLs |
ru init
| Flag | Description |
|---|---|
--example |
Populate repos.txt with example repositories |
ru self-update
| Flag | Description |
|---|---|
--check |
Check for updates without installing |
ru config
| Flag | Description |
|---|---|
--print |
Print all configuration values |
--set KEY=VALUE |
Set a configuration value |
ru prune
| Flag | Description |
|---|---|
| (none) | List orphan repos (dry run, default) |
--archive |
Move orphan repos to archive directory |
--delete |
Permanently delete orphan repos (requires confirmation) |
--force |
Also archive/delete clones of configured repos at old paths and (with --delete) orphans with unsaved work |
ru review
| Flag | Description |
|---|---|
--plan |
Discovery mode: find work items and plan review (default) |
--apply |
Apply mode: process approved changes from a previous plan |
--dashboard |
Launch interactive review dashboard TUI (TTY required) |
--dry-run |
Show what would be discovered without starting sessions |
--status |
Show current review state without running discovery |
--analytics |
Display analytics dashboard for past reviews |
--basic |
Use basic TUI instead of terminal multiplexer |
--mode=MODE |
Session driver: auto, ntm, or local |
--parallel N, -j N |
Run N review sessions concurrently (default: 4) |
--repos=PATTERN |
Filter repos: a glob (*, ?, [) matches the repo name or owner/repo; plain text matches as a substring |
--priority=LEVEL |
Minimum priority threshold: critical, high, normal, low, all |
--skip-days=N |
Skip unchanged items successfully reviewed within N days (default: 7; 0 forces review) |
--max-repos=N |
Limit number of repos to review (cost budget) |
--max-runtime=N |
Maximum runtime in minutes (time budget) |
--resume |
Resume an interrupted review session |
--push |
Allow pushing changes (with --apply) |
ru import
| Flag | Description |
|---|---|
--stars |
Import from your GitHub stars |
--org=NAME |
Import from an organization (repeatable) |
--user=NAME |
Import from a user's repos (repeatable) |
--limit=N |
Read at most N repos from each GitHub source |
--public |
Force all imported repos into the public list |
--private |
Force all imported repos into the private list |
--dry-run |
Preview import without modifying config |
ru agent-sweep
| Flag | Description |
|---|---|
--dry-run |
Preview which repos would be processed |
--parallel N, -jN |
Process N repos concurrently (default: 1) |
--repos=PATTERN |
Filter repos by glob pattern (plain text matches as a substring) |
--show-denylist |
List the active denylist patterns and exit |
--with-release |
Include release step after commit |
--resume |
Resume an interrupted sweep |
--restart |
Clear previous state and start fresh |
--keep-sessions |
Keep tmux sessions after completion |
--keep-sessions-on-fail |
Keep sessions only on failure |
--attach-on-fail |
Attach to session on failure |
--execution-mode=MODE |
Mode: plan, apply, or agent (default: agent) |
--secret-scan=MODE |
Secret scanning: none, warn, block (default: warn) |
--phase1-timeout=N |
Phase 1 timeout in seconds (default: 300) |
--phase2-timeout=N |
Phase 2 timeout in seconds (default: 600) |
--phase3-timeout=N |
Phase 3 timeout in seconds (default: 300) |
--json |
Output results as JSON |
--max-file-mb=N |
Max staged file size in MB |
--verbose, -v |
Verbose output |
--debug, -d |
Debug output (implies verbose) |
ru ai-sync
| Flag | Description |
|---|---|
--dry-run |
Preview dirty repos without starting AI sessions |
--include=PATTERN |
Only process matching repos (glob or plain-text substring) |
--exclude=PATTERN |
Skip matching repos (glob or plain-text substring) |
--timeout=SEC |
Per-repo timeout in seconds (default: 600) |
--no-push |
Commit changes but don't push to remote |
--agent=TYPE |
Agent type: claude (default), codex, gemini, antigravity |
--no-untracked |
Ignore untracked files when scanning for dirty repos |
--sequential |
Process repositories sequentially (default) |
ru dep-update
| Flag | Description |
|---|---|
--dry-run |
Show what would be updated (no changes) |
--manager=NAME |
Only update deps for specific manager (npm, pip, cargo, etc.) |
--include=PATTERN |
Only update deps matching regex pattern |
--exclude=PATTERN |
Skip deps matching regex pattern |
--major |
Include major version updates (default: skip major) |
--test-cmd=CMD |
Custom test command (overrides auto-detection) |
--max-fix-attempts=N |
Max fix iterations per dependency (default: 5) |
--no-push |
Commit changes but don't push to remote |
--repo=PATH |
Process single repo only (default: all repos) |
--agent=TYPE |
Agent type: claude (default), codex, gemini, antigravity |
--timeout=SEC |
Per-repo timeout in seconds (default: 900) |
Fork Previews and Checkout Selection
fork-sync and fork-clean verify the configured repository origin before
fetching and retain that check through checkout changes and publication. They
also refuse operations that would overwrite ignored local files. Their
--dry-run previews use cached upstream refs: they do not fetch, change tracking
refs, or write FETCH_HEAD. Fetch upstream explicitly before previewing when
you need a comparison against newly published commits.
Retrying Fork Cleanup Publication
When ru fork-clean --push finishes local cleanup but a receiver rejects the
push, rerun the same command with the same flags. ru checks each configured
push destination and retries only publication that remains unfinished. It does
not repeat the reset, change the current checkout, or replace the original
rescue branches. A receiver already at the intended commit needs no repeated
push or push-hook execution.
Before a destructive publication, ru requires displaced receiver history to be
preserved by the intended target, the inspected local branch, or another local
branch or tag. A fetched remote-tracking ref alone is insufficient. Unknown or
unpreserved receiver history is refused before local cleanup; fetch and preserve
that work on a local branch or tag before retrying. --no-rescue waives backup
of the inspected local branch, so a later recovery can require explicitly
retaining the old receiver tip. Each push uses the exact inspected receiver tip
as its lease and verifies the result afterward.
JSON reports confirmed publication separately in data.summary.published.
A publication-only retry reports published for the repository and leaves the
cleaned, rescued, and removed_commits counts at zero.
⚙️ Configuration
ru uses XDG Base Directory Specification for configuration.
Directory Structure
~/.config/ru/
├── config # Main configuration file
└── repos.d/
├── public.txt # Public repositories
└── private.txt # Private repositories
~/.cache/ru/
└── (runtime cache)
~/.local/state/ru/
├── logs/
│ ├── 2025-01-03/
│ │ ├── run.log # Main run log
│ │ └── repos/
│ │ ├── mcp_agent_mail.log
│ │ └── beads_viewer.log
│ └── latest -> 2025-01-03 # Symlink to latest run
└── archived/ # Orphan repos (from ru prune)
Configuration File
# ~/.config/ru/config
# Base directory for repositories
PROJECTS_DIR=/data/projects
# Directory layout: flat | owner-repo | full
# flat: $PROJECTS_DIR/repo
# owner-repo: $PROJECTS_DIR/owner/repo
# full: $PROJECTS_DIR/github.com/owner/repo
LAYOUT=flat
# Update strategy: ff-only | rebase | merge
UPDATE_STRATEGY=ff-only
# Auto-stash local changes before pull
AUTOSTASH=false
# Parallel operations (1 = serial)
PARALLEL=1
# Network timeout in seconds (for slow connections)
TIMEOUT=30
# Check for ru updates on run
CHECK_UPDATES=false
Configuration Resolution
Priority (highest to lowest):
- Command-line arguments (
--dir,--rebase, etc.) - Environment variables (
RU_PROJECTS_DIR,RU_LAYOUT, etc.) - Config file (
~/.config/ru/config) - Built-in defaults
📝 Repo List Format
Basic Format
# ~/.config/ru/repos.d/public.txt
# Lines starting with # are comments
# Empty lines are ignored
# Full URL
https://github.com/owner/repo
# Shorthand (assumes github.com)
owner/repo
# Pin to specific branch or tag
owner/repo@develop
owner/[email protected]
# Custom local directory name
owner/repo as custom-name
# Combined: branch + custom name
owner/repo@develop as dev-version
# SSH URL format
[email protected]:owner/repo.git
# SSH with custom name
[email protected]:owner/repo.git as myrepo
# Group related repos under a shared subfolder (see "Grouping Repos" below)
owner/repo-website in myproject
owner/repo-cli@develop in myproject as cli
Advanced Repo Spec Syntax
The repo spec parser supports flexible combinations:
<url_or_shorthand>[@<branch>] [in <group>] [as <local_name>]
| Spec | URL | Branch | Local Name |
|---|---|---|---|
owner/repo |
owner/repo |
(default) | repo |
owner/repo@develop |
owner/repo |
develop |
repo |
owner/repo as myrepo |
owner/repo |
(default) | myrepo |
owner/repo@v2 as stable |
owner/repo |
v2 |
stable |
[email protected]:o/r.git |
[email protected]:o/r.git |
(default) | r |
[email protected]:o/r.git as x |
[email protected]:o/r.git |
(default) | x |
Notes:
- The
@branchspecifier must come beforeas name - Branch names cannot contain
/(usev2notfeature/v2) - The SSH
@in[email protected]is not confused with branch syntax - Custom names are case-sensitive and become the directory name
in <group>andas <name>may appear in either order, once each
Grouping Repos
in <group> inserts a folder between whatever the layout produces and the repo folder. The group folder is never a repo itself; it is just a place to keep related checkouts together. URL, branch, and remotes are unchanged.
| Layout | tmchow/illo-website in illo |
|---|---|
flat |
$PROJECTS_DIR/illo/illo-website |
owner-repo |
$PROJECTS_DIR/tmchow/illo/illo-website |
full |
$PROJECTS_DIR/github.com/tmchow/illo/illo-website |
- Groups can be nested:
owner/repo in clients/acme. Each segment is validated like a custom name (no.., no leading-). - Inside a group,
as <name>renames only the repo folder:tmchow/illo-characters in illo as charactersresolves to.../tmchow/illo/characters. Without a group,as <name>keeps its old meaning and replaces the whole layout path with$PROJECTS_DIR/<name>. - The group is part of the line, so it works the same in
public.txtandprivate.txt.ru add --group illo owner/repowrites thein illoform for you. - A repo listed twice with the same local name but different groups (for example once plain and once
in illo) is kept only at its first location, with a warning. - ru refuses to clone into a path that sits inside another repository's working tree when a group folder is itself a repo (for example a group named like an existing repo). Owner and host folders are not checked, so an owner folder under version control still works.
ru prunescans one level inside group folders, and never treats a repo that contains a configured repo as an orphan.
Supported URL Formats
All of these are equivalent:
https://github.com/owner/repo
https://github.com/owner/repo.git
[email protected]:owner/repo.git
github.com/owner/repo
owner/repo
Path Layout Examples
| Layout | Input | Local Path |
|---|---|---|
flat |
Dicklesworthstone/mcp_agent_mail |
/data/projects/mcp_agent_mail |
owner-repo |
Dicklesworthstone/mcp_agent_mail |
/data/projects/Dicklesworthstone/mcp_agent_mail |
full |
Dicklesworthstone/mcp_agent_mail |
/data/projects/github.com/Dicklesworthstone/mcp_agent_mail |
Note:
flatlayout is the default for backwards compatibility with existing/data/projectsstructures. Useowner-repoif you have repos with the same name from different owners.
Path Collision Detection
When using flat layout, different owners may have repositories with the same name. ru automatically detects these collisions:
⚠️ Path collision detected:
user1/myapp -> /data/projects/myapp
user2/myapp -> /data/projects/myapp
Only the first repository will be synced to this path.
Consider using: ru config --set LAYOUT=owner-repo
How collision detection works:
- Before syncing, ru resolves all repo URLs to local paths
- Different repositories or incompatible branch/tag pins at the same path produce a warning
- The first occurrence in your config wins; conflicting requests are skipped and reported as
collision syncandstatusreturn exit code 2 for collisions; sync includes them in its conflict summary, even on--dry-runor--resume- Equivalent URL forms with the same repository, destination and pin are ordinary duplicates
JSON collision records include configured_spec for the skipped request and
selected_spec for the first request using that path. A completed first request
does not satisfy a conflicting pin during resume. Resolving the configuration
conflict causes resume to recheck the configured destinations.
Resolution options:
- Use
owner-repolayout:ru config --set LAYOUT=owner-repo - Use custom names:
user2/myapp as myapp-user2 - Use one branch/tag pin per destination, or give additional pins distinct custom names
- Remove the conflicting entry from your config
🔄 Sync Workflow
What ru sync Does
┌─────────────────────────────────────────────────────────────────┐
│ ru sync │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────┐
│ Load repo │
│ lists │
└────────┬────────┘
│
▼
┌─────────────────┐
│ For each repo: │
└────────┬────────┘
│
┌──────────────┼──────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Missing? │ │ Exists? │ │ Mismatch?│
│ → Clone │ │ → Pull │ │ → Warn │
└──────────┘ └──────────┘ └──────────┘
│
▼
┌─────────────────┐
│ Check status │
│ (plumbing) │
└────────┬────────┘
│
┌───────────────────┼───────────────────┐
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌────────────┐
│ current │ │ behind │ │ diverged │
│ → Skip │ │ → Pull │ │ → Report │
└────────────┘ └────────────┘ └────────────┘
│
▼
┌─────────────────┐
│ Write result │
│ to log │
└────────┬────────┘
│
▼
┌─────────────────┐
│ Print summary │
│ + exit code │
└─────────────────┘
Per-Repo Processing
For each repository in your lists:
- Parse URL — Extract host, owner, repo name
- Compute local path — Based on layout configuration
- Check existence — Does the directory exist?
- If missing → Clone with
gh repo clone - If exists → Verify remote URL matches, then check status
- Get status — Using git plumbing (ahead/behind/dirty)
- Take action — Pull if behind, skip if current, warn if diverged
- Log result — Per-repo log file + NDJSON result
Parallel Sync
When syncing many repositories, parallel execution can significantly reduce total sync time:
# Sync 4 repos at a time
ru sync --parallel 4
# Or use the short form
ru sync -j 8
How it works:
- Worker pool — ru spawns N worker processes (specified by
--parallelor-j) - Job queue — Repositories are distributed among workers as they become available
- Portable coordination — Directory-based locking prevents race conditions in shared resources
- Aggregated results — All worker results are collected and reported in a unified summary
┌─────────────────────────────────────────────────────────────────┐
│ ru sync --parallel 4 │
└─────────────────────────────────────────────────────────────────┘
│
┌──────────────┼──────────────┐
▼ ▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Worker 1 │ │ Worker 2 │ │ Worker 3 │ │ Worker 4 │
│ repo A │ │ repo B │ │ repo C │ │ repo D │
│ repo E │ │ repo F │ │ repo G │ │ repo H │
│ ... │ │ ... │ │ ... │ │ ... │
└──────────┘ └──────────┘ └──────────┘ └──────────┘
│ │ │ │
└──────────────┴──────────────┴──────────────┘
│
▼
┌─────────────────┐
│ Unified │
│ Summary │
└─────────────────┘
Configuration:
# Set default parallelism in config
ru config --set PARALLEL=4
# Or use environment variable
export RU_PARALLEL=4
Requirements:
- None (portable locking is built in)
Network Timeout Tuning
For slow or unreliable networks, ru provides timeout configuration to prevent hangs:
# Command-line override
ru sync --timeout 60
# Config file
# ~/.config/ru/config
TIMEOUT=60
# Environment variable
export RU_TIMEOUT=60
Timeout precedence is CLI --timeout, then RU_TIMEOUT, then GIT_TIMEOUT,
then the config file's TIMEOUT, then the 30-second default. The selected value
bounds the entire clone, fetch, or pull command, including a stalled subprocess.
Advanced tuning via git environment:
| Variable | Default | Purpose |
|---|---|---|
GIT_TIMEOUT |
30 | Overall network timeout in seconds |
GIT_LOW_SPEED_LIMIT |
1000 | Abort if transfer falls below this bytes/second |
# For very slow connections
GIT_TIMEOUT=120 GIT_LOW_SPEED_LIMIT=100 ru sync
Timeout error detection:
ru automatically recognizes timeout-related errors:
- "RPC failed"
- "timed out"
- "remote end hung up unexpectedly"
- "transfer rate too slow"
When a timeout is detected, the conflict resolution output provides retry suggestions.
Resuming Interrupted Syncs
Sync refuses inherited Git routing overrides before changing repositories,
configuration or saved progress. This includes GIT_DIR, GIT_WORK_TREE,
GIT_INDEX_FILE, shared Git directories, object directories and namespaces.
Run sync from a shell with those overrides unset so each configured checkout
uses its own Git state. JSON refusals report unsafe_git_environment with exit 4.
If a sync is interrupted (Ctrl+C, network failure, etc.), ru saves progress state and can resume where it left off:
# Start a large sync
ru sync
# ^C (interrupted)
# Exit code: 5
# Resume from where you left off
ru sync --resume
# Or discard state and start fresh
ru sync --restart
How state tracking works:
- State file — Progress is saved to
~/.local/state/ru/sync_state.json - Atomic updates — State is updated after each repo completes
- Safe resume — On
--resume, already-completed repos are skipped - Clean restart —
--restartclears state and processes all repos fresh
--dry-run preserves saved progress, Git state, configuration and checkpoint
locks. --resume --dry-run previews the remaining selection when configuration
and execution options match the saved run. Use the same options, such as
--clone-only, as the intended resume. Changed options trigger the same full
recheck and warning as an actual resume. --restart --dry-run previews all
configured repositories while retaining the existing checkpoint.
State file contents:
{
"started_at": "2025-01-03T14:30:00Z",
"repos_completed": ["repo1", "repo2", "repo3"],
"repos_pending": ["repo4", "repo5", "..."],
"last_repo": "repo3",
"interrupted": true
}
Best practices:
- Use
--resumewhen you want to continue after an interruption - Use
--restartwhen the repo list has changed significantly - In CI, prefer
--restartto ensure consistent runs
🔬 Git Status Detection
ru uses git plumbing commands for reliable status detection, never parsing human-readable output.
Why Plumbing Matters
Fragile approach (what other tools do):
# This breaks with non-English locales!
if git pull 2>&1 | grep -q "Already up to date"; then
echo "Current"
fi
Robust approach (what ru does):
# Works regardless of locale or git version
read -r ahead behind < <(git rev-list --left-right --count HEAD...@{u})
if [[ "$ahead" -eq 0 && "$behind" -eq 0 ]]; then
echo "Current"
fi
Status States
| State | Ahead | Behind | Meaning |
|---|---|---|---|
current |
0 | 0 | Fully synchronized |
behind |
0 | >0 | Remote has new commits |
ahead |
>0 | 0 | Local has unpushed commits |
diverged |
>0 | >0 | Both have new commits |
dirty |
— | — | Uncommitted local changes |
no_upstream |
— | — | No tracking branch set |
pin_mismatch |
-1 | -1 | The checkout does not match the branch or tag in the repo spec |
fetch_failed |
-1 | -1 | The fetch failed or the remote no longer confirms the tracked branch or pinned tag. Status exits 1. |
mismatch |
-1 | -1 | The checkout's origin differs from the configured repository. Status skips the requested fetch and exits 1. |
For a pinned repository, ru status --json includes requested_ref beside the checked-out branch. During a fetch, ru verifies that origin still advertises the exact installed tag object, including its annotation. A removed or replaced tag makes status and sync fail while preserving the local tag and checkout. With --no-fetch, a detached checkout at the locally pinned tag reports current with freshness: "cached".
With --no-fetch, a checkout with a different origin still reports its cached branch status and sets mismatch: true. Both status modes reject inherited Git routing overrides with exit 4, as sync does.
Dirty Detection
# Empty output = clean working tree
if [[ -n $(git -C "$repo_path" status --porcelain 2>/dev/null) ]]; then
dirty="true"
fi
🚨 Conflict Resolution
When ru encounters issues, it provides actionable resolution commands.
Example Output
╭─────────────────────────────────────────────────────────────╮
│ ⚠️ Repositories Needing Attention │
╰─────────────────────────────────────────────────────────────╯
1. mcp_agent_mail
Path: /data/projects/mcp_agent_mail
Branch: main
Issue: Dirty working tree (3 files modified)
Log: ~/.local/state/ru/logs/2025-01-03/repos/mcp_agent_mail.log
Resolution options:
a) Stash and pull (git restores only its own stash):
cd /data/projects/mcp_agent_mail && git pull --autostash
b) Commit your changes:
cd /data/projects/mcp_agent_mail && git add . && git commit -m "WIP"
c) Discard local changes (DESTRUCTIVE):
cd /data/projects/mcp_agent_mail && git checkout . && git clean -fd
2. beads_viewer
Path: /data/projects/beads_viewer
Branch: main
Issue: Diverged (2 ahead, 5 behind)
Resolution options:
a) Rebase your changes:
cd /data/projects/beads_viewer && git pull --rebase
b) Merge (creates merge commit):
cd /data/projects/beads_viewer && git pull --no-ff
c) Push your changes first (if intentional):
cd /data/projects/beads_viewer && git push
Common Issues and Fixes
| Issue | Cause | Resolution |
|---|---|---|
| Dirty working tree | Uncommitted changes | Stash, commit, or discard |
| Diverged | Local and remote both have commits | Rebase, merge, or push |
| No upstream | Branch doesn't track remote | git branch --set-upstream-to=origin/main |
| Remote mismatch | Different repo at same path | Remove directory or update list |
| Auth failed | gh not authenticated | gh auth login or set GH_TOKEN |
🧹 Managing Orphan Repositories
Over time, your projects directory may accumulate "orphan" repositories—directories that exist locally but aren't in your configuration. The ru prune command helps identify and manage these.
What is an Orphan?
An orphan is a git repository in your projects directory that:
- Exists as a valid git repository (has
.gitdirectory) - Is NOT listed in any of your
repos.d/*.txtconfiguration files - May have been manually cloned, removed from config, or leftover from experiments
Detection
# List orphan repositories (dry run)
ru prune
# Output:
# Found 3 orphan repositories:
# /data/projects/old-experiment
# /data/projects/manually-cloned
# /data/projects/removed-from-config
#
# Use --archive to move to archive, or --delete to remove
Archive Mode
Move orphans to a timestamped archive directory instead of deleting:
ru prune --archive
# Orphans moved to:
# ~/.local/state/ru/archived/old-experiment_20250103_143022/
# ~/.local/state/ru/archived/manually-cloned_20250103_143022/
# (same-named orphans archived in the same second get a _1, _2, ... suffix)
Benefits of archiving:
- Non-destructive—repos can be recovered
- Timestamped for audit trail
- Clears your projects directory without losing work
Delete Mode
Permanently remove orphan repositories:
# Interactive (asks for confirmation)
ru prune --delete
# Non-interactive (CI-safe, no prompts)
ru --non-interactive prune --delete
# Output when an orphan still holds work:
# ⚠ Skipping /data/projects/old-experiment: unsaved work: 2 uncommitted change(s), 1 stash(es)
# ℹ Kept 1 orphan(s) listed above; check them, then re-run with --force to include them.
Safety measures:
- Interactive mode requires explicit confirmation
--archiveand--deleteare mutually exclusive- Only git repositories with a
.gitdirectory are considered (plain directories, and worktrees or submodules whose.gitis a file, are ignored) - Paths are compared physically, so a configured repo reached through a symlinked folder, spelled with different letter case or Unicode normalization on a case-insensitive filesystem, or under a
PROJECTS_DIRwith a trailing slash is never an orphan --archiveand--deleterefuse to run while any repo line in your config cannot be parsed, any list file (orrepos.ditself) is missing or unreadable, or no repo is configured at all, since those clones would otherwise look like orphans--deletekeeps (and names) any orphan with work that exists only there: uncommitted changes, untracked files that are not ignored, stashes, commits not on any remote branch (including a detached HEAD or a repo with no remote), files marked assume-unchanged/skip-worktree, or linked worktrees. A repo git cannot inspect (corrupted, bare-ish, owned by another user) is kept too.--archiveonly moves folders, so it still archives these- The same checks run on every repository inside an orphan: submodules (including the repository a deinitialized submodule leaves in
.git/modules), nested clones and bare repos, even when the outer repo ignores them. Local refs other than branches count too (notes,refs/original, ...); tags do not. Files outside a sparse checkout's cone are not unsaved work - Ignored files are not unsaved work, but ignored names that usually hold secrets or local state (
.env, keys,*.tfstate, ...) are named in the dry run, in--json(ignored_precious) and as a warning before--deleteremoves them; they never block - Limits: prune does not fetch, so "on a remote branch" means the remote-tracking refs from your last fetch (run
git fetchin an orphan first if they may be stale, e.g. the remote branch was deleted); it does not check that Git LFS objects were pushed; and commits reachable only from the reflog (reset or rebased away) are not counted --archiveand--deletekeep any orphan whoseoriginis one of your configured repos (https, ssh andgit@host:spellings,.gitand letter case are ignored). That is a configured repo's clone left at an old path after a layout change or anasrename; prune reports it asclone of configured repo owner/repo (configured at ...) at an old path--forceincludes the kept orphans above. Without it,--archive/--deleteexit 1 when any orphan was kept, so scripts notice
Layout Awareness
Prune respects your configured layout mode:
| Layout | Scan Depth | Example Orphan Path |
|---|---|---|
flat |
1 level | /data/projects/orphan |
owner-repo |
2 levels | /data/projects/owner/orphan |
full |
3 levels | /data/projects/github.com/owner/orphan |
Custom Names
Prune correctly handles custom-named repositories:
# In repos.d/public.txt:
# owner/long-repository-name as shortname
# The directory 'shortname' is NOT an orphan
# because it matches the custom name in config
📤 Output Modes
Default: Human-Readable (stderr)
Progress and results go to stderr, paths to stdout:
ru sync
# stderr: → Processing 1/47: mcp_agent_mail...
# stderr: ╭─────────── Summary ───────────╮
# stdout: /data/projects/mcp_agent_mail
# stdout: /data/projects/beads_viewer
JSON Mode: --json
Structured output on stdout for scripting. All JSON commands share a normalized envelope:
{
"generated_at": "2026-02-09T18:06:35Z",
"version": "1.2.1",
"output_format": "json",
"command": "<command-name>",
"data": { ... },
"_meta": { ... }
}
| Envelope field | Type | Description |
|---|---|---|
generated_at |
string | ISO-8601 UTC timestamp |
version |
string | ru version |
output_format |
string | "json" or "toon" |
command |
string | Subcommand name (sync, status, list) |
data |
object | Command-specific payload (see below) |
_meta |
object | Optional. Timing, exit code, diagnostics |
sync — data contains config, summary, and repos; _meta includes duration_seconds and exit_code:
ru sync --json 2>/dev/null
{
"generated_at": "2026-02-09T18:08:23Z",
"version": "1.2.1",
"output_format": "json",
"command": "sync",
"data": {
"config": {
"projects_dir": "/data/projects",
"layout": "flat",
"update_strategy": "ff-only"
},
"summary": {
"total": 47,
"cloned": 8,
"updated": 34,
"current": 3,
"conflicts": 2,
"failed": 0
},
"repos": [
{
"name": "mcp_agent_mail",
"path": "/data/projects/mcp_agent_mail",
"action": "pull",
"status": "updated",
"duration": 2
}
]
},
"_meta": {
"duration_seconds": 154,
"exit_code": 2
}
}
status — data contains total and repos:
ru status --json 2>/dev/null
{
"generated_at": "2026-02-09T18:07:09Z",
"version": "1.2.1",
"output_format": "json",
"command": "status",
"data": {
"total": 47,
"repos": [
{
"repo": "owner/repo",
"path": "/data/projects/repo",
"status": "current",
"branch": "main",
"ahead": 0,
"behind": 0,
"dirty": false,
"mismatch": false
}
]
}
}
list — data contains total and repos:
ru list --json 2>/dev/null
{
"generated_at": "2026-02-09T18:06:35Z",
"version": "1.2.1",
"output_format": "json",
"command": "list",
"data": {
"total": 47,
"repos": [
{
"repo": "owner/repo",
"url": "owner/repo",
"path": "/data/projects/repo"
}
]
}
}
Parse with jq:
# Get paths of all cloned repos
ru sync --json 2>/dev/null | jq -r '.data.repos[] | select(.action=="clone") | .path'
# Get count of failures
ru sync --json 2>/dev/null | jq '.data.summary.failed'
# Get all dirty repos from status
ru status --json 2>/dev/null | jq -r '.data.repos[] | select(.dirty) | .repo'
Quiet Mode: --quiet
Only errors to stderr, still outputs paths to stdout:
ru sync --quiet
# Only shows errors, no progress
🤖 AI-Assisted Code Review
ru includes a powerful review orchestration system for managing AI-assisted code review across your repositories. It discovers open issues and pull requests, prioritizes them intelligently, and coordinates review sessions using Claude Code or other AI assistants.
The Review Workflow
┌─────────────────────────────────────────────────────────────────┐
│ ru review --plan │
└─────────────────────────────────────────────────────────────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ GraphQL │ │ Parse │ │ Cache │
│ Batch │ │ Work │ │ Digest │
│ Query │ │ Items │ │ Check │
└──────────┘ └──────────┘ └──────────┘
│ │ │
└───────────────┼───────────────┘
▼
┌─────────────────┐
│ Priority │
│ Scoring │
└────────┬────────┘
│
┌──────────────┼──────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ CRITICAL │ │ HIGH │ │ NORMAL │
│ security │ │ bugs │ │ features │
│ bugs >60d│ │ bugs >30d│ │ │
└──────────┘ └──────────┘ └──────────┘
│
▼
┌─────────────────┐
│ Session Driver │
│ (tmux/ntm) │
└────────┬────────┘
│
┌───────────────────┼───────────────────┐
▼ ▼ ▼
┌────────────┐ ┌────────────┐ ┌────────────┐
│ Session 1 │ │ Session 2 │ │ Session 3 │
│ (worktree) │ │ (worktree) │ │ (worktree) │
└────────────┘ └────────────┘ └────────────┘
Two-Phase Review: Plan then Apply
Phase 1: Discovery (--plan)
- Queries GitHub for open issues and PRs across all repos
- Scores items by priority using label analysis and age
- Clones missing configured repositories that have work to review
- Creates isolated git worktrees for safe review
- Spawns Claude Code sessions in terminal multiplexer
- Checkpoints progress for interruption recovery
Phase 2: Application (--apply)
- Reviews proposed changes from discovery phase
- Runs quality gates (ShellCheck, tests, lint)
- Optionally pushes approved changes (
--push) - Archives completed work items
# Discover and plan reviews
ru review --plan
# After reviewing AI suggestions, apply approved changes
ru review --apply --push
Priority Scoring Algorithm
ru uses a multi-factor scoring system to prioritize work items intelligently:
| Factor | Points | Logic |
|---|---|---|
| Type | 0-20 | PRs: +20, Issues: +10, Draft PRs: -15 |
| Labels | 0-150 | security/critical: +150, bug/urgent: +30, enhancement: +10 |
| Age (bugs) | 0-50 | >60 days: +50, >30 days: +30, >14 days: +15 |
| Age (features) | -10 to 0 | Very old (>180 days): -10 (likely stale) |
| Recency | 0-15 | Updated <3 days: +15, <7 days: +10 |
| Staleness | -20 | Recently reviewed: -20 |
Priority levels:
| Score | Level | Meaning |
|---|---|---|
| ≥150 | CRITICAL | Items labelled security or critical |
| ≥100 | HIGH | Bugs, urgent items |
| ≥50 | NORMAL | Regular features and issues |
| <50 | LOW | Backlog items |
Security and critical labels keep a minimum score of 150 even when recently
reviewed. Discovery follows all issue, PR and label pages before filtering and
ranking. --max-repos selects the highest-priority repositories and retains all
matching items in each selected repository. An API or pagination failure fails
discovery rather than reporting a complete empty backlog.
Pagination uses gh api --paginate and the existing jq dependency; newer
GitHub CLI options are not required. Priority keywords match complete label
names, so labels such as non-critical do not become critical reports.
Session Drivers
ru supports multiple backends for managing review sessions:
| Driver | Description | Best For |
|---|---|---|
auto |
Automatically detect best available | Default choice |
ntm |
Named Tmux Manager integration | Multi-agent workflows |
local |
Direct tmux sessions | Simple setups |
# Use specific driver
ru review --mode=ntm --plan
# Parallel sessions
ru review -j 4 --plan
ntm (Named Tmux Manager) Integration
ntm is a tmux session orchestration tool that provides a robot mode API for automated session management. When available, ru uses ntm for enhanced capabilities:
Robot Mode API Functions:
| Function | Purpose |
|---|---|
ntm --robot-spawn |
Create a Claude Code session in a new tmux pane |
ntm --robot-send |
Submit one complete prompt through --msg-file=- and confirm delivery |
ntm --robot-wait |
Block until session completes with timeout |
ntm --robot-activity |
Query real-time session state (idle/typing/thinking) |
ntm --robot-status |
Get status of all managed sessions |
ntm --robot-interrupt |
Send Ctrl+C to interrupt long operations |
Session Lifecycle:
┌───────────────────────────────────────────────────────────────┐
│ ntm Session Lifecycle │
└───────────────────────────────────────────────────────────────┘
│
▼
┌───────────────┐
│ ntm_spawn_ │◀─────── Creates tmux session with Claude Code
│ session() │ running in isolated worktree
└───────┬───────┘
│
▼
┌───────────────┐
│ ntm_send_ │◀─────── Delivers the complete prompt through stdin
│ prompt() │ Handles message delivery confirmation
└───────┬───────┘
│
▼
┌───────────────┐
│ ntm_wait_ │◀─────── Polls for completion with timeout
│ completion() │ Returns JSON with status/duration
└───────┬───────┘
│
▼
┌───────────────┐
│ ntm_kill_ │◀─────── Cleans up session when done
│ session() │ Idempotent—safe to call on gone sessions
└───────────────┘
Activity State Mapping:
ntm reports granular activity states that ru maps to unified states:
| ntm State | ru Unified State | Meaning |
|---|---|---|
GENERATING |
generating |
Agent is producing output |
WAITING_ON_JOB |
generating |
Agent is waiting for an active job |
WAITING |
waiting |
Agent is ready for input |
THINKING |
thinking |
AI processing |
STALLED |
stalled |
Agent activity has stalled |
IDLE |
idle |
Session is idle |
ERROR |
error |
Something went wrong |
Review activity queries identify the session and select its single Claude agent.
Malformed, failed, cached, or ambiguous observations report unknown; they cannot
make another pane's idle state look like review completion. Long initial prompts
and replies are sent once, with their exact bytes preserved. A refused or
unconfirmed send does not trigger a second submission through tmux.
NTM's native message limit still applies: prompts larger than 10 MiB are refused.
Interactive reviews use a fresh attempt marker in the final plan and a
.ru/review-complete.json receipt for each agent prompt or reply. The receipt binds
the current request to the exact final plan bytes and candidate Git commit.
The agent writes it only after the review and all questions are finished.
An idle pane, an old receipt, or an old event log cannot finish a review.
Activity and replies must belong to the captured tmux session and stable pane
identity, including sessions whose activity reports a bare pane index.
ru stops the owned session once, then rechecks the final receipt, repository identity, and assigned review items before accepting the plan. Normal approval and application quality gates still apply. Questions appear in ordinary interactive review as well as the dashboard. Answers, templates, and skips are recorded only after delivery is confirmed; a refused send leaves the question pending so it can be retried.
External terminal prompts have a separate recovery path. A live yes/no
confirmation appears in the question queue with explicit yes and no
choices. Before answering, inspect the host identity or other details in the
owned terminal. ru rechecks the session, pane, review turn and exact captured
prompt before sending only the chosen response; it leaves the agent's
completion token unchanged. Templates cannot answer these prompts, and Skip
dismisses the reminder without sending input to the terminal.
Password, token, OTP, editor and conflict prompts instead show instructions for attaching to the owned terminal. The dashboard and basic UI do not collect their answers or save terminal history in the queue. Reminders retire when the prompt changes, work resumes, the review finishes, or its session is lost. External prompts are never automatically answered in non-interactive mode.
Fallback Behavior:
When ntm is unavailable, ru uses the local driver through tmux. Each Claude
print-mode invocation reads its full prompt from finite stdin. Questions use
an artifact tied to the current attempt and turn; after acknowledging the
answer, the runner continues with --resume and the exact Claude session ID.
Replies are recorded only after acknowledgment, and retrying an identical
answer does not start another turn.
Local completion requires a successful provider exit, typed success results, and a valid final plan with every question answered. Inactive providers still trigger stall recovery. NTM uses its interactive pane and native activity and delivery receipts for the corresponding lifecycle.
Claude Code Integration
ru orchestrates AI review sessions using Claude Code with stream-json output parsing:
┌─────────────────────────────────────────────────────────────────┐
│ Claude Code Session │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────┐
│ stream-json │
│ NDJSON output │
└────────┬────────┘
│
┌───────────────────┼───────────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ system │ │ assistant│ │ result │
│ events │ │ events │ │ events │
└──────────┘ └──────────┘ └──────────┘
Event types parsed:
| Event | Data Extracted |
|---|---|
system.init |
Session ID, available tools, working directory |
assistant |
Tool uses, text responses, thinking |
result |
Status, duration, cost (USD) |
Interactive question detection:
When Claude Code uses AskUserQuestion, ru detects and surfaces these for human input:
# Session asks: "Should I refactor this function?"
# ru detects and shows:
# [Session owner/repo] Question pending: "Should I refactor this function?"
# Options: 1) Yes 2) No 3) Skip
Cost tracking:
Each session reports cost, enabling budget enforcement:
{"type":"result","status":"success","duration_ms":45000,"cost_usd":0.0234}
Git Worktree Isolation
When a configured repository has work to review but no local checkout, ru review
clones it before creating its review worktree. It preserves the configured URL
transport, directory layout, in <group>, as <name>, and branch, tag, or commit
pin. An explicit @refs/heads/feature pin can select a remote branch that has not
yet been checked out locally; the source checkout stays on its original branch.
Preparation refuses occupied non-Git destinations and symlink clone paths. A
failed clone or unresolved pin returns a failure instead of reporting the
repository as prepared, and a successfully created clone is retained if its pin
cannot be resolved. ru review --dry-run previews discovery without cloning or
creating worktrees.
Each review session operates in an isolated git worktree, ensuring:
- Main working directory stays untouched
- Multiple reviews can run in parallel
- Changes can be discarded without affecting HEAD
- Clean state for each AI session
~/.local/state/ru/worktrees/
└── 20250105-143022-1234/
├── owner_repo1/ # Isolated worktree
├── owner_repo2/ # Isolated worktree
└── mapping.json # Worktree registry
Digest Caching
To avoid redundant API calls and repeated reviews, ru caches repository digests:
~/.local/state/ru/review/
├── digests/ # Cached repo digests
│ ├── owner_repo.json # Issues/PRs snapshot
│ └── ...
├── state.json # Current review state
├── checkpoint.json # Resumable checkpoint
└── results/ # Review outcomes
└── 20250105-143022/
└── results.ndjson # Per-item results
Cache invalidation:
# Invalidate specific repos
ru review --invalidate-cache=owner/repo1,owner/repo2
# Invalidate all caches
ru review --invalidate-cache=all
Cost Budgets
Control resource usage with budget constraints:
# Limit to 10 repos
ru review --max-repos=10 --plan
# Maximum 30 minutes runtime
ru review --max-runtime=30 --plan
# Skip unchanged items successfully reviewed in the last two weeks
ru review --skip-days=14 --plan
# Review every matching item, including recently reviewed items
ru review --skip-days=0 --plan
Review history records each validated plan atomically with the GitHub updatedAt
value seen during discovery. A changed item becomes eligible immediately; older
history without a source revision does not suppress review. Pending repositories
in a resumed checkpoint are retried even when a completion receipt was saved
before the interruption. Recorded decisions are proposals: history does not mean
that commits or GitHub actions were applied or published.
The review scheduler checks --max-runtime while agents are active and before
starting another session. When the deadline expires, it stops active sessions,
saves unfinished repositories for ru review --resume, and exits with code 5.
A failure to stop a session or save its state gives exit code 3.
Ctrl+C and SIGTERM stop new work, shut down confirmed owned sessions, and
exit with code 5. A session created during an interrupted or failed launch is
included in shutdown. Successfully completed repositories remain completed;
unfinished repositories stay in the checkpoint for ru review --resume.
When --resume is combined with --repos, --priority, or --max-repos,
repositories excluded by those limits stay in the same checkpoint. The command
exits with code 5 while saved work remains; continue with ru review --resume
to finish. Completed repositories are not restarted. An empty selection
preserves recovery state; a complete query confirming no open items may finish
the run.
If an owned session cannot be stopped, ru retains the review lock and records
its identity. A later review refuses to start until it can confirm that session
is gone. Inspect ru review --status and resolve the surviving session before
resuming. Stale-lock recovery checks session existence without killing it.
Review Analytics
View statistics on past reviews:
ru review --analytics
Metrics tracked:
~/.local/state/ru/metrics/
├── 2025-01.json # Monthly aggregates
├── 2025-02.json
└── decisions.jsonl # Per-decision audit log
Monthly metrics:
| Metric | Description |
|---|---|
reviews.total |
Total review sessions started |
reviews.repos_reviewed |
Unique repositories reviewed |
reviews.issues_processed |
Issues examined by AI |
reviews.issues_resolved |
Issues closed or fixed |
reviews.questions_asked |
AI questions to human |
reviews.questions_answered |
Human responses |
timing.total_duration_minutes |
Cumulative review time |
timing.avg_session_minutes |
Average session length |
outcomes.changes_applied |
Commits made |
outcomes.changes_rejected |
Changes discarded |
Decision logging:
Every significant action is logged to decisions.jsonl for auditability:
{"timestamp":"2025-01-05T14:30:00Z","repo":"owner/repo","issue":42,"action":"close","reason":"Fixed by commit abc123","actor":"ai"}
{"timestamp":"2025-01-05T14:31:00Z","repo":"owner/repo","issue":43,"action":"label","label":"wontfix","actor":"human"}
Analytics dashboard:
ru review --analytics
Shows:
- Total reviews completed
- Average resolution time
- Most active repositories
- Issue type distribution
- Review velocity trends
- Success/rejection ratios
GitHub Actions Execution
After review sessions complete, ru can execute planned GitHub actions from the review plan:
# Actions are proposed during --plan, executed during --apply
ru review --apply
Supported actions:
| Action | Command | Description |
|---|---|---|
comment |
gh issue comment |
Add comment to issue/PR |
close |
gh issue close |
Close an issue |
label |
gh issue edit --add-label |
Add labels to issue |
Recovery without duplicate actions:
Before contacting GitHub, ru atomically saves an applying receipt in
~/.local/state/ru/review/gh-actions.jsonl. Each receipt identifies the repository,
review run, exact plan digest, candidate HEAD, and effective action arguments.
Concurrent applications cannot claim the same action twice. An invalid or
unwritable receipt ledger stops execution before a remote action starts.
A confirmed action receives an ok receipt and is skipped on later applications,
including a new review plan containing the same action. If the command fails or
the completion receipt cannot be saved, the outcome may already have occurred
on GitHub. The retained applying or unknown receipt blocks automatic replay.
Inspect outstanding receipts without contacting GitHub or starting an agent:
ru review --actions
ru review --actions --json
Each entry includes its exact payload, original run, plan digest, candidate HEAD, and a stable receipt ID. Inspect the remote issue or PR to establish what actually happened, then record that verified outcome and supporting evidence:
ru review --resolve-action="$receipt_id" --outcome=applied \
--evidence="Verified the expected comment at https://github.com/owner/repo/issues/42#issuecomment-123"
ru review --resolve-action="$receipt_id" --outcome=not-applied \
--evidence="Verified the request never reached GitHub and the expected change is absent"
These commands append an audited local resolution; they do not contact GitHub or
execute another action. applied preserves duplicate suppression. not-applied
allows a later normal ru review --apply to attempt the action after its usual
approval and quality checks. Use it only after verifying the operation did not
occur: a failed command alone does not establish that outcome.
The ID binds the exact latest unresolved receipt, so an old ID cannot resolve a
newer attempt. Resolutions preserve the original records and include the evidence,
operator, and timestamp. Reconciliation refuses while another review is active,
or when the ledger is invalid. Keep inspection/reconciliation separate from
--apply, --push, --resume, and other review modes. Changing a run ID,
annotation, or equivalent argument spelling does not authorize another attempt.
Action parsing:
Actions are extracted from review plan files with canonicalization:
owner/repo#42 → repo: owner/repo, type: issue, number: 42
owner/repo/pull/5 → repo: owner/repo, type: pr, number: 5
Review Policies
Configure review behavior with policy files:
# ~/.config/ru/review-policies.d/_default
REQUIRE_TESTS=true
REQUIRE_LINT=true
REVIEW_ALLOW_PUSH=false
REVIEW_REQUIRE_APPROVAL=true
TEST_COMMAND=make test
LINT_COMMAND=make lint
Policies use KEY=VALUE lines. Copy the generated _default.example to
_default to activate it. Repository policies such as owner_repo override
defaults; glob filenames such as owner_* apply between defaults and exact
matches. Test and lint commands override automatic detection. Every executed
nonzero command blocks application, including exit 2 and timeout exits; absent
optional runners report ran: false. REQUIRE_TESTS and REQUIRE_LINT also
block application when the corresponding runner is absent. Secret scanning
always runs during application.
Application checks the plan against the selected run's saved mapping and the
physical worktree. A plan with code changes must include the original
git.base_sha, branch, base ref, and every full candidate commit SHA in reverse
topological order. A comment-only plan may omit the optional git section;
any supplied identity fields must still match, and unreported commits are refused.
Changed base branches, missing commits, foreign worktrees and malformed plans
are refused before test commands or publication.
Preparation also stores the original mapping as a Git object referenced under
refs/ru/review-mappings/; editing the JSON mapping cannot redirect that run.
The mapping binds a fully qualified branch or tag ref, or a resolved commit pin,
and the effective origin push URLs. Tag and commit pins support comment-only
reviews; code publication requires a branch base and preserves immutable pins.
Changing a push URL or its rewrite rules requires a newly prepared review.
Publication explicitly pushes only the validated candidate to its base branch
on origin, regardless of push.default or remote.origin.push settings.
Each prepared receiver uses a frozen transport destination. Its unpublished
history is scanned, its advertised branch tip is checked before transfer, and
the actual receiver is verified afterward. A late remote configuration change
cannot redirect that push; changed identity still blocks subsequent actions.
Issue close actions accept completed or not_planned; ru supplies the
corresponding native CLI argument. PR close reasons remain descriptive comments,
and label actions remain limited to issues. Application rejects PR labels and
merges before running gates or any GitHub action.
REVIEW_REQUIRE_APPROVAL=true is enforced for application, including GitHub
actions without code changes. Interactive ru review --apply displays the
plan and asks for approval; the decision is saved in
.ru/review-approval.json and bound to the plan content and candidate HEAD.
Changing either requires fresh approval. --push does not grant approval.
Approval fingerprints require sha256sum or shasum and use SHA-256.
Non-interactive application requires an existing matching approval or an
explicit applicable REVIEW_REQUIRE_APPROVAL=false policy. Recomputed gate
reports do not invalidate approval; edits to reviewed actions or decisions do.
Application rechecks identity and approval before each GitHub action. If the
plan changes mid-application, remaining actions stop and the run reports failure;
already completed actions retain their idempotence records.
review --apply --dry-run validates identity without running gates or mutations.
review --apply --json emits the common envelope with per-repository exit codes,
the run ID and a summary; refused applications include their actual nonzero result.
When a plan contains commits, application without --push runs its quality gates
and retains the candidate with status pending_push. This validation succeeds
with exit 0, but does not count as an applied plan, post dependent GitHub actions,
record resolution metrics, or clear a pending application checkpoint. The JSON
summary counts these plans separately as pending. An explicit --push forbidden
by REVIEW_ALLOW_PUSH=false returns exit 2 with status blocked_by_policy.
Plans with only GitHub actions still apply without publishing code.
Application progress is retained separately from planning history and binds to
the exact plan and candidate commit. Reapplying a completed plan still performs
identity, approval, gate and publication checks; it does not count the same plan
again in decision history or metrics.
Use ru review --apply --repos='owner/service-*' to apply only matching plans
from the selected run. Positional patterns and repeated --repos options select
their union. A filter with no matches produces an empty result. Only selected
repositories run gates, receive pushes, or perform GitHub actions. A scoped apply
preserves the planning checkpoint for unfinished reviews.
| Policy | Default | Description |
|---|---|---|
REQUIRE_TESTS |
false |
Require a configured or detected test runner |
REQUIRE_LINT |
false |
Require a configured or detected linter |
TEST_COMMAND |
auto-detect | Override the test command |
LINT_COMMAND |
auto-detect | Override the lint command |
REVIEW_ALLOW_PUSH |
false |
Permit pushing when --push is also supplied |
REVIEW_REQUIRE_APPROVAL |
true |
Require explicit approval |
BASE_PRIORITY |
0 |
Adjust repository priority |
LABEL_PRIORITY_BOOST |
empty | Comma-separated label priority adjustments |
MAX_PARALLEL_AGENTS |
4 |
Repository session limit |
SKIP_PATTERNS |
empty | File patterns for automated review to skip |
GraphQL Batch Querying
ru uses efficient GraphQL alias batching to minimize API calls when discovering work items across many repositories:
┌─────────────────────────────────────────────────────────────────┐
│ GraphQL Batch Query │
└─────────────────────────────────────────────────────────────────┘
│
┌────────────────────┼────────────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ repo0: │ │ repo1: │ │ repo24: │
│ issues │ ... │ issues │ ... │ issues │
│ + PRs │ │ + PRs │ │ + PRs │
└──────────┘ └──────────┘ └──────────┘
│ │ │
└────────────────────┼────────────────────┘
▼
┌─────────────────┐
│ Single API │
│ Response │
└─────────────────┘
How it works:
- Alias batching — Up to 25 repositories per GraphQL query using named aliases (
repo0,repo1, ...) - Parallel field fetching — Issues, PRs, and labels retrieved in one request per batch
- Automatic chunking — Large repo lists split into optimal batch sizes
- Retry on failure — Failed batches retried with exponential backoff
Efficiency comparison:
| Approach | 100 Repos | API Calls |
|---|---|---|
| Individual REST | 100 repos × 2 (issues + PRs) | 200 calls |
| GraphQL batched | 100 repos ÷ 25 per batch | 4 calls |
Rate-Limit Governor
ru includes an adaptive parallelism governor that adjusts concurrency based on GitHub API rate limits and error patterns:
# The governor tracks:
# - GitHub API remaining quota
# - Model rate limit (429) responses
# - Error frequency within sliding window
# - Circuit breaker state
Adaptive behavior:
| Condition | Action |
|---|---|
| GitHub remaining < 100 | Reduce parallelism to 1 |
| GitHub remaining < 500 | Reduce parallelism by 50% |
| Model 429 detected | Pause new sessions for 60s |
| Error rate > 50% (5min window) | Open circuit breaker |
| Circuit open > 2 minutes + no errors | Close circuit breaker |
Circuit breaker pattern:
Normal Operation → Errors Spike → Circuit OPEN → Cool-down → Half-Open → Test → CLOSED
↑ │
└──────── More Errors ─────────┘
The governor runs as a background monitor during review sessions, checking rate limits every 30 seconds and adjusting REVIEW_PARALLEL dynamically.
Global Backoff Coordination
Agent-sweep coordinates provider cooldowns across both sequential and parallel
workers. When NTM reports AGENT_ERROR for the owned Claude pane, ru checks
NTM's native rate_limited condition for that exact pane before publishing a
shared pause. Generic agent errors and ordinary timeouts remain failures.
After the cooldown, ru waits for the same pane's native rate_limit_lifted
condition and then its idle completion. The existing planning turn is retained:
recovery sends no additional prompt and does not replay hooks or Git operations.
The cooldown and all recovery waits share the original phase deadline. A limit
that outlasts that deadline leaves the workflow failed and resumable.
Backoff behavior:
| Trigger | Initial Delay | Behavior |
|---|---|---|
| First confirmed rate limit | 30 seconds | Wait, confirm provider recovery, then await completion |
| Repeated rate limit in the run | Previous nominal delay × 2 | Preserve escalation after a cooldown expires |
| Maximum delay | 10 minutes | Cap applies after jitter; the phase deadline still bounds the wait |
| Jitter | ±25% | Spread retries within the maximum delay |
State file format (backoff.state):
{
"reason": "rate_limited",
"pause_until": 1704307200,
"delay": 60,
"run_id": "20260104_120000"
}
Workers check this file before starting each repository and before sending each phase's prompt. Waiting workers re-read it once per second, so they observe a peer's extension and respond to cancellation. Concurrent triggers publish the state atomically under a lock and never shorten an active cooldown. Malformed shared state stops new work until it can be inspected.
Quality Gates
Before applying changes, ru runs automated quality gates to catch issues early:
┌─────────────────────────────────────────────────────────────────┐
│ Quality Gates │
└─────────────────────────────────────────────────────────────────┘
│
┌────────────────────┼────────────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Test │ │ Lint │ │ Secret │
│ Gate │ │ Gate │ │ Scan │
└──────────┘ └──────────┘ └──────────┘
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Auto- │ │ Auto- │ │ Pattern │
│ detect │ │ detect │ │ Match │
└──────────┘ └──────────┘ └──────────┘
Auto-detection by project type:
| Project Type | Test Command | Lint Command |
|---|---|---|
| npm/yarn | npm test / yarn test |
npm run lint / eslint |
| Cargo (Rust) | cargo test --workspace |
cargo clippy |
| Go | go test ./... |
golangci-lint run |
| Python | pytest / python -m pytest |
ruff check / flake8 |
| Makefile | make test |
make lint |
| Shell scripts | (none) | shellcheck *.sh |
Secret scanning patterns:
The secret scanner checks for accidentally committed credentials:
- API keys and tokens (
sk-,ghp_,xox,AKIA) - Private keys (
BEGIN RSA PRIVATE KEY,BEGIN OPENSSH PRIVATE KEY) - Connection strings and passwords
- Cloud provider credentials
# Run quality gates on a specific directory
ru review --apply # Gates run automatically before pushing
# Skip gates (not recommended)
REVIEW_LINT_REQUIRED=false REVIEW_SECRET_SCAN=false ru review --apply
Session Health Monitoring
ru monitors review sessions for external prompts and blocking conditions:
Detected wait reasons:
| Pattern | Risk Level | Description |
|---|---|---|
Password: |
High | Credential prompt |
Enter passphrase |
High | SSH key passphrase |
Enter OTP |
High | Two-factor authentication |
CONFLICT.*Merge |
Medium | Git merge conflict |
(yes/no) |
Medium | Host key verification |
Please enter.*commit |
Low | Git commit message prompt |
Risk classification:
- High risk — Credentials, authentication, permissions (requires human intervention)
- Medium risk — Merge conflicts, host verification (may need review)
- Low risk — Informational prompts (often auto-resolvable)
When a blocking prompt is detected, the session is marked as waiting and the reason is logged for review:
ru review --status
# Shows: Session owner/repo waiting on "Password:" (high risk)
🤖 Agent-Driven Sweep
The ru agent-sweep command orchestrates AI coding agents (via Claude Code) to automatically process repositories with uncommitted changes. It spawns isolated tmux sessions for each repository, monitors agent progress, and aggregates results.
The Agent Sweep Workflow
┌─────────────────────────────────────────────────────────────────┐
│ ru agent-sweep │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────┐
│ Load dirty │
│ repositories │
└────────┬────────┘
│
┌──────────────┼──────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Preflight│ │ Preflight│ │ Preflight│
│ Checks │ │ Checks │ │ Checks │
└──────────┘ └──────────┘ └──────────┘
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Spawn │ │ Spawn │ │ Spawn │
│ Agent │ │ Agent │ │ Agent │
│ (tmux) │ │ (tmux) │ │ (tmux) │
└──────────┘ └──────────┘ └──────────┘
│ │ │
└──────────────┼──────────────┘
▼
┌─────────────────┐
│ Monitor & │
│ Aggregate │
└────────┬────────┘
│
┌──────────────┼──────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Secret │ │ Quality │ │ Push │
│ Scan │ │ Gates │ │ (opt) │
└──────────┘ └──────────┘ └──────────┘
Agent Sweep Prerequisites
Before using agent-sweep, ensure you have:
| Requirement | Description |
|---|---|
| ntm | Named Tmux Manager for session orchestration |
| tmux | Terminal multiplexer for isolated sessions |
| Claude Code | AI coding agent (claude command) |
Verify installation:
# Check ntm
ntm --version
# Check tmux
tmux -V
# Check Claude Code
claude --version
Basic Usage
# Process all repos with uncommitted changes
ru agent-sweep
# Dry run - preview what would be processed
ru agent-sweep --dry-run
# Process 4 repos in parallel
ru agent-sweep -j4
# Filter to specific repos
ru agent-sweep --repos="myproject*"
# Include release step after commit
ru agent-sweep --with-release
# Resume an interrupted sweep
ru agent-sweep --resume
# Start fresh (clear previous state)
ru agent-sweep --restart
# Verbose output with file logging
ru agent-sweep --verbose
# Debug mode for troubleshooting
ru agent-sweep --debug
Three-Phase Agent Workflow
Each repository goes through a structured three-phase workflow that separates planning from execution:
┌─────────────────────────────────────────────────────────────────┐
│ Three-Phase Workflow │
└─────────────────────────────────────────────────────────────────┘
│
┌───────────────┼───────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ PHASE 1 │ │ PHASE 2 │ │ PHASE 3 │
│ Planning │───▶│ Commit │───▶│ Release │
└──────────┘ └──────────┘ └──────────┘
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Analyze │ │ Execute │ │ Create │
│ changes │ │ plan │ │ tag/ │
│ + plan │ │ + commit │ │ release │
└──────────┘ └──────────┘ └──────────┘
Phase 1: Planning (--phase1-timeout, default 300s)
- Claude Code analyzes the uncommitted changes in the repository
- Determines which files should be staged (respecting denylist)
- Generates a structured commit message following conventional commit format
- Outputs a JSON plan with files, message, and rationale
Phase 2: Commit (--phase2-timeout, default 600s)
- Validates the plan from Phase 1 (file existence, denylist compliance)
- Stages approved files with
git add - Creates the commit with the generated message
- Runs quality gates (linting, secret scan)
- Optionally pushes to remote
Phase 3: Release (--phase3-timeout, default 300s, requires --with-release)
- The agent proposes a version, tag, changelog entry, version files and checks; a null version means no release
- ru commits the version-file edits and the changelog entry together as
chore(release): <tag>, touching no other path - Requested checks (
tests,lint,secrets) run on a clean checkout of that commit;secretsscans every file in it, and a failure publishes nothing - The branch and an annotated tag are pushed to the receivers commit plans use, and each receiver is re-read afterwards
autoandgh-releasethen create the GitHub release with--verify-tag;ciwaits for the commit's Actions runs (failing at once when the commit has no workflows) andchecksumsdownloads the assets and checks each against its SHA-256 file (signature files such as.minisigare exempt)- A release plan can name local build artifacts in
files. Each path must exist and have a distinct filename. Before publishing the tag, ru records their SHA-256 digests. New GitHub releases with assets stay in draft until every requested file is verified. On retry, ru checks the recorded release ID and uploads only missing assets. If draft creation succeeded but its response was lost, ru can recover the unique draft bearing the random title it recorded before creation. It restores the intended title when publishing. A changed local artifact, a conflicting remote file, or an unrelated draft stops the retry for inspection. - Progress is recorded in
.git/ru-release/<tag>.json, so rerunning a failed release continues it without a second commit, tag or release - Respects per-repo release strategy configuration (
never,auto,tag-only,gh-release)
Execution modes:
| Mode | Behavior |
|---|---|
--execution-mode=agent |
Generate, validate, and execute commit and optional release plans (default) |
--execution-mode=plan |
Generate and validate plans without executing commits or releases |
--execution-mode=apply |
Generate, validate, and execute plans, using the same workflow as agent |
Why separate phases?
- Auditability: Each phase produces inspectable output
- Recovery: Resume unfinished repositories while preserving successful results and the original run's artifacts
- Control: Can run planning across all repos, then review before applying
- Safety: Validation happens between phases, catching issues early
Preflight Checks
Each selected target must be the root of its Git worktree. Targets that share the same physical root or per-worktree Git directory are rejected before agents start. Linked worktrees with separate indices are allowed.
Before spawning an agent, each repository undergoes preflight validation:
| Check | Reason | Skip Reason |
|---|---|---|
| Is git repository | Basic requirement | not_a_git_repo |
| Git email configured | For commits | git_email_not_configured |
| Git name configured | For commits | git_name_not_configured |
| Not a shallow clone | Some ops may fail | shallow_clone |
| No dirty submodules | Avoid conflicts | dirty_submodules |
| No rebase in progress | Unsafe state | rebase_in_progress |
| No merge in progress | Unsafe state | merge_in_progress |
| No cherry-pick in progress | Unsafe state | cherry_pick_in_progress |
| Not detached HEAD | Need branch ref | detached_HEAD |
| Has upstream branch | For push | no_upstream_branch |
| Not diverged | Would need rebase | diverged_from_upstream |
| No unmerged paths | Merge conflicts exist | unmerged_paths |
| git diff --check clean | Whitespace/conflict markers | diff_check_failed |
| Untracked files < 1000 | Too many untracked | too_many_untracked_files |
Handling preflight failures:
# View why a repo was skipped (JSON output)
ru agent-sweep --json 2>/dev/null | jq '.data.repos[] | select(.status == "skipped")'
# Fix common issues
cd /data/projects/problematic-repo
git config user.email "[email protected]"
git config user.name "Your Name"
git rebase --abort # If rebase in progress
Security Guardrails
Agent-sweep includes multiple security layers to prevent accidents:
1. File Denylist
Certain files are never committed, regardless of agent output:
| Category | Patterns |
|---|---|
| Secrets | .env, .env.*, *.pem, *.key, id_rsa, credentials.json, secrets.json |
| Build artifacts | node_modules, __pycache__, dist, build, .next, target, vendor |
| Logs/temp | *.log, *.tmp, *.swp, .DS_Store |
| IDE files | .idea, .vscode, *.iml |
Extend the denylist:
# Via environment variable
export AGENT_SWEEP_DENYLIST_EXTRA="*.bak *.orig internal/*"
# Via per-repo config (.ru/agent-sweep.conf)
echo 'DENYLIST_EXTRA="*.backup proprietary/*"' >> .ru/agent-sweep.conf
2. Secret Scanning
Before any push, files are scanned for secrets:
# Modes
--secret-scan=none # Disable scanning
--secret-scan=warn # Warn but continue (default)
--secret-scan=block # Block push on detection
Patterns detected:
- API keys (
sk-,ghp_,xox,AKIA) - Private keys (
BEGIN RSA PRIVATE KEY,BEGIN OPENSSH PRIVATE KEY) - Connection strings and passwords
- Cloud provider credentials
3. File Size Limits
Large or binary files are blocked from commits to prevent repository bloat. The default limit is 1MB, configurable via AGENT_SWEEP_MAX_FILE_MB or per-repo config.
4. Plan Validation
Before executing any commit or release plan, ru validates the AI-generated JSON output:
┌─────────────────────────────────────────────────────────────────┐
│ Plan Validation Pipeline │
└─────────────────────────────────────────────────────────────────┘
│
┌────────────────────┼────────────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ JSON │ │ Schema │ │ File │
│ Parse │ │ Verify │ │ Verify │
└──────────┘ └──────────┘ └──────────┘
│ │ │
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Extract │ │ Required │ │ Files │
│ between │ │ fields │ │ exist? │
│ markers │ │ present? │ │ Allowed? │
└──────────┘ └──────────┘ └──────────┘
Validation checks for commit plans:
Commit plans use a private Git index containing only the named paths. Unrelated staged changes and worktree bytes survive successful commits; conflicting staging on a planned path is refused. Validation binds the complete candidate tree and HEAD, and is repeated before each commit and publication. Normal project hooks still run; a pre-commit hook that changes the candidate stops the commit.
commit-sweep --execute uses the same executor and leaves existing staged work
alone. --respect-staging explicitly adds a staged group using its exact index
blobs; a different unstaged version stays in the worktree. In JSON mode, dry runs
count planned commits and executed runs count commits actually created.
--dry-run always takes precedence over --execute and --apply, regardless
of option order. A preview preserves HEAD, staged content and worktree files
without running commit hooks.
File policies and secret scans inspect the exact Git blobs, including planned
untracked files. Publication scans every unpublished commit, so removing a secret
from the final tree does not hide it in earlier history. --secret-scan=block
stops findings, malformed scanner responses and execution errors; warn permits
them with diagnostics, while none explicitly skips secret scanning.
Ranges are derived from each effective push URL, including a separate pushurl;
all receivers must pass before the first push. Changed destinations or receiver
heads revoke the publication check, and successful pushes are verified at the
actual receivers.
Commit publication honors branch.<name>.pushRemote and remote.pushDefault
before the fetch remote. A triangular workflow publishes the current branch to
its push remote. Central plans explicitly publish their configured upstream
branch; push.default=current selects the current branch instead.
Repeated effective push URLs are checked and published once without changing
the repository configuration. Matching or multi-ref settings cannot include
unrelated branches in the planned publication.
| Check | Validation | Failure Behavior |
|---|---|---|
| JSON structure | Valid JSON between ---PLAN-START--- and ---PLAN-END--- markers |
Reject plan |
| Required fields | Nonempty commits array with message and files; optional boolean push and per-commit source (worktree or index) |
Reject plan |
| File existence | Each planned path exists or represents a tracked deletion | Reject missing paths |
| Denylist compliance | No planned file matches denylist patterns | Reject plan |
| Commit message format | Non-empty, reasonable length | Reject if empty |
Validation checks for release plans:
| Check | Validation | Failure Behavior |
|---|---|---|
| Version format | Matches semver (X.Y.Z), or null for no release | Reject plan |
| Tag | Names the version (1.2.0 or v1.2.0); not already local or on a receiver, unless it is this release resuming |
Reject plan |
| Version files | Tracked regular files whose new text is the version; the old text must be found on exactly one declaring line (a VERSION file's content, a JSON "version" key, a TOML [package]/[project] version, or else one whole-word match) |
Reject plan, files unchanged |
| VERSION file | A tracked top-level VERSION must already name the version or be listed in version_files |
Reject plan |
| Uncommitted edits | Version files and the changelog must have no uncommitted changes | Reject plan |
| Checks | Only tests, lint, secrets, ci, checksums; checksums needs a GitHub release, and ci, checksums and gh-release need gh |
Reject plan |
| Release strategy | never, auto, tag-only or gh-release |
never skips; anything else is rejected |
| Changelog entry | Must name the version; it is added above the newest release section (below ## [Unreleased]) of CHANGELOG.md, or of the plan's changelog, which is created if missing and may not lie behind a symbolic link |
Reject plan if it omits the version; no entry means no changelog change |
| Release assets | Plan files must be relative, not denied, and not reached through a symbolic link |
Reject plan |
Why structured output with markers?
AI output often includes explanatory text before/after the JSON. The marker-based extraction (---PLAN-START--- / ---PLAN-END---) reliably isolates the machine-readable portion without complex parsing.
Per-Repository Configuration
Customize agent-sweep behavior per repository:
When a repository has a configuration file, both agent-sweep and
commit-sweep require it to be readable and valid before acting on that
repository. A malformed file, an unavailable parser, or an invalid setting
stops the operation for that checkout. Repositories without a configuration
file use the defaults.
Option 1: YAML config (.ru-agent.yml) — Recommended:
# ~/.../your-repo/.ru-agent.yml
agent_sweep:
enabled: true
max_file_size: 5242880 # 5MB
extra_context: "This is a Python project using FastAPI"
pre_hook: "make lint"
post_hook: "make test"
hook_inputs:
- "Makefile"
- "scripts/checks.sh"
hook_env:
- "CHECK_PROFILE"
skip_phases: []
denylist_extra:
- "*.backup"
- "internal/*"
Option 2: JSON config (.ru-agent.json):
{
"agent_sweep": {
"enabled": true,
"max_file_size": 5242880,
"denylist_extra": ["*.backup", "internal/*"]
}
}
Option 3: Shell config for release strategy (.ru/agent-sweep.conf):
# ~/.../your-repo/.ru/agent-sweep.conf
# Only release strategy is configurable via shell config
AGENT_SWEEP_RELEASE_STRATEGY=auto # never|auto|tag-only|gh-release
Option 4: User config (~/.config/ru/agent-sweep.d/<repo>.conf):
# ~/.config/ru/agent-sweep.d/my-repo.conf
# Per-repo overrides without modifying the repo itself
AGENT_SWEEP_RELEASE_STRATEGY=never
State Management
Agent-sweep tracks progress for resume capability:
--resume preserves the original repository set, location/layout, execution mode,
release choice, and secret/file-size options. Only the latest successful journal
outcome completes a repository; failed, skipped, or missing outcomes remain pending.
The summary shows the latest outcome while the journal retains earlier attempts.
An unfinished run requires an explicit --resume or --restart before a new
execution can begin. Restart archives the previous journal and checkpoint, then
starts a fresh run with no inherited completion markers.
Interrupts stop new phases and keep the instance lock until in-flight workers
finish. Checkpoints are saved for ordinary failures as well as interruptions.
After the commit executor confirms success, a per-checkout receipt records the
resulting commit and tree. If release planning times out, --resume can start
release planning again at that commit. The new agent session receives the
original and confirmed commit identities plus the saved commit plan, so it can
understand the completed work without repeating the commit phases.
Once the release plan is saved, resume
uses that exact plan and its recorded release steps. A completed workflow can
also restore a missing journal summary without another commit, hook, or push.
If local commits are confirmed but a push fails, ru agent-sweep --resume
retries publication from the recorded commit, including when only some push
destinations succeeded. It verifies completed destinations and skips their push
hooks, without repeating agents, commits, or completed workflow hooks. Recovery
requires the exact recorded commit in the original clean checkout and unchanged
publication destinations. An unconfirmed commit_applying receipt still requires
manual recovery because ru cannot infer whether its commits or hooks completed.
Each NTM spawn, prompt delivery, and completion must return a valid successful robot response. Empty, malformed, failed, or contradictory responses stop the workflow before pane output can authorize a commit or release. For each commit or release planning request, ru supplies a fresh reply ID. The agent appends it to both JSON delimiters. Only one complete response carrying that request's ID can be executed; old pane history and echoed example plans are ignored. The checkpoint and original work remain available for inspection and retry.
Sweep sessions are bound to the stable pane and tmux session identities returned at startup. Prompt delivery and output capture verify that ownership; cleanup uses the recorded session ID. A refused spawn never authorizes operations on an existing session with the same name. Partial startup is cleaned up only when its returned pane proves which session was created, including during cancellation.
Continuation requires the original checkout, branch, policy, and publication
destination. Fresh sweeps also recheck the original binding after release
planning, before release publication, and before the post-hook. A changed
receiver or policy leaves the confirmed commit available for recovery rather
than authorizing the next phase with the new settings.
Before resuming release work, ru checks that HEAD matches the
recorded work or release commit and that the index, worktree, and submodules
are clean. This includes nested submodules: inspection bypasses filesystem-monitor
hints and refuses hidden index entries or unfinished Git operations, preserving
their files, index flags, and recovery state for you to inspect.
Hook receipts record the bytes of an executable invoked by path and scripts
passed directly to sh or bash, including ignored and non-executable files.
Paths can use single quotes, double quotes, or backslash escapes. A leading
env or command and shell flags such as -eu, -o pipefail, and --
are supported. For example, changing the script in
env bash -eu -- ".git/check release.sh" blocks continuation.
The same check covers explicit script operands of python, python3, node,
ruby, and perl, and a hook beginning with source ./file or . ./file.
For hooks that expand a script path, run several commands, or load other files,
declare their dependencies in agent_sweep.hook_inputs and
agent_sweep.hook_env. hook_inputs lists literal file paths, relative to the
checkout or absolute. Include sourced helpers, configuration files, Makefiles,
and other inputs whose changes would alter the hook. Inspection does not expand
globs or execute shell expressions. Declared inputs must be readable regular
files; ignored files and scripts without executable permission are supported.
Their contents, resolved target paths, and executable status are bound to the
workflow. A missing file, changed contents, or retargeted symlink blocks retry.
hook_env lists shell variable names used by the hooks, such as a script selector
or a build profile. Values visible to the checkout worker after configuration
loading are captured once and restored when each hook runs. Only their digest is
recorded, so values do not appear in the
receipt. Unset, empty, and multiline values remain distinct. A retry with changed
values stops before starting an agent or running a hook; restoring the original
files and values permits continuation at the confirmed phase.
Automatic inspection covers literal paths in the first command. Dependencies selected by expansion, later commands in a pipeline or command list, and files loaded inside a script must be declared explicitly. The declaration binds those inputs; it does not infer every dependency of arbitrary shell code. If a commit or hook was interrupted while applying, its effects may already have occurred. In that case ru keeps the checkpoint for manual inspection. An older run with an existing anchor or snapshot and no workflow receipt also requires inspection before restarting.
--dry-run, including a leading global flag, previews the selected repositories
without starting agents and does not require NTM or tmux.
Sessions, artifacts, and backup refs use a stable checkout key derived from the
physical worktree root and its Git directory. Repositories with the same name
keep separate evidence. The initial Git snapshot and
refs/agent-sweep/pre-run-<run-id>-<checkout-key> backup ref are preserved across
retries.
~/.local/state/ru/
├── agent-sweep/
│ ├── state.json # Current sweep state
│ ├── results.ndjson # Per-repo results
│ ├── completed_repos.txt # Successfully completed repos
│ ├── instance.lock/ # Concurrent execution lock
│ │ └── pid # Lock holder PID
│ ├── locks/ # Coordination locks
│ └── runs/<run-id>/ # Per-run artifacts
│ └── <checkout-key>/<repo>/ # Git snapshots, plans, and session evidence
└── logs/
└── YYYY-MM-DD/
├── agent_sweep.log # Main log
└── repos/
└── <repo>.log # Per-repo logs
State operations:
# View current state
cat ~/.local/state/ru/agent-sweep/state.json | jq .
# Resume interrupted sweep
ru agent-sweep --resume
# Clear state and start fresh
ru agent-sweep --restart
# View per-repo results
cat ~/.local/state/ru/agent-sweep/results.ndjson | jq -s .
Troubleshooting Agent Sweep
"ntm is not available"
Cause: Named Tmux Manager not installed or not in PATH.
Fix:
# Install ntm (if available via package manager)
# Or add to PATH if installed elsewhere
export PATH="$HOME/.local/bin:$PATH"
# Verify
ntm --version
"Another agent-sweep is already running"
Cause: Lock file exists from previous run.
Fix:
# Check if actually running
ps aux | grep "agent-sweep"
# If stale, remove lock
rm -rf ~/.local/state/ru/agent-sweep/instance.lock
Agent session hangs
Cause: Agent waiting for input or slow network.
Fixes:
- Increase timeouts:
--phase2-timeout=1200 - Attach to session:
ru agent-sweep --attach-on-fail - Keep sessions for debugging:
--keep-sessions-on-fail
# List active sessions
tmux list-sessions
# Attach using the exact session name from the list above
tmux attach -t SESSION_NAME
"diverged_from_upstream" skip reason
Cause: Local and remote branches have diverged.
Fix:
cd /data/projects/affected-repo
git fetch origin
git rebase origin/main # Or merge
Secret detected, push blocked
Cause: Agent committed a file matching secret patterns.
Fixes:
- Remove the secret:
git reset HEAD~1 && git checkout -- file - If false positive, adjust denylist
- Use
--secret-scan=warnto continue with warning
Exit Codes for Agent Sweep
| Code | Meaning |
|---|---|
0 |
All repos processed successfully |
1 |
Some repos failed (agent error, timeout) |
2 |
Quality gate failures (secrets, tests) |
3 |
System error (ntm, tmux missing) |
4 |
Invalid arguments |
5 |
Interrupted (use --resume) |
🤖 AI Sync
The ai-sync subcommand scans for dirty repositories and launches the selected AI agent through ntm to read project context and create logical commits. ru then inspects the resulting Git state and publishes the validated revision when publication is requested.
AI sync and agent-sweep verify that each selected worktree matches its configured repository origin and branch or tag. Linked worktrees are supported. Conflicting destinations, mismatched checkouts, and failed status inspections stop discovery instead of silently omitting work or launching an agent in a different project.
Prerequisites
- ntm (Named Tmux Manager) - for session orchestration
- claude-code, codex, or gemini CLI - for AI agent execution
- tmux and jq - for session ownership checks and typed results
Usage
ru ai-sync # Process all dirty repos
ru ai-sync --dry-run # Show what would be processed
ru ai-sync --include=my-project # Only process repos whose path contains this
ru ai-sync --exclude='test-*' # Skip repos whose name matches this glob
ru ai-sync --timeout=1200 # Allow 20 minutes per repo
ru ai-sync --no-push # Commit but don't push
ru ai-sync --agent=codex # Use a different AI agent
ru ai-sync --no-untracked # Ignore untracked files
How It Works
- Scans all configured repos for uncommitted changes
- For each dirty repo, launches an AI agent session via ntm
- The agent reads
AGENTS.mdandREADME.mdto understand the project - Reviews all changes and groups them into logical commits
- Creates detailed commit messages explaining the changes
- ru confirms that the original branch and history were preserved, the final candidate retains the original dirty working versions, and no tracked or untracked work remains
- Unless
--no-pushis specified, ru scans the unpublished history, pushes the exact validated revision through the captured destination, and verifies the receiver's ref
An idle or disappearing session does not prove that work succeeded. Each result records the transport status, actual before and after revisions, commit SHAs, remaining paths, publication status, process exit code, and an evidence_dir containing the prompt and tool diagnostics. A publication failure returns nonzero and preserves completed local commits.
After a rejected or interrupted push, run ru ai-sync --retry-push=EVIDENCE_DIR
using the original result's evidence_dir. RU rechecks the saved branch, exact
commit, original file contents and publication destination, then retries the
push with a fresh --timeout budget. Recovery requires the recorded clean
checkout, and changed work or a changed receiver stops the attempt. The command
also accepts --dry-run and --json. Each retry retains its own diagnostics
inside the original evidence directory. This recovery is available for runs
that saved publication-recovery.json before their first publication attempt.
Before starting the agent, ru retains the original index and raw dirty files. AI sync asks the agent to commit existing work without editing it, so ru checks that the final Git tree matches the original working snapshot, including additions, deletions, renames and file modes. A single commit of the working version is valid for partially staged files; the original staged version remains recovery evidence. Discarded, rewritten, subsequently reverted or additional unrequested changes fail validation, retain useful local commits and snapshots, and block host publication. Dependency updates retain the same recovery snapshots but use an editing policy, which does not claim original-content preservation.
--timeout covers the entire operation, including readiness, prompt delivery, completion, Git inspection, and requested publication. Cleanup after interruption has a separate two-second budget and termination grace. An unfinished inspection or uncertain publication is reported explicitly.
--no-push makes no host publication or receiver-inspection calls. The prompt directs the agent to work locally, and NTM panes receive an empty GIT_ALLOW_PROTOCOL restriction. This is a transport restriction, not a sandbox: provider tools, scripts, and project hooks can still attempt publication. Preventing every provider-side push attempt remains an open qualification requirement.
📦 Dependency Updates
The dep-update subcommand asks AI agents to update dependencies one at a time.
RU independently checks the actual manifest, locked resolution, installed target
and required tests before retaining each update in the original repository.
Configured targets must match their repository origin and requested branch or
tag, and each destination must be unambiguous. These checks run before package
discovery and remain bound to the original checkout through commit promotion
and publication recovery, including updates made with --no-push. A changed
origin or ref is a failed repository, not a successful preview. An explicit
--repo=PATH selects that worktree root directly; an empty path or a directory
inside another worktree is refused.
Prerequisites
A discovery preview (--dry-run) requires jq and the project’s package manager. Applying updates also requires the following agent tools.
- ntm (Named Tmux Manager) - for session orchestration
- claude-code, codex, or gemini CLI - for AI agent execution
Supported Package Managers
ru dep-update detects these manifests. Automatic discovery currently has
adapters for npm, pnpm, standalone Yarn Classic, Cargo (requires cargo-outdated), Go modules, Composer, and
standalone Python requirements files with exact pins.
| Manager | Detection Files | Discovery |
|---|---|---|
| npm | package.json, npm-shrinkwrap.json, package-lock.json |
npm outdated --json; workspace lock inventory and npm view |
| cargo | Cargo.toml |
cargo outdated --workspace --root-deps-only --format json |
| go | go.mod |
Direct, unreplaced requirements from go list -m -u -json all |
| composer | composer.json |
composer outdated --direct --locked --format=json |
| pnpm | packageManager, pnpm-lock.yaml, pnpm-workspace.yaml |
pnpm outdated --format json per project |
| yarn | yarn.lock |
Yarn Classic yarn outdated --json for standalone projects with a v1 lockfile |
| pip/pipenv | requirements.txt, pyproject.toml, setup.py, Pipfile |
pip index versions for a standalone root requirements.txt with exact package pins. Other Python manifest forms return an unsupported-scan error. |
| bundler | Gemfile |
Explicit unsupported-scan error |
| maven/gradle | pom.xml, build.gradle, build.gradle.kts |
Explicit unsupported-scan error |
Missing tools, malformed output, failed commands, and unsupported scans count
as failed repositories and give a nonzero exit status, including in --dry-run.
A failure in any detected manager prevents an update session for that repository;
partial results do not establish that all dependencies are current. The supported
adapters still require live project and test validation before a release.
Go discovery excludes main modules, indirect dependencies, and replacement-based
resolutions from the update plan. Errors anywhere in the returned module graph
still fail discovery. Composer reads the root composer.json and its lockfile
with plugins and scripts disabled, so an inherited COMPOSER override or stale
vendor installation cannot select different update candidates. Runtime and
development requirements are included; indirect-only updates do not start an
agent transaction.
Cargo discovery includes direct dependencies across workspace members. Each
emitted update retains its crate_name, compat, kind, and platform in JSON;
the same dependency in two members counts as two update records. Transitive
dependencies are outside this manifest-update preview. Cargo's --- and
Removed latest-version status markers require manual review and fail the scan
rather than entering an update session as versions. This adapter preserves the
records cargo-outdated emits; it cannot recover distinctions that tool omits or
independently establish that its successful output lists every expected member.
Automatic Rust test detection selects cargo test --workspace, so a root
package or a restricted workspace.default-members list does not silently omit
other members from the update's host test command. An explicit --test-cmd
still overrides automatic detection. This selects workspace members; it does
not enable every Cargo feature or override a manifest's disabled test targets.
For dependency updates, automatic test selection follows the managers that
still have planned updates after name/major filtering. A mixed npm/Cargo
update runs npm test && cargo test --workspace; a Cargo-only update selects
the Cargo suite even when package.json also exists. Go and Composer suites
are included when their dependencies are updated, with each manager tested
once in the combined command after every accepted dependency candidate.
The locked environments for all selected managers are installed in each fresh
attempt repository. If an updated manager has no detected test command, the update stops
before session setup; provide --test-cmd for a project-specific or combined
suite. An explicit command replaces the automatic selection. Other quality
gate callers retain the existing general detection precedence.
Node projects select a manager through packageManager, the manager named in
devEngines.packageManager, or root manager files such as yarn.lock,
pnpm-lock.yaml, npm-shrinkwrap.json, and package-lock.json. Conflicting declarations or lockfiles
produce a failed scan. A standalone package.json with no manager declaration
defaults to npm. For a standalone Yarn Classic project, ru dep-update --dry-run
reads the locked version, wanted version, registry latest version and dependency
type. It includes development dependencies. Yarn workspaces, modern Yarn and Bun
still require manual discovery. Automatic Yarn Classic updates support standalone
projects with tracked package.json, a v1 yarn.lock, and any root .yarnrc or
.npmrc. They additionally require Python 3 for strict lockfile evidence.
RU checks direct registry version ranges against Yarn's native offline resolver,
installs the frozen lock with lifecycle scripts disabled, and verifies physical
installed package names and versions before and after the project tests.
Automatic test selection uses yarn test. The effective Yarn configuration is
bound to the original checkout and checked again before promotion; workspace,
PnP, alias, linked-dependency and custom installation-directory setups require
manual handling.
For npm workspaces, ru dep-update --manager=npm --dry-run reads direct locked
versions without requiring an existing node_modules. Native npm query and
npm pkg inventories must agree on the workspace members, and every member
manifest, package-manager configuration file and shared v2/v3 root lock must be
tracked. This also catches ignored workspace members that would disappear from
an isolated clone. RU queries each direct registry package through the configured
registry and uses npm's semantic-version comparison to avoid downgrades when a
registry's latest tag is behind the locked version. A failed registry query
fails the scan.
Workspace records retain a relative project path, so the same dependency in
two members produces two independently verified updates. Internal workspace
dependencies remain linked to their original members. Only the selected
member's manifest and the shared root lock may change; all other manifests and
direct resolutions stay fixed. Installation includes the workspace root and
all members, with lifecycle scripts disabled. Automatic test selection runs
npm --workspace=<project> test for each selected member; --test-cmd can
provide a combined suite. Nested lockfiles, external workspace paths, aliases
and external linked dependencies require manual handling.
For pnpm, ru dep-update --manager=pnpm --dry-run discovers direct dependencies
using the native registry and lockfile configuration. In a workspace, RU lists
the members and scans each package separately, including a root package.
JSON records retain the relative project path, dependency type, and locked
wanted version. If the package is uninstalled, its current value is
MISSING and the default major-version filter uses the locked version.
A failed member scan fails the repository. Automatic updates support root
projects and workspaces with a tracked shared pnpm-lock.yaml. They require
pnpm 10.23 or later with native lockfile-only listing.
RU validates the frozen lock, binds the target to its exact importer and
declaration, and verifies the physical installed package before and after tests.
Automatic test selection runs each updated importer's test command from that
project's directory; --test-cmd can provide a combined workspace suite.
For a standalone Python requirements.txt, RU reads each name==version pin and
queries the indexes configured for python3 -m pip. It compares PEP 440
versions for the active interpreter and platform without installing packages.
Activate the project’s .venv first if it has one. If any index is unavailable,
the scan returns a failure for the project.
Epoch and major-release increases are included with --major. Constraints,
includes, hashes, extras, markers, ranges, direct URLs, competing manifests, and
conflicting pins need a project-specific scan. Automatic updates support the
same standalone exact pins with pip 23.0 or newer and Python virtual environment
support. Each candidate installs into a fresh environment owned by RU. Host
tests use that environment through PATH, VIRTUAL_ENV and Python module
execution, and RU verifies the installed distributions again after the tests.
The original activated environment keeps its installed packages.
Python updates preserve the active interpreter and its pip sources, including
environment variables, user/site configuration, and relative local
find-links directories. Source settings are captured before agent work and
checked again before promotion. Installation-routing overrides such as
target, prefix and user, cross-platform resolution, external constraints,
and options that disable dependency validation require manual handling.
Receipts identify dependency_scope: "direct-requirements" and
transitive_lock: false. A requirements edit is verified separately from pip's
version-1 installation report, archive digests, resolved transitive packages,
pip inspect metadata and pip check. The resolution report describes the
packages installed for that attempt.
An actual update requires a successfully detected, nonempty test command or
an explicit --test-cmd. Failed detection and blank commands fail the repository
before AI session setup. --dry-run remains a discovery
preview and does not require or claim test execution.
Verified Update Scope
Discovery support and automatic update verification are separate contracts:
| Manager | Automatically verifiable update scope |
|---|---|
| npm | A root project or workspace with tracked manifests, configuration and one shared v2/v3 root lock. A root npm-shrinkwrap.json takes precedence over package-lock.json; any inactive lockfile stays unchanged. Workspace filesystem and lock inventories must agree. Only the selected importer's manifest and root lock may change, preserving all other direct resolutions and internal workspace identities. Native lock validation, physical installed package metadata and host tests must agree on the requested name and version. Competing managers, nested locks, aliases and external linked dependencies are unsupported. |
| pnpm | A root project or workspace with tracked manifests, configuration and one shared root lockfile. Only the target importer's manifest and the root lock may change. All other direct importer resolutions must remain unchanged. Standard isolated and hoisted installation layouts are supported; separate or branch lockfiles, custom module/lock directories, aliases and linked target dependencies are refused. |
| Yarn Classic | One standalone project with a tracked manifest, v1 lockfile and root configuration. The native offline resolver, frozen installation and physical installed package metadata must agree. The target keeps its package identity and registry origin; every other direct lock entry stays unchanged. Grouped selectors retain resolutions still needed by transitive dependencies. Workspaces, modern Yarn, PnP, aliases, linked direct dependencies and custom installation routing are unsupported. |
| Cargo | One direct registry dependency identified by its workspace member, kind and platform, resolved by cargo metadata --locked --offline. With Python 3.11 or newer, the selected member's explicit version requirement and Cargo.lock may change, including major-version updates; all other manifest settings and direct resolutions stay unchanged. Renamed dependencies and normal, development, build and target-specific declarations are supported. Shared workspace requirements, declarations the TOML reader cannot bind, and environments without tomllib retain lockfile-only support. The required resolution must already be available to the offline reader. |
| Go | A root module with tracked go.mod and go.sum, an unambiguous native read-only module graph, and target archive/module checksums. Workspaces and replacement-based resolutions require manual handling. |
| Composer | One direct locked package with native manifest/lock validation and the standard vendor layout. Installed package metadata must agree with the requested package and locked version. |
| pip | Standalone tracked root requirements.txt containing exact direct pins. Only the selected pin can change, preserving all other file content. A fresh owned virtual environment, native pip installation report, archive hashes, installed distribution metadata and dependency checks verify the requested package and its resolved dependencies. |
Unrelated direct dependencies and manifest settings must remain unchanged. The target requirement may remain unchanged when its range already permits the new locked version. A lockfile change and a changed resolved version are required. Necessary transitive lock changes are recorded but do not inflate the count of requested updates. Changes to source files, test commands, file types or unsupported manifest layouts are refused. A Cargo update that must advance another direct member/kind/platform edge is also refused.
RU runs npm ci, pnpm install --frozen-lockfile or
yarn install --frozen-lockfile with lifecycle scripts
disabled, composer install with scripts and plugins disabled,
cargo fetch --locked, or go mod download before tests.
Projects requiring those disabled installation hooks need a separately reviewed
workflow. Tests run in a fresh clone, so ignored local files and pre-existing
installed packages are not copied from the original project. Project build
outputs need appropriate ignore rules; unexpected tracked or untracked changes
invalidate the candidate. An npm tarball whose embedded package version differs
from its lockfile is refused even if npm ci and npm ls accept it.
Each repository result includes deps_outdated_before for the filtered discovery
count and deps_updated for updates actually verified, tested and promoted into
the original branch. The dependencies array retains manager, name, requested
version, authoritative before/actual versions, exact tested commit,
installation/test receipts, publication status and evidence directory.
| Dependency status | Meaning |
|---|---|
updated |
Native dependency evidence and host tests passed; the exact single commit entered the original branch. Publication has a separate result. |
skipped |
The authoritative baseline already contains the requested version. No new update or test success is counted. |
failed |
The request did not produce a completed valid update, including an agent no-op. |
reverted |
A changed attempt failed validation or tests and remains isolated; the original branch retains its preceding verified state. |
unverified |
Evidence, supported scope, ownership, installed version, deadline or promotion could not be established. |
Failed attempts and raw stdout/stderr remain available for inspection. Rollback
means keeping that attempt out of the original repository; RU never resets or
cleans the original branch. Earlier verified updates remain there, and valid
updates may be published even when other dependencies fail. Such a run reports
partial and exits nonzero. A timeout blocks remaining updates and publication;
already promoted local updates remain available. An uncertain or failed push
also returns nonzero and retains verified local commits.
--no-push performs no receiver inspection or host publication. Attempt clones
have an unusable publication remote and the existing NTM protocol restriction.
These controls do not constitute an operating-system sandbox for arbitrary
provider tools or project scripts. Repository identity, branch, clean state and
publication destination are checked before promotion and publication; concurrent
changes cause refusal rather than a forced reset. A per-repository ownership
lock prevents overlapping RU dependency transactions. Inherited Git repository
and namespace overrides are refused before ownership inspection or cloning.
Update Workflow
- Discover and filter updates, then resolve all required manager test suites.
- Capture the original branch, revision and publication destination. Prepare an independent clone for one requested dependency.
- Read native before/after dependency snapshots around the owned AI session. Refuse no-ops, wrong versions, inconsistent locks and unrelated changes.
- Replace the agent's private intermediate history with one host-created commit containing only the verified final tree. Intermediate failed commits cannot become ancestors of the published update.
- Install the locked environments, verify the installed target, execute the exact required tests, then reinspect the installed target and Git state. Test evidence binds to the exact commit being accepted.
- Fast-forward the original branch only while its ownership and clean baseline still match. Retain failed attempts separately and proceed with other requests within the remaining deadline.
- Publish only accepted commits through the original captured destination, unless
--no-pushwas specified. Report every request separately, including partial failure.
The original --timeout budget is shared by manager detection, dependency
discovery, test-command selection, isolation, all dependency sessions, native
inspection, installation, host tests, promotion and requested publication. This
also bounds --dry-run scans and is not restarted for each manager or dependency.
A stalled scan terminates its owned process group, retains its output and
diagnostics, reports status: "timeout" with error_code: "deadline_expired",
and allows the next repository to proceed with its own budget. Process
termination has a separate one-second grace period. --max-fix-attempts remains the requested
repair budget inside an agent session; the host independently accepts or rejects
the final candidate regardless of what that agent reports.
Deterministic fixtures exercise actual local Git state and controlled provider responses. Native manager fixtures cover only the specific layouts and tools they execute. These checks do not establish public-registry or live-provider execution, all supported project layouts or release qualification. Issue #19 remains open for that broader qualification and the unsupported scopes above.
Basic Usage
# Update all dependencies in all configured repos
ru dep-update
# Preview what would be updated (no changes)
ru dep-update --dry-run
# Update a single repository
ru dep-update --repo=./my-project
# Use a specific AI agent
ru dep-update --agent=codex
Filtering Dependencies
You can control which dependencies get updated using filters:
# Only update npm packages
ru dep-update --manager=npm
# Only update packages matching a pattern
ru dep-update --include='react|vue|angular'
# Exclude specific packages from updates
ru dep-update --exclude='typescript|webpack'
# Include major version updates (risky, disabled by default)
ru dep-update --major
# Combine filters
ru dep-update --manager=pip --exclude='django' --major
Controlling the Update Process
# Custom test command (overrides auto-detection)
ru dep-update --test-cmd="npm run test:ci"
# Increase fix attempts for complex updates
ru dep-update --max-fix-attempts=10
# Commit changes but don't push to remote
ru dep-update --no-push
# Increase timeout for large repos
ru dep-update --timeout=1800
Retrying Publication
If a push fails, the verified dependency commits remain in your local repository. Use the original run's evidence_dir to retry publication directly:
# Verify the retained work and destination without contacting the remote
ru dep-update --retry-push=/tmp/ru-dep-update.RUN --dry-run
# Publish those exact verified commits after fixing the transport problem
ru dep-update --retry-push=/tmp/ru-dep-update.RUN --timeout=120 --json
Recovery requires the original clean checkout, branch, tested commits and configured push destination. It refuses subsequent user changes or a changed destination and preserves that work for inspection. It does not start agents, rescan dependencies, reinstall packages or rerun tests; package managers and AI providers are not required for this mode. Each attempt retains its own diagnostics alongside the immutable publication receipt, and repeating a successful retry confirms the same remote HEAD.
JSON results keep updated and deps_updated at zero. published counts the recovered repository, deps_published counts its retained updates, and retained_updates carries their original verification receipts. unresolved_dependencies preserves the count of earlier requests that did not succeed; publishing the retained commits does not resolve those requests.
Combine --retry-push only with --dry-run, --timeout and output options. A --no-push run does not create publication authorization. If a retry times out or is interrupted during transport, its result reports publication as uncertain; retrying the same receipt verifies the actual receiver before continuing.
Updates and publication retries share an owner-identified repository lock. An interrupted lock operation can recover after its recorded owner exits. Anonymous lock files or directories left by older versions are preserved because their ownership cannot be established; finish those older processes before recovering their locks, and avoid running old and new versions against the same repository concurrently.
Exit Codes
| Code | Meaning |
|---|---|
0 |
All updates successful, or publication recovery completed |
1 |
Some dependencies failed to update, or publication recovery failed |
3 |
Missing dependencies (ntm, claude-code) |
4 |
Invalid arguments |
5 |
Publication retry interrupted |
🔢 Exit Codes
ru uses meaningful exit codes for automation:
| Code | Meaning | When |
|---|---|---|
0 |
Success | All repos synced or already current |
1 |
Partial failure | Some repos failed (network/auth/remote error) |
2 |
Conflicts exist | Some repos have unresolved conflicts |
3 |
Dependency error | gh CLI missing, auth failed, etc. |
4 |
Invalid arguments | Bad CLI options, missing config files |
5 |
Interrupted | Sync interrupted by user (Ctrl+C); use --resume to continue |
Using in Scripts
#!/bin/bash
ru sync --non-interactive
exit_code=$?
case $exit_code in
0) echo "All repos synchronized successfully" ;;
1) echo "Some repos failed - check logs" ;;
2) echo "Conflicts detected - manual resolution required" ;;
3) echo "Missing dependencies - run 'ru doctor'" ;;
4) echo "Invalid configuration" ;;
5) echo "Sync interrupted - run 'ru sync --resume' to continue" ;;
esac
CI Usage
# GitHub Actions example
- name: Sync repositories
run: |
ru sync --non-interactive --json > sync-results.json
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
continue-on-error: true
- name: Check sync status
run: |
if [ $? -eq 2 ]; then
echo "::warning::Some repos have conflicts"
fi
🏗️ Architecture
Component Overview
ru is organized into logical layers, with each layer building on the ones below. The full implementation is approximately 28,500 lines of pure Bash, with no external dependencies beyond git, curl, and optionally gh CLI and gum for enhanced UX.
ru (bash, ~28,500 LOC)
│
├── Core Foundation Layer
│ ├── Utilities & Guards
│ │ ├── is_interactive() # TTY detection for prompts
│ │ ├── can_prompt() # Interactive + non-CI guard
│ │ ├── ensure_dir() # Create directory if missing
│ │ └── json_escape() # Safe JSON string escaping
│ │
│ ├── Logging (stderr=humans, stdout=data)
│ │ ├── log_info/warn/error() # Human messages to stderr
│ │ ├── log_step/success() # Progress indicators
│ │ └── write_result() # NDJSON structured logging
│ │
│ ├── Configuration
│ │ ├── get_config_value() # Read from ini-style file
│ │ ├── set_config_value() # Write to file atomically
│ │ └── resolve_config() # CLI > env > file > default
│ │
│ └── Path Security
│ ├── validate_path() # Reject traversal attacks
│ ├── safe_path_concat() # Prevent /a + ../b escapes
│ └── canonicalize_path() # Resolve symlinks safely
│
├── Infrastructure Layer
│ ├── Portable Locking
│ │ ├── dir_lock_try_acquire() # Atomic mkdir-based locks
│ │ ├── dir_lock_wait() # Blocking lock with timeout
│ │ └── dir_lock_release() # rmdir-based release
│ │
│ ├── URL & Path Parsing
│ │ ├── parse_repo_url() # Extract host/owner/repo
│ │ ├── normalize_url() # Canonical URL form
│ │ ├── parse_repo_spec() # owner/repo@branch as name
│ │ └── url_to_local_path() # Layout-aware path resolution
│ │
│ ├── Dependency Detection
│ │ ├── detect_os() # macOS/Linux detection
│ │ ├── check_gh_*() # gh CLI status checks
│ │ └── ensure_dependencies() # Full dependency flow
│ │
│ └── Gum Integration
│ ├── check_gum() # Feature availability
│ ├── gum_confirm() # Y/N with fallback
│ └── print_banner() # Styled box output
│
├── Git Operations Layer (no cd, plumbing-based)
│ ├── Status Detection
│ │ ├── get_repo_status() # Ahead/behind via rev-list
│ │ ├── is_dirty() # status --porcelain
│ │ └── is_shallow() # rev-parse --is-shallow
│ │
│ ├── Actions
│ │ ├── do_clone() # gh repo clone with retry
│ │ ├── do_pull() # Strategy-aware pull
│ │ └── do_fetch() # Fetch with timeout handling
│ │
│ └── Worktree Management
│ ├── create_worktree() # Isolated checkout for review
│ ├── cleanup_worktree() # Safe removal
│ └── get_worktree_list() # Active worktree tracking
│
├── Sync Orchestration Layer
│ ├── Repo List Management
│ │ ├── load_repo_list() # Parse list files
│ │ ├── detect_collisions() # Path collision warnings
│ │ └── enumerate_repos() # Combine public + private
│ │
│ ├── Work-Stealing Queue
│ │ ├── queue_init() # Write repos to temp file
│ │ ├── queue_dequeue() # Atomic pop with lock
│ │ └── worker_loop() # Process until empty
│ │
│ ├── Sync State Management
│ │ ├── sync_state_init() # Create run directory
│ │ ├── sync_state_save() # Persist resume state
│ │ └── sync_state_load() # Resume interrupted sync
│ │
│ └── Result Aggregation
│ ├── tally_results() # Count by status
│ ├── format_summary() # Human-readable report
│ └── format_json() # Machine-readable output
│
├── Review & Agent Coordination Layer
│ ├── Discovery & Prioritization
│ │ ├── discover_items() # Find issues/PRs to review
│ │ ├── score_priority() # Multi-factor ranking
│ │ └── filter_by_policy() # Apply review policies
│ │
│ ├── Session Management
│ │ ├── create_review_session() # Initialize session
│ │ ├── monitor_session() # Health tracking
│ │ └── cleanup_session() # Resource cleanup
│ │
│ ├── Quality Gates
│ │ ├── validate_commit_plan() # Security & size checks
│ │ ├── check_file_allowlist() # Denylist enforcement
│ │ └── verify_tests_passed() # Test requirement gate
│ │
│ └── GitHub Actions Execution
│ ├── execute_gh_action() # Comment, close, merge, etc.
│ ├── verify_action_safe() # Security validation
│ └── batch_actions() # Rate-limit aware batching
│
├── Agent Sweep Layer
│ ├── Preflight & Safety
│ │ ├── preflight_checks() # Environment validation
│ │ ├── check_repo_config() # Per-repo review settings
│ │ └── abort_conditions() # Safety circuit breakers
│ │
│ ├── Orchestration
│ │ ├── agent_sweep_loop() # Main iteration logic
│ │ ├── spawn_review() # ntm/Claude Code session
│ │ └── wait_for_completion() # Timeout handling
│ │
│ └── State & Recovery
│ ├── sweep_state_save() # Progress checkpointing
│ ├── sweep_state_load() # Resume after interrupt
│ └── cleanup_stale() # Remove orphaned worktrees
│
└── Command Layer
├── Core Commands
│ ├── cmd_sync() # Clone and pull repos
│ ├── cmd_status() # Read-only status check
│ ├── cmd_init() # Create configuration
│ ├── cmd_add() # Add repo to list
│ └── cmd_remove() # Remove from list
│
├── Maintenance Commands
│ ├── cmd_prune() # Detect orphan repos
│ ├── cmd_doctor() # System diagnostics
│ └── cmd_self_update() # Version checking
│
├── Review Commands
│ ├── cmd_review() # Single-repo review mode
│ └── cmd_agent_sweep() # Multi-repo agent sweep
│
└── CLI Infrastructure
├── show_help() # Usage message
├── dispatch_command() # Route to handler
└── on_exit() # Cleanup trap
Data Flow
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Config │────▶│ Repo List │────▶│ Processing │
│ Files │ │ Parser │ │ Loop │
└─────────────┘ └─────────────┘ └─────────────┘
│
┌──────────────────────────────────────────┤
▼ ▼ ▼
┌─────────┐ ┌─────────────┐ ┌──────────┐
│ Clone │ │ Status │ │ Pull │
│ (gh) │ │ (plumbing) │ │ (git) │
└─────────┘ └─────────────┘ └──────────┘
│ │ │
└──────────────────────────────────────────┤
▼
┌─────────────┐
│ Results │
│ (NDJSON) │
└──────────────┘
│
┌──────────────────────────┤
▼ ▼
┌─────────────┐ ┌─────────────┐
│ Summary │ │ JSON │
│ (stderr) │ │ (stdout) │
└─────────────┘ └─────────────┘
NDJSON Results Logging
ru tracks per-repo results in Newline-Delimited JSON (NDJSON) format for easy parsing and CI integration:
{"repo":"mcp_agent_mail","path":"/data/projects/mcp_agent_mail","action":"pull","status":"updated","duration":2,"message":"","timestamp":"2025-01-03T14:30:00Z"}
{"repo":"beads_viewer","path":"/data/projects/beads_viewer","action":"clone","status":"cloned","duration":5,"message":"","timestamp":"2025-01-03T14:30:05Z"}
{"repo":"repo_updater","path":"/data/projects/repo_updater","action":"skip","status":"current","duration":0,"message":"Already up to date","timestamp":"2025-01-03T14:30:05Z"}
Fields:
| Field | Description |
|---|---|
repo |
Repository name |
path |
Local filesystem path |
action |
What was attempted: clone, pull, skip, fail |
status |
Result: cloned, updated, current, conflict, failed |
duration |
Seconds taken |
message |
Error message if failed, empty otherwise |
timestamp |
ISO-8601 timestamp |
Use with jq:
# Count by status
cat ~/.local/state/ru/logs/latest/results.ndjson | jq -s 'group_by(.status) | map({status: .[0].status, count: length})'
# Find failures
cat ~/.local/state/ru/logs/latest/results.ndjson | jq -r 'select(.status == "failed") | "\(.repo): \(.message)"'
Portable Locking
ru uses directory-based locking for coordination across parallel workers and concurrent processes. This approach works on all POSIX systems without requiring flock (which isn't available on all platforms):
# Lock acquisition via atomic mkdir
dir_lock_try_acquire() {
local lock_dir="$1"
if mkdir "$lock_dir" 2>/dev/null; then
# Write lock info for debugging
echo "$$" > "$lock_dir/pid"
return 0
fi
return 1
}
How it works:
mkdiris atomic on POSIX filesystems—only one process can create a directory- Lock holder's PID is written to a file inside the lock directory
- Timeout-based acquisition retries with configurable duration
- Automatic cleanup on process exit via trap handlers
Use cases:
- Parallel sync workers accessing shared state
- Worktree mapping updates during concurrent reviews
- Sync state file coordination
Work-Stealing Queue
For parallel sync operations (--parallel N), ru uses a work-stealing queue pattern where multiple worker processes compete for work items atomically:
┌────────────────────────────────────────────────────────────────┐
│ Work Queue (temp file) │
│ ┌─────────┬─────────┬─────────┬─────────┬─────────┐ │
│ │ repo1 │ repo2 │ repo3 │ repo4 │ repo5 │ ... │
│ └─────────┴─────────┴─────────┴─────────┴─────────┘ │
└────────────────────────────────────────────────────────────────┘
│
┌────────────────────┼────────────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ Worker 1 │ │ Worker 2 │ │ Worker 3 │
│ (subshell)│ │ (subshell)│ │ (subshell)│
└──────────┘ └──────────┘ └──────────┘
│ │ │
│ ┌──────────────┴──────────────┐ │
│ ▼ ▼ │
│ ┌────────────────────────────────────┐ │
└─▶│ Queue Lock (mkdir) │◀┘
│ - Atomic dequeue via head/tail │
│ - Spin-wait with timeout │
└────────────────────────────────────┘
Algorithm:
- Queue initialization: Write all repo specs to a temporary file, one per line
- Worker spawning: Fork N worker subshells that compete for work
- Atomic dequeue:
- Acquire directory lock via
mkdir(atomic on POSIX) - Read first line from queue file (
head -1) - Remove first line (
tail -n +2 > tmp && mv tmp queue) - Release lock via
rmdir
- Acquire directory lock via
- Work completion: Worker processes repo, appends result to shared results file (also lock-protected)
- Progress tracking: Atomic counter updated under separate lock
Why work-stealing?
- Load balancing: Fast repos don't block slow ones—workers grab more work when free
- No coordinator bottleneck: Workers self-organize without a central scheduler
- Graceful degradation: If a worker dies, remaining workers continue
Lock contention handling:
- Spin-wait with 100ms sleep between attempts
- Configurable timeout (default 60s)
- Workers exit cleanly if they can't acquire lock
Path Security Validation
ru includes two security functions that guard against path traversal attacks, especially important when paths come from state files or user input:
_is_safe_path_segment(segment) — Validates individual path components:
| Check | Blocks | Reason |
|---|---|---|
| Empty string | "" |
Invalid path component |
| Dot-only | ., .. |
Path traversal attack |
| Leading dash | -rf |
Git option confusion |
| Path separators | foo/bar |
Unexpected subdirectory |
| Control characters | \x1b[31m |
Terminal escape injection |
_is_path_under_base(path, base) — Verifies a path is safely within a base directory:
# These pass:
_is_path_under_base "/data/projects/repo" "/data/projects" # ✓ Direct child
_is_path_under_base "/data/projects/a/b/c" "/data/projects" # ✓ Nested child
# These fail:
_is_path_under_base "../etc/passwd" "/data/projects" # ✗ Traversal
_is_path_under_base "/data/projects/../etc" "/data/projects" # ✗ Dot segment
_is_path_under_base "relative/path" "/data/projects" # ✗ Not absolute
_is_path_under_base "/data/projects" "/" # ✗ Base is root
Key design decisions:
- Lexical checks only: Does NOT resolve symlinks. This is intentional—
rm -rfon a symlink removes the link, not the target, so lexical containment is the correct safety check. - Rejects dot segments: Any
/.or/..in path or base causes rejection, preventingpath/../../../etc/passwdattacks. - Requires absolute paths: Relative paths are rejected to prevent confusion about the current directory.
These functions are used throughout ru to protect rm -rf operations on worktrees and state directories.
Retry with Exponential Backoff
Network operations and API calls use intelligent retry logic with exponential backoff and jitter:
retry_with_backoff MAX_ATTEMPTS BASE_DELAY_SECONDS -- command args...
Algorithm:
- Attempt the operation
- On failure, wait
BASE_DELAY * 2^(attempt-1)seconds - Add random jitter (±25%) to prevent thundering herd
- Retry until
MAX_ATTEMPTSexhausted - Return last exit code on final failure
Example:
# Retry GitHub API call up to 5 times with 2-second base delay
retry_with_backoff 5 2 -- gh api repos/owner/repo
# Delays: 2s, 4s, 8s, 16s (with jitter)
Capture modes:
--capture=all— Capture both stdout and stderr (default)--capture=stdout— Capture only stdout, let stderr pass through
This is used throughout ru for:
- GitHub GraphQL batch queries
- Clone operations on rate-limited repos
- Network-dependent status checks
JSON Utilities with Fallback Chain
ru provides portable JSON handling that works across environments with varying tool availability:
json_get_field(json, field) — Extract a field from JSON with graceful degradation:
┌─────────────────────────────────────────────────────────────────┐
│ JSON Field Extraction │
└─────────────────────────────────────────────────────────────────┘
│
┌───────────────┼───────────────┬───────────────┐
▼ ▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ jq │ │ python3 │ │ perl │ │ sed │
│ (best) │ │ (good) │ │ (ok) │ │ (basic) │
└──────────┘ └──────────┘ └──────────┘ └──────────┘
│ │ │ │
└───────────────┴───────────────┴───────────────┘
│
▼
┌─────────────────┐
│ Field value │
└─────────────────┘
| Tool | Handles | Limitations |
|---|---|---|
jq |
All JSON types, nested objects, arrays | None (preferred) |
python3 |
All JSON types | Requires Python 3 |
perl |
All JSON types | Requires JSON::PP module |
sed |
Simple string fields only | No nested objects, arrays, escapes |
json_escape(string) — Safe string escaping for JSON embedding:
# Handles all JSON-sensitive characters
json_escape 'Hello "World"' # → Hello \"World\"
json_escape $'Line1\nLine2' # → Line1\nLine2
json_escape 'Path: C:\Users' # → Path: C:\\Users
Characters escaped: \ → \\, " → \", newline → \n, tab → \t, carriage return → \r, backspace → \b, form feed → \f
json_validate(json) — Check if a string is valid JSON:
if json_validate "$response"; then
# Safe to parse
value=$(json_get_field "$response" "status")
fi
The validate function uses the same fallback chain, returning success (0) if any available tool can parse the JSON.
🧭 Design Principles
1. No Global cd
ru never changes the working directory. All git operations use git -C:
# DO: Use git -C
git -C "$repo_path" status --porcelain
git -C "$repo_path" pull --ff-only
# DON'T: cd into directories
cd "$repo_path" # Can fail, leaves state
git status # Which directory are we in?
cd - # Error-prone
2. Explicit Error Handling (No set -e)
ru uses set -uo pipefail but not set -e. This allows:
- Continuing after individual repo failures
- Capturing exit codes correctly
- Aggregating results for summary
# With set -e, this would exit before capturing exit_code:
output=$(failing_command); exit_code=$?
# ru's approach:
if output=$(git pull --ff-only 2>&1); then
log_success "Pulled"
else
exit_code=$?
log_error "Failed: $output"
# Continue to next repo
fi
3. Stream Separation
Human-readable output goes to stderr; data to stdout:
# Human messages → stderr
log_info "Syncing repos..." >&2
log_success "Done!" >&2
# Data → stdout (can be piped)
echo "$repo_path" # For scripts
output_json "$data" # For --json mode
# This works correctly:
ru sync --json | jq '.data.summary'
# Progress shows in terminal, JSON pipes to jq
4. Git Plumbing for Status
Never parse human-readable git output:
# WRONG: Locale-dependent, version-fragile
git pull 2>&1 | grep "Already up to date"
# RIGHT: Machine-readable plumbing
git rev-list --left-right --count HEAD...@{u}
git status --porcelain
git rev-parse HEAD
5. Prompted, Not Automatic
ru never auto-installs without asking:
# Interactive mode: ask first
if gum_confirm "GitHub CLI (gh) not found. Install now?"; then
install_gh
fi
# Non-interactive mode: fail clearly
log_error "gh not installed. Run with --install-deps or install manually."
exit 3
6. Progress Reporting
ru provides real-time progress feedback through a unified progress API:
# Initialize progress tracking
progress_init "$total_repos"
# Report start of each repo
progress_start_repo "$repo_name" "$current_index"
# Report completion with result
progress_complete_repo "$repo_name" "$status" "$duration"
# Final summary
progress_summary
Output adapts to context:
| Context | Behavior |
|---|---|
| Interactive terminal | Live-updating progress line with spinner |
| Non-interactive/CI | Simple line-by-line output |
--quiet mode |
Errors only |
--json mode |
NDJSON events to stdout, human summary to stderr |
7. CI Environment Detection
ru automatically detects CI environments and adjusts behavior accordingly:
Detected CI environments:
- GitHub Actions (
GITHUB_ACTIONS) - GitLab CI (
GITLAB_CI) - Jenkins (
JENKINS_URL) - Travis CI (
TRAVIS) - CircleCI (
CIRCLECI) - Azure Pipelines (
TF_BUILD) - Generic CI (
CI=true)
Behavior changes in CI:
- Forces
--non-interactivemode (no prompts) - Disables gum (uses ANSI fallbacks)
- Suppresses spinners and live progress
- Uses line-buffered output for proper log streaming
- Enables stricter error handling
# Manual CI mode override
CI=true ru sync
# Explicit non-interactive
ru sync --non-interactive
🛡️ File Denylist System
When scanning repositories or processing file changes, ru applies a comprehensive denylist to prevent accidental exposure of secrets, processing of large build artifacts, or noise from IDE/editor files.
Default Denylist Patterns
The built-in denylist covers four categories:
| Category | Patterns | Examples |
|---|---|---|
| Secrets & Credentials | .env, .env.*, *.pem, *.key, id_rsa*, credentials.json, secrets.json, .netrc, .npmrc, .pypirc |
API keys, TLS certificates, SSH keys |
| Build Artifacts | node_modules, __pycache__, dist, build, .next, target, vendor, *.pyc |
Dependencies, compiled output |
| Logs & Temp Files | *.log, *.tmp, *.temp, *.swp, *.swo, *~, .DS_Store, Thumbs.db |
Debug logs, swap files, OS metadata |
| IDE/Editor | .idea, .vscode, *.iml |
JetBrains, VS Code settings |
Pattern Matching Algorithm
The is_file_denied() function uses a three-tier matching approach:
is_file_denied "frontend/node_modules/lodash/index.js" # ✗ Blocked
is_file_denied "src/.env.local" # ✗ Blocked
is_file_denied "src/components/Button.tsx" # ✓ Allowed
Matching order:
- Full path match: Compare entire path against pattern (e.g.,
dist/*matchesdist/bundle.js) - Basename match: Compare just the filename (e.g.,
.envmatchesconfig/.env) - Directory containment: Check if file is inside a denied directory at any nesting level (e.g.,
node_modulesblocksfrontend/node_modules/pkg/index.js)
Extending the Denylist
Via environment variable (space-separated):
export AGENT_SWEEP_DENYLIST_EXTRA="*.custom internal_docs/*"
ru agent-sweep
Via config file (YAML):
# ~/.config/ru/config.yml
agent_sweep:
denylist_extra:
- "*.custom"
- "internal_docs/*"
- "vendor/private/*"
Via config file (JSON):
{
"agent_sweep": {
"denylist_extra": ["*.custom", "internal_docs/*"]
}
}
Programmatic Access
# List all active denylist patterns
ru agent-sweep --show-denylist
# From scripts, use the exported functions:
source /path/to/ru
if is_file_denied "path/to/file"; then
echo "File is blocked by denylist"
fi
# Filter a list of files
echo -e "main.py\n.env\nREADME.md" | filter_files_denylist
# Output: main.py
# README.md
🧪 Testing
ru includes a comprehensive test suite with 70+ test files covering unit tests, integration tests, and end-to-end workflows. The testing infrastructure is designed around a key principle: tests must work offline and deterministically.
Why Offline Testing Matters
Git operations are notoriously difficult to test reliably:
- Network dependencies make tests flaky and slow
- Real repositories can change unexpectedly
- CI environments may have restricted network access
- Authentication tokens expire or get revoked
ru solves this with a local git harness that creates temporary repositories with precisely controlled states—ahead, behind, diverged, dirty, shallow, detached—all without touching the network.
Test Architecture
scripts/
├── test_framework.sh # Core assertion library and utilities
├── test_git_harness.sh # Offline git repository factory
├── test_e2e_framework.sh # E2E test isolation and helpers
│
├── Unit Tests (test_unit_*.sh) — 36 files
│ ├── test_unit_config.sh # Configuration loading and resolution
│ ├── test_unit_core_utils.sh # Core utility functions
│ ├── test_unit_parsing_functions.sh # URL/spec parsing (40 tests)
│ ├── test_unit_git_harness.sh # Git harness self-tests (24 tests)
│ ├── test_unit_dependencies.sh # Dependency checking logic
│ ├── test_unit_quality_gates.sh # Commit plan validation
│ ├── test_unit_command_validation.sh # Argument validation
│ └── ... (29 more unit test files)
│
├── Integration Tests
│ ├── test_parsing.sh # URL parsing (76 tests, 156 assertions)
│ ├── test_local_git.sh # Local git operations with harness
│ └── test_sync_state.sh # Sync state management
│
└── End-to-End Tests (test_e2e_*.sh) — 20 files
├── test_e2e_sync_clone.sh # Clone operations
├── test_e2e_sync_pull.sh # Pull operations
├── test_e2e_sync_edge_cases.sh # Edge case handling
├── test_e2e_add_remove.sh # Repo list management
├── test_e2e_status.sh # Status command
└── ... (15 more E2E test files)
Git Harness: Deterministic Repository States
The git harness (test_git_harness.sh) creates temporary git repositories with specific states for testing. It uses bare repositories as "remotes" in /tmp, enabling complete offline testing of sync operations.
# Create a repo that's 2 commits ahead of remote
git_harness_setup
repo=$(git_harness_create_repo "myrepo" --ahead=2)
# $repo now contains a working directory with 2 unpushed commits
# Create a diverged state (local and remote have different commits)
repo=$(git_harness_create_repo "diverged" --ahead=1 --behind=3)
# Create various states
repo=$(git_harness_create_repo "dirty" --dirty) # Uncommitted changes
repo=$(git_harness_create_repo "shallow" --shallow=5) # Shallow clone
repo=$(git_harness_create_repo "detached" --detached) # Detached HEAD
repo=$(git_harness_create_repo "nobranch" --no-remote) # No tracking branch
git_harness_cleanup # Removes all temp directories
Available state options:
| Option | Effect |
|---|---|
--ahead=N |
Create N local commits not on remote |
--behind=N |
Create N remote commits not in local |
--diverged |
Shortcut for --ahead=1 --behind=1 |
--dirty |
Add uncommitted changes to working tree |
--shallow=N |
Create shallow clone with depth N |
--detached |
Checkout detached HEAD state |
--no-remote |
Create repo without remote tracking |
--branch=NAME |
Use NAME instead of 'main' |
Manipulation helpers:
git_harness_add_commit "$repo" "feat: new feature" # Add local commit
git_harness_add_commit_and_push "$repo" "fix: bug" # Add and push
git_harness_make_dirty "$repo" # Add uncommitted changes
git_harness_make_staged "$repo" # Add staged changes
git_harness_add_untracked "$repo" "newfile.txt" # Add untracked file
git_harness_simulate_rebase "$repo" # Create rebase state
git_harness_simulate_merge "$repo" # Create merge conflict
Query helpers:
status=$(git_harness_get_status "$repo") # Returns: current|ahead|behind|diverged
git_harness_is_dirty "$repo" && echo "Has uncommitted changes"
git_harness_is_shallow "$repo" && echo "Is shallow clone"
git_harness_is_detached "$repo" && echo "HEAD is detached"
Why this design? The harness uses git plumbing commands exclusively (per AGENTS.md guidelines), ensuring reliable detection regardless of locale or git version. Each test runs against known states, making failures reproducible and debuggable.
Running Tests
# Run all tests
./scripts/run_all_tests.sh
# Run specific test file
./scripts/test_parsing.sh
# Run with verbose output
VERBOSE=1 ./scripts/test_unit_review.sh
# Run only unit tests
for f in scripts/test_unit_*.sh; do "$f"; done
# Run E2E tests
for f in scripts/test_e2e_*.sh; do "$f"; done
# Check test coverage summary
./scripts/test_coverage.sh
Test Tiers and Requirements
Unit tests use extracted ru functions and avoid external network dependencies.
Integration tests use local git repos under /tmp (no network).
E2E tests run full CLI flows in isolated XDG roots and capture detailed logs.
Required tools:
bash4.4+,gitjqfor JSON-oriented tests (skips when missing)ghfor tests that exercise GitHub auth behavior (skips when missing or unauthenticated)ntm/tmuxonly for agent-sweep tests (mocked by default in E2E)
The structured-output conformance tests require Python 3 with jsonschema==4.19.2
and rfc3339-validator==0.1.4, plus the actual toon_rust encoder (toon, or tru
before v0.2). ru calls that CLI itself for --format toon; a Bash helper at
TOON_SH_PATH (default: ~/.local/lib/toon.sh) that defines toon_encode and
toon_available takes precedence. Missing prerequisites
fail this conformance check. They are test dependencies; ordinary ru commands do
not require Python or jsonschema. CI installs them explicitly, verifies the pinned
TOON release archive, and uses a test adapter that calls the real encoder.
Install the Python validators in an isolated environment before running the suite:
python3 -m venv /tmp/ru-test-venv
/tmp/ru-test-venv/bin/python -m pip install 'jsonschema==4.19.2' 'rfc3339-validator==0.1.4'
PATH="/tmp/ru-test-venv/bin:$PATH" bash scripts/run_all_tests.sh
Once these tools are installed, schema and TOON checks run offline against actual CLI output and local Git repositories. Controlled provider and GitHub endpoints exercise failure behavior; they do not qualify live services.
Logging and Artifacts
The test frameworks support structured logs and artifact capture:
TF_LOG_LEVEL=debug|info|warn|error|nonecontrols verbosity.TF_LOG_FILE=/path/to/test.logwrites human-readable logs.TF_JSON_LOG_FILE=/path/to/test.jsonlwrites machine-readable JSON lines.- E2E runs create
$E2E_TEMP_DIR/test_logs/with per-test stdout/stderr captures. - Failed-test artifacts can be preserved under
TF_FAILED_ARTIFACTS_DIR(default:/tmp/ru-test-failures).
Gated Tests (gh/ntm)
Some tests require external tooling and will skip gracefully:
- GitHub auth: use
require_gh_auth(fromscripts/test_framework.sh) in tests that need authenticatedgh.- Force-skip with
TF_SKIP_GH_AUTH=1|true|yes.
- Force-skip with
- ntm/tmux: E2E tests use mocks via
e2e_create_mock_ntm; you can control behavior withNTM_MOCK_SCENARIO(seescripts/test_bin/ntm).
Test Categories
Unit Tests — Test individual functions in isolation:
- URL parsing (
parse_repo_url,normalize_url) - Repo spec parsing (
parse_repo_specwith@branch as name) - Configuration resolution
- Gum wrapper fallback behavior
E2E Tests — Test complete workflows with real file operations:
- Full init → add → sync → status cycle
- Prune detection and archive/delete modes
- Self-update version checking
- Error handling and edge cases
Test Framework: Assertion Library
The test framework (test_framework.sh) provides a comprehensive assertion library designed for Bash testing. It tracks pass/fail counts, supports structured logging, and handles cleanup automatically.
Core assertions:
# Value comparisons
assert_equals "expected" "$actual" "Values should match"
assert_not_equals "bad" "$actual" "Should differ"
assert_contains "$haystack" "needle" "Should contain substring"
assert_not_contains "$output" "error" "Should not have errors"
# Boolean assertions (execute expressions)
assert_true "[[ -f '$file' ]]" "File should exist"
assert_false "[[ -d '$dir' ]]" "Directory should not exist"
# Exit code testing
assert_exit_code 0 some_command arg1 arg2 "Command should succeed"
assert_exit_code 1 failing_command "Command should fail"
# File system assertions
assert_file_exists "/path/to/file" "Config file created"
assert_dir_exists "/path/to/dir" "Directory created"
assert_file_contains "/path/to/file" "pattern" "File has expected content"
Test lifecycle:
# Run a test with automatic timing and result tracking
run_test test_my_feature
# Skip tests conditionally
skip_test "Requires network access"
# Print final results with exit code
print_results
exit "$(get_exit_code)"
Structured logging:
The framework supports both human-readable and machine-readable output:
# Control log level
TF_LOG_LEVEL=debug ./scripts/test_unit_config.sh
# Write human logs to file
TF_LOG_FILE=/tmp/test.log ./scripts/test_unit_config.sh
# Write NDJSON for CI integration
TF_JSON_LOG_FILE=/tmp/test.jsonl ./scripts/test_unit_config.sh
Function extraction for unit testing:
Unit tests can source individual functions from ru without executing the whole script:
source_function "parse_repo_url"
source_function "normalize_url"
# Now test the isolated functions
local host owner repo
parse_repo_url "https://github.com/owner/repo" host owner repo
assert_equals "github.com" "$host" "Host extracted"
Writing Tests
#!/usr/bin/env bash
source "$(dirname "${BASH_SOURCE[0]}")/test_framework.sh"
test_parse_url_https_basic() {
log_test_start "parse_repo_url handles HTTPS URLs"
local host owner repo
parse_repo_url "https://github.com/owner/repo" host owner repo
assert_equals "github.com" "$host" "Host extracted"
assert_equals "owner" "$owner" "Owner extracted"
assert_equals "repo" "$repo" "Repo extracted"
log_test_pass "parse_repo_url handles HTTPS URLs"
}
test_sync_with_dirty_repo() {
log_test_start "sync skips dirty repos"
# Create a dirty repo using the git harness
git_harness_setup
local repo=$(git_harness_create_repo "dirtytest" --dirty)
# Test sync behavior
local output
output=$("$RU_SCRIPT" sync --dir="$(dirname "$repo")" 2>&1)
assert_contains "$output" "dirty" "Reports dirty state"
assert_exit_code 0 git -C "$repo" status --porcelain "Still has changes"
git_harness_cleanup
log_test_pass "sync skips dirty repos"
}
# Register and run tests
setup_cleanup_trap
run_test test_parse_url_https_basic
run_test test_sync_with_dirty_repo
print_results
exit "$(get_exit_code)"
Test Best Practices
The test suite follows these principles:
- No network dependencies — Use the git harness for repository states
- Isolated environments — Each test gets fresh XDG directories
- Deterministic results — Same input always produces same output
- Fast execution — Unit tests complete in milliseconds
- Clear failures — Assertion messages explain what went wrong
- Bash 4.4+ — Matches ru's own minimum; tests still use
${arr[@]+"${arr[@]}"}for empty arrays
🧭 Troubleshooting
Common Issues
"gh: command not found"
Cause: GitHub CLI not installed.
Fix: Install gh and authenticate:
# macOS
brew install gh
# Ubuntu/Debian
sudo apt install gh
# Then authenticate
gh auth login
"gh: auth required"
Cause: gh CLI installed but not authenticated.
Fixes:
- Interactive:
gh auth login - Non-interactive: Set
GH_TOKENenvironment variable
export GH_TOKEN=ghp_xxxxxxxxxxxx
ru sync --non-interactive
"Cannot fast-forward"
Cause: Local and remote have diverged.
Fixes:
- Rebase:
git pull --rebase - Merge:
git pull --no-ff - Use
--rebaseflag:ru sync --rebase - Push first if your changes are intentional
"dirty working tree"
Cause: Uncommitted local changes.
Fixes:
- Stash and pull:
git pull --autostash(a baregit stash && git pull && git stash poppops an older stash when only untracked files are dirty) - Commit:
git add . && git commit -m "WIP" - Use
--autostash:ru sync --autostash - Discard (careful!):
git checkout . && git clean -fd
Config directory doesn't exist
Cause: First run without ru init.
Fix:
ru init
# Creates ~/.config/ru/ with default files
Wrong repository cloned to path
Cause: Path collision from different owners with same repo name.
Fixes:
- Use
owner-repolayout:ru config --set LAYOUT=owner-repo - Use custom name:
owner/repo as different-name - Remove conflicting directory and re-sync
Debug Mode
Check per-repo logs for detailed output:
# View latest run log
cat ~/.local/state/ru/logs/latest/run.log
# View specific repo log
cat ~/.local/state/ru/logs/latest/repos/mcp_agent_mail.log
System Check
Run diagnostics:
ru doctor
Checks performed:
| Check | What It Verifies |
|---|---|
| Git | Installation and version |
| GitHub CLI (gh) | Installation, version, and authentication status |
| gh auth | Shows logged-in GitHub username |
| Config directory | Existence of ~/.config/ru/ |
| Repo count | Number of repositories configured |
| Projects directory | Existence and write permissions |
| gum (optional) | Availability for prettier terminal UI |
Example output:
╭─────────────────────────────────────────────────────────────╮
│ 🔍 ru doctor │
╰─────────────────────────────────────────────────────────────╯
✓ git: 2.43.0
✓ gh: 2.40.1 (authenticated as yourname)
✓ Config: ~/.config/ru/ (47 repos configured)
✓ Projects: /data/projects (writable)
✓ gum: 0.13.0 (optional)
All checks passed!
Exit code: Returns 3 if critical issues found, 0 otherwise
🌐 Environment Variables
Runtime Variables
| Variable | Description | Default |
|---|---|---|
RU_PROJECTS_DIR |
Base directory for repos | /data/projects |
RU_LAYOUT |
Path layout (flat/owner-repo/full) | flat |
RU_PARALLEL |
Number of parallel workers | 1 |
RU_TIMEOUT |
Network timeout in seconds | 30 |
RU_AUTOSTASH |
Auto-stash before pull | false |
RU_UPDATE_STRATEGY |
Pull strategy (ff-only/rebase/merge) | ff-only |
RU_CONFIG_DIR |
Configuration directory | ~/.config/ru |
RU_LOG_DIR |
Log directory | ~/.local/state/ru/logs |
GH_TOKEN |
GitHub token for authentication | (from gh CLI) |
CI |
Detected CI environment | unset |
XDG Variables
| Variable | Description | Default |
|---|---|---|
XDG_CONFIG_HOME |
Base config directory | ~/.config |
XDG_STATE_HOME |
Base state directory | ~/.local/state |
XDG_CACHE_HOME |
Base cache directory | ~/.cache |
Installer Variables
| Variable | Description | Default |
|---|---|---|
DEST |
Install directory | ~/.local/bin |
RU_SYSTEM |
Install to /usr/local/bin |
unset |
RU_VERSION |
Specific version to install | latest |
RU_UNSAFE_MAIN |
Install from main branch | unset |
RU_INSTALLER_NO_SELF_REFRESH |
Disable installer self-refresh when piped | unset |
📦 Dependencies
Required
| Dependency | Version | Purpose |
|---|---|---|
| Bash | 4.4+ | Script runtime (namerefs need 4.3; earlier Bash treats an empty "${array[@]}" as unbound under set -u) |
| git | 2.0+ | Repository operations |
| curl | any | Installation and updates |
Optional
| Dependency | Purpose |
|---|---|
| gh | Authenticated GitHub clones and GitHub API features such as review and import from stars. Sync can clone public repositories with Git alone. Native Git also supports private repositories when Git credentials or SSH keys are configured. |
| gum | Beautiful terminal UI |
| jq | JSON processing (for scripts) |
System Requirements
| Platform | Requirements |
|---|---|
| macOS | macOS 10.15+ (Catalina or later) |
| Linux | glibc 2.17+ (Ubuntu 18.04+, Debian 10+) |
🛡️ Security & Privacy
Security Features
- Checksum verification: Installer verifies SHA256 before installation
- Release downloads: Default installation from GitHub Releases, not main
- No credential storage: Uses gh CLI's secure credential storage
- Prompted installation: Never auto-installs without user confirmation
Privacy & External Services
- No telemetry:
ruitself collects no analytics or telemetry, and keeps all config, state, and logs local on your machine. - Core Git/GitHub commands (
sync,status,list,prune,import,fork-*,commit-sweep): Execute locally and communicate only with your configured Git remotes and GitHub (viagit/gh). - AI-assisted workflows (
review,agent-sweep,ai-sync,dep-update): Invoke external AI agent CLIs you select (claude,codex,gemini, orantigravity, optionally viantm). When you run those commands (outside--dry-run), repository prompts, diffs, issue/PR context, and dependency plans are sent to the configured AI provider under that CLI's credentials and privacy terms. - Dependency discovery & changelogs (
dep-update): Package managers (npm,cargo-outdated,go,composer) and changelog lookups query their configured package registries and GitHub Releases.
Audit
The entire codebase is a single bash script:
less ~/.local/bin/ru
🔧 Uninstallation
# Remove script
rm ~/.local/bin/ru
# Remove configuration
rm -rf ~/.config/ru
# Remove logs and state
rm -rf ~/.local/state/ru
# Remove cache
rm -rf ~/.cache/ru
🤝 Contributing
About Contributions: Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other "stakeholders," which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via
ghand independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.
📄 License
MIT License. See LICENSE for details.
Built with Bash, git plumbing, and a desire to never manually cd into 47 directories again.
Explore related projects
Loading…