Skip to content

Commit 22e3226

Browse files
committed
docs: add comprehensive architecture, gpu scaling, integration, skeptic, and replay guides
1 parent 471113b commit 22e3226

5 files changed

Lines changed: 312 additions & 0 deletions

File tree

docs/architecture.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# 🏗️ Architecture Guide
2+
3+
GhostCoder operates as a decentralized, event-driven assistant running entirely locally. It bridges the gap between your workspace (IDE/Editor), your terminal (Shell), and local Large Language Models (via Ollama) without requiring any cloud APIs or external telemetry.
4+
5+
```mermaid
6+
graph TD
7+
subgraph Client / Environment
8+
Shell[Shell Hooks: Bash/Zsh]
9+
Editor[Editor Plugins: Neovim/VSCode]
10+
end
11+
12+
subgraph GhostCoder Daemon
13+
IPC[IPC Server: Unix Socket / TCP]
14+
Observer[Workspace Watcher: Watchdog]
15+
Session[Session Tracker: JSON DB]
16+
Brain[Ghost Brain Router]
17+
Skeptic[Ghost Skeptic Validator]
18+
ModelMgr[Model Manager]
19+
end
20+
21+
subgraph Local LLM Provider
22+
Ollama[Ollama API]
23+
end
24+
25+
Shell -->|Command Pre/Post Events| IPC
26+
Editor -->|Cursor/Editor Changes| IPC
27+
Observer -->|File Write Events| Session
28+
IPC -->|Trigger Action| Brain
29+
Brain -->|Route to Specialist Agent| ModelMgr
30+
ModelMgr -->|classification/generation| Ollama
31+
ModelMgr -->|adversarial check| Skeptic
32+
Skeptic -->|JSON challenge| Ollama
33+
Brain -->|Return approved hint/fix| IPC
34+
IPC -->|Push Inline Hint| Editor
35+
```
36+
37+
---
38+
39+
## 📡 The Daemon & IPC Protocol
40+
The background daemon (`ghostcoder start`) starts an asynchronous server. By default, it attempts to bind to a Unix Domain Socket at `~/.ghostcoder/ghostcoder.sock`. If running on an unsupported platform or environment, it falls back to a local loopback TCP port (`48673`).
41+
42+
### Core IPC Message Schema
43+
Clients (IDE plugins, shell wrappers) exchange JSON payloads terminated by newlines (`\n`):
44+
45+
* **`editor_change`**: Sent by the IDE on cursor movement or document modification. Contains file paths, active lines, and raw buffer contents.
46+
* **`command_pre` / `command_post`**: Sent by shell hook scripts when a terminal command is run and when it finishes (capturing status codes and stderr output).
47+
* **`status_request`**: Queried by the CLI to retrieve active VRAM consumption, GPU tier metrics, loaded models, and stack definitions.
48+
* **`reload_config`**: Used by the CLI client to notify a running daemon of configuration changes, triggering hot-swapping of models.
49+
50+
---
51+
52+
## 🧠 Ghost Brain Routing
53+
When an event (like a command failure or code edit matching a structural vulnerability) is sent to the daemon, the **Ghost Brain Router** resolves the context:
54+
55+
1. **Tech Stack Detection**: It inspects file extensions and manifests to identify project technologies (e.g., Node.js, Python, Rust).
56+
2. **Specialist Agent Selection**: The classification model routes the situation to the most relevant engineering specialist (e.g., `agency-application-security-engineer`, `agency-devops-automator`, or `agency-senior-developer`).
57+
3. **Prompt Assembly**: The system prompt is dynamically assembled from the selected agent's instructions.
58+
4. **Generation & Skeptic Validation**: The suggestion is produced by the Coder model and validated by the Ghost Skeptic before being returned to the IDE.
59+
60+
---
61+
62+
## 💾 Session Tracker & Replay DB
63+
All events, raw error messages, model prompts, and user interactions (apply, dismiss) are logged to a local JSON database at `~/.ghostcoder/sessions/`. This transaction log serves as the single source of truth for replay automation and explanation commands.

