Skip to main content

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:

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

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-agentWhy it matters: Other agents can discover and message you
Shows critical coordination info at session start:
╔══════════════════════════════════════════════╗
║  🤖 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-reservationsWhy it matters: You see coordination status before starting work
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-memoriesWhy it matters: AI has context from previous sessions without manual explanation
Warns if critical acknowledgments are pending:
⚠️  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-itemsWhy it matters: You don’t forget critical obligations

Exit Codes

CodeMeaningWhen Used
0Allow session startDefault - no blocking issues
2Block session startCritical pending acks that must be addressed first
Example blocking scenario:
⛔ 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

~/.ulpi/config.json
{
  "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

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-pathsResult: Zero merge conflicts, guaranteed
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 expirationMCP Tool Used: reserve-file-pathsWhy it matters: You don’t manually manage file locks
When edits are blocked, suggests coordination actions:
⛔ 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

Exit Codes

CodeMeaningWhen Used
0Allow editFile available OR already reserved by this agent
2Block editFile 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

~/.ulpi/config.json
{
  "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

Shows tasks/obligations related to the edited file:
📋 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-itemsWhy it matters: You don’t forget required follow-ups
If edit is part of a tracked task, updates task progress:
✓ 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
Records edit for coordination audit trail:
  • Timestamp
  • File path
  • Agent identity
  • Reservation status
  • Lines changed
MCP Tool Used: log-eventWhy it matters: Complete transparency for team oversight

Exit Codes

CodeMeaningWhen Used
0ContinueAlways (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

~/.ulpi/config.json
{
  "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

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-memoryResult: Critical context preserved even after compaction
Intelligently extracts what matters:
💾 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

Exit Codes

CodeMeaningWhen Used
0Allow compactionDefault - snapshot created successfully
2Block compactionCritical 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

~/.ulpi/config.json
{
  "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

Displays high-priority coordination messages before AI responds:
🚨 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
Reminds about pending acks that need attention:
📬 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-itemsWhy it matters: Obligations don’t get forgotten

Exit Codes

CodeMeaningWhen Used
0Allow responseNo urgent messages or user dismissed alerts
2Block responseUrgent 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

~/.ulpi/config.json
{
  "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

Blocks stop if critical operations are incomplete:
⚠️  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
Warns about unacknowledged critical messages:
⚠️  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-itemsWhy it matters: Important coordination doesn’t fall through cracks

Exit Codes

CodeMeaningWhen Used
0Allow stopSafe to stop - no critical pending operations
2Block stopCritical 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

~/.ulpi/config.json
{
  "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

Releases all file reservations automatically:
🧹 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-reservationsResult: Zero orphaned file locks
Marks agent as offline in Coordination:
  • Sets status to “offline”
  • Records last seen timestamp
  • Updates session duration
MCP Tool Used: update-agent-statusWhy it matters: Other agents know you’re no longer active
Optionally creates final memory snapshot:
  • Saves unresolved tasks
  • Records session learnings
  • Stores pending obligations
MCP Tool Used: store-memoryWhy it matters: Next session continues seamlessly

Exit Codes

CodeMeaningWhen Used
0Complete cleanupAlways (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

~/.ulpi/config.json
{
  "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

Stores subagent learnings to shared memory:
📚 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-memoryWhy it matters: Subagent learnings benefit entire team
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-reservationsWhy it matters: No orphaned locks from subagents
Reports subagent results to parent:
✓ 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-taskWhy it matters: Parent agent knows when delegated work is done

Exit Codes

CodeMeaningWhen Used
0Complete cleanupAlways (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

~/.ulpi/config.json
{
  "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

HookAvg LatencyMCP CallsBlockingUser Impact
session-start150ms3-5Dashboard shown
pre-tool-use:edit120ms1-2Imperceptible
post-tool-use:edit80ms1None (async)
pre-compact200ms2-3~200ms compaction delay
user-prompt-submit100ms1-2Slight response delay
stop90ms1~100ms stop delay
session-end110ms2-3None (async)
subagent-stop95ms1-2None (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