# OGFocus Agent Integration Guide (`agentguide.md`)

> **The Execution Operating System for Builders & Autonomous Agents**  
> Use this guide to connect any AI Agent, IDE (Cursor, Claude Code, Antigravity), project board (Dots, Group Board), webhook, or automated bot directly to an OGFocus account.

---

## 1. Quick Start & Authentication

All Agent API requests require two secure authentication headers:

```http
X-OGFOCUS-KEY: <YOUR_API_KEY>
X-OGFOCUS-SECRET: <YOUR_API_SECRET>
Content-Type: application/json
```

*Alternative Bearer format:*  
`Authorization: Bearer <YOUR_API_KEY>:<YOUR_API_SECRET>`

### Base API URLs & Direct Documentation Access
- **Production API:** `https://www.ogfocus.com/api/v1/agent`
- **Local Dev API:** `http://localhost/ogfocus.com/api/v1/agent`
- **Direct Guide URL (Public Markdown):** `https://www.ogfocus.com/agentguide.md` or `https://www.ogfocus.com/api/v1/agent/guide`
- **Dashboard Download Link:** `https://www.ogfocus.com/u/download-agent-guide.php`

*(The API supports both REST paths like `/tasks` and query actions like `?action=create_task` for universal compatibility across all frameworks and agents).*

---

## 2. System Instructions for AI Agents (Copy-Paste)

Feed this prompt directly to your autonomous AI Agent (e.g., Cursor Rules, Claude System Prompt, AutoGPT, LangChain):

```markdown
You are an autonomous Execution Partner integrated with OGFocus.
Your objective is to help the user execute relentlessly: organize boards, assign and complete tasks, track daily discipline habits, and log code submissions.

API Base URL: https://www.ogfocus.com/api/v1/agent
Headers:
  X-OGFOCUS-KEY: [YOUR_API_KEY]
  X-OGFOCUS-SECRET: [YOUR_API_SECRET]
  Content-Type: application/json

Core Rules:
1. Backlog Inspection: Always check pending tasks before beginning work:
   - Call: GET /tasks?status=pending (supports page=1&limit=50 or all=1 to fetch all tasks)
2. Task Assignment: When the user assigns work or when creating milestones from a board (e.g. dots, group board):
   - Call: POST /tasks
3. Board Movement: When moving a task to a project or backlog/inbox:
   - Call: POST /tasks/move with {"task_id": 123, "project_id": 4} (or null project_id for Inbox)
4. Projects & Missions: When creating higher-level project boards or missions:
   - Call: POST /projects or POST /missions
5. Code Submissions: When finishing a coding feature, submit the code patch and mark the task completed in one request:
   - Call: POST /code with {"mark_task_completed": true}
6. Daily Discipline: When managing discipline, create or log daily habits:
   - Call: POST /habits and POST /habits/log
7. Gamification Integrity: Gamification metrics (Karma, Integrity, Rank) are strictly governed server-side. Never attempt to forge scores.
```

---

## 3. Endpoints Matrix & Reference

### 3.1. Profile & Gamification Stats
Check the user's current rank, Karma, integrity percentage, and task totals.

- **Request:** `GET /me` (or `?action=get_me`)
- **Headers:** `X-OGFOCUS-KEY`, `X-OGFOCUS-SECRET`
- **Response Example:**
```json
{
  "success": true,
  "data": {
    "user": {
      "id": 12,
      "username": "alexbuilder",
      "full_name": "Alex Vance",
      "role": "user"
    },
    "gamification": {
      "karma": 480,
      "rank": "Relentless",
      "integrity_percentage": 94,
      "active_days": 21,
      "focus_blocks_completed": 35,
      "commitments_kept": 58,
      "tasks_completed": 42,
      "tasks_pending": 7,
      "active_habits_count": 5
    }
  },
  "message": "Profile retrieved successfully."
}
```

---

### 3.2. Tasks & Boards Management

#### A. List Tasks (With Real Pagination)
- **Request:** `GET /tasks` (or `?action=get_tasks`)
- **Query Parameters:**
  - `status`: `'pending'` (default), `'completed'`, or `'all'`
  - `page`: page number (1-based, default `1`)
  - `limit`: number of tasks per page (default `50`, max `200`)
  - `all`: pass `1` or `true` to fetch all tasks (up to 1,000) in a single request
  - `priority`: `'high'`, `'medium'`, `'low'`
  - `project_id`: filter by project ID
  - `is_top_priority`: `1` or `0`
- **Response Schema:**
```json
{
  "success": true,
  "data": {
    "tasks": [
      {
        "id": 105,
        "title": "Implement Webhook Verification for Dots Board",
        "notes": "Verify HMAC SHA256 signature on incoming board webhooks",
        "priority": "high",
        "status": "pending",
        "is_completed": false,
        "is_top_priority": true,
        "due_date": "2026-10-15",
        "project_id": 4,
        "project_name": "Payment Gateway",
        "created_at": "2026-10-03 14:00:00",
        "completed_at": null,
        "subtasks": [
          {
            "id": 106,
            "title": "Generate secret token in dashboard",
            "is_completed": false
          }
        ]
      }
    ],
    "pagination": {
      "total": 84,
      "page": 1,
      "limit": 50,
      "total_pages": 2,
      "has_next": true,
      "has_prev": false
    }
  },
  "message": "Tasks retrieved successfully."
}
```

#### B. Create Task
Create a new task with optional subtasks, priority, and project mapping.
- **Request:** `POST /tasks` (or `?action=create_task`)
- **Payload Schema:**
```json
{
  "title": "Implement Webhook Verification for Dots Board",
  "notes": "Verify HMAC SHA256 signature on incoming board webhooks",
  "priority": "high",
  "is_top_priority": 1,
  "due_date": "2026-10-15",
  "project_id": 4,
  "subtasks": [
    "Generate secret token in dashboard",
    "Add signature check middleware",
    "Write automated integration test"
  ]
}
```

#### C. Mark Task Complete
Marks a task and all its child subtasks complete. Server automatically calculates and rewards authentic Karma!
- **Request:** `POST /tasks/complete` (or `POST /tasks/{id}/complete` or `?action=complete_task`)
- **Payload Schema:**
```json
{
  "task_id": 105
}
```
- **Response:**
```json
{
  "success": true,
  "data": {
    "task_id": 105,
    "status": "completed",
    "is_completed": true,
    "current_karma": 483,
    "integrity": 95
  },
  "message": "Task marked as completed! Karma score updated."
}
```

#### D. Move Task Between Projects or Inbox
Move an existing task to another project or return it to the root Inbox backlog.
- **Request:** `POST /tasks/move` (or `POST /tasks/{id}/move` or `?action=move_task`)
- **Payload Schema:**
```json
{
  "task_id": 105,
  "project_id": 4
}
```
*(Set `"project_id": null` or `0` to move the task back to the Inbox).*
- **Response:**
```json
{
  "success": true,
  "data": {
    "task_id": 105,
    "project_id": 4,
    "project_name": "Payment Gateway"
  },
  "message": "Task moved to project 'Payment Gateway'."
}
```

#### E. Update Task
- **Request:** `POST /tasks/update` (or `PUT /tasks/{id}` or `?action=update_task`)
- **Payload Schema:**
```json
{
  "task_id": 105,
  "title": "Updated Task Title",
  "priority": "high",
  "notes": "Updated instructions",
  "project_id": 4,
  "is_top_priority": false,
  "due_date": "2026-10-20"
}
```

#### F. Reopen / Uncomplete Task
Reopens a completed task and its child subtasks back to pending, updating server-side metrics.
- **Request:** `POST /tasks/reopen` (or `POST /tasks/{id}/reopen` or `?action=reopen_task`)
- **Payload Schema:** `{"task_id": 105}`

#### G. Delete Task
Soft-deletes a task. Enforces OGFocus standard: completed task Karma is never penalized or revoked.
- **Request:** `POST /tasks/delete` (or `DELETE /tasks/{id}` or `?action=delete_task`)
- **Payload Schema:** `{"task_id": 105}`

---

### 3.3. Projects & Missions (Board Mapping)

Use projects and missions to mirror your external boards (Dots, Group Boards, GitHub Projects):

#### A. List Projects & Missions
- **Request:** `GET /projects` (or `?action=get_projects`)
- **Response:**
```json
{
  "success": true,
  "data": {
    "missions": [
      {
        "id": 1,
        "title": "Q4 Revenue Scaling",
        "description": "Enterprise customer acquisition",
        "projects": [
          { "id": 4, "name": "Payment Gateway", "color": "#BFFF00" },
          { "id": 5, "name": "Customer Onboarding", "color": "#00FFF2" }
        ]
      }
    ],
    "standalone_projects": [
      { "id": 9, "name": "Dots Sync Board", "color": "#BFFF00" }
    ]
  }
}
```

#### B. Create Mission (High-Level Objective)
- **Request:** `POST /missions` (or `?action=create_mission`)
- **Payload Schema:**
```json
{
  "title": "Q4 Revenue Scaling",
  "description": "Enterprise customer acquisition"
}
```

#### C. Create Project (Board / Epic)
- **Request:** `POST /projects` (or `?action=create_project`)
- **Payload Schema:**
```json
{
  "name": "Dots Group Sync",
  "description": "Board synchronization for group members",
  "color": "#BFFF00",
  "mission_id": 1
}
```

---

### 3.4. Habit Tracking & Daily Discipline

#### A. List Active Habits
- **Request:** `GET /habits` (or `?action=get_habits`)
- **Query Parameters:** `date` (optional, defaults to today `YYYY-MM-DD`)
- **Response:**
```json
{
  "success": true,
  "data": [
    {
      "id": 7,
      "title": "Review Group Board & Pull Requests",
      "streak": 14,
      "is_completed_for_date": false,
      "frequency_type": "daily",
      "timer_duration": 30
    }
  ]
}
```

#### B. Create Habit
- **Request:** `POST /habits` (or `?action=create_habit`)
- **Payload Schema:**
```json
{
  "title": "Daily 45-Min Deep Work Code Block",
  "frequency_type": "daily",
  "timer_duration": 45
}
```

#### C. Log Habit Completion
- **Request:** `POST /habits/log` (or `?action=log_habit`)
- **Payload Schema:**
```json
{
  "habit_id": 7,
  "date": "2026-10-03",
  "completed": true,
  "notes": "Reviewed 4 PRs and assigned tasks on dots board."
}
```

---

### 3.5. Code Submissions & Dev Logs

External agents or CI/CD pipelines can submit code snippets, feature diffs, or commit logs directly to OGFocus.

- **Request:** `POST /code` (or `?action=submit_code`)
- **Payload Schema:**
```json
{
  "title": "Refactored JWT Auth Middleware",
  "code_content": "function verifyAuthToken($token) { ... }",
  "language": "php",
  "task_id": 105,
  "mark_task_completed": true,
  "commit_message": "feat(auth): verify JWT HMAC signature",
  "repository_url": "https://github.com/myorg/core-api",
  "branch": "main"
}
```
*Tip:* Setting `"mark_task_completed": true` automatically marks `task_id` completed and triggers server Karma calculations in a single atomic request!

---

### 3.6. Log Focus Sessions

- **Request:** `POST /focus` (or `?action=log_focus_session`)
- **Payload Schema:**
```json
{
  "duration_mins": 50,
  "completed": 1
}
```

---

## 4. Code Examples

### Python Example (Tasks, Pagination & Moving)
```python
import requests

API_URL = "https://www.ogfocus.com/api/v1/agent"
HEADERS = {
    "X-OGFOCUS-KEY": "YOUR_API_KEY",
    "X-OGFOCUS-SECRET": "YOUR_API_SECRET",
    "Content-Type": "application/json"
}

# 1. Fetch paginated pending tasks
res = requests.get(f"{API_URL}/tasks?status=pending&page=1&limit=50", headers=HEADERS)
data = res.json().get("data", {})
tasks = data.get("tasks", [])
pagination = data.get("pagination", {})
print(f"Loaded {len(tasks)} tasks out of {pagination.get('total', 0)} total.")

# 2. Create a project
proj_res = requests.post(f"{API_URL}/projects", json={
    "name": "Dots Sprint 12",
    "color": "#BFFF00"
}, headers=HEADERS)
project_id = proj_res.json()["data"]["id"]

# 3. Create a task in that project
task_res = requests.post(f"{API_URL}/tasks", json={
    "title": "Verify OAuth tokens",
    "priority": "high",
    "project_id": project_id
}, headers=HEADERS)
task_id = task_res.json()["data"]["id"]

# 4. Move task to another project or inbox
requests.post(f"{API_URL}/tasks/move", json={
    "task_id": task_id,
    "project_id": None # Set None or 0 to move to Inbox
}, headers=HEADERS)

# 5. Submit code and mark task complete
code_payload = {
    "title": "Dots Board Webhook Listener",
    "code_content": "const express = require('express'); ...",
    "language": "javascript",
    "task_id": task_id,
    "mark_task_completed": True
}
requests.post(f"{API_URL}/code", json=code_payload, headers=HEADERS)
print("Code submitted and task completed successfully!")
```

### Node.js / JavaScript Example
```javascript
const API_URL = "https://www.ogfocus.com/api/v1/agent";
const HEADERS = {
  "X-OGFOCUS-KEY": "YOUR_API_KEY",
  "X-OGFOCUS-SECRET": "YOUR_API_SECRET",
  "Content-Type": "application/json"
};

async function logDailyDiscipline(habitId) {
  const response = await fetch(`${API_URL}/habits/log`, {
    method: "POST",
    headers: HEADERS,
    body: JSON.stringify({
      habit_id: habitId,
      completed: true,
      notes: "Checked off by AI Assistant"
    })
  });
  const data = await response.json();
  console.log("Habit logged:", data);
}
```

### cURL Examples
```bash
# 1. Fetch Profile
curl -X GET "https://www.ogfocus.com/api/v1/agent/me" \
     -H "X-OGFOCUS-KEY: YOUR_API_KEY" \
     -H "X-OGFOCUS-SECRET: YOUR_API_SECRET"

# 2. Fetch Tasks (Page 1, 50 tasks)
curl -X GET "https://www.ogfocus.com/api/v1/agent/tasks?page=1&limit=50" \
     -H "X-OGFOCUS-KEY: YOUR_API_KEY" \
     -H "X-OGFOCUS-SECRET: YOUR_API_SECRET"

# 3. Create Project
curl -X POST "https://www.ogfocus.com/api/v1/agent/projects" \
     -H "X-OGFOCUS-KEY: YOUR_API_KEY" \
     -H "X-OGFOCUS-SECRET: YOUR_API_SECRET" \
     -H "Content-Type: application/json" \
     -d '{"name":"Dots Board Sync","color":"#BFFF00"}'

# 4. Move Task to Project
curl -X POST "https://www.ogfocus.com/api/v1/agent/tasks/move" \
     -H "X-OGFOCUS-KEY: YOUR_API_KEY" \
     -H "X-OGFOCUS-SECRET: YOUR_API_SECRET" \
     -H "Content-Type: application/json" \
     -d '{"task_id":105,"project_id":4}'
```

---

## 5. Security & Rate Limiting Guidelines

1. **Keep Secrets Private**: The `API Secret` is hashed using bcrypt on the server and is never viewable after initial generation. Never commit keys or secrets to public repositories.
2. **Rate Limits**: The API allows up to **120 requests per minute** per key. Responses exceeding this threshold will return HTTP 429 (`Too Many Requests`).
3. **Data Isolation**: All resources are strictly bound to the authenticated user ID. Any request referencing another user's project, habit, or task ID will be rejected with HTTP 404.
4. **Gamification Integrity**: Direct mutation of Karma, Integrity score, or Rank is prohibited. All scores reflect authentic server-computed actions.
