Skip to content

feat: support per-agent compaction overrides in agents.list[] - #14598

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

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

Conversation

@curtismercier

@curtismercier curtismercier commented Feb 12, 2026 •

Copy link
Copy Markdown

Summary

Adds optional compaction configuration to individual agent entries in agents.list[], allowing per-agent override of agents.defaults.compaction settings. When a per-agent compaction config is present, it takes precedence over the global defaults for that agent. When absent, the agent inherits the global defaults — no behavioral change for existing configurations.

Motivation

Multi-agent deployments often need different context management strategies for different agents. A long-running research agent benefits from aggressive memory flushing and a high reserveTokensFloor, while a quick-turnaround chat agent may need earlier compaction via a lower maxHistoryShare. An orchestration agent might use safeguard mode while execution agents stay on default.

Today, compaction is only configurable globally in agents.defaults.compaction, which forces all agents into the same strategy. Other agent-level settings like heartbeat, humanDelay, memorySearch, and tools already support per-agent overrides — compaction is the notable gap.

Example:

agents:
  defaults:
    compaction:
      mode: default
      reserveTokensFloor: 20000
      memoryFlush:
        enabled: true
        softThresholdTokens: 50000
  list:
    - id: researcher
      compaction:
        reserveTokensFloor: 40000  # Higher floor — preserve more context
        maxHistoryShare: 0.8       # Compact later
    - id: executor
      compaction:
        maxHistoryShare: 0.4       # Compact earlier — short-lived tasks
        memoryFlush:
          enabled: false           # No pre-compaction flush needed
    - id: chat
      # No compaction override — inherits defaults

Changes

  • Extract compaction Zod schema into reusable CompactionSchema constant, add to AgentEntrySchema (zod-schema.agent-runtime.ts, zod-schema.agent-defaults.ts)
  • Add compaction to ResolvedAgentConfig and resolveAgentConfig() output (agent-scope.ts)
  • Add resolveAgentCompaction(cfg, agentId?) helper — merges per-agent overrides with global defaults:
    • Top-level fields: per-agent wins, falls back to default
    • memoryFlush sub-object: shallow-merged one level deeper so partial overrides (e.g., enabled: false) don't wipe the default prompt/systemPrompt
    • Returns undefined when neither per-agent nor defaults are set
  • Update resolveCompactionMode(), resolveCompactionReserveTokensFloor(), resolveMemoryFlushSettings() to accept optional agentId and use merged config (extensions.ts, pi-settings.ts, memory-flush.ts)
  • Thread agentId (via sessionAgentId) through all callsites in compact.ts, run/attempt.ts, agent-runner-memory.ts

How Resolution Works

Per-agent (agents.list[].compaction)
  ↓ overrides
Global defaults (agents.defaults.compaction)
  ↓ falls back to
Hardcoded defaults (DEFAULT_PI_COMPACTION_RESERVE_TOKENS_FLOOR, etc.)

For memoryFlush, the merge is one level deeper:

// Per-agent memoryFlush = { enabled: false }
// Default memoryFlush = { enabled: true, softThresholdTokens: 50000, prompt: "..." }
// Resolved = { enabled: false, softThresholdTokens: 50000, prompt: "..." }

Testing

12 test cases in agent-scope.test.ts covering:

  • Per-agent override takes precedence over defaults
  • Fallback to defaults when no per-agent config
  • Partial override merges correctly (e.g., only maxHistoryShare set, inherits mode and memoryFlush)
  • memoryFlush sub-object shallow merge — partial override preserves unrelated default fields
  • Unknown agent falls back to global defaults
  • No config at all returns undefined (hardcoded fallbacks apply)
  • NaN safety on reserveTokensFloor

Backward Compatibility

Fully backward compatible. The compaction field on agent entries is optional. Existing configs with no per-agent compaction work exactly as before — all three resolution functions fall back to agents.defaults.compaction. No new required fields.

Monkey Patch (for immediate use)

A standalone patch script for current OpenClaw releases is available at curtismercier/openclaw-mods — apply/revert/status with version tracking and pre-flight safety checks.

Closes #13736
Closes #14446

Greptile Overview

Greptile Summary

This PR adds per-agent compaction overrides under agents.list[], reusing a shared CompactionSchema, and threads an agentId through compaction/memory-flush resolution so individual agents can override agents.defaults.compaction.

The main behavioral change is centralized in resolveAgentCompaction(cfg, agentId?) (src/agents/agent-scope.ts), which merges per-agent and default compaction settings (including a one-level-deeper merge for memoryFlush). Call sites in embedded runner setup and memory flush now pass the session’s effective agent id so the right compaction settings are applied per agent.

Confidence Score: 2/5

  • This PR is not safe to merge as-is due to a confirmed runtime crash in compaction resolution when only per-agent memoryFlush is configured.
  • The new resolveAgentCompaction merge logic can throw a TypeError by spreading undefined when an agent defines compaction.memoryFlush but defaults omit it. This is a straightforward, high-impact runtime failure in a newly introduced codepath. Other changes look consistent and well-covered by tests, but this edge case isn’t exercised by the current test suite.
  • src/agents/agent-scope.ts

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

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Feb 12, 2026
@curtismercier
curtismercier force-pushed the feat/per-agent-compaction branch from f995375 to 770e7ff Compare February 12, 2026 10:59

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

10 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

