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

# Lifecycle Events

> Deep dive into all 8 ULPI hooks: when they fire, what they enable, and how to use them effectively

# Understanding ULPI Lifecycle Hooks

**Every AI coding assistant goes through a predictable lifecycle:** start session → receive prompts → execute tools → compact context → end session.

**ULPI Hooks intercept 8 critical moments** in this lifecycle to enable coordination, memory preservation, and conflict prevention.

This guide explains each hook in detail: when it fires, what it enables, exit codes, performance characteristics, and integration with other ULPI products.

***

## Hook Execution Flow

Understanding when hooks fire in relation to your AI assistant's operations:

```mermaid theme={null}
sequenceDiagram
    participant User
    participant IDE as AI Assistant (Claude Code, Cursor, etc.)
    participant Hooks as ULPI Hooks
    participant API as ULPI API

    User->>IDE: Start new session
    IDE->>Hooks: session-start hook
    Hooks->>API: Register agent, fetch inbox, load memories
    API-->>Hooks: Dashboard data
    Hooks-->>IDE: Display coordination dashboard
    IDE-->>User: Session ready

    User->>IDE: Send prompt
    IDE->>Hooks: user-prompt-submit hook
    Hooks->>API: Check urgent messages
    alt Urgent message exists
        Hooks-->>IDE: Display alert (block=true)
        IDE-->>User: Show urgent message
    else No urgent messages
        Hooks-->>IDE: Continue (block=false)
    end

    IDE->>IDE: Process prompt, plan edits
    IDE->>Hooks: pre-tool-use:edit hook
    Hooks->>API: Check file reservations
    alt File reserved by another agent
        Hooks-->>IDE: Block edit (exit code 2)
        IDE-->>User: Show conflict message
    else File available
        Hooks->>API: Create reservation
        Hooks-->>IDE: Allow edit (exit code 0)
        IDE->>IDE: Execute file edit
        IDE->>Hooks: post-tool-use:edit hook
        Hooks->>API: Update obligations
        Hooks-->>IDE: Show pending tasks
    end

    Note over IDE: Context approaching token limit
    IDE->>Hooks: pre-compact hook
    Hooks->>API: Create memory snapshot
    Hooks-->>IDE: Allow compaction
    IDE->>IDE: Compact conversation

    User->>IDE: Stop execution
    IDE->>Hooks: stop hook
    Hooks->>API: Check pending acks
    alt Critical acks pending
        Hooks-->>IDE: Block stop (exit code 2)
    else All clear
        Hooks-->>IDE: Allow stop (exit code 0)
    end

    User->>IDE: End session
    IDE->>Hooks: session-end hook
    Hooks->>API: Release reservations, store snapshot
    Hooks-->>IDE: Cleanup complete
    IDE-->>User: Session ended
```

***

## Hook 1: session-start

### When It Fires

**Trigger:** Your AI coding assistant starts a new chat session

**Frequency:** Once per session (typically when you open the IDE or create a new chat)

**Blocking:** ✅ Can block session start if critical issues exist

***

### What It Enables

<AccordionGroup>
  <Accordion title="Agent Registration" icon="id-card">
    Automatically registers your AI assistant with ULPI Coordination:

    * Creates unique agent identity (e.g., "Claude-Code-YourName")
    * Sets online status
    * Associates with project/repository
    * Establishes contact policies

    **MCP Tool Used:** `register-agent`

    **Why it matters:** Other agents can discover and message you
  </Accordion>

  <Accordion title="Coordination Dashboard Display" icon="dashboard">
    Shows critical coordination info at session start:

    ```plaintext theme={null}
    ╔══════════════════════════════════════════════╗
    ║  🤖 ULPI Coordination Dashboard              ║
    ╠══════════════════════════════════════════════╣
    ║  📬 Unread Messages: 3 (1 urgent)            ║
    ║  🔒 Active File Reservations: 5              ║
    ║  💾 Memories Loaded: 47                      ║
    ║  ⚡ Online Agents: 4                         ║
    ╚══════════════════════════════════════════════╝
    ```

    **MCP Tools Used:** `fetch-inbox`, `list-file-reservations`

    **Why it matters:** You see coordination status before starting work
  </Accordion>

  <Accordion title="Memory Context Loading" icon="brain">
    Retrieves relevant memories from previous sessions:

    * Searches for memories related to current project
    * Loads high-salience memories (importance > 0.7)
    * Injects context into session automatically

    **MCP Tool Used:** `search-memories`

    **Why it matters:** AI has context from previous sessions without manual explanation
  </Accordion>

  <Accordion title="Pending Acknowledgments Alert" icon="bell">
    Warns if critical acknowledgments are pending:

    ```plaintext theme={null}
    ⚠️  3 pending acknowledgments require your attention:
    - Security review for auth.ts changes (overdue 2 days)
    - Code review requested by Alice (urgent)
    - Deploy approval for staging environment
    ```

    **MCP Tool Used:** `get-action-items`

    **Why it matters:** You don't forget critical obligations
  </Accordion>
</AccordionGroup>

***

### Exit Codes

| Code | Meaning             | When Used                                          |
| ---- | ------------------- | -------------------------------------------------- |
| `0`  | Allow session start | Default - no blocking issues                       |
| `2`  | Block session start | Critical pending acks that must be addressed first |

**Example blocking scenario:**

```plaintext theme={null}
⛔ Session Blocked

You have 1 critical overdue acknowledgment:

Security vulnerability in auth.ts
Reported by: Security Scanner
Priority: Critical
Overdue: 3 days

You must acknowledge this issue before starting new work.

[Acknowledge Now] [Contact Security Team] [Override (Admin Only)]
```

***

### Performance

* **Average latency:** 150ms
* **MCP calls:** 3-5 (register-agent, fetch-inbox, list-file-reservations, search-memories, get-action-items)
* **Network requests:** 3-5 (one per MCP call)
* **User impact:** Minimal - dashboard appears within 200ms of session start

***

### Configuration

```json ~/.ulpi/config.json theme={null}
{
  "hooks": {
    "sessionStart": {
      "enabled": true,
      "showDashboard": true,        // Display coordination dashboard
      "loadMemories": true,          // Auto-load relevant memories
      "blockOnPendingAcks": true,    // Block if critical acks pending
      "minMemoryImportance": 0.7     // Only load high-importance memories
    }
  }
}
```

***

## Hook 2: pre-tool-use:edit

### When It Fires

**Trigger:** AI assistant attempts to edit any file

**Frequency:** Before every `Write` or `Edit` tool execution

**Blocking:** ✅ Can block edits to prevent conflicts

***

### What It Enables

<AccordionGroup>
  <Accordion title="File Conflict Prevention" icon="shield-check">
    Checks if file is reserved by another agent before allowing edit:

    **Flow:**

    1. Hook fires before edit
    2. Queries Coordination API: "Is this file reserved?"
    3. If reserved by another agent → **Block edit** (exit code 2)
    4. If not reserved → **Create reservation** → Allow edit (exit code 0)

    **MCP Tools Used:** `list-file-reservations`, `reserve-file-paths`

    **Result:** Zero merge conflicts, guaranteed
  </Accordion>

  <Accordion title="Automatic File Reservation" icon="lock">
    Auto-reserves files on first edit:

    **Reservation modes:**

    * **Shared:** Multiple agents can read/edit (used for config files, docs)
    * **Exclusive:** Only one agent can edit (used for critical code files)

    **Default behavior:** Shared mode with 2-hour expiration

    **MCP Tool Used:** `reserve-file-paths`

    **Why it matters:** You don't manually manage file locks
  </Accordion>

  <Accordion title="Conflict Resolution Guidance" icon="messages">
    When edits are blocked, suggests coordination actions:

    ```plaintext theme={null}
    ⛔ Edit Blocked

    File: src/auth.ts
    Reserved by: Claude-Cursor-Alice
    Mode: Exclusive
    Expires: 1 hour 23 minutes

    Coordination Options:
    1. [Message Alice] - Ask when she'll be done
    2. [Wait for expiration] - Set reminder for 1h 23m
    3. [Request override] - Emergency situations only
    4. [Edit different file] - Work on something else

    [Choose Option]
    ```

    **MCP Tool Used:** `send-message` (if user chooses to message)

    **Why it matters:** Clear path to resolving conflicts
  </Accordion>
</AccordionGroup>

***

### Exit Codes

| Code | Meaning    | When Used                                                       |
| ---- | ---------- | --------------------------------------------------------------- |
| `0`  | Allow edit | File available OR already reserved by this agent                |
| `2`  | Block edit | File reserved by another agent in exclusive or conflicting mode |

***

### Performance

* **Average latency:** 120ms (fastest hook)
* **MCP calls:** 1-2 (list-file-reservations, optionally reserve-file-paths)
* **Network requests:** 1-2
* **User impact:** Imperceptible - edits proceed normally unless conflict detected

***

### Configuration

```json ~/.ulpi/config.json theme={null}
{
  "hooks": {
    "preEdit": {
      "enabled": true,
      "autoReserve": true,           // Auto-create reservations on first edit
      "defaultMode": "shared",       // "shared" or "exclusive"
      "reservationDuration": 7200,   // 2 hours in seconds
      "blockConflicts": true,        // Block conflicting edits
      "showGuidance": true           // Show coordination options when blocked
    }
  }
}
```

***

## Hook 3: post-tool-use:edit

### When It Fires

**Trigger:** AI assistant completes a file edit successfully

**Frequency:** After every `Write` or `Edit` tool execution

**Blocking:** ❌ Non-blocking (always returns exit code 0)

***

### What It Enables

<AccordionGroup>
  <Accordion title="Obligation Tracking" icon="clipboard-check">
    Shows tasks/obligations related to the edited file:

    ```plaintext theme={null}
    📋 Pending Obligations for src/auth.ts:

    Required:
    - ⚠️  Security review (due in 2 days)
    - ⚠️  Unit test coverage (minimum 80%)
    - ⚠️  Code review by senior engineer

    Optional:
    - 💡 Update documentation
    - 💡 Add integration tests
    ```

    **MCP Tool Used:** `get-action-items`

    **Why it matters:** You don't forget required follow-ups
  </Accordion>

  <Accordion title="Task Status Updates" icon="check-square">
    If edit is part of a tracked task, updates task progress:

    ```plaintext theme={null}
    ✓ Task Updated

    Task: Implement OAuth login
    Progress: 60% → 75% (auth.ts completed)
    Remaining: Add tests, update docs
    ```

    **MCP Tool Used:** `update-task` (via ULPI Tasks integration)

    **Why it matters:** Automatic task tracking without manual updates
  </Accordion>

  <Accordion title="Audit Logging" icon="scroll">
    Records edit for coordination audit trail:

    * Timestamp
    * File path
    * Agent identity
    * Reservation status
    * Lines changed

    **MCP Tool Used:** `log-event`

    **Why it matters:** Complete transparency for team oversight
  </Accordion>
</AccordionGroup>

***

### Exit Codes

| Code | Meaning  | When Used                  |
| ---- | -------- | -------------------------- |
| `0`  | Continue | Always (non-blocking hook) |

***

### Performance

* **Average latency:** 80ms (runs asynchronously)
* **MCP calls:** 1 (get-action-items)
* **Network requests:** 1
* **User impact:** None - runs in background

***

### Configuration

```json ~/.ulpi/config.json theme={null}
{
  "hooks": {
    "postEdit": {
      "enabled": true,
      "showObligations": true,   // Display pending obligations
      "updateTasks": true,        // Auto-update task progress
      "logAudit": true            // Record to audit log
    }
  }
}
```

***

## Hook 4: pre-compact

### When It Fires

**Trigger:** Claude approaches token limit and prepares to compact conversation

**Frequency:** Varies - typically every 2-3 hours in long sessions

**Blocking:** ✅ Can block compaction (rarely used)

***

### What It Enables

<AccordionGroup>
  <Accordion title="Automatic Memory Snapshots" icon="camera">
    Creates memory snapshot of important context before compaction:

    **What gets saved:**

    * Architecture decisions and rationale
    * Important code patterns and conventions
    * Project-specific context and constraints
    * Active tasks and their status
    * Pending obligations

    **Salience filtering:** Only saves memories with importance ≥ configured threshold (default 0.5)

    **MCP Tool Used:** `store-memory`

    **Result:** Critical context preserved even after compaction
  </Accordion>

  <Accordion title="Context Extraction" icon="filter">
    Intelligently extracts what matters:

    ```plaintext theme={null}
    💾 Pre-Compact Snapshot

    Saving critical context to memory:
    ✓ 12 architecture decisions
    ✓ 8 code conventions
    ✓ 3 active tasks
    ✓ 5 pending obligations

    Excluded (low importance):
    - 47 routine exchanges
    - 23 error debugging steps (resolved)
    - 15 exploratory questions
    ```

    **MCP Tool Used:** `store-memory` (with bulk insert)

    **Why it matters:** AI has long-term memory across sessions
  </Accordion>
</AccordionGroup>

***

### Exit Codes

| Code | Meaning          | When Used                                 |
| ---- | ---------------- | ----------------------------------------- |
| `0`  | Allow compaction | Default - snapshot created successfully   |
| `2`  | Block compaction | Critical context extraction failed (rare) |

***

### Performance

* **Average latency:** 200ms (slowest hook due to context extraction)
* **MCP calls:** 2-3 (analyze conversation, store-memory bulk)
* **Network requests:** 2-3
* **User impact:** Minimal - compaction delayed by \~200ms

***

### Configuration

```json ~/.ulpi/config.json theme={null}
{
  "hooks": {
    "preCompact": {
      "enabled": true,
      "createSnapshot": true,    // Create memory snapshot
      "minImportance": 0.5,      // Save memories with importance ≥ 0.5
      "includeCode": true,       // Include code snippets in memories
      "includeTasks": true       // Include active task status
    }
  }
}
```

***

## Hook 5: user-prompt-submit

### When It Fires

**Trigger:** User submits a prompt to the AI assistant

**Frequency:** Before every AI response

**Blocking:** ✅ Can block response to show urgent alerts

***

### What It Enables

<AccordionGroup>
  <Accordion title="Urgent Message Alerts" icon="siren">
    Displays high-priority coordination messages before AI responds:

    ```plaintext theme={null}
    🚨 URGENT MESSAGE

    From: Security Scanner
    Subject: Critical vulnerability detected
    Priority: Urgent
    Received: 5 minutes ago

    SQL injection vulnerability found in src/auth.ts line 45.
    Do not deploy until reviewed and fixed.

    [View Details] [Acknowledge] [Dismiss]
    ```

    **MCP Tool Used:** `fetch-inbox` (filter: priority=urgent, unread=true)

    **Why it matters:** Critical info never missed
  </Accordion>

  <Accordion title="Pending Acknowledgment Reminders" icon="bell">
    Reminds about pending acks that need attention:

    ```plaintext theme={null}
    📬 Pending Acknowledgments (3)

    - Code review request from Alice (2 days old)
    - Deploy approval needed for staging (urgent)
    - Security audit findings (overdue)

    [Review Now] [Remind Me Later]
    ```

    **MCP Tool Used:** `get-action-items`

    **Why it matters:** Obligations don't get forgotten
  </Accordion>
</AccordionGroup>

***

### Exit Codes

| Code | Meaning        | When Used                                                |
| ---- | -------------- | -------------------------------------------------------- |
| `0`  | Allow response | No urgent messages or user dismissed alerts              |
| `2`  | Block response | Urgent message requires acknowledgment before proceeding |

***

### Performance

* **Average latency:** 100ms
* **MCP calls:** 1-2 (fetch-inbox, get-action-items)
* **Network requests:** 1-2
* **User impact:** Slight delay before AI responds (only if urgent messages exist)

***

### Configuration

```json ~/.ulpi/config.json theme={null}
{
  "hooks": {
    "userPrompt": {
      "enabled": true,
      "showUrgentMessages": true,   // Display urgent coordination messages
      "requireAck": true,            // Block response until urgent messages acknowledged
      "showPendingAcks": true,       // Remind about pending acknowledgments
      "urgentOnly": true             // Only show urgent priority messages
    }
  }
}
```

***

## Hook 6: stop

### When It Fires

**Trigger:** User clicks stop/cancel button during AI execution

**Frequency:** Only when user manually stops execution

**Blocking:** ✅ Can block stop to prevent unsafe interruption

***

### What It Enables

<AccordionGroup>
  <Accordion title="Prevent Unsafe Shutdowns" icon="shield-halved">
    Blocks stop if critical operations are incomplete:

    ```plaintext theme={null}
    ⚠️  Unsafe to Stop

    Critical pending tasks:
    - Database migration in progress (45% complete)
    - File reservation transaction open
    - Memory snapshot upload in progress

    Stopping now may corrupt data.

    [Force Stop] [Wait for Completion] [Cancel]
    ```

    **MCP Tool Used:** `get-action-items` (filter: blocking=true)

    **Why it matters:** Prevents data corruption and orphaned locks
  </Accordion>

  <Accordion title="Pending Acknowledgment Warnings" icon="exclamation-triangle">
    Warns about unacknowledged critical messages:

    ```plaintext theme={null}
    ⚠️  Pending Acknowledgments

    You have 2 unacknowledged urgent messages:
    - Security vulnerability report (requires ack)
    - Deploy blocker from QA team (requires ack)

    Are you sure you want to stop without acknowledging?

    [Acknowledge Now] [Stop Anyway] [Cancel]
    ```

    **MCP Tool Used:** `get-action-items`

    **Why it matters:** Important coordination doesn't fall through cracks
  </Accordion>
</AccordionGroup>

***

### Exit Codes

| Code | Meaning    | When Used                                             |
| ---- | ---------- | ----------------------------------------------------- |
| `0`  | Allow stop | Safe to stop - no critical pending operations         |
| `2`  | Block stop | Critical operations incomplete or urgent acks pending |

***

### Performance

* **Average latency:** 90ms
* **MCP calls:** 1 (get-action-items)
* **Network requests:** 1
* **User impact:** Stop button delayed by \~100ms (only if blocking issues exist)

***

### Configuration

```json ~/.ulpi/config.json theme={null}
{
  "hooks": {
    "stop": {
      "enabled": true,
      "blockUnsafe": true,        // Block stop if critical ops pending
      "warnPendingAcks": true,    // Warn about unacknowledged messages
      "allowForceStop": true      // Allow user to force stop anyway
    }
  }
}
```

***

## Hook 7: session-end

### When It Fires

**Trigger:** AI assistant session ends (user closes chat, IDE closes, etc.)

**Frequency:** Once per session

**Blocking:** ❌ Non-blocking (cleanup hook)

***

### What It Enables

<AccordionGroup>
  <Accordion title="Automatic File Reservation Release" icon="unlock">
    Releases all file reservations automatically:

    ```plaintext theme={null}
    🧹 Session Cleanup

    Releasing file reservations:
    ✓ src/auth.ts (exclusive)
    ✓ src/utils.ts (shared)
    ✓ src/api.ts (shared)

    All locks released successfully.
    ```

    **MCP Tool Used:** `release-file-reservations`

    **Result:** Zero orphaned file locks
  </Accordion>

  <Accordion title="Agent Status Update" icon="signal">
    Marks agent as offline in Coordination:

    * Sets status to "offline"
    * Records last seen timestamp
    * Updates session duration

    **MCP Tool Used:** `update-agent-status`

    **Why it matters:** Other agents know you're no longer active
  </Accordion>

  <Accordion title="Final Memory Snapshot" icon="floppy-disk">
    Optionally creates final memory snapshot:

    * Saves unresolved tasks
    * Records session learnings
    * Stores pending obligations

    **MCP Tool Used:** `store-memory`

    **Why it matters:** Next session continues seamlessly
  </Accordion>
</AccordionGroup>

***

### Exit Codes

| Code | Meaning          | When Used                  |
| ---- | ---------------- | -------------------------- |
| `0`  | Complete cleanup | Always (non-blocking hook) |

***

### Performance

* **Average latency:** 110ms (runs async, doesn't delay session close)
* **MCP calls:** 2-3 (release-file-reservations, update-agent-status, store-memory)
* **Network requests:** 2-3
* **User impact:** None - runs in background as session closes

***

### Configuration

```json ~/.ulpi/config.json theme={null}
{
  "hooks": {
    "sessionEnd": {
      "enabled": true,
      "releaseReservations": true,  // Auto-release all file locks
      "updateStatus": true,          // Mark agent offline
      "createSnapshot": true         // Save final memory snapshot
    }
  }
}
```

***

## Hook 8: subagent-stop

### When It Fires

**Trigger:** A spawned subagent completes its task

**Frequency:** When using Task agent or spawning subagents

**Blocking:** ❌ Non-blocking (cleanup hook)

***

### What It Enables

<AccordionGroup>
  <Accordion title="Learning Consolidation" icon="graduation-cap">
    Stores subagent learnings to shared memory:

    ```plaintext theme={null}
    📚 Consolidating Subagent Learnings

    Subagent: Subagent-3-AuthRefactor
    Task: Refactor authentication module
    Duration: 23 minutes
    Files edited: 5

    Learnings saved to memory:
    ✓ OAuth implementation pattern
    ✓ JWT token validation approach
    ✓ Error handling conventions
    ✓ Test coverage strategy

    Available for parent agent and future subagents.
    ```

    **MCP Tool Used:** `store-memory`

    **Why it matters:** Subagent learnings benefit entire team
  </Accordion>

  <Accordion title="Subagent Reservation Release" icon="unlock-keyhole">
    Releases files reserved by subagent:

    * Subagent file reservations are auto-released
    * Parent agent can access those files again
    * Other agents can now reserve them

    **MCP Tool Used:** `release-file-reservations`

    **Why it matters:** No orphaned locks from subagents
  </Accordion>

  <Accordion title="Task Result Reporting" icon="chart-bar">
    Reports subagent results to parent:

    ```plaintext theme={null}
    ✓ Subagent Task Complete

    Task: Write unit tests for auth module
    Status: Completed
    Files created: 12 test files
    Coverage: 92%
    Duration: 18 minutes

    Results available to parent agent.
    ```

    **MCP Tool Used:** `update-task`

    **Why it matters:** Parent agent knows when delegated work is done
  </Accordion>
</AccordionGroup>

***

### Exit Codes

| Code | Meaning          | When Used                  |
| ---- | ---------------- | -------------------------- |
| `0`  | Complete cleanup | Always (non-blocking hook) |

***

### Performance

* **Average latency:** 95ms (async)
* **MCP calls:** 1-2 (store-memory, release-file-reservations, update-task)
* **Network requests:** 1-2
* **User impact:** None - subagent cleanup is background operation

***

### Configuration

```json ~/.ulpi/config.json theme={null}
{
  "hooks": {
    "subagentStop": {
      "enabled": true,
      "consolidateLearnings": true,  // Save subagent learnings to memory
      "releaseReservations": true,   // Release subagent file locks
      "reportResults": true          // Report completion to parent
    }
  }
}
```

***

## Hook Performance Summary

| Hook               | Avg Latency | MCP Calls | Blocking | User Impact              |
| ------------------ | ----------- | --------- | -------- | ------------------------ |
| session-start      | 150ms       | 3-5       | ✅        | Dashboard shown          |
| pre-tool-use:edit  | 120ms       | 1-2       | ✅        | Imperceptible            |
| post-tool-use:edit | 80ms        | 1         | ❌        | None (async)             |
| pre-compact        | 200ms       | 2-3       | ✅        | \~200ms compaction delay |
| user-prompt-submit | 100ms       | 1-2       | ✅        | Slight response delay    |
| stop               | 90ms        | 1         | ✅        | \~100ms stop delay       |
| session-end        | 110ms       | 2-3       | ❌        | None (async)             |
| subagent-stop      | 95ms        | 1-2       | ❌        | None (async)             |

**Total overhead across all hooks:** \~140ms average per hook execution
**Network efficiency:** 14 total MCP calls distributed across 8 hooks
**Perceived performance impact:** Minimal - blocking hooks only fire when necessary

***

## Next Steps

<CardGroup cols={2}>
  <Card title="File Conflict Prevention Deep Dive" icon="shield-check" href="/hooks/file-conflict-prevention">
    Master the pre-edit hook and achieve zero merge conflicts
  </Card>

  <Card title="Memory Integration" icon="brain" href="/hooks/memory-integration">
    Learn how pre-compact hooks preserve context automatically
  </Card>

  <Card title="Use Cases" icon="book-open" href="/hooks/use-cases">
    See real-world scenarios where hooks save hours daily
  </Card>

  <Card title="Assistant Compatibility" icon="puzzle-piece" href="/hooks/assistant-compatibility">
    Setup guides for Claude Code, Cursor, Windsurf, and more
  </Card>
</CardGroup>
