{"id":46459510,"url":"https://github.com/sbay-dev/terminalstateguard","last_synced_at":"2026-04-18T17:12:20.568Z","repository":{"id":341774653,"uuid":"1171360641","full_name":"sbay-dev/TerminalStateGuard","owner":"sbay-dev","description":"⚡ TSG — Terminal State Guard: Cross-platform CLI tool for Copilot performance boosting, safe monitoring \u0026 session recovery","archived":false,"fork":false,"pushed_at":"2026-03-06T02:08:14.000Z","size":44,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-03-06T05:13:21.110Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PowerShell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sbay-dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-03T06:26:07.000Z","updated_at":"2026-03-06T02:08:04.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/sbay-dev/TerminalStateGuard","commit_stats":null,"previous_names":["sbay-dev/terminalstateguard"],"tags_count":6,"template":false,"template_full_name":null,"purl":"pkg:github/sbay-dev/TerminalStateGuard","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sbay-dev%2FTerminalStateGuard","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sbay-dev%2FTerminalStateGuard/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sbay-dev%2FTerminalStateGuard/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sbay-dev%2FTerminalStateGuard/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sbay-dev","download_url":"https://codeload.github.com/sbay-dev/TerminalStateGuard/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sbay-dev%2FTerminalStateGuard/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30207389,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-07T03:24:23.086Z","status":"ssl_error","status_checked_at":"2026-03-07T03:23:11.444Z","response_time":53,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-03-06T03:04:21.096Z","updated_at":"2026-04-18T17:12:20.560Z","avatar_url":"https://github.com/sbay-dev.png","language":"PowerShell","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\n# ⚡ TSG — Terminal State Guard\n\n### The Complete Terminal Intelligence Platform for Developers\n\n[![NuGet](https://img.shields.io/nuget/v/TerminalStateGuard?style=for-the-badge\u0026logo=nuget\u0026color=004880)](https://www.nuget.org/packages/TerminalStateGuard)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](LICENSE)\n[![.NET 10](https://img.shields.io/badge/.NET-10.0-512BD4?style=for-the-badge\u0026logo=dotnet)](https://dotnet.microsoft.com)\n[![Platform](https://img.shields.io/badge/Platform-Windows%20%7C%20Linux-blue?style=for-the-badge)]()\n\n**Real-time window tracking · Live tab detection · Process management · Session recovery**\n\n[Installation](#-installation) · [Commands](#-commands) · [Windows](#-window-tracking) · [Processes](#-process-manager) · [Monitor](#-safe-monitor) · [Recovery](#-session-recovery)\n\n---\n\n\u003c/div\u003e\n\n## 🚀 Installation\n\n```bash\ndotnet tool install -g TerminalStateGuard\ntsg install\n```\n\n**Done.** Reopen your terminal — shortcuts, profiles, and integration are active.\n\n### What `tsg install` does:\n\n| Platform | Action |\n|----------|--------|\n| **Windows** | Installs [Windows Terminal Fragment](https://learn.microsoft.com/en-us/windows/terminal/json-fragment-extensions) with dedicated profiles \u0026 icons |\n| **Windows** | Configures PSReadLine keyboard shortcuts in PowerShell profile |\n| **Windows** | Deploys `FileSystemWatcher` for event-driven state tracking |\n| **Linux** | Adds shell aliases and keybindings to `.bashrc`/`.zshrc` |\n| **Both** | Deploys scripts to `~/.tsg/` and creates SQLite database |\n\n## ⌨️ Commands\n\n### Core\n\n```bash\ntsg install       # Setup scripts, shortcuts \u0026 terminal integration\ntsg uninstall     # Remove configuration\ntsg doctor        # 🩺 Diagnose environment issues\ntsg config        # ⚙️ Show/set configuration (max-snapshots, etc.)\ntsg version       # Show version\n```\n\n### Copilot Performance\n\n```bash\ntsg boost         # ⚡ Elevate Copilot process priority (Admin/sudo)\ntsg monitor       # 📊 Safe live monitor with diagnostics\ntsg status        # 📋 Quick health check\ntsg restore       # 🔄 Revert all priority changes\ntsg focus         # 🎯 Focus ALL resources on stuck process (Admin)\n```\n\n### Window \u0026 Session Management\n\n```bash\ntsg windows            # Show active \u0026 recently closed windows with tabs\ntsg windows -i         # 🖥️ Interactive window dashboard\ntsg windows --history  # Browse window history from database\ntsg windows --restore  # Restore closed windows with all tabs\ntsg recover            # 🔄 Recover terminal tabs + Copilot sessions\ntsg snapshots          # 📸 List all saved terminal snapshots\ntsg snapshots --all    # Show all with tab details\ntsg capture            # Capture current terminal state to SQLite\n```\n\n### Process Manager\n\n```bash\ntsg processes          # Show dev processes with ports \u0026 resource usage\ntsg ps                 # Alias for tsg processes\ntsg ps -i              # 🔧 Interactive process manager with navigation\ntsg ps --orphans       # ⚠️ Show only orphaned background processes\ntsg ps --ports         # 🌐 Show only port-binding processes\ntsg ps --kill \u003cPID\u003e    # 💀 Kill a process (with confirmation)\ntsg ps --kill-tree \u003cPID\u003e  # 🌳 Kill process tree\n```\n\n### Database Query\n\n```bash\ntsg db \"SELECT * FROM windows\"              # Query terminal database\ntsg db \"SELECT * FROM events ORDER BY ts DESC LIMIT 10\"\n```\n\n### Keyboard Shortcuts\n\n| Shortcut | Action | Terminal Profile |\n|----------|--------|-----------------|\n| `Ctrl+Alt+B` | Boost | — |\n| `Ctrl+Alt+M` | Monitor | — |\n| `Ctrl+Alt+S` | Status | — |\n| `Ctrl+Alt+F` | Recover | — |\n| `Ctrl+Alt+R` | Restore | — |\n| `Ctrl+Alt+W` | Window Dashboard | 🖼️ TSG Windows |\n| `Ctrl+Alt+N` | Snapshots | 📸 TSG Snapshots |\n| `Ctrl+Alt+P` | Process Manager | 🔧 TSG Processes |\n\n## 🖥️ Window Tracking\n\nTSG provides **real-time window and tab tracking** using COM IUIAutomation — no stale data.\n\n```\n  🪟 Terminal Windows — 2 active, 1 recently closed\n  📅 2026-04-18 12:15:05  📑 8 tabs  🤖 5  [live]  👁️ UIA:2\n\n  ── Active Windows ──\n  🟢 Window 1  [a1b2c3d4e5f6]  📑 6 tabs  🤖 3\n     📅 Opened: 2026-04-18 10:30:00  👁️ Last seen: 2026-04-18 12:15:05\n     🤖 Build microservice API\n     🤖 Fix auth middleware\n     🤖 Debug test failures\n     📂 Project Documentation\n     📂 Terminal Configs\n     📂 Source Repos\n\n  🟢 Window 2  [f6e5d4c3b2a1]  📑 2 tabs  🤖 2\n     🤖 Deploy staging\n     🤖 Monitor logs\n\n  ── Recently Closed ──\n  🔴 Window 3  [x9y8z7w6v5u4]  📑 4 tabs\n     📅 Opened: 2026-04-18 08:00:00  ❌ Closed: 2026-04-18 11:45:00\n     🤖 Old debug session (restorable)\n```\n\n### Interactive Dashboard (`tsg windows -i`)\n\nThe interactive dashboard provides a menu-driven interface:\n\n- **[R] Restore** — Restore closed windows with all their tabs\n- **[S] Snapshot** — Take a snapshot of current terminal state\n- **[H] History** — Browse window open/close timeline from database\n- **[P] Processes** — Switch to process manager\n- **[F] Refresh** — Refresh live window data\n- **[Q] Quit**\n\n### How Live Detection Works\n\nTSG uses **COM IUIAutomation** (via P/Invoke with `CoCreateInstance`) to enumerate real terminal windows and tabs in real-time. This replaces the unreliable `state.json` which never removes closed tabs.\n\n- **Primary source:** Live UIA tab enumeration (class `CASCADIA_HOSTING_WINDOW_CLASS`)\n- **Fallback:** `state.json` replay actions (when UIA is unavailable)\n- **Event tracking:** `FileSystemWatcher` on `state.json` triggers re-capture on any change\n- **Storage:** All captures stored in SQLite at `~/.tsg/terminal.db`\n\n## 🔧 Process Manager\n\nA comprehensive dev process manager that identifies development servers, background tasks, and orphaned processes.\n\n```\n  🔧 Dev Processes — 45 found | 4200 MB | 3 ports | 2 orphans\n\n  ── 🖥️ Terminal (PID 18672) ──  (12 processes, 1800 MB)\n  ▶   20360  copilot     396.1 MB  ⏱️ 1.0h  🕐 9h\n             📋 copilot-win32-x64.exe --stdio\n      34388  pwsh        146.8 MB  ⏱️ 5s    🕐 16m\n             📋 \"C:\\Program Files\\PowerShell\\7\\pwsh.exe\"\n      48008  wsl          13.1 MB  ⏱️ 0s    🕐 1m   🌐 :8080\n             📋 wsl.exe bash -lc \"npm run dev\"\n\n  ── ⚠️ Unattributed ──  (33 processes, 2400 MB)\n      21904  devenv     1329.2 MB  ⏱️ 10m   🕐 12h\n      ...\n```\n\n### Interactive Mode (`tsg ps -i`)\n\nFull keyboard-driven process management with viewport scrolling:\n\n| Key | Action |\n|-----|--------|\n| `↑` `↓` | Navigate processes (viewport auto-scrolls) |\n| `Enter` | Expand process details with impact analysis |\n| `K` | Kill selected process (with confirmation) |\n| `T` | Tree-kill process and all children |\n| `O` | Filter to orphan processes only |\n| `P` | Filter to port-binding processes only |\n| `C` | Clean ALL orphan processes |\n| `F` | Refresh (rescan all processes) |\n| `Q` | Quit |\n\n### Process Detail View\n\nPressing `Enter` on a process shows:\n\n```\n  ═══ Process Details ═══\n  Name:       node\n  PID:        48008\n  Parent:     pwsh (34388)\n  Memory:     256.4 MB\n  CPU Time:   2m 15s\n  Uptime:     45 minutes\n  Terminal:   Window 1 (PID 18672)\n  Ports:      :3000, :3001\n\n  📋 Command Line:\n  node /home/user/project/node_modules/.bin/next dev --port 3000\n\n  👶 Child Processes (3):\n    PID 48120  node     45.2 MB\n    PID 48200  node     32.1 MB\n    PID 48350  esbuild  12.0 MB\n\n  ⚠️ Kill Impact Analysis:\n    💾 Memory freed: 345.7 MB (4 processes)\n    🌐 Ports released: :3000, :3001\n    📂 Directories affected: /home/user/project\n\n  [K] Kill  [T] Tree-kill  [←] Back\n```\n\n### What It Detects\n\n| Category | Detection Method |\n|----------|-----------------|\n| **Terminal processes** | Parent chain tracing to `WindowsTerminal.exe` |\n| **Dev servers** | Keywords: node, python, dotnet, cargo, go, java, ruby, etc. |\n| **Listening ports** | P/Invoke `GetExtendedTcpTable` from `iphlpapi.dll` |\n| **Orphan processes** | Parent PID points to dead/non-existent process |\n| **Resource usage** | WMI `Win32_Process` bulk query + working set size |\n\n## 📊 Safe Monitor\n\n**100% read-only** — never modifies Copilot's internal files.\n\n```\n  ⚡ TSG MONITOR  06:30:00  [🟢 BOOSTED] [4/4]\n  ══════════════════════════════════════════════════════\n  PID 221120  | copilot    | 180 MB | H:    234 | Δ  0.3s | 🟢 IDLE\n           📂 MyProject — Implement auth system\n           📄 Events: 2.1MB | Last: assistant.turn_end | ok\n  PID 52300   | copilot-ls |  16 MB | H:    120 | Δ  0.0s | 🟢 IDLE\n           🟣 Visual Studio\n  ══════════════════════════════════════════════════════\n  TOTAL: 196 MB | CPU: 125.3s | Threads: 31\n```\n\n### Diagnostic Indicators\n\n| State | Meaning | Action |\n|-------|---------|--------|\n| 🟢 IDLE | Healthy, idle | None |\n| 🟡 ACTIVE | Processing | Wait |\n| 🔴 HIGH CPU | Heavy computation | Wait or close → resume |\n| 🔴 HANDLE LEAK | events.jsonl too large | Close tab → `copilot --resume` |\n| ❄️ STUCK | Turn never completed | Close tab → resume (auto-recovers) |\n\n## 🔄 Session Recovery\n\n```bash\ntsg recover\n```\n\nScans Windows Terminal state + Copilot sessions and reopens tabs with `copilot --resume`:\n\n```\n  🔄 Session Recovery\n  ✅ 8 tabs (5 copilot)\n\n  [1] 🤖 MyProject (Win 1)\n      💬 Implement auth system\n  [2] 📂 Documents (Win 1)\n  [3] 🤖 WebApp (Win 2)\n      💬 Fix DllNotFoundException\n```\n\n### Window Restore (`tsg windows --restore`)\n\nRestores closed windows with their last known tabs from the SQLite database:\n\n```bash\ntsg windows --restore    # Interactive selection from closed windows\n```\n\n## 📸 Snapshots\n\nSnapshots capture the complete terminal state (windows, tabs, directories, Copilot sessions) at a point in time:\n\n```bash\ntsg snapshots       # List recent snapshots with timestamps\ntsg snapshots --all # Show all snapshots with tab details\ntsg capture         # Take a manual snapshot\n```\n\n```\n  📸 Terminal Snapshots (15 total)\n  [ 1] 📅 2026-04-18 12:15:05  ⏱️ 2m ago   📺 2 win  📑 8 tabs  🤖 5\n  [ 2] 📅 2026-04-18 12:10:00  ⏱️ 7m ago   📺 2 win  📑 8 tabs  🤖 5\n  [ 3] 📅 2026-04-18 11:45:00  ⏱️ 32m ago  📺 3 win  📑 12 tabs 🤖 8\n```\n\nSnapshots are configurable via `tsg config max-snapshots \u003cN\u003e` (default: 50, range: 5–1000).\n\n## 🗄️ SQLite Database\n\nAll terminal state is tracked in a local SQLite database at `~/.tsg/terminal.db`:\n\n| Table | Purpose |\n|-------|---------|\n| `captures` | Point-in-time state captures with quality flags |\n| `capture_windows` | Windows in each capture |\n| `capture_tabs` | Tabs with titles, directories, types |\n| `windows` | Persistent window identity (first_seen, last_seen, closed_at) |\n| `events` | State change timeline (window_opened, window_closed) |\n\nQuery directly with:\n\n```bash\ntsg db \"SELECT * FROM windows WHERE closed_at IS NOT NULL\"\ntsg db \"SELECT * FROM events ORDER BY ts DESC LIMIT 20\"\n```\n\n### Data Quality Flags\n\n| Flag | Source | Reliability |\n|------|--------|-------------|\n| `live` | COM IUIAutomation real-time | ✅ Highest |\n| `verified` | UIA confirmed | ✅ High |\n| `trimmed` | UIA-corrected count | ✅ High |\n| `stale` | state.json age \u003e threshold | ⚠️ Low |\n| `no-uia` | UIA unavailable | ⚠️ Fallback |\n\n## 🩺 Doctor\n\n```bash\ntsg doctor\n```\n\n```\n  🩺 TSG Doctor — Environment Check\n\n  ✅ .NET 10.0.0\n  ✅ Shell: C:\\Program Files\\PowerShell\\7\\pwsh.exe\n  ✅ TSG dir: C:\\Users\\you\\.tsg\n  ✅ Copilot sessions: 12\n  ✅ Snapshots: 15/50 (max configurable)\n  ⚠️ 1 session(s) \u003e 20MB — may cause slowness\n  ✅ Windows Terminal Fragment installed\n  ✅ Terminal state: 2 windows, 8 tabs\n\n  🎉 All checks passed!\n```\n\n## 🛡️ Safety\n\n\u003e **TSG never modifies Copilot's internal files.**\n\n- ✅ All monitoring is **read-only** — only reads metadata\n- ✅ Never deletes, trims, or edits `events.jsonl`\n- ✅ Session recovery uses native `copilot --resume`\n- ✅ Process kill requires explicit user confirmation with impact analysis\n- ✅ All data stored locally in `~/.tsg/` — no network access\n\n## ⚡ Architecture\n\n```\ntsg (dotnet tool)\n ├── Platform/\n │   ├── IPlatformHost.cs      — Cross-platform abstraction\n │   ├── WindowsHost.cs        — Windows Terminal Fragment + PSReadLine\n │   └── LinuxHost.cs          — bash/zsh aliases + keybindings\n ├── Scripts/\n │   ├── windows/*.ps1         — PowerShell monitoring \u0026 tracking scripts\n │   └── linux/*.sh            — Bash monitoring scripts\n ├── CommandRegistry.cs        — Lambda-based command routing (C# 14)\n ├── Configuration.cs          — Persistent settings (max-snapshots, etc.)\n ├── StateCapture.cs           — Live state capture engine (UIA + state.json)\n ├── UiaComHelper.cs           — COM IUIAutomation interop via P/Invoke\n ├── TerminalDatabase.cs       — SQLite temporal database layer\n ├── Windows.cs                — Window tracking \u0026 interactive dashboard\n ├── ProcessManager.cs         — Dev process manager with interactive UI\n ├── Snapshots.cs              — Snapshot listing and management\n ├── DbQuery.cs                — Direct SQL query interface\n ├── Installer.cs              — Script deployment + profile config\n ├── ScriptRunner.cs           — Cross-platform script execution\n └── Diagnostics.cs            — Environment health checks\n```\n\n**Built with:** .NET 10 · C# 14 · COM IUIAutomation · SQLite · Windows Terminal Fragments API\n\n**Dependencies:** `Microsoft.Data.Sqlite` 10.0.6 (single external dependency)\n\n## 📦 Requirements\n\n| Platform | Requirements |\n|----------|-------------|\n| **Windows** | Windows Terminal, PowerShell 7+, .NET 10 Runtime |\n| **Linux** | bash/zsh, .NET 10 Runtime |\n| **Both** | GitHub Copilot CLI (`npm i -g @github/copilot`) |\n\n## 🗑️ Uninstall\n\n```bash\ntsg uninstall\ndotnet tool uninstall -g TerminalStateGuard\n```\n\nRemoves all configuration including Fragment profiles, PSReadLine shortcuts, and `~/.tsg/` scripts. The SQLite database (`~/.tsg/terminal.db`) is preserved for reference.\n\n## 📄 License\n\n[MIT](LICENSE) — Made with ⚡ by [sbay-dev](https://github.com/sbay-dev)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsbay-dev%2Fterminalstateguard","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsbay-dev%2Fterminalstateguard","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsbay-dev%2Fterminalstateguard/lists"}