## PROJECT OVERVIEW
**Project Name:** Agent Guard
**Value Proposition:** Agent Guard is a revolutionary SaaS platform designed to provide robust security and containment for AI agents operating on user systems, particularly Linux environments. It addresses the critical and growing problem of AI agents with broad machine access causing accidental data loss, file corruption, or complete system wipes. Agent Guard allows users to grant AI agents controlled access to specific directories and workflows without handing over unfettered access to their entire system. By employing a "copy-on-write" overlay system and meticulous logging, Agent Guard ensures that AI interactions are confined, auditable, and reversible, empowering users to leverage AI tools with confidence and peace of mind.
**Problem Solved:** The core problem is the inherent risk associated with giving AI agents, especially those executed via simple commands or scripts, direct access to a user's filesystem. Incidents of data loss, emptied working directories, and wiped drives are increasingly reported. Existing solutions like full containerization (Docker, VMs) present a high barrier to entry for quick tasks, requiring complex setup and image management. Agent Guard bridges this gap by offering a lightweight, one-command solution for isolating AI agent workflows.
**Core Value:** "Go hard on agents, not on your filesystem." Agent Guard enables users to utilize powerful AI capabilities without compromising their data integrity and system security. It provides effortless containment, real-time monitoring, and a safety net for reversible actions.
## TECH STACK
- **Frontend Framework:** React with Next.js (App Router)
- **Styling:** Tailwind CSS
- **ORM:** Drizzle ORM (PostgreSQL or SQLite)
- **Database:** PostgreSQL (recommended for production) or SQLite (for local development/simplicity)
- **Authentication:** NextAuth.js (or Clerk for a managed solution)
- **UI Library:** shadcn/ui (for accessible, themeable components)
- **State Management:** React Context API / Zustand (for global state), Component-level state
- **Form Handling:** React Hook Form + Zod (for validation)
- **API Layer:** Next.js API Routes (Server Actions)
- **Deployment:** Vercel (recommended for Next.js)
- **Other Packages:** `lucide-react` (icons), `clsx` (classnames), `tailwind-merge`, date-fns/moment (date formatting), charting library (e.g., Recharts or Chart.js for monitoring visualization)
## DATABASE SCHEMA
**1. `users` Table:**
- `id` (UUID, PK)
- `name` (VARCHAR)
- `email` (VARCHAR, UNIQUE)
- `emailVerified` (TIMESTAMP, nullable)
- `image` (VARCHAR, nullable)
- `createdAt` (TIMESTAMP, default: now())
- `updatedAt` (TIMESTAMP, default: now())
**2. `agents` Table:**
- `id` (UUID, PK)
- `userId` (UUID, FK to `users.id`)
- `name` (VARCHAR, not null)
- `description` (TEXT, nullable)
- `executionPath` (VARCHAR, not null) - The directory where the agent is configured to run.
- `createdAt` (TIMESTAMP, default: now())
- `updatedAt` (TIMESTAMP, default: now())
**3. `agentRuns` Table:**
- `id` (UUID, PK)
- `agentId` (UUID, FK to `agents.id`)
- `userId` (UUID, FK to `users.id`)
- `commandExecuted` (TEXT, not null) - The actual command or script executed by the agent.
- `startTime` (TIMESTAMP, default: now())
- `endTime` (TIMESTAMP, nullable)
- `status` (VARCHAR, e.g., 'running', 'completed', 'failed', 'reverted')
- `overlayId` (UUID, FK to `overlays.id`, nullable) - Links to the overlay session if applicable.
- `stdout` (TEXT, nullable) - Standard output from the command.
- `stderr` (TEXT, nullable) - Standard error from the command.
**4. `overlays` Table:**
- `id` (UUID, PK)
- `agentRunId` (UUID, FK to `agentRuns.id`)
- `basePath` (VARCHAR, not null) - The root directory of the overlay session.
- `overlayPath` (VARCHAR, not null) - The temporary path where changes are staged.
- `state` (JSON, nullable) - Stores diffs or change manifests.
- `createdAt` (TIMESTAMP, default: now())
- `isActive` (BOOLEAN, default: true)
**5. `permissions` Table:**
- `id` (UUID, PK)
- `agentId` (UUID, FK to `agents.id`)
- `userId` (UUID, FK to `users.id`)
- `path` (VARCHAR, not null) - The specific file or directory path granted access.
- `accessType` (VARCHAR, e.g., 'read', 'write', 'execute')
- `isRecursive` (BOOLEAN, default: false)
- `createdAt` (TIMESTAMP, default: now())
**Relationships:**
- One `user` can have many `agents`.
- One `agent` can have many `agentRuns`.
- One `agent` can have many `permissions`.
- One `agentRun` can be associated with one `overlay` (during execution).
## CORE FEATURES & USER FLOW
**1. User Authentication & Management:**
- **Flow:** Users sign up/log in using email/password or OAuth (Google, GitHub). Upon successful login, they are directed to their dashboard.
- **Functionality:** Secure authentication, profile management (name, image).
**2. Agent Registration & Configuration:**
- **Flow:** Authenticated user navigates to 'Agents' -> 'Add New Agent'. User provides a name, description, and crucially, the `executionPath` (e.g., `/home/user/projects/ai_projects`). User then defines specific file/directory `permissions` (e.g., `/home/user/projects/ai_projects/data` with 'read' access, `/home/user/projects/ai_projects/src` with 'read', 'write', 'execute').
- **Functionality:** CRUD operations for agents. Permission management interface allowing path specification and access type selection (read, write, execute).
**3. Secure Agent Execution:**
- **Flow:** User selects an agent from their list and initiates an execution, providing the command/script to run (e.g., `python train.py --data ./data/input.csv`). Agent Guard intercepts this command. It verifies the `executionPath` and `permissions` associated with the agent. An overlay is created at the `executionPath`. The command is executed within this isolated overlay environment. `stdout` and `stderr` are captured. If the command completes successfully, the user is prompted to review changes made within the overlay. If approved, changes are merged to the real filesystem; otherwise, they are discarded, and the overlay is removed.
- **Functionality:** Command interception, overlay creation (using tools like `overlayfs` or similar techniques at the OS level if possible, or simulating it via file operations), execution sandboxing, capturing output, user confirmation for file system changes.
**4. Monitoring & Logging:**
- **Flow:** User navigates to the 'Activity Log' or 'Agent Runs' section. They see a list of past and current agent executions, their status (running, completed, failed), duration, and the command executed. Clicking on a specific run shows detailed `stdout`, `stderr`, and a diff view of the changes made (if any) during the overlay session.
- **Functionality:** Real-time activity feed, historical log retrieval, detailed run analysis, diff visualization.
**5. Overlay Management & Reversion:**
- **Flow:** During execution or after completion, if a user decides a command had unintended consequences, they can navigate to the specific `agentRun` and select 'Revert Changes'. Agent Guard will then undo the file modifications recorded in the overlay for that specific run.
- **Functionality:** Rollback mechanism for file system changes made during an agent run via the overlay.
## API & DATA FETCHING
- **Authentication:** Handled by NextAuth.js, providing session data to server components and API routes.
- **Agent Management API (Server Actions / API Routes):**
- `POST /api/agents`: Create a new agent.
- `GET /api/agents`: Get list of agents for the logged-in user.
- `GET /api/agents/{id}`: Get details of a specific agent.
- `PUT /api/agents/{id}`: Update an agent (permissions, path, etc.).
- `DELETE /api/agents/{id}`: Delete an agent.
- **Agent Execution API (Server Actions):**
- `POST /api/agents/run`: Trigger an agent execution. Accepts agent ID and command. Returns an `agentRunId`.
- `GET /api/agents/run/{runId}`: Get status and output of a specific agent run. Used for polling.
- `POST /api/agents/run/{runId}/confirm`: User confirms changes made by the agent run.
- `POST /api/agents/run/{runId}/revert`: User requests to revert changes made by the agent run.
- **Data Fetching:** Use Server Components for initial data loading (agents list, dashboard stats). Use Client Components with `useEffect` or SWR/React Query for polling run status and real-time updates. API routes/Server Actions will interact directly with Drizzle ORM to query/mutate the database.
**Example Request Body (POST /api/agents/run):**
```json
{
"agentId": "uuid-of-agent",
"command": "ls -la /home/user/projects/ai_projects/data"
}
```
**Example Response Body (POST /api/agents/run):**
```json
{
"agentRunId": "uuid-of-run",
"status": "running"
}
```
## UI/UX DESIGN & VISUAL IDENTITY
- **Design Style:** Modern, Clean, and Trustworthy. Emphasis on clarity, security, and control.
- **Color Palette:**
- Primary: `#1E3A8A` (Deep Blue - conveys trust, stability)
- Secondary: `#2563EB` (Bright Blue - for calls to action, highlights)
- Accent: `#6366F1` (Indigo - for subtle highlights, graphs)
- Background: `#F3F4F6` (Light Gray)
- Card/Surface: `#FFFFFF` (White)
- Text (Primary): `#1F2937` (Dark Gray)
- Text (Secondary): `#6B7280` (Medium Gray)
- Success: `#10B981` (Green)
- Warning/Revert: `#F59E0B` (Amber)
- Danger/Error: `#EF4444` (Red)
- **Typography:** Inter (or similar sans-serif like Roboto) - Clean, readable, modern.
- Headings: Inter Bold
- Body Text: Inter Regular
- **Layout:**
- Sidebar Navigation (Dashboard, Agents, Activity Log, Settings).
- Main content area using cards and clear section dividers.
- Responsive: Mobile-first approach, adapting to tablet and desktop gracefully. Sidebar collapses on smaller screens.
- **Visual Elements:** Subtle use of gradients in headers or buttons. Iconography (Lucide React) for actions and status indicators. Clear visual distinction between 'safe' and 'monitored' areas.
## COMPONENT BREAKDOWN (Next.js App Router)
- **`app/layout.tsx`:** Root layout, includes global providers (Auth, Theme), Tailwind CSS setup, global styles.
- **`app/(auth)/layout.tsx`:** Layout for auth pages (Login, Signup).
- **`app/(auth)/login/page.tsx`:** Login form component.
- **`app/(auth)/signup/page.tsx`:** Signup form component.
- **`app/(app)/layout.tsx`:** Main application layout with sidebar and header.
- **`app/(app)/dashboard/page.tsx`:** Dashboard overview (summary stats: active agents, recent runs, security status).
- Components: `StatCard`, `RecentRunsTable`, `SecurityStatusWidget`.
- **`app/(app)/agents/page.tsx`:** List of registered agents.
- Components: `AgentList`, `AgentListItem`, `AddAgentButton`.
- **`app/(app)/agents/[agentId]/page.tsx`:** Detailed view of a single agent, including configuration and permissions.
- Components: `AgentConfigForm`, `PermissionManager`, `RunAgentButton`.
- **`app/(app)/activity/page.tsx`:** Log of all agent execution activities.
- Components: `ActivityLogTable`, `LogEntryDetails` (modal or separate page).
- **`app/(app)/settings/page.tsx`:** User settings page.
- **`app/api/auth/[...nextauth]/route.ts`:** NextAuth.js route handler.
- **`components/ui/`:** Re-exported shadcn/ui components (Button, Input, Card, Table, Alert, etc.).
- **`components/layout/`:** `Sidebar`, `Header`, `PageWrapper`.
- **`components/forms/`:** `AgentForm`, `PermissionForm`.
- **`components/`:** `AgentListItem`, `StatCard`, `RunStatusIndicator`, `DiffViewer`.
**State Management:**
- **Global:** Auth status (via NextAuth context), UI theme.
- **Page-level:** Data fetched for the specific page (e.g., list of agents), form states.
- **Component-level:** Local UI state (e.g., modal open/closed, input field values).
## ANIMATIONS
- **Page Transitions:** Subtle fade-in/slide-in for new pages/content using Next.js `app/(app)/layout.tsx` and potentially a library like `Framer Motion` if more complex animations are needed.
- **Button Interactions:** Slight scale-down on click, subtle background color change on hover.
- **Loading States:** Skeleton loaders for data tables and cards. Spinner animations within buttons when submitting forms or triggering actions.
- **Data Updates:** Gentle highlighting or subtle animations on table rows/cards when data updates (e.g., status change in `ActivityLogTable`).
- **Hover Effects:** Subtle background highlights on list items (agents, log entries).
## EDGE CASES
- **Authentication:**
- Unauthenticated access to protected routes redirects to login.
- Session expiry handling.
- **Authorization:** Users can only access their own agents and data.
- **Empty States:** Dashboard, Agent List, and Activity Log should display informative messages and clear calls to action when empty (e.g., "You haven't created any agents yet. [Add Agent]").
- **Form Validation:** Client-side and server-side validation for all forms (agent creation, permissions) using Zod and React Hook Form. Clear error messages displayed near the relevant fields.
- **Agent Execution Errors:**
- Command not found within the container/overlay.
- Permission denied errors (even within the overlay, if restricted).
- Overlay creation failure.
- Handle `stdout` and `stderr` gracefully, displaying them to the user.
- **File System Interaction:** Robust handling of file operations within the overlay. Ensure `copy-on-write` logic is sound. Handle potential race conditions.
- **Network Errors:** Graceful handling of API request failures (e.g., using SWR/React Query with error fallback UI).
- **Agent Path:** Validation that the `executionPath` is a valid, accessible directory.
## SAMPLE DATA
**1. Agent Data:**
```json
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"userId": "user-uuid-1234",
"name": "Code Linter Agent",
"description": "Lints Python code in the src directory.",
"executionPath": "/home/developer/my_project",
"createdAt": "2023-10-26T10:00:00Z",
"updatedAt": "2023-10-26T10:00:00Z"
}
```
**2. Permissions Data (for the above agent):**
```json
[
{
"id": "p1",
"agentId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"userId": "user-uuid-1234",
"path": "/home/developer/my_project/src",
"accessType": "read",
"isRecursive": true,
"createdAt": "2023-10-26T10:05:00Z"
},
{
"id": "p2",
"agentId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"userId": "user-uuid-1234",
"path": "/home/developer/my_project/pyproject.toml",
"accessType": "read",
"isRecursive": false,
"createdAt": "2023-10-26T10:06:00Z"
}
]
```
**3. Agent Run Data (Running):**
```json
{
"id": "ar987654-dcba-0987-6543-210fedcba987",
"agentId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"userId": "user-uuid-1234",
"commandExecuted": "flake8 /home/developer/my_project/src",
"startTime": "2023-10-27T14:30:00Z",
"endTime": null,
"status": "running",
"overlayId": "ov112233-aabb-4455-6677-8899aabbccdd",
"stdout": "",
"stderr": ""
}
```
**4. Agent Run Data (Completed with changes):**
```json
{
"id": "ar111111-aaaa-0000-1111-222222cccccc",
"agentId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"userId": "user-uuid-1234",
"commandExecuted": "touch /home/developer/my_project/src/new_file.py",
"startTime": "2023-10-27T15:00:00Z",
"endTime": "2023-10-27T15:00:05Z",
"status": "completed",
"overlayId": null, // Overlay likely cleaned up after confirmation
"stdout": "",
"stderr": ""
}
```
**5. Agent Run Data (Failed):**
```json
{
"id": "ar333333-bbbb-1111-2222-333333dddddd",
"agentId": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"userId": "user-uuid-1234",
"commandExecuted": "python /home/developer/my_project/invalid_script.py",
"startTime": "2023-10-27T15:10:00Z",
"endTime": "2023-10-27T15:10:01Z",
"status": "failed",
"overlayId": "ov998877-ddee-6655-4433-2211aabb00ff",
"stdout": "",
"stderr": "python: can't open file '/home/developer/my_project/invalid_script.py': [Errno 2] No such file or directory"
}
```
**6. Example Dashboard Stats:**
```json
{
"totalAgents": 5,
"runningAgentRuns": 1,
"completedRunsLast24h": 15,
"failedRunsLast24h": 1
}
```
**7. Example Activity Log Entry:**
```json
{
"runId": "ar111111-aaaa-0000-1111-222222cccccc",
"agentName": "Code Linter Agent",
"command": "touch /home/developer/my_project/src/new_file.py",
"status": "completed",
"startTime": "2023-10-27T15:00:00Z",
"durationSeconds": 5
}
```