Skip to content

feat(hooks): add session:compact:pre and session:compact:post events#6768

Closed
g1itchbot8888-del wants to merge 1 commit into
openclaw:mainfrom
g1itchbot8888-del:feat/compaction-hooks
Closed

feat(hooks): add session:compact:pre and session:compact:post events#6768
g1itchbot8888-del wants to merge 1 commit into
openclaw:mainfrom
g1itchbot8888-del:feat/compaction-hooks

Conversation

@g1itchbot8888-del

@g1itchbot8888-del g1itchbot8888-del commented Feb 2, 2026

Copy link
Copy Markdown

Summary

Adds hook events before and after context compaction to allow agents to save and restore working state across compaction boundaries.

Motivation

When context compaction occurs (either manually via /compact or automatically on context overflow), agents lose their working state. This makes it difficult for memory systems to preserve continuity across compaction.

With these hooks, a memory skill can:

  1. Pre-compaction: Capture the current task state, recent decisions, and working context
  2. Post-compaction: Inject that state back into the agent's context

Events

session:compact:pre

Fired before compaction begins. Context includes:

  • sessionId: Session identifier
  • sessionFile: Path to session transcript
  • workspaceDir: Agent workspace directory
  • messageCount: Number of messages before compaction

session:compact:post

Fired after compaction completes. Context includes:

  • sessionId: Session identifier
  • sessionFile: Path to session transcript
  • workspaceDir: Agent workspace directory
  • summary: Compaction summary generated by the model
  • tokensBefore: Token count before compaction
  • tokensAfter: Token count after compaction
  • firstKeptEntryId: ID of first kept message

Example Hook

const handler: HookHandler = async (event) => {
  if (event.type === 'session' && event.action === 'compact:pre') {
    // Save working state before compaction
    const state = await captureAgentState(event.context.workspaceDir);
    await saveToMemory(state);
  }
  
  if (event.type === 'session' && event.action === 'compact:post') {
    // Inject state back after compaction
    const state = await loadFromMemory();
    await injectContext(event.context.workspaceDir, state);
  }
};

Testing

  • Tested with manual /compact command
  • Tested with auto-compaction on context overflow
  • Hooks fire in correct order (pre before, post after)

Related

This enables memory skills like openclaw-memory to maintain continuity across compaction events.

Greptile Overview

Greptile Summary

Adds two new internal hook events around Pi session compaction (session:compact:pre and session:compact:post) so hooks can persist and restore agent working state across manual or automatic compaction. Implementation wires these events into the embedded Pi compaction flow (src/agents/pi-embedded-runner/compact.ts) and documents the new events and their context fields in docs/hooks.md.

Confidence Score: 3/5

  • Generally safe to merge, but event timing/semantics likely don’t match the documented intent for pre-compaction state capture.
  • Changes are localized and straightforward, but session:compact:pre currently fires after history is already pruned/replaced, which undermines the primary use-case (capturing full pre-compaction state). Additionally, hook errors are swallowed by the internal hook dispatcher so failures won’t be visible to callers.
  • src/agents/pi-embedded-runner/compact.ts

(2/5) Greptile learns from your feedback when you react with thumbs up/down!

Context used:

  • Context from dashboard - CLAUDE.md (source)
  • Context from dashboard - AGENTS.md (source)

Adds hook events before and after context compaction to allow agents
to save and restore working state across compaction boundaries.

Events:
- session:compact:pre: fired before compaction, includes message count
- session:compact:post: fired after, includes summary and token counts

Use case: Memory systems can capture active task state before compaction
wipes the context, then inject it back after compaction completes.
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling labels Feb 2, 2026

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 file reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

Comment on lines +430 to +440
// Trigger pre-compaction hook
const preCompactEvent = createInternalHookEvent(
"session",
"compact:pre",
params.sessionKey ?? params.sessionId,
{
sessionId: params.sessionId,
sessionFile: params.sessionFile,
workspaceDir: effectiveWorkspace,
messageCount: session.messages.length,
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P0] session:compact:pre is fired after messages are already replaced/limited

The doc says “before context compaction begins”, but this event is emitted after limitHistoryTurns() and session.agent.replaceMessages(limited) have already mutated the session history; hooks that want to snapshot “current task state / working context” will see a truncated view (and messageCount will reflect the truncated count). If the intent is to snapshot the pre-compaction state, emit the hook before any pruning/replacement (or pass both counts / both message sets in context).

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/compact.ts
Line: 430:440

Comment:
[P0] `session:compact:pre` is fired after messages are already replaced/limited

The doc says “before context compaction begins”, but this event is emitted after `limitHistoryTurns()` and `session.agent.replaceMessages(limited)` have already mutated the session history; hooks that want to snapshot “current task state / working context” will see a truncated view (and `messageCount` will reflect the truncated count). If the intent is to snapshot the pre-compaction state, emit the hook before any pruning/replacement (or pass both counts / both message sets in context).

How can I resolve this? If you propose a fix, please make it concise.

Comment on lines 444 to 446
const result = await session.compact(params.customInstructions);
// Estimate tokens after compaction by summing token estimates for remaining messages
let tokensAfter: number | undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Hook failures are silently swallowed; compaction proceeds even if hooks need to block

triggerInternalHook() catches and logs handler errors internally, so a failing compact:pre/compact:post hook won’t stop compaction and the caller can’t tell it failed. If these events are meant for state preservation across compaction, this can lead to “lost state” without any surfaced error. Consider whether compaction should fail fast (or at least return warnings) when these hooks error, especially for compact:pre.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/compact.ts
Line: 444:446

Comment:
[P1] Hook failures are silently swallowed; compaction proceeds even if hooks need to block

`triggerInternalHook()` catches and logs handler errors internally, so a failing `compact:pre`/`compact:post` hook won’t stop compaction and the caller can’t tell it failed. If these events are meant for state preservation across compaction, this can lead to “lost state” without any surfaced error. Consider whether compaction should fail fast (or at least return warnings) when these hooks error, especially for `compact:pre`.

How can I resolve this? If you propose a fix, please make it concise.

@sebslight

Copy link
Copy Markdown
Contributor

Closing as duplicate of #8244. If this is incorrect, comment and we can reopen.

@sebslight sebslight closed this Feb 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants