# NeuralLoom: Unified AI Agent Orchestrator & Context Bridge

NeuralLoom is a local Next.js orchestration cockpit and terminal bridge designed to manage multiple concurrent terminal agent sessions (such as **Claude Code** and **Aider**) in isolated or overlapping workspaces. It streams pseudo-terminal (PTY) streams to the browser over secure WebSockets, manages system prompt environments, compiles directory maps, tracks active token costs, and displays visual resource telemetry.

---

## 🚀 Key Features

* **Multi-Session Workspace Switcher**: Swap between separate active workspaces via a top tab bar. The file explorer tree, git diff panel, terminal stream, and active files are cached independently per session so you never lose your context when swapping projects.
* **Split Terminal Console**: Split the terminal view horizontally (50/50) to monitor and interact with two different agent sessions simultaneously.
* **Resource & Token Analytics**: 
  - Real-time CPU and Memory telemetry (via `docker stats` for container runners or process-RSS for local host PTYs).
  - Regex-based PTY stdout parsing to extract input/output tokens and estimated dollar cost metrics on the fly.
* **Context Hub & Command Injection**: 
  - Write shared prompts (`cprompt.md`) and global guidelines (`AGENTS.md`).
  - Stage context and directories maps to instantly inject standard commands (like `/ccc` and `/ccp`) with one click.
* **Inline Git Diff Viewer**: Scan changes via `git status --porcelain` and view modified files with line-by-line syntax-highlighted diffs in a virtual read-only editor tab.
* **Flexible Runtimes**: Launch sessions in three different environments:
  1. **Local Host OS** (via Git Bash pseudo-terminals).
  2. **Docker Containers** (isolated alpine nodes mounting local folders).
  3. **Remote VMs** (interactive SSH sessions).

---

## 🛠️ Architecture & Deployment Model

> [!IMPORTANT]
> **NeuralLoom is a local/self-hosted orchestrator and cannot be deployed to serverless environments (like Vercel).**
> It depends on a persistent server runtime to manage active node-pty terminal threads, keep sockets connected, write to the local filesystem, and interface with Docker/SSH. 

### Core Components
1. **Next.js Frontend (Port 3000)**: Visual IDE layout containing the file explorer, Monaco-style editor textareas, resource telemetry gauges, and xterm.js terminals.
2. **Next.js Backend API routes**: Filesystem operations, git diff generator, context compilers, and launcher configurations.
3. **WebSocket Server Gateway (Port 3001)**: Intercepts raw keystrokes from the browser, pipes them to respective PTY child processes on the server, and routes stdout buffers back to the UI terminal wrapper.

## 🚀 Instant Run via npx (Recommended)

Since NeuralLoom is published on the NPM registry, you can start the orchestrator immediately in any workspace without cloning the code:

```bash
npx neural-loom
```

Alternatively, you can install it globally on your machine:

```bash
# Install globally
npm install -g neural-loom

# Run the command
neural-loom
```

Once started, open **[http://localhost:3000](http://localhost:3000)** in your browser to start launching and managing your AI coding agent sessions.

> [!NOTE]
> On Windows, ensure you run this command in a terminal that has access to Git Bash (for runner wrapping) and Node/NPM. If `npm` is not in your global path, you can prepend the path:
> ```powershell
> $env:Path = "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VisualStudio\NodeJs;" + $env:Path
> npx neural-loom
> ```

---

## 🏁 Getting Started (Manual Clone & Run)

### 1. Prerequisites
- **Node.js**: Version 18 or 20 (Required to compile `node-pty`).
- **Windows Build Tools**: If running on Windows, compile dependencies using Visual Studio Build Tools (C++ development workload).
- **Git Bash for Windows**: Ensure Git Bash is installed (used to safely wrapper shell prompts for node-pty).

### 2. Path Setup (Windows)
Prepend the Visual Studio Node.js build PATH to ensure all sub-PTYs can access standard command configurations. In PowerShell:
```powershell
$env:Path = "C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VisualStudio\NodeJs;" + $env:Path
```

### 3. Installation
Clone the repository and install npm packages:
```bash
npm install
```

### 4. Running the Dev Server
Launches the Next.js app and the background WebSocket gateway concurrently:
```bash
npm run dev
```
Open **[http://localhost:3000](http://localhost:3000)** to launch your dashboard.

### 5. Compiling for Production Local Run
To build the bundle and boot up the production server locally:
```bash
# Clear any lock-induced cache
rm -Force -Recurse .next

# Build the project
npm run build

# Start production server
npm run start
```

---

## 📂 Project Directory Structure

```
neural-loom/
├── src/
│   ├── app/
│   │   ├── api/
│   │   │   ├── context/          # Claude & Aider wizard launchers persistence API
│   │   │   ├── files/            # File tree explorer and editor actions (read/write/delete)
│   │   │   ├── git/              # Porcelain status and diff reader
│   │   │   └── sessions/         # Launch, stats, and injection routes
│   │   ├── components/
│   │   │   ├── ClaudeWizard.tsx  # Claude session workspace launch configuration modal
│   │   │   ├── AiderWizard.tsx   # Aider session launch modal (flags and keys)
│   │   │   ├── SshWizard.tsx     # SSH VM credential tester
│   │   │   ├── IdeLayout.tsx     # Workspace controller (Tab switcher, Split Terminal)
│   │   │   └── TerminalConsole.tsx # xterm.js socket bridge wrapper
│   │   ├── page.tsx              # Main dashboard launcher view
│   │   └── layout.tsx            # Theme wrapper and HTML document
│   └── lib/
│       └── agents/
│           ├── AgentRunner.ts    # Base class parsing logs and piping buffers
│           ├── ClaudeRunner.ts   # Local Claude Code process configuration
│           ├── DockerRunner.ts   # Alpine sandbox launcher mounting workspaces
│           ├── SSHRunner.ts      # VM CLI connector
│           ├── WebSocketServer.ts # WS Gateway forwarding user inputs to terminals
│           └── SessionManager.ts # Session lifecycles (resume, start, kill)
└── .ai/
    └── neural-loom/              # Local persisted runtime DB (claude.json, aider.json, ssh.json)
```

---

## 🛠️ Troubleshooting

### EPERM errors during `npm run build`
On Windows, sometimes system processes lock the `.next` compilation folder. Run the following clean script before rebuilding:
```powershell
Remove-Item -Recurse -Force .next
npm run build
```

### Git Bash not found
If Git Bash is installed in a non-standard directory, set the path explicitly in your environment variables:
```powershell
$env:WINGMAN_BASH_PATH = "C:\Your\Path\To\bash.exe"
```
