Hiiro
A lightweight, extensible CLI framework for Ruby. Build your own multi-command tools similar to git or docker.
Features
- Subcommand dispatch - Route commands to executables or Ruby blocks
-
Abbreviation matching - Type
h ex helinstead ofh example hello - Plugin system - Extend functionality with reusable modules
- Per-command storage - Each command gets its own pin/config namespace
-
TUI helpers - Build keyboard-driven list screens with
Hiiro::Tui::ListScreen
See docs/ for detailed documentation on all subcommands.
Shared command context
Directory and workflow commands use one resolved Hiiro::TaskLocation per operation. It carries the optional task, app/project identity, root and effective directory, selection provenance, and calling Herdr IDs. Explicit task selection wins; inference uses the calling workspace, then realpath directory containment. t also permits the saved task pin as its final fallback. Root workflows and table scope do not consult that pin.
Exact names win over unique prefixes. Ambiguous selections open an object-mapped picker on a terminal and fail otherwise. Stale pins, conflicting terminal IDs, overlapping task directories, and missing explicit targets are errors, not fallback choices. Project and home operations require no task.
Illustrative resolved values:
{
task: "build", taskSource: "explicit", app: "api",
root: "/work/build", directory: "/work/build/apps/api",
directorySource: "app",
terminal: { workspaceId: "ws-build", paneId: "pane-1" }
}t path build api and t cd build api use the same directory. App path prints relative to the captured invocation directory; app abspath prints absolute. cd targets the calling pane, never whichever pane has focus. Native shell/editor/search payload arguments remain unchanged.
t run build --app api all test, t queue build ls, and h app run --app api all test pass an explicitly selected context into the nested workflow. Task mounts are queue, service, and run; app mounts are service, run, and file. Configured service base_dir and tracked files remain root-relative; tools run in the effective directory. Project path/abspath/sh/cd/open and home path/abspath/sh/cd/open use taskless directory contexts. Home search retains its rg -S and rgall --no-ignore-vcs profiles. See task selection, apps, projects, queue frontmatter, services, tools, and tracked files.
Owned launches
h queue, h service, and h bg launch through one contract, Hiiro::OwnedRun. A Herdr tab is an allocation, not proof that a command started; a supervisor in that tab records the started pid (with its start time), optional readiness, and the actual exit status or signal:
{ id: "run-20261013120000-1a2b3c4d", owner: { kind: "queue", name: "fix-login" },
state: "failed", process: { pid: 4242, started: "Tue Oct 13 12:00:01 2026" },
outcome: { exit_code: 7, signal: null } }Queue entries have one claimant and land in done/ only on exit 0. The same service definition in two task directories runs as two instances that stop independently; stop signals only the recorded process and waits for its exit. Concurrent h bg launches never share a pane. h capture streams to disk, passes stdin and binary bytes through, and exits with the child's status. See owned runs.
h run, h js all, and h ch make run their commands through one validation runner: filenames reach tools as exact arguments (argv recipes, or "$@" in authored shell recipes), every command runs even after an earlier failure, the exit status is the first failure's, and failed logs are kept with their run id, cwd, times, and task context. h run queue turns a run's retained failures into a queue prompt without launching anything. See h run.
Scheduled work
Reminders, the queue, the PR monitor, loop recipes, and plain commands run on a recurrence through h schedule, defined in ~/.config/hiiro/schedules.yml and registered with launchd only by h schedule enable NAME (plan shows the exact plist first). Each run claims its occurrence once, runs under the owned-run supervisor with a timeout, and records one outcome:
{ run_id: "run-…", definition: "nightly", occurrence: "2026-10-13 02:30 local", outcome: "failed", exit_code: 3,
log_path: "~/.local/share/hiiro/jobs/nightly/run-….log", artifacts: [{ path: "/work/out/report.txt", bytes: 120 }] }
// outcomes: completed | failed | interrupted | startup-failed | stale-owner | skipped-overlaph schedule status, h schedule ui, h loop status|render|ui, and failure notifications read these records; no agent writes status files or rebuilds dashboards. Polling (reminders, PR monitor) starts no agent; queue and prompt-loop schedules start one only when configured with agent:. See h schedule, h remind, and h loop.
Installation
Via RubyGems
Requires Ruby 3.2 or newer.
gem install hiiro
h setup # read-only drift plan: what would change, and why
h setup --apply # install missing assets, update unmodified managed onesThe gem's shared assets are its commands (bin/h-*, installed to ~/bin as h-NAME, or hiiro-NAME for hiiro setup), the files those commands load from bin/lib/ (installed to ~/bin/lib/), and its plugins (installed to ~/.config/hiiro/plugins/). Ensure ~/bin is in your $PATH.
Managed installation
Every file h setup --apply writes is recorded in ~/.config/hiiro/install-manifest.json with its source, package version and root, SHA-256, and mode:
{ "/Users/me/bin/h-task": { asset: "command", source: "bin/h-task", package: "hiiro", version: "0.1.393",
root: "/…/gems/hiiro-0.1.393", sha256: "9f2c…", mode: "0755", owner: "installed", link: "../exe/t" } }h setup compares each packaged asset with its destination and the manifest. Planning writes nothing and creates no directories.
| Plan | Meaning | --apply |
|---|---|---|
missing |
No file at the destination | installs it |
unchanged |
Hiiro wrote it and it matches the package | nothing |
updatable |
Hiiro wrote it, nobody changed it, the package differs | replaces it |
user-modified |
Hiiro wrote it and it was edited (bytes, mode, or replaced by a link) since | keeps it |
collision |
A file hiiro never wrote, even with identical bytes | keeps it; --adopt NAME records it as managed without writing |
obsolete |
Hiiro wrote it and the package no longer ships it |
--retire removes it while it still holds the bytes hiiro wrote |
NAME (a destination basename such as h-pr, a destination path, or a package path such as bin/h-pr) narrows any action. Apply rechecks each destination just before writing, so an edit made after planning survives (reported as changed). Writes go to a temporary file renamed over the destination, so a linked destination is replaced, never written through. Ownership is recorded only for writes that landed: a failed write, or a manifest that cannot be saved, reports failed, exits 1, and leaves the file unowned. To take the package's version of a user-modified file, delete it and apply again.
h update installs the gem into the current Ruby (-a: every compatible rbenv Ruby, each independently), then runs h setup --apply once, from the Ruby with the newest installed hiiro, and names that source (Shared assets: hiiro 0.1.393 from ruby 3.3.10). It exits 1 if any Ruby failed. h delayed_update VERSION runs h update -a --wait VERSION --notify in the background: it waits until both the RubyGems API and the gem index list VERSION. h bin list, h bin docs, and h edit NAME show each command's origin: managed hiiro VERSION, modified (managed hiiro VERSION), package hiiro VERSION, or user.
From a checkout, script/install (h setup for the checkout), script/compare (plan plus a diff of each differing file), and script/sync (plan, nvim -d per differing file, then an optional apply) use the same plan.
Dependencies
# For h alert (macOS)
brew install terminal-notifier
# Terminal workspace, tab, and pane management
# Install Herdr 0.8.2 or newer.
# For the remaining simple fuzzy-finder selectors (the shared picker needs neither)
brew install sk # (or fzf)
# For h video, h audio, h screencap, h crop (h crop also needs python3), h asciinema, h mermaid
brew install ffmpeg asciinema python
npm i -g @mermaid-js/mermaid-cli # mmdc, or: h mermaid install
# For GitHub PR management
brew install ghh mcp needs no extra install: the gem depends on mcp (~> 1.5), faraday, and event_stream_parser.
Quick Start
# List available subcommands
h
# Simple test
h ping
# => pongFind processes by port
h ps byport 4399 prints each matching process PID and working directory,
separated by a tab. Pass multiple ports with h ps byport 4399 3000.
If no processes match, it prints No processes found on port(s): 4399.
This command requires ps and lsof.
Save clipboard content
h save saves whatever is on the macOS clipboard to ~/saved/ and prints the
saved path. Images (via pngpaste) are saved as PNG; otherwise the text from
pbpaste is saved as .txt. Arguments are saved as text instead of the
clipboard: h save hello world saves hello world.
Files are named <timestamp>-<slug>.txt or <timestamp>-image.png, where the
slug is the first few words of the text. Collisions get a -2, -3 suffix (up to -1000).
Saved files can be listed, printed, copied back to the clipboard, opened,
edited, or removed with h save ls|show|copy|open|edit|rm. See
docs/h-save.md.
h save --bundle --task TASK attaches the file it just wrote to the current
h context bundle and to the task (one association each, however often it is
repeated). h img save, h context save|tmp|img|tmpimage, and h note save
capture through the same code and keep their own destinations: the ~/saved
inbox, ~/notes/ctx/YYYY-MM-DD/ plus the bundle manifest, and $NOTES_DIR
named notes. Named destinations refuse to replace an existing file without
--force. An empty clipboard, a missing pngpaste, a failing clipboard tool,
and an unwritable destination are reported separately and write nothing; a
failed attachment after a successful save exits 2 and keeps the file.
h context open edits the manifest through a copy: a line naming a missing
path leaves the bundle unchanged and keeps the edited text under
~/.local/share/hiiro/edits/.
Bookmarks (h link select|copy|open), Obsidian notes (h obsidian select|url|open|copy), and Portfolio documents (h docs open|url|copy, --all
for every match) share one picker and open/copy actions while keeping their own
stores: the link database and URL templates, vault-relative obsidian:// URIs,
and Portfolio's API IDs. The picker returns the chosen record, so equal
titles cannot select the wrong item.
Pick, prune, and restore choices
Choosing among commands, task files and documents, tasks, projects, branches,
PRs, and saved information opens one in-process picker. Search with /,
choose with Enter, and mark several rows with Tab where a command accepts
several. Ctrl-E opens the listed rows and this picker's exclusion rules in
$EDITOR. Deleting a row excludes that item, keyed by its stable identity
(file path under a base, task ID, branch qualified by repository, PR by
repository and number, saved record ID). A rule can also hide a group: for
example {mode: extglob, field: path, pattern: "**/*.@(bak|tmp)"}. Modes are
literal, substring, regex, glob, and extglob, and each rule has a
scope: this picker, this task, this project, or global. Global must be chosen
explicitly. A preview lists every item that becomes excluded or restored, and
nothing is saved until you confirm. Invalid edits save nothing and keep your
text. Ctrl-X shows the excluded rows with their rules, and u restores one.
Exclusions only hide choices; files, tasks, branches, PRs, and records are
never changed. See the picker.
Extract files, directories, and links
h extract files, h extract dirs, and h extract links read text from stdin
or input files and print one unique match per line, in first-encounter order.
# Read text from stdin
printf '%s\n' 'README.md:12:3' 'README.md' | h extract files
printf '%s\n' 'docs/' './docs/' | h extract dirs
printf '%s\n' '(https://example.org/a_(b)).' | h extract links
# Read text from input files
h extract files build.log
h extract dirs build.log
h extract links notes.txt build.logFiles and directories must exist and match the requested type. Relative paths
are checked against the current directory by default. Repeat --base-dir DIR
or -b DIR to replace that default with explicit bases. A match under any one
base is enough:
h extract files --base-dir /path/to/project -b /path/to/other-project build.logBase directories affect path checks, not the locations of input files. Output
preserves the original path spelling rather than expanding or normalizing it.
Quotes and surrounding wrappers are removed, as are :line and :line:column
suffixes. Quoted paths can contain spaces, such as "src/my file.rb:12:3".
Links must use HTTP or HTTPS. Trailing punctuation is removed, while balanced
parentheses in URLs are kept.
--no-check skips filesystem checks and uses text heuristics, not actual
existence or type. Files need a slash or a dotted filename and cannot end in a
slash. Directories need a slash and cannot have a dotted basename. These rules
can misclassify paths or omit real files and directories:
printf '%s\n' '"src/my file.rb:12:3"' | h extract files --no-check
printf '%s\n' 'missing/output/' | h extract dirs --no-checkStrip terminal escapes and controls
h strip ctrl removes terminal escape sequences and control characters from
files, piped stdin, or literal text. Tabs, newlines, and UTF-8 text are preserved.
h strip ctrl terminal.log > clean.log
printf '\033[31mhello\033[0m\n' | h strip ctrl
h strip ctrl hello world
h strip ctrl --helpThe command writes to stdout without adding a newline and reads the whole input into memory. Redirect to a different file, not the input file. The command does not reconstruct a terminal screen. See the strip reference for input selection and supported escape sequences.
Task CLI
t and tt are gem executables in exe/, installed alongside h. They are thin
Hiiro.run launchers over Hiiro::TaskCli in lib/hiiro/task_cli.rb, which uses
the add_cmd DSL and existing task records. bin/t and bin/tt are symlinks to
the exe/ files for running from a checkout with ruby -Ilib bin/t. t new NAME
creates a task and its notes directory; t tree new NAME adds a Git worktree.
Use t COMMAND [TASK] [ARGS...]. Bare t, t ls, or t list lists every task,
including done and archived tasks, with the count of open todos after each name.
Commands that act on a task take it from the first positional argument when
that word names a task (exact or unique case-sensitive prefix); otherwise the
current task is used and the word stays in the payload, exactly like the old
h task commands. -t TASK forces a task, -f picks one with a fuzzy finder,
. is the current task, and - selects orphan todos. On a terminal, an ambiguous
prefix or a missing current task opens the fuzzy finder; non-interactive runs fail.
The current task is the calling Herdr workspace, then the current directory
inside a task home, code directory, worktree, or registered directory, then the
task saved with t use TASK. t switch TASK [APP] focuses or creates the task
workspace and also saves it; APP (exact name or unique prefix from the apps
registry) opens the workspace in that app's directory under the task worktree.
t cd TASK [APP] sends the same cd to the calling Herdr pane. t current
only prints.
t new investigation
t next investigation "Inspect the failing request"
t todo add investigation Compare the retry settings
tt add Inspect --help output # current task
t doc new investigation findings
t show investigation
t todo rm 42 # an ID printed by show or todo list
t use investigation
t switch investigation
t switch investigation frontend # open in an app directory (unique prefix)
t switch --show
t next . "Write the handoff"
t start investigation frontend # tree new + app start directoryA task has one next_action and can have multiple independent todos. t show
and t todo print todos with their IDs, statuses, and text in ID order.
t todo show ID prints one todo's text and t todo rm ID deletes it.
tt ... is t todo .... Use t todo - and tt add - TEXT for orphan todos.
Every argument after the task in todo add is literal text, including flags and
--, except a leading -h or --help. Empty text fails. Only t new NAME
creates tasks.
t, tt, and h todo share canonical SQLite todos with database-owned IDs.
None maintains todo.yml. Adding or removing a todo does not
change the task's next action, status, or saved selection. Task completion and
archival preserve todos. h task is a symlink to t, so both share one grammar.
t omp [TASK], t codex or cdx, and t claude or cld start fresh
native CLI sessions in new focused Herdr tabs. Claude always runs claude.
t path [TASK] [APP], t cd [TASK] [APP], and t switch [TASK] [APP]
resolve APP by exact name or unique prefix and use its configured relative
directory beneath the task's code directory. t start NAME [APP] is the
direct form of t tree new NAME [APP].
Tasks can share an existing directory, including a worktree. t does not change
Git state or promise task-isolated persisted AI sessions in shared directories.
See the task command reference for all commands and the workflow introduction for practical examples.
Subcommands
Base Commands
| Command | Description |
|---|---|
h version |
Display the Hiiro version |
h ping |
Simple test command (returns "pong") |
h setup |
Show the drift plan for shared commands and plugins; --apply installs (managed installation) |
h edit [NAME...] |
Open the h script, or the source h NAME dispatches to (refuses ambiguous names) |
h alert |
macOS desktop notifications via terminal-notifier |
h herdr |
Herdr task popups plus Vim-style pane focus, movement, resize, swap, and zoom controls (h herdr install) |
h task |
Same program as t: task records, todos, worktrees (t NAME tree new), and Herdr workspaces; t ui is a tree TUI over tasks, subtasks, and todos |
hiiro is the long name of h: exe/hiiro registers the same root commands, and hiiro setup installs commands as hiiro-NAME.
External Subcommands
| Command | Description |
|---|---|
h alias |
Append safely quoted zsh aliases |
h app |
Manage app directories within tasks/projects |
h bin |
Create, list, and edit Hiiro executables |
h branch |
Git branch management with fuzzy selection and copy |
h claude |
Claude CLI wrapper with Herdr split support |
h commit |
Choose a commit SHA in the shared commits picker |
h config |
Open config files (vim, git, Herdr, zsh, starship, claude, ssh, profile) |
h date / h time |
Unix timestamps, strftime shortcuts, durations, and differences over one set of registrations |
h encode / h decode |
Binary-safe Base64/Base64url/hex/percent/form/HTML/JSON-string/ROT13 filters over one codec table |
h dotenv |
Compare .env files; read-only (copy_to reports differences, it copies nothing) |
h sign |
Inspect and verify an app bundle's code signature with codesign (it never signs) |
h env / h export |
Append literal export NAME="VALUE" lines (--file, else ~/.zshenv.d/vars.zsh, else ~/.zshenv) |
h home / h dotfiles / h vim |
Directory profiles: path, search, edit, and each profile's own actions |
h video / h audio |
FFmpeg presets (one table), clips, durations, transcription adapter |
h screencap / h crop / h asciinema |
Window recording, amber-border crop, dated terminal casts; personal paths from profile.yml
|
h ruby iface / h iface rb |
Ruby declaration lines by pattern group |
h git commit |
Plan logical commits for all pending changes with claude; -n previews without touching the index, and invalid plans or failures stop before or at the failing commit |
h extract |
Extract file paths, directories, and HTTP(S) links from text |
h hub |
Central ~/hub of symlinks to notes, projects, config, harness sessions and skills; init, sync, doctor, list, path, open, find, recent, latest, add (originals never changed) |
h link |
Manage saved links with URL, description, and shorthand |
h loop |
Recurring loop recipes run as schedules; status and render read recorded cycle outcomes |
h mcp |
Local MCP registrations, saved tool schemas, direct tool calls, and HTTP-only client sync (require 'hiiro/mcp') |
h pane |
Herdr pane management |
h plugin |
Manage hiiro plugins (list, edit, search) |
h pr |
GitHub PR management via gh CLI; PRs are owner/name#N with fresh/stale/unknown snapshots; single and YAML-selected bulk actions share one implementation |
h pr-monitor |
Notify tracked PR check, review, and dependency changes once (checkpointed); opt-in fix queueing |
h cpr |
Run an h pr subcommand on the current branch's PR |
h project |
Project navigation with Herdr workspace management; h project ui is the projects screen over every worktree, directory, and alias |
h registry |
Named resources by type with short aliases; the same rows as h table
|
h queue |
Prompt queue with Herdr-based task execution; tick is the bounded one-shot pass a schedule runs |
h remind |
Reminders delivered once per occurrence by h remind check; failed deliveries stay due |
h schedule |
Explicitly enabled launchd schedules for existing one-shot workers, with recorded outcomes and an outcome screen |
h service |
Manage background dev services with env variations and groups |
h file |
Track and open frequently-used files per app |
h run |
Run dev tools (lint/test/format) against changed files; keep failed logs and queue them on request |
h session |
Compatibility commands for Herdr workspaces |
h sha |
Choose, show, and copy commit SHAs in the shared commits picker |
h strip ctrl |
Strip terminal escapes and controls from files, stdin, or text |
h table |
TUI and scriptable CLI over registry tables (links, sounds, pins, ...) with task scope, tags, per-table actions, and fuzzy completion in prompts |
h todo |
Todo list management with tags and task association |
h tuios |
TUIOS inbox server, skills, and startup rules; h tuios ui is the windows screen over every session, with --hosts for remote sessions |
h window |
Compatibility commands for Herdr tabs |
h wtree |
Git worktree management |
h jumplist |
Optional tmux back/forward pane history; needs a running tmux server |
These are the maintained commands. Demonstrations live in examples/, which h does not dispatch and h setup does not install. h otask, h osubtask, h zosubtask, h .config, h dsstore, h uri, h tags, and h buffer were removed; docs/README.md names each replacement.
h claude agents|commands|skills -a prints the absolute file path for each matching .claude tool, including SKILL.md for skills.
Shell helpers
h env add exam ple
h alias add ll 'ls -al'
h alias add --global PAGER '| less'
h bin add scratch
h bin add josh list showh env add NAME VALUE appends a literal export NAME="VALUE" to
~/.zshenv.d/vars.zsh when that file exists, otherwise to ~/.zshenv.
h alias add NAME COMMAND... similarly prefers ~/.zshrc.d/aliases.zsh,
falling back to ~/.zshrc. Existing contents are preserved. A single quoted
command string preserves shell syntax; separate command arguments retain their
argument boundaries. Use --global or -g for a global zsh alias.
These commands use native Hiiro option parsing and help. Use -- before
flag-like data, for example h env add LABEL -- --literal or
h alias add inspect -- tool --help. Start a new shell or source the relevant
configuration file to apply additions.
h bin add NAME [COMMAND ...] creates an executable ~/bin/h-NAME using
Hiiro.run. Without commands its block is empty; each command adds an empty
add_cmd block with a Ruby symbol. Existing files and symlinks are never
overwritten. See the bin command reference.
Abbreviations
Any subcommand can be abbreviated as long as the prefix uniquely matches:
h ses ls # matches h session ls
h win # matches h windowIf multiple commands match, nothing runs: Hiiro lists the candidates and exits 1.
Command catalog
h, help, h edit NAME, and h bin list|edit|complete|docs read one table (Hiiro::Catalog), so they agree on what runs.
-
Candidates: inline registrations (
add_subcmd/add_cmd; extra names are aliases) andh-NAMEexecutables onPATH. An executable candidate is a regular file, or a symlink to one, with the executable bit; directories, non-executables, and broken links are ignored. Discovery never runs a candidate. - PATH: searched in order and read when the command runs. An empty entry means the current directory, a relative entry resolves against it, and a repeated directory counts once.
-
Precedence for a name: an external
h-NAME(first in PATH) beats an inlineNAME, which beats an inline aliasNAME. Every loser stays listed as shadowed under the winner; same-name copies later in PATH never make a prefix ambiguous. -
Origin:
h bin list,h bin docs, andh editname where the winner came from:managed hiiro VERSION(written byh setup, unchanged),modified (managed …),package hiiro VERSION(inside the running package), oruser. -
Prefixes: an exact name or alias wins; otherwise a unique prefix. A child name yields to its parent (
h pwith onlyprandpr-monitorrunspr). Unknown external grammar is not inspected.
h bin list pr # winners for names starting with pr, with shadowed copies
h bin complete se # every name and alias starting with se
h bin docs # Markdown command table; --json for the catalog data
h edit svc # opens the file that defines `service` (alias svc)Lazy startup
Importing hiiro, registering commands, help (h, h queue, h version --help, t --help), completion, and docs create no database, history, tags, or config/plugin directories. Persistence starts when an operation first uses it: that creates or upgrades the database, records the invocation, and (for h) tags the current branch with the current task. Every Hiiro.init adds a frame to HIIRO_INVOCATION_FRAMES, inherited by external commands, so h registry add ... records one invocation with resolutions h registry then h-registry add. An operation that never uses persistence (h ping) is not recorded.
Plugins
Plugins are Ruby modules a command names with plugins: [:Name]. The file name.rb loads from ~/.config/hiiro/plugins/, else from the gem's plugins/, only for that command; importing hiiro loads none:
| Plugin | Description |
|---|---|
| Pins | Typed SQLite key/value storage scoped by command |
| Project | Project directory navigation with Herdr workspace management |
| Tasks |
Hiiro::TaskManager worktree creation and current-task environment used by t, h service, h run, and h file
|
| Notify | Herdr desktop notifications |
Adding Subcommands
Method 1: External Executables
Create an executable named h-<subcommand> anywhere in your $PATH:
# ~/bin/h-greet
#!/bin/bash
echo "Hello, $1!"h greet World
# => Hello, World!For nested subcommands, use hiiro in your script:
#!/usr/bin/env ruby
# ~/bin/h-example
require 'hiiro'
Hiiro.run(*ARGV) do
add_subcmd(:hello) { puts "Hi!" }
add_subcmd(:bye) { puts "Goodbye!" }
endh example hello # => Hi!
h example bye # => Goodbye!Building TUIs
Use Hiiro::Tui::ListScreen for simple full-screen list interfaces. Subclass it, override header_lines, format_row, and handle_key, then run it from a normal Hiiro.run subcommand.
Method 2: Inline Subcommands
Modify exe/h directly to add subcommands to the base h command:
Hiiro.run(*ARGV, plugins: [Tasks], cwd: Dir.pwd) do
add_subcmd(:hello) do |*args|
puts "Hello, #{args.first || 'World'}!"
end
endGlobal values (like cwd) are accessible via get_value:
add_subcmd(:pwd) do |*args|
puts get_value(:cwd)
endCommands with declared options
Use add_cmd to expose a command's options in help. Choose a declaration bucket
for each undeclared name:
-
opts:creates a string-valued option with a default ofnil. -
flags:creates a boolean flag with a default offalse. Flags do not consume the next positional argument. -
mopts:creates a repeatable string-valued option with a default of[].
Hiiro.run do
add_option :task, short: :t, desc: 'Task name'
add_cmd :test, opts: %i[task], flags: %i[a b c d], mopts: %i[tag] do
puts 'a was set' if opts.a
puts opts.task if opts.task
puts opts.args
end
endHere, test -a payload -t investigation --tag ruby --tag cli sets opts.a
to true, leaves payload in opts.args, sets opts.task to
investigation, and sets opts.tag to ['ruby', 'cli'].
test -h and test --help display the selected options without running the
command block.
Names accept strings or symbols and are deduplicated across the buckets. Existing definitions keep their type, default, short alias, and description, regardless of the bucket used to select them. New definitions are registered on the parent option set so later commands reuse them.
Automatic short aliases use the first unused alphanumeric character in the full
name, scanning left to right. All existing short aliases and -h are reserved;
aliases are never reassigned. A name with no available character has only its long form.
For a command that delegates to run_child, use add_cmd(..., passthrough: true).
It forwards control without parsing the parent's arguments or intercepting the
child's --help. The child declares and parses its own options.
Generated help uses the original command block's source location and declared args:, not the
internal wrapper's signature.
run_child is the convenience form of make_child(...).run. make_child
returns an unrun child when the caller needs to configure it before dispatch.
Module-level build_hiiro methods are builders that return such a child; callers
run the result. They are not required for an inline child command group.
Child commands inherit the parent's resolvers, so a task can be bound once and
shared with nested groups without consuming its name again.
For a CLI that should dispatch only registered blocks, pass
external_commands: false to Hiiro.run and its run_child or make_child calls. This
prevents unrelated same-prefix executables on PATH from taking precedence.
Pass builtin_commands: false as well to skip the automatic pry and edit
commands, for CLIs whose first word is data rather than a command name.
Raise Hiiro::Error (or a subclass) for expected user-facing failures such as
bad arguments or missing records. Hiiro#run prints ERROR: message to stderr
and exits 1 without a backtrace; any other exception still prints its backtrace.
open_default(target) opens a path or URL with the OS handler (open or xdg-open).
Writing Plugins
Plugins are Ruby modules that extend Hiiro instances:
# ~/.config/hiiro/plugins/my_plugin.rb
module MyPlugin
def self.load(hiiro)
attach_methods(hiiro)
add_subcommands(hiiro)
end
def self.add_subcommands(hiiro)
hiiro.add_subcmd(:mycmd) do |*args|
# command logic
end
end
def self.attach_methods(hiiro)
hiiro.instance_eval do
def my_helper
# helper method available to other plugins
end
end
end
endLoad plugins in your command:
Hiiro.run(*ARGV, plugins: [:MyPlugin]) do # requires my_plugin.rb on demand
# ...
endConfiguration
The database, definitions, preferences, and some runtime files live in ~/.config/hiiro/:
~/.config/hiiro/
plugins/ # Plugin files (loaded when a command names them)
hiiro.db # Canonical mutable records (registry tables hold links, project aliases, pins, sounds)
pins/ # Legacy pin files; explicit h db migrate inputs into tables named after the command (h-sha -> sha)
sounds.yml # Legacy; explicit h db migrate input into registry table sound
projects.yml # Legacy project aliases; explicit h db migrate input into registry table project
services/ # Service instance state and per-instance launch scripts
bg-history.txt # Background command history
env_templates/ # Base .env templates for services
services.yml # Service and service group definitions
tools.yml # Runner tool definitions
sparse_groups.yml # Sparse checkout definitions
tables.yml # Per-table action definitions
config.yml # Preferences
profile.yml # Personal recipe policy: casts, screencap, transcribe (docs/README.md#personal-profile)
app_files.yml # Per-app tracked file lists
Runtime data lives separately:
~/.local/share/hiiro/
queue/ # Prompt queue (wip, pending, running, done, failed)
runs/ # Owned run records (RUN_ID.json) for queue, service, and background launches
bg/ # Background pane reservations
captures/ # h capture output files; validation/RUN_ID/ holds failed h run / h js all / h ch make logs
notify_log.yml # Herdr notification log
Persistence ownership
Each durable type has one current owner. The first operation that uses persistence creates or upgrades database schemas; it does not import legacy domain YAML.
| Durable type | Owner |
|---|---|
| Todos | SQLite todos, Hiiro::TodoItem, shared by t, tt, and h todo
|
| Tasks and task resources | SQLite tasks and task_resources, Hiiro::TaskRecord and Hiiro::TaskResource
|
| Worktree assignments | SQLite assignments, Hiiro::Assignment
|
| Saved links | SQLite registry table link, Hiiro::RegistryEntry through bin/h-link's LinkPresenter and h table link
|
| Branches | SQLite branches, Hiiro::Branch
|
| Pinned PRs and check snapshots | SQLite prs and check_runs, Hiiro::PinnedPr and Hiiro::CheckRun; remote snapshots (head, fetch time, completeness, freshness) are written only by PinnedPRManager#refresh, local tags/task/dependencies only by tracking commands; see h-pr
|
| PR monitor checkpoints | SQLite pr_monitor_checkpoints, Hiiro::PrMonitorCheckpoint; written only by Hiiro::PrMonitor after an effect succeeded; see h-pr-monitor
|
| Project aliases | SQLite registry table project, Hiiro::RegistryEntry through Hiiro::Projects
|
| App mappings | SQLite apps, Hiiro::AppRecord
|
| Command pins and sounds | SQLite registry tables named after the command (sha, t, ...) and sound, Hiiro::RegistryEntry through the Pins plugin and h table
|
| Named pane homes | SQLite pane_homes, Hiiro::PaneHome
|
| Reminders and scheduling checkpoints | SQLite reminders, Hiiro::Reminder
|
| Recurring work: occurrence claims, outcomes, and schedule checkpoints | SQLite job_claims, job_outcomes, and schedule_checkpoints, Hiiro::Job, Hiiro::JobOutcome, and Hiiro::Schedule; see h schedule
|
| Generic named entries | SQLite registry, Hiiro::RegistryEntry through Hiiro::Table
|
| MCP registrations, saved catalogs, and sync ownership | SQLite mcps through MCPRegistry, and registry rows of type mcp-sync; see h-mcp
|
| Tags | SQLite tags, Hiiro::Tag
|
| Captures (including retained validation failures), invocations, and resolutions | SQLite captures, invocations, and invocation_resolutions, Hiiro::Capture, Hiiro::Invocation, and Hiiro::InvocationResolution
|
| Import verification and row mappings | SQLite schema_migrations, migration_sources, and migration_rows, Hiiro::DB
|
| Service, tool, sparse, table action, and schedule definitions |
services.yml through Hiiro::ServiceManager, tools.yml through Hiiro::RunnerTool, sparse_groups.yml through Hiiro::SparseGroups, tables.yml through Hiiro::TableActions, and schedules.yml plus ~/ai/loops/*/config.yml through Hiiro::Schedule (read, never rewritten) |
| Preferences and tracked app files |
config.yml through Hiiro::Config, app_files.yml through Hiiro::AppFiles
|
| Runtime state, history, and notification logs | Service instance files through Hiiro::ServiceManager, background history and pane reservations through h bg, navigation history through h jumplist, and notification logs through h notify
|
| Launch and process outcomes | Run files under ~/.local/share/hiiro/runs/ through Hiiro::OwnedRun; see owned runs
|
| Queue prompts and companion files | Existing files through Hiiro::Queue; claims and done/failed moves through Hiiro::QueueClaim from the run's outcome |
| Task notes, saved files, indexes, and generated SQL | Ordinary files through their existing commands |
Domain commands update selected records rather than rewriting a loaded collection. Temporary editor documents are database projections, not a second store. Failed editors, invalid input, or conflicting edits do not apply a partial batch.
Registry entries retain their IDs, resource_type, name, value, short alias, description, metadata, nullable task_id, and tags. TableScope still distinguishes global and task entries, and table rename retains entry IDs. Table actions remain in tables.yml.
Task records retain tree/session/app/color fields, status, next_action, waiting_on, primary_directory, timestamps, and additional detail keys in metadata_json. Task resources reference the task ID; task notes remain ordinary files.
New pins preserve value types. The strings "42", "false", and JSON-looking text stay strings, distinct from numbers, booleans, and collections. Preexisting unmarked pins retain their historical decoder until an explicit typed import resolves ambiguity. Reminders retain interval, one-time scheduling, enabled state, sound, and last_triggered checkpoints.
Legacy todo.yml, links.yml, branches.yml, PR YAML, task YAML, apps.yml, projects.yml, pane_homes.yml, command-pin files, reminders.yml, and tags.yml are retained explicit import inputs, not live stores. Definitions, preferences, runtime files, and ordinary artifacts are excluded from domain migration. See h-db for the owned-store manifest, import plans, typed exports, and conflict-safe recovery.
h db plan exposes selected sources and conflicts before explicit import. Accepted-source replay preserves later database changes and deletions. Typed exports refuse existing destinations; recovery merges absent or identical records and aborts on conflicts. Recovery leaves later additions intact but can recreate exported records deleted after export. It is not a chronological rollback. Invocation/resolution audit history, definitions, and ordinary files remain outside canonical export.
Testing
Run the test suite:
bundle exec rake testEvery child process a test starts is waited for or killed (test/support/child_guard.rb): an Open3 or PTY.spawn child still running after HIIRO_TEST_CHILD_LIMIT seconds (default 300) is killed with its process tree and fails the test, a test that leaves a descendant running fails and the descendant is killed, and the end of a run (even by Ctrl-C) kills any that remain.
End-to-end acceptance
script/acceptance runs the redesigned workflows against real commands in disposable sandboxes:
script/acceptance -o /tmp/hiiro-acceptance # every scenario
script/acceptance -o /tmp/hiiro-acceptance 02 06 # selected onesEach scenario in script/acceptance.d/NN-*.sh gets its own HOME (with the default file database under it), data roots, empty GEM_HOME, GEM_PATH set to the runtime gems (HIIRO_ACCEPTANCE_GEMS), PATH of recording fixtures, a link to one Ruby (HIIRO_ACCEPTANCE_RUBY), the checkout, and /usr/bin:/bin, and TERM=dumb with no multiplexer identity; it runs under env -i, with every command killed with its process group after a time limit. The clipboard, open, osascript, say, terminal-notifier, and launchctl are always recorders. Every check prints its literal expected value before the command runs; OUT/NN-name.out holds expected and observed text, OUT/results.tsv one row per check (pass, FAIL, incomplete), and the script exits 1 if any check failed.
| Scenario | Proves |
|---|---|
00-procedure |
the sandbox itself: PATH resolution, environment, checkout load path, database location; snapshots the caller's real home (metadata only) |
02-migration |
h db plan/migrate of synthetic legacy stores, conflicts, repeat, reload, export/restore, concurrent writers, registry task scope, tags, and table actions |
03-context |
t/tt/h task with explicit, inferred, pane, ambiguous, and missing tasks; path and execution cwd agree; read-only help writes nothing |
04-execution, 04-artifacts-jobs
|
owned launches through capture, run, queue, service, and background; validation failure artifacts, clipboard bytes, attachments, and recurring-job outcomes under a fixed clock |
05-git-pr |
index-preserving commit planning and qualified PR snapshots, actions, and monitoring through a controlled gh
|
06-picker |
the picker and a refreshing screen driven in real terminal windows (needs a tuios session and HIIRO_ACCEPTANCE_TUIOS; otherwise incomplete) |
07-package |
the built gem installed into a disposable gem home: installed entrypoints, setup, provenance, MCP over stdio, utilities |
99-live-untouched |
the caller's ~/bin, ~/.config/hiiro, ~/.local/share/hiiro, LaunchAgents, and installed gems are unchanged |
License
MIT
COMPLEX SERVICES
❯ in this setup...can you configure a couple complex services that use variations, etc. i need examples of how to configure it. and then can you show me how to run it for different variations
⏺ Here's an example ~/.config/hiiro/services.yml:
# Individual services
api-rails:
base_dir: ~/work/api
host: localhost
port: 3000
init:
- bundle install
start:
- bin/rails s -p 3000
cleanup: []
env_file: .env.development
base_env: api-rails.env
env_vars:
DATABASE_URL:
variations:
local: postgres://localhost:5432/api_dev
docker: postgres://db:5432/api_dev
REDIS_URL:
variations:
local: redis://localhost:6379
docker: redis://redis:6379
graphql:
base_dir: ~/work/graphql
host: localhost
port: 4000
init:
- npm install
start:
- npm run dev
env_file: .env.local
base_env: graphql.env
env_vars:
API_URL:
variations:
local: http://localhost:3000
staging: https://api.staging.example.com
AUTH_PROVIDER:
variations:
local: http://localhost:8080/auth
staging: https://auth.staging.example.com
frontend:
base_dir: ~/work/frontend
host: localhost
port: 8080
start:
- npm run dev
env_file: .env.local
base_env: frontend.env
env_vars:
GRAPHQL_URL:
variations:
local: http://localhost:4000/graphql
staging: https://graphql.staging.example.com/graphql
# Service groups
full-stack:
services:
- name: api-rails
use:
DATABASE_URL: local
REDIS_URL: local
- name: graphql
use:
API_URL: local
AUTH_PROVIDER: local
- name: frontend
use:
GRAPHQL_URL: local
staging-fe:
services:
- name: graphql
use:
API_URL: staging
AUTH_PROVIDER: staging
- name: frontend
use:
GRAPHQL_URL: local
Usage:
# Start a single service (defaults to "local" variations)
h service start api-rails
# Start with specific variations
h service start api-rails --use DATABASE_URL=docker --use REDIS_URL=docker
# Start the full local stack (one Herdr tab per service)
h service start full-stack
# Start frontend pointing at staging backends
h service start staging-fe
# No args — fuzzy select from all services + groups
h service start
The key ideas:
- local is the default variation — if you don't pass --use, each env var gets its local value
- Groups let you pre-bake variation combos — full-stack vs staging-fe are just different use: presets for the same services
- Base env templates live in ~/.config/hiiro/env_templates/ (e.g., api-rails.env) — they get copied to base_dir/env_file first, then variations are injected on top
Development
Testing locally:
ruby -I lib bin/h-ps search ruby