> ## Documentation Index
> Fetch the complete documentation index at: https://docs.namastex.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Attempts

> Execute and manage task attempts

## Overview

Attempts represent individual executions of tasks by AI agents. Each task can have multiple attempts with different agents or configurations.

**Base URL**: `http://localhost:8887/api/attempts`

***

## List Attempts

Get all attempts with filtering.

```http theme={null}
GET /api/attempts
```

### Query Parameters

| Parameter | Type    | Description        |
| --------- | ------- | ------------------ |
| `taskId`  | string  | Filter by task     |
| `llm`     | string  | Filter by AI agent |
| `status`  | enum    | Filter by status   |
| `page`    | integer | Page number        |
| `limit`   | integer | Items per page     |

### Status Values

* `created` - Queued, not started
* `running` - Currently executing
* `completed` - Finished successfully
* `failed` - Execution failed
* `cancelled` - Cancelled by user

<RequestExample>
  ```bash cURL theme={null}
  curl "http://localhost:8887/api/attempts?taskId=task_abc123&status=completed"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:8887/api/attempts?taskId=task_abc123&status=completed');
  const data = await response.json();
  ```

  ```python Python theme={null}
  import requests

  response = requests.get('http://localhost:8887/api/attempts?taskId=task_abc123&status=completed')
  data = response.json()
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "success": true,
    "data": [
      {
        "id": "attempt_abc123",
        "taskId": "task_xyz789",
        "llm": "claude",
        "status": "completed",
        "worktreePath": ".forge/worktrees/task-xyz-claude",
        "startedAt": "2024-01-15T10:30:00Z",
        "completedAt": "2024-01-15T10:45:00Z",
        "duration": 900000,
        "filesChanged": 8,
        "linesAdded": 245,
        "linesRemoved": 12,
        "cost": {
          "inputTokens": 15420,
          "outputTokens": 3890,
          "totalCost": 0.23
        }
      }
    ]
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "success": false,
    "error": {
      "code": "UNAUTHORIZED",
      "message": "Authentication required"
    }
  }
  ```
</ResponseExample>

***

## Get Attempt

Retrieve detailed attempt information.

```http theme={null}
GET /api/attempts/:id
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "id": "attempt_abc123",
    "taskId": "task_xyz789",
    "llm": "claude",
    "model": "claude-3-5-sonnet-20241022",
    "status": "completed",
    "worktreePath": ".forge/worktrees/task-xyz-claude",
    "startedAt": "2024-01-15T10:30:00Z",
    "completedAt": "2024-01-15T10:45:00Z",
    "duration": 900000,
    "changes": {
      "filesChanged": 8,
      "filesCreated": 2,
      "filesModified": 6,
      "filesDeleted": 0,
      "linesAdded": 245,
      "linesRemoved": 12
    },
    "cost": {
      "inputTokens": 15420,
      "outputTokens": 3890,
      "totalCost": 0.23
    },
    "output": {
      "summary": "Successfully implemented JWT authentication",
      "changes": [
        "Created src/auth/jwt.ts for token generation",
        "Added login endpoint to src/api/auth.ts",
        "Added signup endpoint with validation",
        "Created authentication middleware",
        "Added comprehensive tests"
      ]
    }
  }
}
```

***

## Create Attempt

Start a new attempt for a task.

```http theme={null}
POST /api/attempts
```

### Request Body

```json theme={null}
{
  "taskId": "task_xyz789",
  "llm": "claude",
  "options": {
    "temperature": 0.7,
    "maxTokens": 4096,
    "timeout": 60000
  },
  "description": "Focus on security and edge cases"
}
```

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST http://localhost:8887/api/attempts \
    -H "Content-Type: application/json" \
    -d '{
      "taskId": "task_xyz789",
      "llm": "claude"
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:8887/api/attempts', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({...})
  });
  const data = await response.json();
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'http://localhost:8887/api/attempts',
      json={...}
  )
  data = response.json()
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "success": true,
    "data": {
      "id": "attempt_new123",
      "taskId": "task_xyz789",
      "llm": "claude",
      "status": "created",
      "createdAt": "2024-01-15T11:00:00Z"
    }
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "success": false,
    "error": {
      "code": "UNAUTHORIZED",
      "message": "Authentication required"
    }
  }
  ```
</ResponseExample>

***

## Start Attempt

Begin execution of a created attempt.

```http theme={null}
POST /api/attempts/:id/start
```

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST http://localhost:8887/api/attempts/attempt_new123/start
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:8887/api/attempts/attempt_new123/start', { method: 'POST' });
  const data = await response.json();
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'http://localhost:8887/api/attempts/attempt_new123/start',
      json={...}
  )
  data = response.json()
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "success": true,
    "data": {
      "id": "attempt_new123",
      "status": "running",
      "startedAt": "2024-01-15T11:00:00Z",
      "processId": "proc_abc123"
    }
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "success": false,
    "error": {
      "code": "UNAUTHORIZED",
      "message": "Authentication required"
    }
  }
  ```
