# Integration Guide

Learn how to integrate Nexus Memory with various tools, workflows, and custom applications.

## Table of Contents

1. [Integration Patterns](#integration-patterns)
2. [Claude Code Integration](#claude-code-integration)
3. [Git Workflow Integration](#git-workflow-integration)
4. [CI/CD Integration](#cicd-integration)
5. [Custom Applications](#custom-applications)
6. [MCP Server Integration](#mcp-server-integration)
7. [Webhook Integration](#webhook-integration)
8. [Best Practices](#best-practices)

---

## Integration Patterns

### Pattern 1: Direct Hook Usage

The simplest integration—pipe JSON directly to hooks.

```bash
# Store
echo '{"content": "...", "event_type": "fix"}' | ~/.claude/hooks/store-memory.sh

# Recall
echo '{"query": "..."}' | ~/.claude/hooks/recall-memory.sh
```

**Best for:** Scripts, automation, simple integrations

### Pattern 2: HTTP API

Call the REST API directly for full control.

```bash
curl -X POST "https://api.adverant.ai/api/memory/store" \
  -H "Content-Type: application/json" \
  -H "X-Company-ID: your-company" \
  -H "X-App-ID: your-app" \
  -H "X-User-ID: $USER" \
  -d '{"content": "...", "metadata": {...}}'
```

**Best for:** Custom applications, non-bash environments

### Pattern 3: Wrapper Scripts

Create domain-specific wrappers.

```bash
#!/bin/bash
# store-fix.sh - Convenience wrapper for bug fixes

FIX_DESCRIPTION="$1"
ERROR_CODE="$2"

echo "{
  \"content\": \"$FIX_DESCRIPTION. Error code: $ERROR_CODE\",
  \"event_type\": \"fix\"
}" | ~/.claude/hooks/store-memory.sh

echo "✅ Fix stored: $FIX_DESCRIPTION"
```

**Usage:**
```bash
./store-fix.sh "Fixed null pointer in user service" "NPE-2024-001"
```

**Best for:** Team-specific workflows, standardized inputs

---

## Claude Code Integration

### Skill Invocation

Claude Code automatically uses the skill when relevant:

```
User: "Remember that we need to use pnpm for this project"

Claude: I'll store that preference for future sessions.
[Invokes nexus-memory skill → store-memory.sh]
```

### Explicit Commands

Users can explicitly trigger memory operations:

```
User: "Store this: Always run type-check before committing"

User: "Recall what we learned about TypeScript configuration"
```

### Automatic Context

The skill automatically captures:
- Current project directory
- Project name
- Session ID
- Timestamp
- User ID

### Customizing Skill Behavior

Edit `~/.claude/skills/nexus-memory/SKILL.md` to customize:

```markdown
---
name: nexus-memory
description: Your custom description
allowed-tools: Bash
---

# Custom instructions here

Add project-specific guidelines...
```

---

## Git Workflow Integration

### Pre-Commit Hook

Store context before each commit:

```bash
#!/bin/bash
# .git/hooks/pre-commit

# Get staged files summary
STAGED=$(git diff --cached --name-only | head -10 | tr '\n' ', ')

# Get commit context
BRANCH=$(git branch --show-current)

# Store as context
echo "{
  \"content\": \"Committing changes to $BRANCH: $STAGED\",
  \"event_type\": \"context\"
}" | ~/.claude/hooks/store-memory.sh
```

### Post-Commit Hook

Link commits to decisions:

```bash
#!/bin/bash
# .git/hooks/post-commit

COMMIT_MSG=$(git log -1 --pretty=%B)
COMMIT_HASH=$(git log -1 --pretty=%H | head -c 7)

# Store significant commits as context
if [[ "$COMMIT_MSG" =~ ^(feat|fix|refactor): ]]; then
  echo "{
    \"content\": \"Commit $COMMIT_HASH: $COMMIT_MSG\",
    \"event_type\": \"context\"
  }" | ~/.claude/hooks/store-memory.sh
fi
```

### Commit Message Enhancement

Recall relevant context when writing commits:

```bash
#!/bin/bash
# git-commit-with-context.sh

# Get changed files
FILES=$(git diff --cached --name-only | tr '\n' ' ')

# Recall relevant memories
CONTEXT=$(echo "{\"query\": \"$FILES\"}" | ~/.claude/hooks/recall-memory.sh | jq -r '.memories[0].content // empty')

if [ -n "$CONTEXT" ]; then
  echo "📝 Relevant context:"
  echo "$CONTEXT"
  echo ""
fi

# Proceed with commit
git commit "$@"
```

---

## CI/CD Integration

### GitHub Actions

Store CI context automatically:

```yaml
# .github/workflows/memory.yml
name: Store CI Memory

on:
  push:
    branches: [main]
  pull_request:
    types: [closed]

jobs:
  store-memory:
    runs-on: ubuntu-latest
    if: github.event.pull_request.merged == true
    steps:
      - name: Store PR context
        run: |
          curl -X POST "https://api.adverant.ai/api/memory/store" \
            -H "Content-Type: application/json" \
            -H "X-Company-ID: ${{ secrets.NEXUS_COMPANY_ID }}" \
            -H "X-App-ID: github-actions" \
            -H "X-User-ID: ${{ github.actor }}" \
            -d '{
              "content": "PR #${{ github.event.number }}: ${{ github.event.pull_request.title }}",
              "tags": ["ci", "pr-merged", "project:${{ github.repository }}"],
              "metadata": {
                "eventType": "context",
                "projectName": "${{ github.repository }}",
                "timestamp": "${{ github.event.pull_request.merged_at }}"
              }
            }'
```

### Store Build Failures

Learn from CI failures:

```yaml
- name: Store build failure
  if: failure()
  run: |
    curl -X POST "https://api.adverant.ai/api/memory/store" \
      -H "Content-Type: application/json" \
      -H "X-Company-ID: ${{ secrets.NEXUS_COMPANY_ID }}" \
      -H "X-App-ID: github-actions" \
      -H "X-User-ID: ci-bot" \
      -d '{
        "content": "Build failed on ${{ github.ref }}: ${{ github.job }}",
        "tags": ["ci", "build-failure"],
        "metadata": {
          "eventType": "context",
          "projectName": "${{ github.repository }}"
        }
      }'
```

---

## Custom Applications

### Node.js Integration

```javascript
const https = require('https');

async function storeMemory(content, eventType) {
  const data = JSON.stringify({
    content,
    tags: ['nodejs-app', `type:${eventType}`],
    metadata: {
      eventType,
      projectName: process.env.PROJECT_NAME || 'unknown',
      timestamp: new Date().toISOString()
    }
  });

  const options = {
    hostname: 'api.adverant.ai',
    path: '/api/memory/store',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Company-ID': process.env.NEXUS_COMPANY_ID,
      'X-App-ID': 'nodejs-app',
      'X-User-ID': process.env.USER,
      'Content-Length': data.length
    }
  };

  return new Promise((resolve, reject) => {
    const req = https.request(options, (res) => {
      let body = '';
      res.on('data', chunk => body += chunk);
      res.on('end', () => resolve(JSON.parse(body)));
    });
    req.on('error', reject);
    req.write(data);
    req.end();
  });
}

// Usage
storeMemory('Fixed memory leak in event handler', 'fix')
  .then(console.log)
  .catch(console.error);
```

### Python Integration

```python
import requests
import os
from datetime import datetime

class NexusMemory:
    def __init__(self, company_id, app_id):
        self.base_url = os.getenv('NEXUS_API_URL', 'https://api.adverant.ai')
        self.headers = {
            'Content-Type': 'application/json',
            'X-Company-ID': company_id,
            'X-App-ID': app_id,
            'X-User-ID': os.getenv('USER', 'unknown')
        }

    def store(self, content: str, event_type: str, tags: list = None):
        payload = {
            'content': content,
            'tags': tags or [],
            'metadata': {
                'eventType': event_type,
                'timestamp': datetime.utcnow().isoformat() + 'Z'
            }
        }
        response = requests.post(
            f'{self.base_url}/api/memory/store',
            json=payload,
            headers=self.headers
        )
        return response.json()

    def recall(self, query: str, limit: int = 10):
        payload = {'query': query, 'limit': limit}
        response = requests.post(
            f'{self.base_url}/api/memory/recall',
            json=payload,
            headers=self.headers
        )
        return response.json()

# Usage
memory = NexusMemory('adverant', 'python-app')
memory.store('Optimized database queries with indexes', 'fix')
results = memory.recall('database performance')
```

### Go Integration

```go
package main

import (
    "bytes"
    "encoding/json"
    "net/http"
    "os"
    "time"
)

type NexusMemory struct {
    BaseURL   string
    CompanyID string
    AppID     string
    UserID    string
}

type StoreRequest struct {
    Content  string            `json:"content"`
    Tags     []string          `json:"tags"`
    Metadata map[string]string `json:"metadata"`
}

func (n *NexusMemory) Store(content, eventType string) error {
    payload := StoreRequest{
        Content: content,
        Tags:    []string{"go-app", "type:" + eventType},
        Metadata: map[string]string{
            "eventType": eventType,
            "timestamp": time.Now().UTC().Format(time.RFC3339),
        },
    }

    data, _ := json.Marshal(payload)
    req, _ := http.NewRequest("POST", n.BaseURL+"/api/memory/store", bytes.NewBuffer(data))

    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("X-Company-ID", n.CompanyID)
    req.Header.Set("X-App-ID", n.AppID)
    req.Header.Set("X-User-ID", n.UserID)

    client := &http.Client{}
    _, err := client.Do(req)
    return err
}

func main() {
    memory := &NexusMemory{
        BaseURL:   "https://api.adverant.ai",
        CompanyID: "adverant",
        AppID:     "go-app",
        UserID:    os.Getenv("USER"),
    }

    memory.Store("Implemented graceful shutdown", "pattern")
}
```

---

## MCP Server Integration

### Planned MCP Server Mode (Q1 2025)

Nexus Memory will expose an MCP server for integration with any MCP-compatible LLM:

```json
{
  "mcpServers": {
    "nexus-memory": {
      "command": "nexus-memory-server",
      "args": ["--company-id", "adverant"],
      "env": {
        "NEXUS_API_URL": "https://api.adverant.ai"
      }
    }
  }
}
```

### Available Tools (Planned)

```json
{
  "tools": [
    {
      "name": "nexus_store_memory",
      "description": "Store a memory for future recall",
      "inputSchema": {
        "type": "object",
        "properties": {
          "content": {"type": "string"},
          "event_type": {"type": "string", "enum": ["fix", "decision", "learning", "pattern", "preference", "context"]}
        },
        "required": ["content"]
      }
    },
    {
      "name": "nexus_recall_memory",
      "description": "Recall relevant memories",
      "inputSchema": {
        "type": "object",
        "properties": {
          "query": {"type": "string"},
          "limit": {"type": "number"}
        },
        "required": ["query"]
      }
    }
  ]
}
```

---

## Webhook Integration

### Incoming Webhooks (Planned)

Receive events from external services:

```bash
# Configure webhook endpoint
curl -X POST "https://api.adverant.ai/api/webhooks/configure" \
  -H "Content-Type: application/json" \
  -H "X-Company-ID: adverant" \
  -d '{
    "url": "https://api.adverant.ai/api/webhooks/ingest/YOUR_TOKEN",
    "events": ["github.push", "slack.message"],
    "transform": {
      "github.push": {
        "content": "{{commits[0].message}}",
        "event_type": "context"
      }
    }
  }'
```

### Outgoing Webhooks (Planned)

Get notified when memories are stored:

```bash
curl -X POST "https://api.adverant.ai/api/webhooks/subscribe" \
  -H "Content-Type: application/json" \
  -H "X-Company-ID: adverant" \
  -d '{
    "url": "https://your-app.com/webhooks/nexus",
    "events": ["memory.stored", "memory.recalled"],
    "secret": "your-webhook-secret"
  }'
```

---

## Best Practices

### 1. Use Appropriate Event Types

| Scenario | Event Type |
|----------|------------|
| Fixed a bug | `fix` |
| Made architecture choice | `decision` |
| Discovered something | `learning` |
| Found reusable code | `pattern` |
| Noted a preference | `preference` |
| Documented project info | `context` |

### 2. Include Searchable Keywords

```bash
# Good - includes searchable terms
echo '{"content": "Safari iOS date parsing NaN: use explicit timezone T00:00:00", "event_type": "fix"}'

# Bad - missing keywords
echo '{"content": "Fixed the date bug", "event_type": "fix"}'
```

### 3. Handle Errors Gracefully

```bash
# Check for errors
RESPONSE=$(echo '{"query": "test"}' | ~/.claude/hooks/recall-memory.sh)
if echo "$RESPONSE" | jq -e '.error' > /dev/null 2>&1; then
  echo "Error: $(echo "$RESPONSE" | jq -r '.message')"
  exit 1
fi
```

### 4. Batch Operations (Future)

When storing multiple memories, batch them:

```bash
# Future API
curl -X POST "https://api.adverant.ai/api/memory/batch" \
  -d '{
    "memories": [
      {"content": "...", "event_type": "fix"},
      {"content": "...", "event_type": "learning"}
    ]
  }'
```

### 5. Respect Rate Limits

```bash
# Add delays between bulk operations
for memory in "${memories[@]}"; do
  echo "$memory" | ~/.claude/hooks/store-memory.sh
  sleep 0.1  # 100ms delay
done
```

---

## See Also

- [API Reference](api-reference.md) — Full API documentation
- [Architecture](architecture.md) — System design
- [Getting Started](getting-started.md) — Quick start