Comment thread src/agents/agent-scope.ts
Comment on lines +151 to +158
return {
...defaults,
...perAgent,
memoryFlush:
perAgent.memoryFlush || defaults.memoryFlush
? { ...defaults.memoryFlush, ...perAgent.memoryFlush }
: 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.

MemoryFlush merge bug

resolveAgentCompaction does { ...defaults.memoryFlush, ...perAgent.memoryFlush } when either side is present, but defaults.memoryFlush can be undefined. Spreading undefined throws at runtime when an agent defines compaction.memoryFlush but agents.defaults.compaction.memoryFlush is not set. This makes per-agent memoryFlush unusable unless defaults also define memoryFlush.

A safe merge needs to spread {} instead of undefined (or branch on each side) before spreading.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/agent-scope.ts
Line: 151:158

Comment:
**MemoryFlush merge bug**

`resolveAgentCompaction` does `{ ...defaults.memoryFlush, ...perAgent.memoryFlush }` when either side is present, but `defaults.memoryFlush` can be `undefined`. Spreading `undefined` throws at runtime when an agent defines `compaction.memoryFlush` but `agents.defaults.compaction.memoryFlush` is not set. This makes per-agent `memoryFlush` unusable unless defaults also define `memoryFlush`.

A safe merge needs to spread `{}` instead of `undefined` (or branch on each side) before spreading.


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

@curtismercier

Copy link
Copy Markdown
Author

Good catch by @greptile-apps — fixed in cb33279.

The memoryFlush spread now uses nullish coalescing on both sides to guard against undefined:

{ ...(defaults.memoryFlush ?? {}), ...(perAgent.memoryFlush ?? {}) }

Added a test case for the exact scenario: per-agent defines memoryFlush when agents.defaults.compaction has no memoryFlush sub-object.

@greptile-apps

greptile-apps Bot commented Feb 12, 2026

Copy link
Copy Markdown
Contributor

Thanks for the quick fix! I verified the commit and the new test case looks good.

The nullish coalescing guards on both spreads correctly handle all three scenarios:

  1. Both defined → shallow merge as intended
  2. Only defaults defined → spreads defaults, empty object from per-agent (no-op)
  3. Only per-agent defined (the crash scenario) → spreads empty object from defaults, per-agent config wins

The new test case 'resolves memoryFlush when only per-agent config is set' directly exercises scenario 3, and the implementation now returns { enabled: false } instead of throwing.

One minor observation: the test expects softThresholdTokens and prompt to be absent in the resolved config when defaults don't provide them. That's correct behavior — the downstream code will fall back to hardcoded defaults. Just making sure you intended that (vs. e.g., always injecting hardcoded defaults at resolution time). Based on the pattern in resolveMemoryFlushSettings(), this is consistent with how other fallbacks work.

Extract the compaction Zod schema from AgentDefaultsSchema into a
reusable CompactionSchema constant in zod-schema.agent-runtime.ts.
Add it as an optional field on AgentEntrySchema, enabling per-agent
compaction overrides alongside the existing defaults.

AgentDefaultsSchema now imports and reuses CompactionSchema, keeping
the shape in sync and eliminating duplication.
…n helper

Add compaction field to the ResolvedAgentConfig type and include it
in resolveAgentConfig() output.

Introduce resolveAgentCompaction(cfg, agentId?) which merges per-agent
compaction overrides with agents.defaults.compaction. Top-level fields
use per-agent-wins semantics; memoryFlush is shallow-merged one level
deeper so partial overrides (e.g., enabled: false) preserve unrelated
default fields like prompt and systemPrompt.
…sites

Update resolveCompactionMode(), resolveCompactionReserveTokensFloor(),
and resolveMemoryFlushSettings() to accept an optional agentId and use
resolveAgentCompaction() for merged config resolution instead of reading
agents.defaults.compaction directly.

Thread agentId (from sessionAgentId) through buildEmbeddedExtensionPaths()
and ensurePiCompactionReserveTokens() callsites in both run/attempt.ts
and compact.ts. Extract agentId from sessionKey in agent-runner-memory.ts
for the memory flush path.

All functions remain backward compatible — omitting agentId falls back
to global defaults.
…rging

Cover per-agent override precedence, partial override merging with
defaults, memoryFlush sub-object shallow merge (partial override
preserves unrelated default fields), per-agent without defaults,
unknown agent fallback, and undefined memoryFlush propagation.

12 test cases focused on the merge edge cases most likely to regress.
Add AgentCompactionConfig to the AgentConfig type in types.agents.ts,
fixing TS2339 errors where agent-scope.ts references entry.compaction.
Use nullish coalescing (defaults.memoryFlush ?? {}) to prevent
spreading undefined when per-agent sets memoryFlush but global
defaults omit it. Adds a test case for this exact scenario.
- Add 'off' to AgentCompactionMode union (schema + types)
- Skip ensurePiCompactionReserveTokens when mode is 'off' (compact.ts, attempt.ts)
- Skip safeguard extension when mode is 'off' (extensions.ts)
- Return null from resolveMemoryFlushSettings when mode is 'off'
- Add contextPruning.mode to AgentEntrySchema for per-agent override
- Add resolveAgentContextPruningMode helper with per-agent precedence
- Wire per-agent contextPruning mode into buildContextPruningExtension
- Add tests for mode 'off' and resolveAgentContextPruningMode
- Add contextPruning field to AgentConfig type definition
- Fix TypeScript narrowing issue in extensions.ts where cfg was
  narrowed to 'never' in else branch of ternary
@curtismercier

Copy link
Copy Markdown
Author

Superseded by #19329 — cleaner implementation with review feedback addressed, integration tested, and unrelated changes removed.

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

Labels

agents Agent runtime and tooling size: L

Projects

None yet

1 participant