docs/gpu_scaling.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# ⚡ GPU Scaling & Model Presets Guide
2+
3+
GhostCoder features a dynamic **GPU Auto-Scaling engine** that auto-detects your local GPU hardware VRAM capacity and automatically loads the largest compatible models.
4+
5+
---
6+
7+
## 📟 GPU Tier System
8+
When the daemon initializes, it parses `nvidia-smi` (or platform equivalents) to estimate VRAM availability and assigns a hardware profile:
9+
10+
| Profile Tier | VRAM Capacity | Max Model Size | Classifier Model | Coder Model | Reasoner Model | Skeptic Model |
11+
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
12+
| **`entry`** | < 6 GB | 3B params | `qwen2.5:0.5b` | `qwen2.5-coder:1.5b` | `qwen2.5-coder:1.5b` | `qwen2.5:0.5b` |
13+
| **`mid`** | 6 - 12 GB | 7B params | `qwen2.5:0.5b` | `qwen2.5-coder:7b` | `qwen2.5-coder:7b` | `qwen2.5:0.5b` |
14+
| **`high`** | 12 - 20 GB | 14B params | `qwen2.5:0.5b` | `qwen2.5-coder:14b` | `deepseek-coder:6.7b` | `qwen2.5:3b` |
15+
| **`workstation`** | 20 - 48 GB | 32B params | `qwen2.5:3b` | `qwen2.5-coder:32b` | `deepseek-coder:33b` | `qwen2.5:7b` |
16+
| **`datacenter`** | >= 48 GB | 72B param+ | `qwen2.5:7b` | `qwen2.5-coder:72b` | `deepseek-coder:33b` | `qwen2.5:14b` |
17+
18+
---
19+
20+
## 💾 Memory Allocations & Keep-Alive Lifecycle
21+
To operate seamlessly alongside other user processes, GhostCoder implements strict VRAM management:
22+
23+
1. **VRAM Limit**: The maximum memory allowed for models is calculated as `min(Total_VRAM * 85%, Total_VRAM - Headroom)`. The default safety headroom is `500 MB`.
24+
2. **Continuous Classifier**: The fast classifier model is loaded permanently with `keep_alive = -1`.
25+
3. **On-Demand Coder**: The heavier Coder model is loaded only when generating a suggestion.
26+
4. **Auto-Unload Guard**: When loading the Coder model would violate the VRAM budget limit, GhostCoder automatically triggers an eviction command to unload any other active models from Ollama memory (`keep_alive = 0`). Once idle for `30 seconds`, the Coder model is automatically unloaded to free VRAM.
27+
28+
---
29+
30+
## ⚙️ Hardware Overrides & Hot-Swapping
31+
32+
### Project and Global Configuration File
33+
You can override hardware-detected defaults using global or local YAML configurations:
34+
- **Global**: `~/.ghostcoder/config.yaml`
35+
- **Per-Project**: `.ghostcoder/config.yml` in your project root.
36+
37+
```yaml
38+
# Override config.yaml example
39+
gpu_tier: workstation
40+
model_coder: deepseek-coder:33b
41+
vram_headroom_mb: 1000
42+
```
43+
44+
### CLI Overrides
45+
Configure settings directly from the terminal. If the background daemon is running, it will be notified and hot-swap its models immediately:
46+
```bash
47+
# Force a mid-range GPU tier profile
48+
ghostcoder config --gpu-tier mid
49+
50+
# Customize the code generation model
51+
ghostcoder config --model-coder deepseek-coder:6.7b
52+
53+
# View active GPU metrics and configuration
54+
ghostcoder status
55+
```

docs/integrations.md

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# 🔌 Shell & Editor Integrations
2+
3+
GhostCoder hooks directly into your shell session and your editor via an asynchronous IPC broker, providing zero-latency assistance as you work.
4+
5+
---
6+
7+
## 🐚 Shell Hook Setup
8+
9+
During initialization (`ghostcoder init`), shell scripts are configured to hook into your prompt lifecycle.
10+
11+
### How it works
12+
The scripts define command hook wrappers (`preexec` and `precmd` equivalents):
13+
- **`command_pre`**: Triggered before a command starts execution. It alerts the daemon to temporarily pause editor file watches or prepare context.
14+
- **`command_post`**: Triggered immediately after a command finishes. It captures:
15+
- Command exit status code.
16+
- Errors from `stderr`.
17+
- Directory stack info.
18+
19+
If a command fails (exit code > 0), the wrapper sends a payload to the daemon over TCP/Unix sockets.
20+
21+
---
22+
23+
## 💤 Neovim Integration
24+
25+
The Neovim plugin hooks into editor events using autocmd rules.
26+
27+
### Installation
28+
Add the following template to your Neovim configurations (`init.lua` or your plugin manager directory):
29+
30+
```lua
31+
-- lazy.nvim Example
32+
{
33+
"anujsingh-cse/GhostCoder",
34+
event = { "BufReadPost", "BufNewFile" },
35+
config = function()
36+
local gc = require("ghostcoder")
37+
gc.setup({
38+
socket_path = "~/.ghostcoder/ghostcoder.sock",
39+
enable_inline_virtual_text = true,
40+
highlight_groups = {
41+
suggestion = "Comment",
42+
warning = "DiagnosticWarn"
43+
}
44+
})
45+
end
46+
}
47+
```
48+
49+
### Event Listeners
50+
- **CursorHold / CursorMoved**: Periodically reports active file path and cursor line position to the daemon.
51+
- **TextChanged / TextChangedI**: Notifies the daemon of buffer changes, updating hashes used for dynamic context matching.
52+
53+
---
54+
55+
## 💻 VS Code Extension
56+
57+
The VS Code extension exposes inline recommendations utilizing standard `vscode.languages` diagnostics and inline decoration APIs.
58+
59+
### Setup
60+
Ensure the Extension configuration specifies the correct fallback port or IPC domain path:
61+
62+
```json
63+
{
64+
"ghostcoder.socketPath": "~/.ghostcoder/ghostcoder.sock",
65+
"ghostcoder.fallbackPort": 48673,
66+
"ghostcoder.showHintsInline": true
67+
}
68+
```
69+
70+
The extension automatically creates a socket channel client to connect with the local daemon on startup, parsing any returned JSON messages to inject annotations directly.

docs/replay_and_audit.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# 🔁 Replay & Audit Trail Guide
2+
3+
Every event, routing decision, code evaluation, and model response in GhostCoder is tracked in a transparent audit ledger. This allows you to inspect, review, and reproduce any changes.
4+
5+
---
6+
7+
## 💾 The Ledger System
8+
9+
Logs are saved as discrete session transactions in your local folder:
10+
`~/.ghostcoder/sessions/`
11+
12+
Each session file contains sequential events:
13+
14+
```json
15+
{
16+
"session_id": "20260716-112000",
17+
"git_branch": "main",
18+
"project_path": "/users/developer/ghostcoder",
19+
"events": [
20+
{
21+
"timestamp": 1784175600.123,
22+
"event_type": "command_failed",
23+
"command": "npm run test",
24+
"exit_code": 1,
25+
"stderr": "TypeError: Cannot read properties of undefined (reading 'config')"
26+
},
27+
{
28+
"timestamp": 1784175601.456,
29+
"event_type": "agent_suggestion_generated",
30+
"agent": "agency-senior-developer",
31+
"prompt_hash": "a8e9f2d...",
32+
"suggestion": "Initialize the config object before parsing...",
33+
"skeptic_challenges": []
34+
}
35+
]
36+
}
37+
```
38+
39+
---
40+
41+
## 🔍 CLI Audit Commands
42+
43+
Use these CLI utilities to audit and replay past actions.
44+
45+
### 1. Explain Decisions
46+
To query the AI logic behind a specific suggestion:
47+
```bash
48+
ghostcoder explain --session <session_id> --event <event_index>
49+
```
50+
*Outputs: The original code, the exact agent instructions, the stderr traceback, and the reasoning path chosen by the models.*
51+
52+
### 2. Activity Reporting
53+
Generate a summary report of issues encountered, agent routing statistics, and fix success rates:
54+
```bash
55+
# Get a summary of the current week
56+
ghostcoder report --period week
57+
58+
# Get a summary of the current month
59+
ghostcoder report --period month
60+
```
61+
62+
### 3. Session Replay
63+
If you reset your workspace or branch and want to re-apply all code modifications proposed during a session:
64+
```bash
65+
ghostcoder replay --session <session_id>
66+
```
67+
*This parses the transaction log and safely applies all accepted code edits to matching lines in the workspace.*

docs/skeptic_and_safety.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# 🛡️ Ghost Skeptic & Safety Guardrails Guide
2+
3+
GhostCoder implements dual-layer safety validation to prevent incorrect code insertion and protect developers from executing destructive operations.
4+
5+
---
6+
7+
## 🔁 Ghost Skeptic: Adversarial Self-Validation
8+
9+
Every time an engineering specialist agent generates a fix or code block, it is intercepted and evaluated by a separate **Ghost Skeptic** workflow.
10+
11+
```
12+
[Brain Specialist Agent] ──> Proposes Suggested Fix
13+
14+
15+
[Ghost Skeptic Agent] ──> Evaluates Suggestion against original code and context
16+
17+
┌─────────────────┴─────────────────┐
18+
▼ ▼
19+
[No Flaws Found] [Flaws Detected]
20+
│ │
21+
▼ ▼
22+
Approve suggestion for User Attempt Auto-Correction
23+
(Max 3 iterations)
24+
25+
26+
Inject Warning or Block
27+
```
28+
29+
### Skeptic Evaluation Prompts
30+
The Skeptic runs with a temperature of `0.1` and uses a structured schema to enforce logical consistency:
31+
32+
```json
33+
{
34+
"challenges": [
35+
{
36+
"flaw": "Removes a variable validation check, introducing a Potential NoneType dereference.",
37+
"severity": "critical",
38+
"scenario": "When lookup returns null and caller accesses profile properties",
39+
"fix": "Reintroduce if user is not None check before dereference.",
40+
"confidence": 0.98
41+
}
42+
],
43+
"improved_fix": "A corrected code block incorporating the re-added check."
44+
}
45+
```
46+
47+
---
48+
49+
## 🧱 Static Command Guardrails
50+
51+
GhostCoder intercepts and screens terminal commands and proposed code changes against a blocklist of high-risk operational patterns.
52+
53+
### Enforced Rules
54+
55+
1. **Destructive Operations**: Prohibits any command or patch containing unchecked database drop statements (`DROP DATABASE`, `DROP TABLE` without confirmation).
56+
2. **Unbounded Deletions**: Flags or blocks recursive file system removal statements containing wildcards or targeting system paths (e.g., `rm -rf /`, `rm -rf *` inside critical workspace directories).
57+
3. **Command Execution Blocks**: If an inline suggestion contains commands, they are shown in red to the user in the IDE and require manual copy-paste confirmation to execute (they are never run silently).

0 commit comments

Comments
 (0)