Skip to content
Scrates1Public

About

A native Windows & PowerShell implementation inspired by tobi/try — fresh experiment directories for every idea

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

tri

A humble Windows & PowerShell implementation inspired by tobi/try — instant dated scratchpads & fuzzy switcher for every idea.

CI Live Demo PowerShell Platform Dependencies License: MIT

English · 简体中文 · Live Interactive Demo ↗ · Changelog


tri interactive fuzzy picker running in Windows PowerShell


Why I Built This

Huge thanks to Tobias Lütke (@tobi) for creating tobi/try and sharing it under the MIT license! I immediately fell in love with its philosophy — giving every quick prototype, 3 AM idea, or PR review a clean, date-prefixed home (YYYY-MM-DD-name) and jumping back into it effortlessly.

Because my day-to-day workflow lives on Windows and PowerShell, I really wanted to use try natively without setting up Ruby or switching into WSL just to manage local folders. So I built this Windows/PowerShell edition following the spirit and UX of the original project. Since PowerShell reserves try as a language keyword (try { } catch { }), the command is named tri.

Comparison with tobi/try & Our Own Little Touches

tri is not a line-by-line clone — while staying faithful to the spirit of tobi/try, we made a few deliberate adaptations and small quality-of-life touches for Windows and PowerShell workflows:

Dimension Upstream tobi/try tri (Windows / PowerShell Edition)
Target environment macOS / Linux native (Ruby / Spinel), minimal & portable Windows 10/11 (PowerShell 5.1 & 7+), zero Ruby / WSL / .NET SDK needed
Command name try tri (avoids PowerShell's reserved try keyword)
Shell integration Portable POSIX eval "$(try init)" hook Auto-discovered via PSModulePath with in-process Set-Location -LiteralPath and native PowerShell Tab completion — never touches $PROFILE or PATH
Startup model Fast Ruby / native CLI invocation Runtime-tagged precompiled C# DLLs (117–184 ms cold start, ~0 ms subsequent calls in the same terminal)
Recency tracking Uses directory mtime (zero extra metadata files) Dedicated .tri.json (locked atomic writes + single-scan stale-entry pruning) so project directory timestamps stay untouched
Fuzzy ranking Lightweight subsequence & recency scoring (our direct inspiration) Non-greedy DP optimal alignment so searching a suffix inside a long folder name isn't hijacked by earlier scattered letters (13–17 ms for 5,000 dirs)
Input & Unicode Standard POSIX terminal UX East Asian wide-char (CJK / Emoji) alignment, grapheme-aware inline cursor editing (←/→, Ctrl-←/→, Home/End, Delete, segment-aware Ctrl-W / Ctrl-Backspace), and Windows AltGr support
Windows & Git safety POSIX filesystem conventions Iterative nested-junction/reparse-point safe delete, cross-volume MoveDirectorySafe, [wt] worktree badges, plus automatic git worktree prune on delete & link repair on rename/graduate/migrate
Scope & extras Supports terminal multiplexer tab renaming, etc. Multiplexer tab renaming is not ported; adds native PowerShell object pipelines (tri list), unambiguous slug/fuzzy CLI resolution, and strict -NonInteractive scripting

Credit & scope note: All credit for the original concept, UX, and fuzzy-scoring idea goes to tobi/try. tri is an independent community Windows/PowerShell port, not an official upstream release.


30-Second Quick Start

Install

Clone the repository and run .\install.ps1 from PowerShell:

git clone https://github.com/Scrates1/tri.git
cd tri
.\install.ps1
tri help

Windows PowerShell 5.1 ExecutionPolicy note: On a fresh Windows machine, Windows PowerShell 5.1 defaults to Restricted. If running .\install.ps1 reports a script execution policy error, run the installer once with process-scoped bypass (no system policy change):

powershell -ExecutionPolicy Bypass -File .\install.ps1

What install.ps1 does (and does not do):

  • Copies Tri (1.3.1) to your user module folders (Documents\PowerShell\Modules\Tri\1.3.1 and Documents\WindowsPowerShell\Modules\Tri\1.3.1).
  • Automatically precompiles runtime-specific engine DLLs for both PowerShell 7 (pwsh) and Windows PowerShell 5.1 (powershell) when present on your machine.
  • Makes zero edits to $PROFILE, PATH, ExecutionPolicy, or Git config, and requires no administrator privileges. New PowerShell windows auto-discover tri (with native Tab completion included).

Upgrading: Run git pull inside your cloned tri folder, re-run .\install.ps1, and open a new PowerShell window to load the updated module and DLL.

Optional 1-letter alias: If three letters is still too many, you can optionally add Set-Alias t tri to your own $PROFILE (tri itself never modifies $PROFILE).

Try it without installing (ad-hoc module load)
Import-Module .\Tri\Tri.psd1

On first use, tri automatically compiles and caches its DLL in %LOCALAPPDATA%\Tri\cache (falling back to in-memory compilation if the cache folder is read-only).

Your First Session

tri                           # Opens interactive picker (shows empty-state onboarding prompt if ~/src/tries is empty)
tri new api gateway bench     # Creates C:\Users\you\src\tries\2026-12-03-api-gateway-bench & enters it
tri api                       # Fuzzy-jump back from anywhere (opens picker pre-filtered with "api")
tri mv api-bench api-v2       # Renames via unambiguous fuzzy/slug match — no need to type YYYY-MM-DD-
tri grad api-v2               # Graduates out of TRI_PATH into D:\projects\api-v2 (or parent dir) & enters it
tri new throwaway             # Spin up a quick scratchpad
tri rm throwaway              # Prompts [y/N] before deleting (pass -Force in scripts)

Interactive Lifecycle

Everything happens in one tight terminal loop — rename, graduate, or batch-delete projects without ever leaving the picker, while preserving your selection and scroll position across inline actions:

flowchart LR
    Start["tri or tri query"] --> Picker["Fuzzy Picker TUI"]
    Picker -->|"Enter on match"| Open["Enter directory and record visit"]
    Picker -->|"Enter on + Create"| Create["Create YYYY-MM-DD-name and enter"]
    Picker -->|"Ctrl-R"| Rename["Inline Rename (slug pre-fill + live preview)"]
    Picker -->|"Ctrl-G"| Graduate["Inline Graduate Move"]
    Picker -->|"Ctrl-D + Enter + y"| Delete["Multi-Mark Safe Delete"]
    Rename -->|"Preserve selection + status"| Picker
    Graduate -->|"Preserve selection + status"| Picker
    Delete -->|"Prune worktrees + reload"| Picker
    Picker -->|"Esc / Ctrl-C"| Cancel["Exit without changing CWD"]
Loading

Interactive Keybindings

Interactive selection runs in any standard Windows terminal (Windows Terminal, ConHost, VS Code integrated terminal). For PowerShell ISE, redirected streams, or automation scripts, use non-interactive commands.

Category Keybinding Action
Navigation ↑ / ↓, Ctrl-P / Ctrl-N, Ctrl-K / Ctrl-J Move selection up / down
PageUp / PageDown Jump one page up / down
Inline Editing (Query, Rename & Graduate) ← / → Move cursor left / right across graphemes
Ctrl-← / Ctrl-→ Jump cursor by word / segment (stops at -, _, \, /, and whitespace)
Home / Ctrl-A · End / Ctrl-E Jump to start / end of input
Backspace / Delete Delete character before / at cursor
Ctrl-W / Ctrl-Backspace Segment-aware backward delete (stops at -, _, \, /, and whitespace)
Ctrl-U Clear entire input line
Actions Enter Open selected project, run + Create, or open delete confirmation (y to confirm) when items are marked
Ctrl-R Rename selected project inline (pre-fills the slug with a live -> YYYY-MM-DD-<slug> preview; preserves the date prefix unless changed)
Ctrl-G Graduate selected project inline (defaults to slug; accepts relative name, relative subdirectory like work/api-v2, or full/~ path; refreshes picker in place while preserving selection/scroll without changing CWD, whereas CLI tri graduate enters the graduated directory)
Ctrl-D Toggle [x] delete mark (advances selection when marking, stays put when unmarking) for rapid batch selection
Esc Cancel sub-prompt → clear delete marks → exit picker without changing directory
Ctrl-C Cancel current prompt or exit picker immediately

TUI visual cues:

  • Linked Git worktrees display a subtle [wt] badge in the picker list.
  • Status messages use semantic colors (green for success, yellow for warnings/deletes, red for errors) and an empty tries folder displays a friendly onboarding prompt (No experiments yet -- type a name to create YYYY-MM-DD-<name>).

Command Reference & Git Workflows

Core Commands

Command Alias Description
tri — Open interactive fuzzy picker
tri <query> — Open picker pre-filled with <query>
tri new <name> — Create YYYY-MM-DD-<name> (unquoted spaces become -) and enter it
tri cd [query] — Pick from existing projects only (hides + Create)
tri cd <name> -NonInteractive — Unambiguous jump for scripts (throws on 0 or >1 matches)
tri list [query] — Output ranked [pscustomobject] items for PowerShell pipelines
tri rename <old> <new> tri mv Rename project (resolves unambiguous slug/fuzzy <old>, accepts unquoted multi-word <new>), preserve date prefix, handle case-only renames & Git worktrees
tri delete <name> [-Force] tri rm Safely delete project (resolves unambiguous slug/fuzzy <name>); prompts [y/N] interactively, requires -Force in non-interactive scripts, prints Deleted <path>, and auto-prunes Git worktrees
tri graduate <name> [target] tri grad Move project (resolves unambiguous slug/fuzzy <name>, accepts relative name, relative subdirectory like work/api-v2, unquoted multi-word [target], or full/~ path) to graduate root, stripping date prefix by default, and enter it
tri migrate <dir> [name] — Move an external directory into tries using its LastWriteTime date and enter it
tri root — Print the resolved tries root directory
tri help --help, -h Show built-in usage reference
tri version --version Print installed version (tri 1.3.1)

Names starting with -, matching a subcommand, or using --: PowerShell strips an unquoted -- before passing arguments, so use tri new -- -demo for leading-dash names (2026-12-03--demo), and quote it as tri '--' list (or pass tri -- -- list) to search literally for "list" instead of running tri list. Note that named parameters (-Path, -NonInteractive, -Force) must appear before an unquoted -- (otherwise PowerShell treats them as literal positional tokens) — or use the quoted form tri '--' list -NonInteractive.

Native Tab Completion

Importing Tri registers a native PowerShell argument completer (Register-ArgumentCompleter) for tri:

  • First argument: completes subcommands (new, cd, list, rename/mv, delete/rm, graduate/grad, migrate, clone, worktree, root, help, version) and existing experiment names.
  • After cd, rename/mv, delete/rm, or graduate/grad: completes existing experiment names (honoring -Path / $env:TRI_PATH).

Git Workflows

Requires Git for Windows on PATH. If Git fails, tri reports the error and leaves your current directory unchanged. Unquoted multi-word custom names work across clone, worktree, and ..

# Clone repositories (explicit or URL shorthand — HTTPS, HTTP, SSH, git@)
tri clone https://github.com/tobi/try.git
tri clone https://github.com/tobi/try.git my copy name
tri https://github.com/tobi/try.git

# Review GitHub Pull Requests directly (fetches refs/pull/<id>/head & checks out detached HEAD)
# Defaults to YYYY-MM-DD-<owner>-<repo>-pr-<id> to prevent same-day multi-PR collisions
tri https://github.com/owner/repo/pull/123
tri https://github.com/owner/repo/pull/123/files   # Also accepts /commits, /checks, /changes, ?query, #anchor

# Detached Git worktrees (explicit, local path shorthand, or current directory)
tri worktree 'D:\projects\my-repo' experiment
tri 'D:\projects\my-repo' my custom branch test
tri .                                              # Inside Git repo: detached worktree named after the repo root
tri . experiment                                   # Inside Git repo: detached worktree with custom name "experiment"
                                                   # Outside Git repo: falls back to creating a regular dated directory

Worktree lifecycle hygiene:

  • When deleting (or batch-deleting via Ctrl-D) a worktree created by tri, git worktree prune runs automatically against the main repository.
  • When renaming (tri rename), graduating (tri graduate), or migrating (tri migrate) a Git worktree, tri uses git worktree move (or falls back to safe move + git worktree repair) so .git links remain intact.
  • Ready to keep your worktree changes? Run git switch -c my-branch inside the worktree.

Configuration

Setting Priority / Default Example
Tries root -Path > $env:TRI_PATH > ~/src/tries $env:TRI_PATH = 'D:\experiments'
Graduate root -Destination > $env:TRI_GRADUATE_PATH > parent of tries root (or $HOME if tries root is a drive root) $env:TRI_GRADUATE_PATH = 'D:\projects'
# Current session
$env:TRI_PATH = 'D:\experiments'
$env:TRI_GRADUATE_PATH = 'D:\projects'

# Single-command overrides & relative subdirectory graduation
tri -Path 'D:\experiments'
tri graduate api-gateway-bench -Destination 'D:\projects'
tri grad api-v2 work/api-v2
tri graduate api-gateway-bench 'D:\projects\api-gateway'

# Persist across future terminals (reopen PowerShell to apply)
[Environment]::SetEnvironmentVariable('TRI_PATH', 'D:\experiments', 'User')
[Environment]::SetEnvironmentVariable('TRI_GRADUATE_PATH', 'D:\projects', 'User')

PowerShell Automation & Scripting

tri list emits structured PowerShell objects (Name, Path, LastUsed, Score), and the module exports idiomatic verb-noun cmdlet functions for clean automation:

# Pipeline queries
tri list api | Select-Object Name, Score, LastUsed | Format-Table -AutoSize

# Strict non-interactive navigation & deletion in scripts
tri cd api-gateway-bench -NonInteractive
tri rm api-gateway-bench -Force

# Exported PowerShell functions (take exact directory names)
$p   = New-TriProject    -Name 'demo' -Path 'D:\experiments'                 # Returns DirectoryInfo without changing CWD
Get-TriProject           -Query 'demo' -Path 'D:\experiments'
Enter-TriProject         -Name $p.Name -Path 'D:\experiments'
$r   = Rename-TriProject -Name $p.Name -NewName 'demo-v2' -Path 'D:\experiments'
Move-TriProject          -Name $r.Name -Destination 'D:\projects' -Path 'D:\experiments'
Import-TriProject        -SourcePath 'D:\old-lab' -Path 'D:\experiments'
$tmp = New-TriProject    -Name 'scratch' -Path 'D:\experiments'
Remove-TriProject        -Name $tmp.Name -Path 'D:\experiments'              # Supports -WhatIf and -Confirm

Note: Low-level *-TriProject cmdlets accept exact directory names (such as $p.Name, e.g. 2026-12-03-demo), whereas tri adds date-stripped slug and fuzzy resolution.

Unambiguous matching rules: tri cd <name> -NonInteractive, tri delete, tri rename, and tri graduate all share the same resolver: prefer a unique exact match against the full directory name or date-stripped slug (with whitespace normalized to -), then fall back to a unique fuzzy match. Ambiguous matches or zero matches throw a descriptive error instead of guessing.


Architecture, Performance & Safety

Measured on Windows with precompiled runtime DLLs installed via .\install.ps1:

Benchmark Result Notes
Cold start — PowerShell 7.6 (pwsh) 184 ms Down from 838 ms before precompiled DLL caching
Cold start — Windows PowerShell 5.1 117 ms Down from 203 ms before precompiled DLL caching
Warm call (same terminal session) ~0 ms Type already loaded in AppDomain / AssemblyLoadContext
5,000 directories end-to-end (LoadItems + Rank) 13–17 ms Single-level enumeration, zero recursive disk crawl
5,000 directories pure fuzzy Rank 3–4 ms Pooled workspace + optimal DP subsequence bounds
Automated test suite 100% passing (PS 5.1 & 7) All automated tests pass on both Windows PowerShell 5.1 and PowerShell 7
Engine & Metadata Architecture
  • Modular C# engine (Tri/Engine/*.cs, namespace TriV2): Split into six focused source files — Models.cs, FileSystem.cs, FuzzyRanker.cs, ProjectValidator.cs, AnsiRenderer.cs, and Picker.cs — compiled together into a single runtime-tagged DLL (bin\Tri.Engine.<runtime><major>.<hash>.dll, where <runtime> is netcore or netfx and <hash> is the combined SHA-256 prefix of all Tri/Engine/*.cs files). Uninstalled imports cache into %LOCALAPPDATA%\Tri\cache automatically and fall back to in-memory Add-Type if the cache is read-only. No external .NET SDK is required.
  • Single-source validation (ProjectValidator): Directory naming rules, + Create eligibility, rename target resolution, and graduate path checks are centralized in TriV2.ProjectValidator so the TUI and PowerShell CLI enforce identical guarantees.
  • Non-greedy DP fuzzy scorer (TriV2.Engine.Rank): Normalizes whitespace to -, evaluates both the full directory name and the date-stripped slug (taking the higher score), and uses exact Dynamic Programming with forward/backward subsequence bounds to reward string-start (+3.5), word-boundary (+2.5), consecutive runs (+4.5), tight proximity, and exact matches (+1000), blended with recency decay (4 / sqrt(hours + 1)).
  • Atomic visit metadata (.tri.json): Recent-use timestamps live in <root>\.tri.json so tri never mutates your project folders' modification times. Updates acquire an exclusive .tri.lock, write a temp file, atomically swap via File.Replace, and prune missing entries via fast single-scan FindStaleVisitKeys.
Windows Security & Filesystem Guarantees
  • Zero code evaluation: tri never calls Invoke-Expression or emits shell strings to eval. Remaining arguments are captured literally (PositionalBinding=$false), and external git calls always pass -- before user-supplied paths or URLs.
  • Literal path handling: All PowerShell file operations use -LiteralPath or [WildcardPattern]::Escape(...), safely handling directories containing [brackets], spaces, single quotes, and CJK/Unicode names.
  • Safe deletion (DeleteDirectorySafe): Uses an iterative bottom-up stack traversal (immune to stack overflow on deep node_modules trees), clears ReadOnly attributes, and checks FileAttributes.ReparsePoint on the root and every nested subdirectory so symbolic links and junctions are unlinked without ever traversing into or deleting their targets.
  • Safe cross-volume moves (MoveDirectorySafe): Uses atomic Directory.Move on the same volume. Across volumes, performs a file-by-file copy that explicitly rejects reparse points/junctions (rolling back partial copies on failure) before safely removing the source.
  • Windows naming rules: Rejects Windows reserved device names (CON, PRN, AUX, NUL, COM1–9, LPT1–9), invalid filename characters, trailing dots/spaces, reserved .tri / .tri.* names, and slugs exceeding 120 characters (255 total). Case-only renames on NTFS are handled cleanly via a two-step temporary move.
  • Path-length note (PS 5.1 vs. PS 7): Windows PowerShell 5.1 runs on .NET Framework 4.x and remains subject to the OS 260-character MAX_PATH limit for deeply nested paths, whereas PowerShell 7 supports long paths when enabled on Windows.

Development, Testing, Uninstall & Attribution

Run the Test Suite

pwsh -NoProfile -File .\tests\run.ps1
powershell -NoProfile -File .\tests\run.ps1

All automated tests execute inside isolated temporary directories using local Git repositories (zero network dependency) and clean up automatically — verified on both Windows PowerShell 5.1 and PowerShell 7.

Uninstall

Close any PowerShell window that has loaded Tri, then delete the installed module folders (and optional DLL cache):

$docs = [Environment]::GetFolderPath('MyDocuments')
Remove-Item -LiteralPath (Join-Path $docs 'PowerShell\Modules\Tri') -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath (Join-Path $docs 'WindowsPowerShell\Modules\Tri') -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath "$env:LOCALAPPDATA\Tri\cache" -Recurse -Force -ErrorAction SilentlyContinue

Your project directories and .tri.json metadata are stored separately and remain untouched.

License & Attribution

Released under the MIT License.

Heartfelt thanks to Tobias Lütke (@tobi) for creating tobi/try. Its clean idea and UX inspired this Windows/PowerShell port, and the fuzzy scoring in Tri/Engine/FuzzyRanker.cs adapts upstream lib/fuzzy.rb; the original copyright notice and MIT license are preserved in THIRD-PARTY-NOTICES.md.

About

A native Windows & PowerShell implementation inspired by tobi/try — fresh experiment directories for every idea

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages