Skip to content

feat: add per-agent compaction and context pruning overrides - #19329

Closed
curtismercier wants to merge 9 commits into
openclaw:mainfrom
curtismercier:feat/per-agent-compaction-v2
Closed

curtismercier wants to merge 9 commits into
openclaw:mainfrom
curtismercier:feat/per-agent-compaction-v2

Conversation

@curtismercier

@curtismercier curtismercier commented Feb 17, 2026 •

Copy link
Copy Markdown

PR: Per-agent compaction and context pruning overrides

Title

feat: add per-agent compaction and context pruning overrides

Body

Summary

Adds per-agent compaction and contextPruning configuration to agents.list[] entries, allowing different agents to use different compaction behavior. Currently, all agents share the same global agents.defaults.compaction settings — this is a significant gap when running agents on models with different context windows or when agents have fundamentally different session lifetimes.

Motivation

A multi-agent setup might include:

  • A coding agent on a large-context model that should compact aggressively to stay fast
  • A companion agent that should never compact (managed by a plugin or external process)
  • A research agent with a higher reserveTokensFloor to preserve more working context

Today, all of these agents share identical compaction behavior. This PR lets each agent override:

  • compaction.mode — "default", "safeguard", or "off" (new)
  • compaction.reserveTokensFloor — per-agent token reserve
  • compaction.maxHistoryShare — per-agent history share limit
  • compaction.memoryFlush — per-agent flush prompt, system prompt, threshold, and enabled flag
  • contextPruning — per-agent pruning mode, TTL, and keepLastAssistants

Example config

{
  agents: {
    defaults: {
      compaction: {
        mode: "safeguard",
        reserveTokensFloor: 20000,
        memoryFlush: { enabled: true }
      }
    },
    list: [
      {
        id: "researcher",
        compaction: {
          reserveTokensFloor: 80000  // higher floor, inherits mode + memoryFlush from defaults
        }
      },
      {
        id: "plugin-managed",
        compaction: {
          mode: "off"  // compaction handled externally
        }
      },
      {
        id: "companion",
        compaction: {
          memoryFlush: {
            prompt: "Save emotional context, personal stories, and relationship details."
          }
        }
      }
    ]
  }
}

What changed

Schema & types (commit 1):

  • Extracted CompactionSchema from zod-schema.agent-defaults.ts into zod-schema.agent-runtime.ts for reuse
  • Added compaction and contextPruning fields to AgentEntrySchema
  • Added "off" to AgentCompactionMode type

Resolvers (commit 2):

  • resolveAgentCompaction(cfg, agentId?) — deep merges per-agent overrides with global defaults; memoryFlush sub-object is shallow-merged one level deeper so partial overrides don't wipe sibling fields
  • resolveAgentContextPruning(cfg, agentId?) — merges per-agent context pruning with global defaults
  • isCompactionEnabled(cfg, agentId?) — guard helper that encapsulates the mode !== "off" check

Callsite wiring (commit 3, 6 files):

  • compact.ts — skips ensurePiCompactionReserveTokens when mode is "off"
  • attempt.ts — same skip logic for run attempts
  • extensions.ts — uses resolved per-agent config for both compaction mode and context pruning
  • pi-settings.ts — resolveCompactionReserveTokensFloor now takes optional agentId
  • memory-flush.ts — resolveMemoryFlushSettings uses per-agent compaction config; returns null when mode is "off"
  • agent-runner-memory.ts — extracts agentId from session key and passes it through

Tests (commit 4):

  • 38 tests covering all resolver functions, merge semantics, mode combinations, edge cases (missing agent, empty overrides, partial memoryFlush, undefined spread safety)

Review feedback (commit 5):

  • Removed dead code in buildContextPruningExtension
  • Widened per-agent contextPruning type to include ttl and keepLastAssistants
  • Used named AgentContextPruningConfig type instead of inline return type

Integration tested

Tested on a live gateway with a dedicated test agent (claude-haiku-4-5, 200k context):

Test Config Result
Custom floor reserveTokensFloor: 80000 Compacted at ~120k used (98k → 17k) ✅
Mode off mode: "off" No compaction at 222k+ tokens ✅

Breaking changes