</ResponseExample>

***

## Cancel Attempt

Stop a running attempt.

```http theme={null}
POST /api/attempts/:id/cancel
```

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST http://localhost:8887/api/attempts/attempt_abc123/cancel
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:8887/api/attempts/attempt_abc123/cancel', { method: 'POST' });
  const data = await response.json();
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'http://localhost:8887/api/attempts/attempt_abc123/cancel',
      json={...}
  )
  data = response.json()
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "success": true,
    "data": {
      "id": "attempt_abc123",
      "status": "cancelled",
      "cancelledAt": "2024-01-15T11:05:00Z"
    }
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "success": false,
    "error": {
      "code": "UNAUTHORIZED",
      "message": "Authentication required"
    }
  }
  ```
</ResponseExample>

***

## Delete Attempt

Remove an attempt and cleanup worktree.

```http theme={null}
DELETE /api/attempts/:id
```

<Warning>
  This permanently deletes the attempt and removes the associated Git worktree.
</Warning>

<RequestExample>
  ```bash cURL theme={null}
  curl -X DELETE http://localhost:8887/api/attempts/attempt_abc123
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:8887/api/attempts/attempt_abc123', {
    method: 'DELETE'
  });
  const data = await response.json();
  ```

  ```python Python theme={null}
  import requests

  response = requests.delete('http://localhost:8887/api/attempts/attempt_abc123')
  data = response.json()
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "success": true,
    "data": {
      "deleted": true,
      "attemptId": "attempt_abc123"
    }
  }
  ```

  ```json 404 Not Found theme={null}
  {
    "success": false,
    "error": {
      "code": "NOT_FOUND",
      "message": "Attempt not found"
    }
  }
  ```
</ResponseExample>

***

## Get Attempt Logs

Retrieve execution logs for an attempt.

```http theme={null}
GET /api/attempts/:id/logs
```

### Query Parameters

| Parameter | Type      | Description               |
| --------- | --------- | ------------------------- |
| `follow`  | boolean   | Stream logs in real-time  |
| `level`   | enum      | Filter by log level       |
| `since`   | timestamp | Only logs after this time |

<RequestExample>
  ```bash cURL theme={null}
  curl "http://localhost:8887/api/attempts/attempt_abc123/logs?follow=true"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:8887/api/attempts/attempt_abc123/logs?follow=true');
  const reader = response.body.getReader();
  // Stream logs line by line
  while (true) {
    const {done, value} = await reader.read();
    if (done) break;
    console.log(new TextDecoder().decode(value));
  }
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      'http://localhost:8887/api/attempts/attempt_abc123/logs',
      params={'follow': True},
      stream=True
  )

  for line in response.iter_lines():
      if line:
          print(line.decode('utf-8'))
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success (Streaming) theme={null}
  {"level":"info","message":"Starting attempt execution","timestamp":"2024-01-15T10:30:00Z"}
  {"level":"info","message":"Creating git worktree","timestamp":"2024-01-15T10:30:01Z"}
  {"level":"info","message":"Worktree created: .forge/worktrees/task-xyz-claude","timestamp":"2024-01-15T10:30:02Z"}
  {"level":"info","message":"Initializing LLM: claude","timestamp":"2024-01-15T10:30:03Z"}
  {"level":"info","message":"Generating code...","timestamp":"2024-01-15T10:30:05Z"}
  {"level":"info","message":"Created file: src/auth/jwt.ts","timestamp":"2024-01-15T10:32:15Z"}
  ```

  ```json 401 Unauthorized theme={null}
  {
    "success": false,
    "error": {
      "code": "UNAUTHORIZED",
      "message": "Authentication required"
    }
  }
  ```
</ResponseExample>

***

## Get Attempt Diff

Get code changes made by the attempt.

```http theme={null}
GET /api/attempts/:id/diff
```

### Query Parameters

| Parameter | Type   | Description                                   |
| --------- | ------ | --------------------------------------------- |
| `file`    | string | Specific file to diff                         |
| `format`  | enum   | `unified`, `split`, `json` (default: unified) |

<RequestExample>
  ```bash cURL theme={null}
  curl "http://localhost:8887/api/attempts/attempt_abc123/diff?format=json"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:8887/api/attempts/attempt_abc123/diff?format=json');
  const diff = await response.json();
  ```

  ```python Python theme={null}
  import requests

  response = requests.get(
      'http://localhost:8887/api/attempts/attempt_abc123/diff',
      params={'format': 'json'}
  )
  diff = response.json()
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "success": true,
    "data": {
      "files": [
        {
          "path": "src/auth/jwt.ts",
          "status": "added",
          "additions": 67,
          "deletions": 0,
          "changes": [
            {
              "type": "add",
              "lineNumber": 1,
              "content": "import jwt from 'jsonwebtoken';"
            }
          ]
        },
        {
          "path": "src/api/auth.ts",
          "status": "modified",
          "additions": 132,
          "deletions": 13,
          "changes": [...]
        }
      ],
      "summary": {
        "filesChanged": 8,
        "additions": 245,
        "deletions": 12
      }
    }
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "success": false,
    "error": {
      "code": "UNAUTHORIZED",
      "message": "Authentication required"
    }
  }
  ```
</ResponseExample>

***

## Merge Attempt

Merge attempt changes into main branch.

```http theme={null}
POST /api/attempts/:id/merge
```

### Request Body

```json theme={null}
{
  "message": "Add JWT authentication",
  "strategy": "squash",
  "cleanup": true
}
```

### Merge Strategies

* `ff` - Fast-forward merge (default)
* `no-ff` - Create merge commit
* `squash` - Squash commits into one

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST http://localhost:8887/api/attempts/attempt_abc123/merge \
    -H "Content-Type: application/json" \
    -d '{
      "message": "Add JWT authentication (Claude implementation)",
      "strategy": "squash",
      "cleanup": true
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('http://localhost:8887/api/attempts/attempt_abc123/merge', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({...})
  });
  const data = await response.json();
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'http://localhost:8887/api/attempts/attempt_abc123/merge',
      json={...}
  )
  data = response.json()
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "success": true,
    "data": {
      "attemptId": "attempt_abc123",
      "commitSha": "abc123def456",
      "merged": true,
      "mergedAt": "2024-01-15T11:10:00Z",
      "cleanup": true
    }
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "success": false,
    "error": {
      "code": "UNAUTHORIZED",
      "message": "Authentication required"
    }
  }
  ```
</ResponseExample>

***

## Compare Attempts

Compare two attempts side-by-side.

```http theme={null}
POST /api/attempts/compare
```

### Request Body

```json theme={null}
{
  "attemptIds": ["attempt_1", "attempt_2"]
}
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "attempts": [
      {
        "id": "attempt_1",
        "llm": "claude",
        "duration": 900000,
        "cost": 0.23,
        "filesChanged": 8,
        "linesAdded": 245
      },
      {
        "id": "attempt_2",
        "llm": "gemini",
        "duration": 450000,
        "cost": 0.00,
        "filesChanged": 6,
        "linesAdded": 189
      }
    ],
    "comparison": {
      "fasterAttempt": "attempt_2",
      "cheaperAttempt": "attempt_2",
      "moreCompleteAttempt": "attempt_1"
    }
  }
}
```

***

## Get Commit Info

Get commit information for a task attempt.

```http theme={null}
GET /api/task-attempts/:id/commit-info
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "commitId": "abc123def456",
    "message": "Add user authentication (automagik-forge a1b2)",
    "author": "Claude AI <ai@automagik.ai>",
    "timestamp": "2024-01-15T10:45:00Z",
    "filesChanged": 8,
    "insertions": 245,
    "deletions": 12
  }
}
```

***

## Compare to Head

Compare task attempt branch to HEAD of target branch.

```http theme={null}
GET /api/task-attempts/:id/compare-to-head
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "diff": "diff --git a/src/auth.ts...",
    "filesChanged": 8,
    "ahead": 3,
    "behind": 0,
    "conflicts": []
  }
}
```

***

## Merge Attempt

Merge task attempt into target branch.

```http theme={null}
POST /api/task-attempts/:id/merge
```

### Request Body

```json theme={null}
{
  "strategy": "squash",
  "message": "Add authentication system",
  "cleanup": true
}
```

### Parameters

| Parameter  | Type    | Default  | Description                                 |
| ---------- | ------- | -------- | ------------------------------------------- |
| `strategy` | enum    | `squash` | Merge strategy: `squash`, `merge`, `rebase` |
| `message`  | string  | auto     | Custom commit message                       |
| `cleanup`  | boolean | `true`   | Delete worktree after merge                 |

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "commitId": "abc123def456",
    "mergedAt": "2024-01-15T11:00:00Z",
    "branch": "main",
    "filesChanged": 8
  }
}
```

***

## Push Branch

Push task attempt branch to remote.

```http theme={null}
POST /api/task-attempts/:id/push
```

### Request Body

```json theme={null}
{
  "remote": "origin",
  "force": false
}
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "remote": "origin",
    "branch": "forge/task-abc123-attempt-1",
    "pushedAt": "2024-01-15T10:50:00Z"
  }
}
```

***

## Create GitHub PR

Create a pull request from task attempt branch.

```http theme={null}
POST /api/task-attempts/:id/create-pr
```

### Request Body

```json theme={null}
{
  "title": "Add user authentication",
  "body": "Implements JWT-based authentication with refresh tokens",
  "baseBranch": "main",
  "draft": false
}
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "prNumber": 42,
    "url": "https://github.com/user/repo/pull/42",
    "createdAt": "2024-01-15T10:55:00Z"
  }
}
```

***

## Attach Existing PR

Attach an existing GitHub PR to this attempt.

```http theme={null}
POST /api/task-attempts/:id/attach-pr
```

### Request Body

```json theme={null}
{
  "prNumber": 42,
  "repository": "user/repo"
}
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "prNumber": 42,
    "url": "https://github.com/user/repo/pull/42",
    "status": "open"
  }
}
```

***

## Open in Editor

Open task attempt worktree in IDE/editor.

```http theme={null}
POST /api/task-attempts/:id/open-in-editor
```

### Request Body

```json theme={null}
{
  "editor": "vscode"
}
```

### Supported Editors

* `vscode` - Visual Studio Code
* `cursor` - Cursor IDE
* `idea` - IntelliJ IDEA
* `sublime` - Sublime Text

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "editor": "vscode",
    "worktreePath": "/path/to/.forge/worktrees/task-abc123",
    "opened": true
  }
}
```

***

## Get Branch Status

Get git status of task attempt branch.

```http theme={null}
GET /api/task-attempts/:id/branch-status
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "branch": "forge/task-abc123-attempt-1",
    "baseBranch": "main",
    "ahead": 3,
    "behind": 0,
    "conflicted": false,
    "modifiedFiles": [],
    "untrackedFiles": [],
    "status": "clean"
  }
}
```

***

## Change Target Branch

Change the base branch for this attempt.

```http theme={null}
POST /api/task-attempts/:id/change-target-branch
```

### Request Body

```json theme={null}
{
  "newBaseBranch": "develop"
}
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "previousBase": "main",
    "newBase": "develop",
    "conflicts": []
  }
}
```

***

## Rebase Attempt

Rebase task attempt onto latest base branch.

```http theme={null}
POST /api/task-attempts/:id/rebase
```

### Request Body

```json theme={null}
{
  "interactive": false
}
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "status": "success",
    "conflicts": [],
    "commitsReplayed": 3
  }
}
```

**Conflict Response**:

```json theme={null}
{
  "success": false,
  "data": {
    "status": "conflict",
    "conflicts": [
      "src/auth.ts",
      "src/users.ts"
    ]
  }
}
```

***

## Abort Conflicts

Abort merge/rebase conflicts and return to clean state.

```http theme={null}
POST /api/task-attempts/:id/abort-conflicts
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "status": "clean",
    "abortedOperation": "rebase"
  }
}
```

***

## Delete File

Delete a file from task attempt worktree.

```http theme={null}
DELETE /api/task-attempts/:id/files/:path
```

### Example

```bash theme={null}
curl -X DELETE \
  http://localhost:8887/api/task-attempts/attempt_123/files/src/old-file.ts
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "path": "src/old-file.ts",
    "deleted": true
  }
}
```

***

## Start Dev Server

Start development server in task attempt worktree.

```http theme={null}
POST /api/task-attempts/:id/start-dev-server
```

### Request Body

```json theme={null}
{
  "script": "dev",
  "port": 3000
}
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "processId": "process_abc123",
    "port": 3000,
    "url": "http://localhost:3000",
    "status": "running"
  }
}
```

***

## Get Child Tasks

Get tasks created from this attempt (subtasks).

```http theme={null}
GET /api/task-attempts/:id/children
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": [
    {
      "id": "task_child1",
      "title": "Add unit tests for auth",
      "status": "todo",
      "createdAt": "2024-01-15T11:00:00Z"
    }
  ]
}
```

***

## Replace Process

Replace the running execution process with a new one.

```http theme={null}
POST /api/task-attempts/:id/replace-process
```

### Request Body

```json theme={null}
{
  "executorProfileId": {
    "executor": "CLAUDE_CODE",
    "variant": null
  },
  "prompt": "Continue with different approach"
}
```

### Example Response

```json theme={null}
{
  "success": true,
  "data": {
    "oldProcessId": "process_123",
    "newProcessId": "process_456",
    "status": "running"
  }
}
```

***

## SDK Examples

### JavaScript/TypeScript

```typescript theme={null}
import { ForgeClient } from '@automagik/forge-sdk';

const forge = new ForgeClient();

// List attempts
const attempts = await forge.attempts.list({
  taskId: 'task_xyz789',
  status: 'completed'
});

// Create and start attempt
const attempt = await forge.attempts.create({
  taskId: 'task_xyz789',
  llm: 'claude'
});

await forge.attempts.start(attempt.id);

// Get logs (streaming)
const logs = await forge.attempts.logs(attempt.id, {
  follow: true
});

for await (const log of logs) {
  console.log(log.message);
}

// Get diff
const diff = await forge.attempts.diff(attempt.id);

// Merge when ready
await forge.attempts.merge(attempt.id, {
  message: 'Add authentication',
  strategy: 'squash',
  cleanup: true
});

// Compare attempts
const comparison = await forge.attempts.compare([
  'attempt_1',
  'attempt_2'
]);
```

### Python

```python theme={null}
from automagik_forge import ForgeClient

forge = ForgeClient()

# Create and start attempt
attempt = forge.attempts.create(
    task_id='task_xyz789',
    llm='claude'
)

forge.attempts.start(attempt.id)

# Stream logs
for log in forge.attempts.logs(attempt.id, follow=True):
    print(log.message)

# Get diff
diff = forge.attempts.diff(attempt.id)

# Merge
forge.attempts.merge(
    attempt.id,
    message='Add authentication',
    strategy='squash',
    cleanup=True
)
```

***

## WebSocket Events

Subscribe to real-time attempt updates:

```javascript theme={null}
const ws = new WebSocket('ws://localhost:8887/ws');

ws.send(JSON.stringify({
  type: 'subscribe',
  channel: 'attempts',
  attemptId: 'attempt_abc123'
}));

ws.onmessage = (event) => {
  const update = JSON.parse(event.data);
  // { type: 'attempt.status_changed', attemptId: '...', status: 'running' }
};
```

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Tasks API" icon="list-check" href="/forge/api/tasks">
    Manage tasks
  </Card>

  <Card title="Processes API" icon="gear" href="/forge/api/processes">
    Monitor running processes
  </Card>

  <Card title="MCP Tools" icon="plug" href="/forge/api/mcp-tools">
    Use from AI agents
  </Card>
</CardGroup>
