# GitSetu Documentation (llms.txt) This file contains the complete, unformatted markdown documentation for GitSetu. It is intended for consumption by Large Language Models (LLMs), AI Agents, and automated tools. Project: GitSetu Homepage: https://gitsetu.bhaskarjha.dev --- START OF FILE: adr/0001-dual-ssh-routing-strategy.md --- --- title: "ADR 0001: Dual SSH Routing" description: "Architectural Decision Record: Dual SSH key routing via Match blocks versus include directives." category: "adr" slug: "adr/0001-dual-ssh-routing-strategy" --- # ADR 0001: The Dual-Strategy SSH Routing Architecture ## Status **Accepted** (May 2026) ## Context GitSetu operates on a core philosophy of zero external dependencies. A critical component of its architecture is routing Git traffic through the correct SSH identity. There was significant debate regarding whether to rely exclusively on Git's native `core.sshCommand` (via `includeIf`) or to continue mutating the OS-level `~/.ssh/config` file to provide host aliases (e.g., `github-pro`). Theoretical audits suggested that `core.sshCommand` was sufficient and that the `~/.ssh/config` strategy was a "brittle legacy" approach. Extensive terminal simulations were conducted to test Git's internal evaluation of `includeIf` during the `git clone` lifecycle and, critically, how external package managers interact with Git subprocesses. ## Decision We will **permanently retain the dual-strategy architecture** (using both `core.sshCommand` and `~/.ssh/config` aliases). ### 1. Why `core.sshCommand` alone is insufficient When external package managers (such as `go get`, `npm`, `cargo`, or `terraform init`) fetch private dependencies, they frequently spawn a `git clone` subprocess that targets a **global cache directory** (e.g., `~/.go/pkg/mod/...` or `~/.npm/...`). Because the target directory of the clone falls *outside* the developer's mapped local workspace (e.g., `~/work/`), Git's `includeIf "gitdir:~/work/"` directive silently fails. The `core.sshCommand` is dropped, authentication defaults to the generic SSH key, and the package manager abruptly fails. ### 2. The Necessity of `~/.ssh/config` Because Git cannot dynamically route identities for external cache directories based purely on the `pwd` of the parent process, the only mathematically sound solution is OS-level network routing. By providing `~/.ssh/config` aliases (e.g., `Host github-pro`), developers have a definitive manual escape hatch. They can configure their package managers (e.g., via `url.insteadOf` or direct aliases) or manually clone repositories into unmapped directories while explicitly enforcing the correct identity. ## Consequences * **For Developers:** Future contributors and AI agents are strictly forbidden from attempting to "refactor" or remove the `~/.ssh/config` alias generation under the mistaken belief that Git's `includeIf` is a monolithic solution. * **For Architecture:** The complexity of maintaining two separate routing layers is accepted as a permanent, necessary cost of doing business in a flawed multi-tenant Git ecosystem. --- END OF FILE: adr/0001-dual-ssh-routing-strategy.md --- --- START OF FILE: adr/0002-ssh-config-include-directive.md --- --- title: "ADR 0002: OpenSSH Include Pivot" description: "Architectural Decision Record: Standardizing on modular Include ~/.config/gitsetu/profiles/ssh_config." category: "adr" slug: "adr/0002-ssh-config-include-directive" --- # ADR 0002: The OpenSSH `Include` Directive Pivot ## Status **Accepted** (May 2026) ## Context As established in ADR 0001, GitSetu must generate OS-level SSH host aliases (`Host github-pro`) to provide a manual fallback for complex dependency cloning workflows. Historically, GitSetu implemented this by using inline `awk` commands to rip open the user's global `~/.ssh/config` file, locate specific `[gitsetu:managed:start]` markers, and surgically replace the text blocks. This approach was identified as a critical architectural vulnerability (a "ticking time bomb"). Complex user configurations, unexpected formatting, or process interruptions during the atomic `mv` operation posed a massive risk of corrupting the user's global network access configuration. This violated GitSetu's core "Zero-Trust" mandate. ## Decision We will **migrate SSH alias orchestration exclusively to the OpenSSH `Include` directive.** 1. GitSetu will cease all inline mutation of `~/.ssh/config` blocks. 2. All generated aliases will be written to a dedicated, isolated file: `~/.config/gitsetu/profiles/ssh_config`. 3. During setup, GitSetu will perform a one-time check to ensure the directive `Include ~/.config/gitsetu/profiles/ssh_config` exists at the **absolute top** of the user's `~/.ssh/config` file. ### Why the Absolute Top? OpenSSH configuration parsing operates on a **"first-match wins"** rule. If the `Include` directive is placed at the bottom of the file, any generic blocks (e.g., `Host *` or `Host github.com`) defined earlier by the user will lock in their parameter values, causing GitSetu's aliases to be silently overridden. Placing the `Include` directive at the top guarantees precedence while cleanly isolating the tool's footprint. ### Sandbox Validation Testing confirmed that if the included file (`~/.config/gitsetu/profiles/ssh_config`) does not exist (e.g., following a `gitsetu teardown` operation), OpenSSH gracefully and silently ignores the `Include` directive without crashing or terminating the SSH handshake. ## Consequences * **For Security:** Complete Zero-Trust isolation is achieved. GitSetu no longer risks corrupting the user's legacy SSH configurations. * **For Maintainability:** The Bash script logic in `lib/ssh.sh` becomes drastically simpler, eliminating the need for brittle, multi-line `awk` parsers. * **For Compatibility:** The `Include` directive requires OpenSSH 7.3+ (released August 2016). This is deemed an acceptable minimum requirement for modern Git multi-tenant environments. --- END OF FILE: adr/0002-ssh-config-include-directive.md --- --- START OF FILE: core-engines/credential-broker.md --- --- title: "Credential Broker" description: "OS keychain integration and encrypted credential vault storing personal access tokens securely." category: "core-engines" slug: "core-engines/credential-broker" --- # Credential Broker Engine **Native OS keychain isolation preventing HTTPS Personal Access Token (PAT) cross-profile pollution.** Corporate network firewalls frequently block outbound connections on SSH Port 22 entirely. This forces developers to clone, push, and pull repositories using HTTPS protocols backed by Personal Access Tokens (PATs). However, operating system credential stores natively introduce a critical vulnerability when managing multiple tokens across overlapping environments. GitSetu includes a specialized **Credential Broker Engine** to resolve this challenge permanently. --- ## The Operational Vulnerability When authenticating over HTTPS, Git streams a credential request directly to your underlying operating system (macOS Keychain, Windows Credential Manager, or Linux Secret Service). ``` [ git push https://github.com/org/repo.git ] │ ▼ [ Upstream Request: "github.com" ] │ ▼ [ OS Keychain blindly returns first cached token ] │ ▼ [ Return payload: Personal Token ] │ ▼ [ HTTP 403 Forbidden Error ] ``` Because external keychains key authentication strictly off the base domain string (`github.com`), they blindly return the first matching token encountered. You end up attempting to authenticate against an enterprise repository using your personal access token, raising persistent, confusing access errors. --- ## The GitSetu Intercept Architecture GitSetu intercepts this systemic failure by registering itself as a proxy credential helper within your dynamically mapped configuration layers. Inside your target `.gitconfig` bounds, GitSetu statefully compiles: ```ini [credential] helper = "gitsetu credential" ``` ### The Isolated Resolution Flow 1. **Trigger Operation:** You execute `git push` over HTTPS inside a managed workspace folder. 2. **Helper Interception:** Git streams an authentication verification payload directly to the configured credential helper. 3. **Context Evaluation:** GitSetu leverages its optimized path-matching algorithm to identify the active profile context instantly. 4. **Namespaced Query:** Instead of requesting credentials for `github.com` from the OS, GitSetu constructs an isolated, unique namespace query: `gitsetu:work:github.com`. 5. **Target Delivery:** The OS keychain (macOS Keychain, Linux Secret Service, or Windows Git Credential Manager) returns the exact token explicitly mapped to your `work` profile context. 6. **Execution Success:** GitSetu passes the isolated token payload back to Git. Upstream communication succeeds flawlessly. > [!NOTE] > **Windows Credential Manager Integration:** > On Windows (Git Bash), GitSetu automatically configures `credential.helper = manager`, natively delegating to Microsoft's **Git Credential Manager (GCM)** backed by Windows DPAPI and Windows Credential Manager. --- ## Token Lifecycle Management To securely seed or update a Personal Access Token within an isolated profile scope, you can: 1. **Interactive Setup:** Enter your PAT when prompted during the interactive `gitsetu setup` wizard. 2. **Headless Profile Registration:** Provide credentials when invoking profile commands: ```bash gitsetu profile add work --email=dev@company.com --dir=~/work ``` 3. **Standard Git Credential Helper Interface:** Store or retrieve credentials directly via standard Git credential protocol inputs: ```bash printf "protocol=https\nhost=github.com\nusername=dev-corp\npassword=PAT_TOKEN\n" | gitsetu credential store ``` ### Encrypted Fallback Storage In environments where native OS keychain facilities are absent (such as headless Linux or minimal WSL containers), GitSetu securely falls back to a restricted credential vault at `~/.config/gitsetu/.tokens`. This file is strictly enforced with `chmod 600` permissions (read/write only by the current user) immediately upon creation, preventing world-readable token exposure. Passwords and tokens are never stored in plain-text global configuration files. --- END OF FILE: core-engines/credential-broker.md --- --- START OF FILE: core-engines/identity-routing.md --- --- title: "Identity Routing" description: "Hierarchical includeIf routing engine mapping repository working directories to isolated Git identities." category: "core-engines" slug: "core-engines/identity-routing" --- # Identity Routing Engine **A deep dive into directory-scoped Git conditional mechanics and native credential switching.** At the core of GitSetu's magical context-switching capability lies a seamless fusion of standard Git configuration files with advanced conditional file inclusion rules. Unlike brittle wrapper utilities that alias the `git` binary or long-running supervisor daemons that monitor your file descriptors, GitSetu shifts runtime evaluation entirely to Git itself. --- ## The Routing Architecture When you provision a workspace profile via `gitsetu setup`, GitSetu statefully compiles your global configuration file (`~/.gitconfig`), injecting a structured conditional routing table. ```ini [gitsetu:managed:start] [user] useConfigOnly = true [init] defaultBranch = main # Global Fallback Identity (unmapped directories) [include] path = "~/.config/gitsetu/profiles/personal.gitconfig" # Directory-Scoped Conditional Interceptors [includeIf "gitdir:~/work/"] path = "~/.config/gitsetu/profiles/work.gitconfig" [includeIf "gitdir:~/clients/acme/"] path = "~/.config/gitsetu/profiles/acme.gitconfig" [gitsetu:managed:end] ``` ### How Runtime Evaluation Operates 1. **Working Directory Transition:** You navigate your shell into `~/work/api-service/`. 2. **Git Operation Intercept:** You execute any standard git command (e.g. `git clone`, `git fetch`, or `git commit`). 3. **Path Matching:** Git natively evaluates `~/.gitconfig` top-down. Upon encountering `includeIf "gitdir:~/work/"`, it verifies if the local repository resides within that absolute tree bounds. 4. **Target Inclusion:** Because the bounds match, Git dynamically parses and applies the target profile configuration file (`~/.config/gitsetu/profiles/work.gitconfig`) mid-flight. --- ## Inside the Profile Payload The isolated target file (`work.gitconfig`) contains your precise overrides: ```ini [user] name = Corporate Author Name email = dev@company.com [core] # Injects the exact cryptographic key context required by this profile (safe space-quoted) sshCommand = ssh -F ~/.ssh/config -o IdentitiesOnly=yes -i "~/.ssh/id_ed25519_work" ``` This absolute separation of concerns guarantees that **personal sandbox credentials never leak into corporate repositories**, while preventing single-key remote auth failures. --- ## Path Resolution Safeguards & Zero-Trust Architecture Because cross-platform filesystems handle casing, symlinks, and trailing paths differently, GitSetu applies strict compilation guard rails: - **Trailing Slashes:** Every compiled `gitdir:` path string strictly terminates with a `/` character to ensure deep sub-folder recursion acts properly. - **Tilde Expansion:** Standardizes shell `$HOME` prefixes to absolute directory markers to stop parsing errors across disparate terminal environments. - **Windows Case-Insensitive Matching (`gitdir/i:`):** On Windows / Git Bash, GitSetu automatically compiles `gitdir/i:` instead of `gitdir:`. Because Windows filesystems (NTFS) are case-preserving but case-insensitive, this ensures that directory matching never breaks if paths differ in casing (e.g. `C:/Users` vs `c:/users`). - **Canonical Drive Letter Normalization:** Converts Windows paths (`/c/Users/...` or `c:\users\...`) into canonical `C:/Users/...` format, which is fully recognized and resolved by native Win32 `git.exe` across both Git Bash and Windows native shells (PowerShell, CMD). - **Virtualization Support:** Silently filters out malformed line endings and maps target workspace trees across Windows Subsystem for Linux (WSL) boundaries flawlessly. ### Automatic Workspace Directory Provisioning (`mkdir -p`) When registering a new profile (interactively in `gitsetu setup` or via `gitsetu add`), GitSetu automatically checks if the declared target directory exists on disk. If absent, it provisions the directory hierarchy via `mkdir -p` (while respecting `--dry-run` invariants), eliminating "directory does not exist" failures before cloning or committing. ### Longest-Prefix Match Routing When nested workspace directories exist (e.g., a general work directory `~/work/` and a nested client project `~/work/clients/acme/`), GitSetu's routing, prompt engine, and pre-commit guard employ a deterministic longest-prefix match algorithm. The most specific directory boundary wins: Git evaluates conditional rules sequentially, and GitSetu tools compute matching prefix lengths to ensure the deeper child profile takes absolute precedence over the parent. On Windows and macOS, path matching is case-insensitive, avoiding casing drift. ### Multi-Profile Persistence & Re-hydration Running `gitsetu setup` multiple times is safe and non-destructive. GitSetu automatically loads and re-hydrates existing profiles from `~/.config/gitsetu/profiles.conf`, preserving their names, emails, keys, and directory bindings in memory. Users can review, adjust, or append profiles without overwriting previously configured identities. ### Co-existence with Pre-Existing Manual `includeIf` Setups For developers transitioning from hand-crafted `includeIf` directives and custom `.gitconfig` files: 1. **Zero-Destruction Boundary:** GitSetu encapsulates all generated rules strictly within `# [gitsetu:managed:start]` and `# [gitsetu:managed:end]`. Any manual `includeIf` rules, aliases, and settings outside this block are never altered, deleted, or reordered. 2. **Top-Down Sequential Precedence:** Git evaluates `~/.gitconfig` sequentially from top to bottom. Because GitSetu's managed block is appended at the end of `~/.gitconfig`, GitSetu profiles take precedence for directories they manage, ensuring correct SSH key and identity routing. All directories managed exclusively by your manual `includeIf` continue to operate normally. 3. **Automated Discovery Migration:** Running `gitsetu setup --auto` uses GitSetu's built-in discovery engine (`lib/discovery.sh`) to scan existing manual `includeIf` directives in `~/.gitconfig` and existing SSH keys in `~/.ssh/`. It automatically imports existing directory mappings and identities into the profile registry, eliminating manual re-configuration. 4. **Clean Reversibility:** If you ever decide to remove GitSetu, executing `gitsetu teardown` excises only the managed block, restoring your original manual configuration completely intact. ### Profile Teardown, Unmounting & Orphan Pruning When a profile is removed via `gitsetu remove