Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 25 additions & 6 deletions docs/contracts/CONTEXT_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,8 @@ async def _compact_internal(self) -> None:
# Emit pre-compaction event
await self._hooks.emit("context:pre_compact", {
"message_count": len(self._messages),
"token_count": self._token_count
"token_count": self._token_count,
"metadata": {"strategy": "sliding_window", "trigger": "token_limit", "budget": 195000},
})

# Build tool_call_id -> tool_use index map
Expand Down Expand Up @@ -408,14 +409,26 @@ async def _compact_internal(self) -> None:
break

recent_messages = self._messages[recent_start:]

messages_removed = len(self._messages) - len(recent_messages)
self._messages = system_messages + recent_messages
self._token_count = sum(self._estimate_tokens(m) for m in self._messages)

# Emit compaction event
await self._hooks.emit("context:compaction", {
"message_count": len(self._messages),
"token_count": self._token_count,
"metadata": {
"compaction_trigger": "token-budget-exceeded",
"strategy": "budget",
"messages_removed": messages_removed,
},
})

# Emit post-compaction event
await self._hooks.emit("context:post_compact", {
"message_count": len(self._messages),
"token_count": self._token_count
"token_count": self._token_count,
"metadata": {"budget_remaining": 97500, "storage_quota_pct": 0.42},
})
```

Expand Down Expand Up @@ -496,8 +509,14 @@ coordinator.register_contributor(
```

Standard events to emit:
- `context:pre_compact` - Before compaction (include message_count, token_count)
- `context:post_compact` - After compaction (include new counts)
- `context:pre_compact` - Before compaction (include message_count, token_count, metadata)
- `context:post_compact` - After compaction (include new counts, metadata)
- `context:compaction` - After compaction with strategy details (include before/after stats, metadata)

All context events should include an optional `metadata: dict | null` field as an
extensible property bag for implementation-specific data (e.g., compaction strategy
variant, trigger reason, context manager configuration). Consumers that don't need
metadata ignore it. Set to `null` when no implementation-specific data is available.

See [CONTRIBUTION_CHANNELS.md](../specs/CONTRIBUTION_CHANNELS.md) for the pattern.

Expand Down Expand Up @@ -530,7 +549,7 @@ Additional examples:
### Recommended

- [ ] Token counting for accurate compaction triggers
- [ ] Emits context:pre_compact and context:post_compact events
- [ ] Emits context:pre_compact and context:post_compact events with metadata field
- [ ] Preserves system messages during compaction
- [ ] Thread-safe for concurrent access
- [ ] Configurable thresholds
Expand Down