openclaw - 💡(How to fix) Fix Feature request: native config-backed automatic context rollover with durable handoff for Telegram/direct sessions [1 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
openclaw/openclaw#75699Fetched 2026-05-02 05:31:29
View on GitHub
Comments
1
Participants
2
Timeline
1
Reactions
2
Author
Timeline (top)
commented ×1

Please add native, config-backed automatic context/session rollover for long-running channel sessions, especially Telegram direct sessions.

OpenClaw already supports session reset triggers like /new and /reset, plus lazy reset policy via session.reset. However, long-running owner/operator sessions can grow large without the user realizing it. Today, the system can remain on an aging high-token session until the user manually types /new, /reset, or until a context overflow/compaction path is hit.

Requested feature: a native session guard that monitors context usage percentage and automatically prepares handoff summaries and routes future inbound messages into a fresh session before the session becomes unstable.

Primary target channels:

  • Telegram direct sessions
  • other long-running direct messaging channels
  • business-owner/operator sessions where the same peer chats with the assistant for days/weeks

Error Message

"warn": false, "warn": false, Warn/checkpoint stage. "warn": false, State: warn

Root Cause

Because at 90%+ usage, the existing entry may be “fresh” by time-based policy but unhealthy by context pressure.

Fix Action

Fix / Workaround

A local patch/wrapper is risky because:

Code Example

{
  "session": {
    "contextRollover": {
      "enabled": true,
      "channels": ["telegram"],
      "sessionTypes": ["direct"],
      "warnPercent": 80,
      "handoffPercent": 88,
      "rolloverPercent": 90,
      "mode": "same-session-key-new-session-id",
      "preserveDelivery": true,
      "handoff": {
        "enabled": true,
        "dir": "${OPENCLAW_HOME}/session-handoffs",
        "includeRecentMessages": true,
        "maxRecentMessages": 20,
        "maxSummaryTokens": 1200,
        "retention": "30d"
      },
      "notifications": {
        "warn": false,
        "rollover": true,
        "rolloverMessage": "I started a fresh work session to keep things stable and carried over the important context."
      },
      "dryRun": false
    }
  }
}

---

{
  "session": {
    "contextRolloverByChannel": {
      "telegram": {
        "enabled": true,
        "warnPercent": 80,
        "handoffPercent": 88,
        "rolloverPercent": 90,
        "notifications": {
          "warn": false,
          "rollover": true
        }
      }
    }
  }
}

---

{
  "session": {
    "contextRolloverByType": {
      "direct": {
        "enabled": true,
        "rolloverPercent": 90
      },
      "group": {
        "enabled": false
      },
      "thread": {
        "enabled": false
      }
    }
  }
}

---

contextUsagePercent < warnPercent

---

contextUsagePercent >= warnPercent

---

contextUsagePercent >= handoffPercent

---

contextUsagePercent >= rolloverPercent

---

same logical channel/session key
new backing session id
old transcript retained
handoff summary stored
new session receives handoff context
delivery identity preserved

---

channel
provider
account id
chat/direct identity
delivery context
thread id, if applicable
last recipient/to field

---

same logical sessionKey
new backing sessionId
old transcript retained

---

{
  "oldSessionId": "...",
  "newSessionId": "...",
  "handoffPath": "...",
  "rolledOverAt": "...",
  "reason": "context_rollover_threshold"
}

---

{
  "dryRun": true
}

---

{
  "notifications": {
    "warn": false,
    "rollover": true
  }
}

---

/new
/reset
/compact
session.reset
session.resetByType
session.resetByChannel
session.maintenance

---

handoffPercent < warnPercent
rolloverPercent < handoffPercent
rolloverPercent > 100
warnPercent <= 0

---

/context_status
/handoff_now --dry-run
/rollover_now --dry-run

---

inbound message received
sessionKey resolved
sessionStore[sessionKey] loaded
context rollover policy evaluated
possible handoff/rollover performed
normal reply continues

---

resolveSessionResetPolicy(...)
evaluateSessionFreshness(...)
evaluateContextRolloverPolicy(...)
maybePrepareHandoff(...)
maybeRolloverBackingSession(...)

---

if existing entry is fresh, reuse entry.sessionId

---

usagePercent = totalTokens / contextTokens * 100

---

totalTokens
contextTokens
totalTokensFresh

---

{
  "sessionKey": "<session-key>",
  "oldSessionId": "<old-session-id>",
  "newSessionId": "<new-session-id-if-rolled-over>",
  "channel": "telegram",
  "sessionType": "direct",
  "usagePercent": 90.4,
  "reason": "context_rollover_threshold",
  "handoffPath": "<handoff-path>",
  "createdAt": "<timestamp>",
  "rolledOverAt": "<timestamp-or-null>"
}

---

# Session Handoff

Generated: <timestamp>
Channel: telegram
Session type: direct
Context usage: <percent>

## Current task/context summary

<concise summary>

## Important facts to carry forward

- ...

## Open items

- ...

## Last meaningful user intent

<short sanitized summary>

## New-session instruction

Continue the same conversation using this handoff as continuity context.
Do not mention internal session mechanics unless the user asks.

---

/context_status

---

/handoff_now

---

/handoff_latest

---

/rollover_now

---

Session health

Context: 82.4%
State: warn
Rollover threshold: 90%
Handoff: not created yet
Auto-rollover: enabled

---

Session health

Context: 88.7%
State: handoff_prepared
Rollover threshold: 90%
Handoff: created
Auto-rollover: enabled

---

I started a fresh work session to keep things stable and carried over the important context.

---

{
  "session": {
    "contextRollover": {
      "enabled": false
    }
  }
}

---

/new
/reset
/compact
session.reset
session.resetByType
session.resetByChannel
session.maintenance
RAW_BUFFERClick to expand / collapse

Summary

Please add native, config-backed automatic context/session rollover for long-running channel sessions, especially Telegram direct sessions.

OpenClaw already supports session reset triggers like /new and /reset, plus lazy reset policy via session.reset. However, long-running owner/operator sessions can grow large without the user realizing it. Today, the system can remain on an aging high-token session until the user manually types /new, /reset, or until a context overflow/compaction path is hit.

Requested feature: a native session guard that monitors context usage percentage and automatically prepares handoff summaries and routes future inbound messages into a fresh session before the session becomes unstable.

Primary target channels:

  • Telegram direct sessions
  • other long-running direct messaging channels
  • business-owner/operator sessions where the same peer chats with the assistant for days/weeks

Observed current behavior

In OpenClaw 2026.4.27:

  • session.reset is supported.
  • /new and /reset are supported.
  • /compact is supported.
  • session.maintenance is supported for session-store pruning/retention.
  • Idle/daily reset appears to be evaluated lazily during inbound message/session initialization.
  • Existing sessions may still appear in the Sessions UI as old/stale until a new inbound message arrives.
  • There does not appear to be native config-backed support for:
    • session.contextSafety
    • percent-based automatic rollover
    • /context_status
    • /handoff_now
    • /handoff_latest
    • /rollover_now
    • durable handoff creation before rollover
    • automatic fresh session routing at a context usage threshold

This means a long-running Telegram direct session can accumulate a large context footprint without proactive rollover.

Why lazy idle reset is not enough

Lazy idle reset is useful, but it solves a different problem.

session.reset.idleMinutes / daily reset answers:

“Should this old session be considered stale the next time an inbound message arrives?”

It does not answer:

“Is this active session approaching model context limits and likely to become unstable?”

A session may remain active for hours and continue growing. If the user keeps sending messages, idle reset may never trigger. Daily reset may also not be ideal if the session is still active but already context-heavy before the reset window.

Also, lazy reset does not automatically produce a durable handoff summary, so even if a new session starts, continuity can be lost unless the user manually manages the transition.

For context-heavy assistant workflows, especially owner/operator usage, automatic rollover should be based on context/token pressure, not only time since last interaction.

Why Telegram owner/operator usage needs automatic rollover

Telegram is commonly used as a lightweight “always available” owner/operator interface.

In that mode:

  • the same Telegram direct session may stay active for days or weeks
  • the owner may use the assistant for unrelated tasks in one channel
  • the session can grow large without obvious warning
  • the user should not need to understand context windows or remember to type /new
  • context overflow or emergency compaction is too late as the primary control
  • continuity matters; a fresh session should receive a concise handoff summary

For business-owner or personal-operator channels, the assistant should quietly keep itself healthy.

The desired behavior is:

When the session gets too large, OpenClaw should preserve the same Telegram peer identity, create a handoff summary, and route the next message into a fresh backing session automatically.

No customer/operator should need to know internal session mechanics.

Proposed config shape

Example:

{
  "session": {
    "contextRollover": {
      "enabled": true,
      "channels": ["telegram"],
      "sessionTypes": ["direct"],
      "warnPercent": 80,
      "handoffPercent": 88,
      "rolloverPercent": 90,
      "mode": "same-session-key-new-session-id",
      "preserveDelivery": true,
      "handoff": {
        "enabled": true,
        "dir": "${OPENCLAW_HOME}/session-handoffs",
        "includeRecentMessages": true,
        "maxRecentMessages": 20,
        "maxSummaryTokens": 1200,
        "retention": "30d"
      },
      "notifications": {
        "warn": false,
        "rollover": true,
        "rolloverMessage": "I started a fresh work session to keep things stable and carried over the important context."
      },
      "dryRun": false
    }
  }
}

Optional per-channel override:

{
  "session": {
    "contextRolloverByChannel": {
      "telegram": {
        "enabled": true,
        "warnPercent": 80,
        "handoffPercent": 88,
        "rolloverPercent": 90,
        "notifications": {
          "warn": false,
          "rollover": true
        }
      }
    }
  }
}

Optional per-session-type override:

{
  "session": {
    "contextRolloverByType": {
      "direct": {
        "enabled": true,
        "rolloverPercent": 90
      },
      "group": {
        "enabled": false
      },
      "thread": {
        "enabled": false
      }
    }
  }
}

Desired behavior

Below 80%

No action.

contextUsagePercent < warnPercent

The session continues normally.

At or above 80%

Warn/checkpoint stage.

contextUsagePercent >= warnPercent

Desired behavior:

  • record that the session is approaching the configured threshold
  • optionally show a warning if enabled
  • do not force rollover yet
  • avoid repeated warnings on every message
  • store lightweight internal rollover state

Default recommendation: no user-visible warning for Telegram/customer-style channels unless explicitly enabled.

At or above 88%

Durable handoff stage.

contextUsagePercent >= handoffPercent

Desired behavior:

  • create or refresh a durable handoff summary
  • retain old session/transcript
  • do not force a new session yet unless threshold is also above rollover threshold
  • store handoff metadata in rollover state
  • avoid creating duplicate handoff files on every message unless content materially changes

At or above 90%

Automatic rollover stage.

contextUsagePercent >= rolloverPercent

Desired behavior:

  1. Ensure a current handoff summary exists.
  2. Preserve the same channel peer identity.
  3. Preserve the same logical sessionKey.
  4. Create a fresh backing session/session id.
  5. Route the inbound message into that fresh session.
  6. Attach/inject the handoff summary into the new session context.
  7. Retain/archive old session safely.
  8. Optionally send a short rollover notice if configured.

Important: this should behave like automatic /new, but with durable handoff and without requiring the user to type /new.

Recommended default behavior:

same logical channel/session key
new backing session id
old transcript retained
handoff summary stored
new session receives handoff context
delivery identity preserved

Rollover should be atomic/idempotent:

  • If the session is already rolled over, do not roll it again.
  • If a handoff already exists for the current old session id, reuse/update it.
  • If handoff generation fails, do not destroy or detach the old session.
  • If delivery identity cannot be safely preserved, block rollover and report/log a safe warning instead of risking broken Telegram replies.

Safety requirements

Preserve delivery identity

For Telegram direct sessions, rollover must preserve all fields needed to reply to the same peer.

Examples:

channel
provider
account id
chat/direct identity
delivery context
thread id, if applicable
last recipient/to field

The rollover must not create an orphaned session that cannot reply.

Preserve logical session key

The feature should not require a new Telegram peer/session key.

Desired model:

same logical sessionKey
new backing sessionId
old transcript retained

Never delete old sessions by default

Automatic rollover should not delete old transcripts/sessions.

Old session data should remain available under normal retention/archive policy.

Durable handoff before rollover

At rollover threshold, OpenClaw should ensure a handoff summary exists before replacing the backing session id.

If handoff creation fails:

  • do not roll over silently
  • keep existing session attached
  • log/report failure safely
  • optionally attempt compaction if configured

Idempotent behavior

Repeated inbound messages should not cause repeated handoff/rollover loops.

The system should track:

{
  "oldSessionId": "...",
  "newSessionId": "...",
  "handoffPath": "...",
  "rolledOverAt": "...",
  "reason": "context_rollover_threshold"
}

If the same session was already rolled over, no duplicate rollover should occur.

Dry-run support

Config should support:

{
  "dryRun": true
}

Dry-run should:

  • calculate usage
  • report what would happen
  • optionally write a dry-run report
  • not mutate session store
  • not send messages
  • not create a new backing session

Quiet by default

For messaging channels, warnings should be configurable and quiet by default.

Suggested default:

{
  "notifications": {
    "warn": false,
    "rollover": true
  }
}

Customer-facing installs may want even rollover notifications disabled.

Avoid sensitive data leakage

Handoff summaries and status commands should not expose:

  • tokens
  • auth secrets
  • private local filesystem paths unless explicitly requested by an authorized local operator
  • raw peer ids unless necessary and authorized
  • unrelated user memory/context
  • private account identifiers in user-facing messages

Peer/session identifiers should be redacted in normal user-facing output.

Compatible with existing session features

This feature should not break:

/new
/reset
/compact
session.reset
session.resetByType
session.resetByChannel
session.maintenance

Context rollover should be a separate lifecycle policy that coexists with idle/daily reset.

Testing expectations

Unit tests

Add tests for:

  • config parsing
  • disabled policy
  • invalid threshold ordering
  • channel filtering
  • session type filtering
  • usage percent calculation
  • missing token fields
  • dry-run mode
  • notification settings
  • handoff retention config

Threshold validation should reject unsafe ordering such as:

handoffPercent < warnPercent
rolloverPercent < handoffPercent
rolloverPercent > 100
warnPercent <= 0

Session-store tests

Use copied/fake session stores.

Cases:

  1. 50% usage → no action
  2. 80% usage → warning/checkpoint state
  3. 88% usage → handoff summary created
  4. 90% usage → new backing session id created
  5. missing contextTokens → safe no-op or fallback estimate
  6. missing delivery context → block rollover safely
  7. repeated 90% checks → no duplicate rollover
  8. old session retained
  9. same logical session key preserved
  10. handoff generation failure → no destructive mutation
  11. dry-run mode → no mutation

Telegram/direct-channel simulation

Test with fake Telegram-like direct session metadata, not a real token or real peer.

Validate:

  • same logical session key remains
  • delivery fields are preserved
  • new backing session id is created
  • old transcript remains
  • handoff is available to new session
  • optional rollover notice is generated only if configured
  • no real Telegram network send happens in tests

Integration tests

Safe integration path:

  1. create a fake direct channel session
  2. seed token usage above threshold
  3. pass a simulated inbound message through the local reply/session initialization path
  4. verify rollover happens before model call
  5. verify reply flow uses new session id
  6. verify old session transcript remains
  7. verify handoff is injected/attached to new session context
  8. verify no real Telegram send occurs in test mode

Manual operator tests

Suggested dry-run/status commands:

/context_status
/handoff_now --dry-run
/rollover_now --dry-run

Suggested live test process:

  1. enable feature only for a test peer/channel
  2. seed a test session above threshold
  3. send one harmless test message
  4. verify new backing session id
  5. verify delivery still works
  6. verify old session retained
  7. only then consider enabling for real owner/operator sessions

Implementation notes / likely hook point

The guard should run after OpenClaw resolves the logical session key and loads the existing session entry, but before it decides to reuse the old backing session id.

Conceptual hook:

inbound message received
sessionKey resolved
sessionStore[sessionKey] loaded
context rollover policy evaluated
possible handoff/rollover performed
normal reply continues

This likely belongs near existing session freshness/reuse logic, not in maintenance pruning.

Conceptual structure:

resolveSessionResetPolicy(...)
evaluateSessionFreshness(...)
evaluateContextRolloverPolicy(...)
maybePrepareHandoff(...)
maybeRolloverBackingSession(...)

The feature should run before this kind of decision:

if existing entry is fresh, reuse entry.sessionId

Because at 90%+ usage, the existing entry may be “fresh” by time-based policy but unhealthy by context pressure.

Context usage calculation

Preferred calculation:

usagePercent = totalTokens / contextTokens * 100

Use cached session-store token fields when fresh:

totalTokens
contextTokens
totalTokensFresh

Fallbacks:

  1. latest runtime usage metadata
  2. transcript/context estimate
  3. safe no-op with warning if usage cannot be determined

If usage cannot be determined, default should be non-destructive.

Handoff generation

The handoff summary should be generated before the old session becomes unstable.

Possible sources:

  • recent transcript messages
  • current session metadata
  • existing summaries/compaction artifacts if available
  • model-generated concise summary

Suggested handoff metadata:

{
  "sessionKey": "<session-key>",
  "oldSessionId": "<old-session-id>",
  "newSessionId": "<new-session-id-if-rolled-over>",
  "channel": "telegram",
  "sessionType": "direct",
  "usagePercent": 90.4,
  "reason": "context_rollover_threshold",
  "handoffPath": "<handoff-path>",
  "createdAt": "<timestamp>",
  "rolledOverAt": "<timestamp-or-null>"
}

Suggested handoff content:

# Session Handoff

Generated: <timestamp>
Channel: telegram
Session type: direct
Context usage: <percent>

## Current task/context summary

<concise summary>

## Important facts to carry forward

- ...

## Open items

- ...

## Last meaningful user intent

<short sanitized summary>

## New-session instruction

Continue the same conversation using this handoff as continuity context.
Do not mention internal session mechanics unless the user asks.

Suggested commands

Optional but useful:

/context_status

Shows current session usage and configured threshold state.

/handoff_now

Forces handoff summary creation for current session without rollover.

/handoff_latest

Shows latest handoff metadata/path for current session.

/rollover_now

Forces rollover for current session, preserving channel identity and creating handoff first.

All commands should obey authorization rules and avoid exposing sensitive channel identifiers to unauthorized users.

Example status output

Session health

Context: 82.4%
State: warn
Rollover threshold: 90%
Handoff: not created yet
Auto-rollover: enabled

At handoff stage:

Session health

Context: 88.7%
State: handoff_prepared
Rollover threshold: 90%
Handoff: created
Auto-rollover: enabled

At rollover:

I started a fresh work session to keep things stable and carried over the important context.

Backwards compatibility

Default should be disabled unless explicitly enabled:

{
  "session": {
    "contextRollover": {
      "enabled": false
    }
  }
}

Existing installs should not change behavior unless configured.

Existing commands and policies should keep working:

/new
/reset
/compact
session.reset
session.resetByType
session.resetByChannel
session.maintenance

The new policy should layer beside time-based reset, not replace it.

Why this belongs upstream

This is core session lifecycle behavior.

A local patch/wrapper is risky because:

  • bundled runtime files change between releases
  • Telegram delivery/session identity must be preserved carefully
  • rollover must happen before session reuse/model invocation
  • session store mutation must be atomic and idempotent
  • handoff generation should integrate with transcript/session metadata
  • config schema, docs, commands, and runtime behavior should stay aligned

Native support would make long-running OpenClaw deployments safer and less dependent on users manually remembering /new.

This is especially useful for:

  • Telegram owner/operator sessions
  • always-on personal assistants
  • business assistants
  • long-running direct message channels
  • mobile-first workflows where the user does not monitor context usage

Acceptance criteria

A complete implementation should satisfy:

  • config schema accepts session.contextRollover
  • default behavior remains unchanged when disabled
  • Telegram direct sessions can be configured for automatic rollover
  • usage thresholds are evaluated before reusing an existing backing session
  • 80% warning/checkpoint behavior works
  • 88% durable handoff behavior works
  • 90% automatic fresh-session routing works
  • same logical Telegram session key/peer identity is preserved
  • old session/transcript is retained
  • new session receives handoff context
  • dry-run mode verifies behavior without mutation
  • commands/status are authorization-safe
  • tests cover fake direct-channel sessions without real Telegram sends
  • repeated messages do not cause duplicate rollovers
  • handoff failure does not detach or destroy the active session

extent analysis

TL;DR

To implement native, config-backed automatic context/session rollover for long-running channel sessions, especially Telegram direct sessions, modify the session management logic to evaluate context usage percentage and automatically prepare handoff summaries and route future inbound messages into a fresh session before the session becomes unstable.

Guidance

  • Evaluate the context usage percentage before reusing an existing backing session to determine if a rollover is needed.
  • Implement a handoff mechanism that creates a durable handoff summary before replacing the backing session ID, ensuring continuity and preserving the same logical session key and delivery identity.
  • Develop a dry-run mode to verify behavior without mutating the session store, and ensure that repeated messages do not cause duplicate rollovers.
  • Integrate the new policy with existing session features, such as idle/daily reset, and ensure that it does not break existing commands and policies.
  • Implement authorization-safe commands and status outputs to provide users with information about session health and rollover status.

Example

{
  "session": {
    "contextRollover": {
      "enabled": true,
      "channels": ["telegram"],
      "sessionTypes": ["direct"],
      "warnPercent": 80,
      "handoffPercent": 88,
      "rolloverPercent": 90
    }
  }
}

This example configuration enables automatic context rollover for Telegram direct sessions, with warning, handoff, and rollover thresholds set to 80%, 88%, and 90%, respectively.

Notes

  • The implementation should ensure that the new policy layers beside time-based reset and does not replace it, providing a separate lifecycle policy that coexists with idle/daily reset.
  • The feature should be designed to preserve delivery identity and logical session key, and should not delete old sessions by default, instead retaining them under normal retention/archive policy.
  • The handoff summary should be generated before the old session becomes unstable, and should include relevant information such as recent transcript

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

openclaw - 💡(How to fix) Fix Feature request: native config-backed automatic context rollover with durable handoff for Telegram/direct sessions [1 comments, 2 participants]