None. All new fields are optional. Agents without per-agent overrides behave exactly as before (global defaults apply).

Checklist

  • Schema extraction (no duplication between defaults and per-agent)
  • Deep merge with memoryFlush sub-object handling
  • mode: "off" support with guard helper
  • All callsites wired
  • 38 unit tests passing
  • Type check clean
  • Integration tested on live gateway
  • No unrelated changes in diff

Greptile Summary

Adds per-agent compaction and contextPruning configuration overrides to agents.list[] entries, enabling different agents to use different compaction behaviors. The implementation introduces a new "off" mode for compaction, along with resolver functions that deep-merge per-agent settings with global defaults.

Key changes:

  • Extracted CompactionSchema for reuse between AgentDefaultsSchema and AgentEntrySchema
  • Added resolveAgentCompaction(), resolveAgentContextPruning(), and isCompactionEnabled() helpers with proper deep-merge semantics for memoryFlush sub-object
  • Wired per-agent config through all callsites (compact.ts, attempt.ts, extensions.ts, pi-settings.ts, memory-flush.ts, agent-runner-memory.ts)
  • Added comprehensive test coverage (38 tests covering merge semantics, edge cases, mode: "off" behavior)
  • Migrated existing e2e tests to unit tests in agent-scope.test.ts

The implementation follows the existing pattern for per-agent model overrides and maintains backward compatibility - all new fields are optional and default to global settings when not specified.

Confidence Score: 5/5

  • This PR is safe to merge with minimal risk.
  • The implementation is well-architected with proper deep-merge semantics for nested config objects, comprehensive test coverage (38 tests), clean extraction of shared schema components, and systematic wiring through all callsites. The mode: "off" feature is correctly guarded at every integration point. All changes maintain backward compatibility.
  • No files require special attention

Last reviewed commit: 0a2dce7

(3/5) Reply to the agent's comments like "Can you suggest a fix for this @greptileai?" or ask follow-up questions!

Closes #13736
Closes #17735
Relates to #16546 (this PR adds per-agent compaction; contextTokens override is a separate concern)

@coolmanns coolmanns 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.

This is exactly what we need. Running 14 agents across Opus 4.6, Sonnet 4.6, and Haiku heartbeats — all sharing one global compaction config today. Per-agent overrides would let us tune reserveTokensFloor for Haiku heartbeats, disable memoryFlush on utility agents, and give coding agents more history share. 👍 from a real multi-agent deployment.

@coolmanns

Copy link
Copy Markdown
Contributor

👍 This is exactly what we need. Running 14 agents across Opus 4.6, Sonnet 4.6, and Haiku heartbeats — all sharing one global compaction config today. Per-agent overrides would let us tune reserveTokensFloor for Haiku heartbeats, disable memoryFlush on utility agents, and give coding agents more history share. Appreciate the deep merge approach — keeps the config clean.

@curtismercier

Copy link
Copy Markdown
Author

Rebased onto latest upstream/main (v2026.2.17) — no conflicts, all 38 tests passing, build clean. Also submitted a small formatting fix in #19659 found during the rebase.

@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label Feb 18, 2026
@curtismercier
curtismercier force-pushed the feat/per-agent-compaction-v2 branch from a4d47dc to 12e52d9 Compare February 18, 2026 21:37
@openclaw-barnacle openclaw-barnacle Bot removed the cli CLI command changes label Feb 18, 2026
@openclaw-barnacle openclaw-barnacle Bot added the gateway Gateway runtime label Feb 18, 2026
@fmangot

fmangot commented Feb 21, 2026

Copy link
Copy Markdown

+1 👍 Great step with per-agent compaction/context pruning. This will help immediately; looking forward to per-agent contextTokens next.

@fmangot

fmangot commented Feb 21, 2026

Copy link
Copy Markdown

One additional ask: it would be great to extend this pattern to support context limits per provider/model (or per-agent model profile), not only compaction/pruning. In mixed-model stacks this would let us tune context budgets cleanly (e.g., Codex vs GPT-5 vs Claude) without global cap tradeoffs.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Feb 28, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #pr-thunderdome-dangerzone on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime size: XL stale Marked as stale due to inactivity

Projects

None yet

3 participants