Skip to main content

Context Hooks

Context hooks let you observe and modify context tree operations - every insert, update, and delete that happens to the PACT structure.

Overview

Context hooks provide 5 execution points:

Hook Registration

Decorator Syntax

Subscribe API

Context Hook Context

Every context hook receives a ContextExecContext with:

Execution Flow

Before Change Hook

Fires before any context operation - can cancel by raising exception:

After Change Hook

Fires after any context operation - for auditing and reactive updates:

On Add Hook

Fires when a component is added to context:

On Dispatch Hook

Fires when a component is dispatched/published:

On Update Hook

Fires when a component is updated:

Usage Patterns

Pattern 1: Context Size Monitoring

Track context tree size and warn on growth:

Pattern 2: Change History Tracking

Maintain complete history of context modifications:

Pattern 3: Reactive Scaffold Updates

Trigger scaffold re-renders on context changes:

Pattern 4: Component Validation

Enforce component structure rules:

Pattern 5: Depth-Based Policies

Apply different rules based on context depth:

Pattern 6: Context Snapshots

Automatically create snapshots on significant changes:

Reactive Scaffolds

Context hooks are the foundation of reactive scaffolds - all scaffolds with _reactive = True automatically re-render on context changes:
How it works:
  1. CONTEXT_AFTER_CHANGE hook fires on every context modification
  2. Reactive scaffolds check should_rerender(ctx)
  3. If True, scaffold’s render() is called automatically
  4. New content updates context tree

Operation Types

Context hooks fire for three operation types:

Insert Operations

Update Operations

Delete Operations

Best Practices

Performance Considerations

  • Hook overhead: Less than 3ms per hook on average
  • before_change blocking: Blocks operation until completed
  • after_change async: Runs after operation completes
  • Reactive scaffolds: Less than 5% overhead with 5+ scaffolds

Integration with Scaffolds

Context hooks enable reactive scaffolds:

Error Handling

Errors in before_change cancel the operation:

What’s Next?

Tool Hooks

Tool execution lifecycle hooks

Streaming Hooks

Real-time content processing

Subscribe API

Dynamic hook registration

Context Management

Learn about the context tree