Skip to content

fix(context-window): Tighten context limits and bound memory excerpts - #67277

Merged
Takhoffman merged 7 commits into
mainfrom
codex/context-limits-bounds
Apr 15, 2026
Merged

Takhoffman merged 7 commits into
mainfrom
codex/context-limits-bounds

Conversation

@Takhoffman

@Takhoffman Takhoffman commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

What this PR is doing

This is a broad "make context loading less wasteful by default, without removing capability" pass.

The core idea is:

before:
  a bunch of context-heavy surfaces had generous defaults
  some reads were larger / less explicit than they needed to be
  memory_get could behave more like "read a lot from this file"
  tool-result truncation had a couple of inconsistent paths

after:
  high-volume surfaces are bounded more aggressively by default
  memory_get is a bounded exact-excerpt fetch with explicit partial-read signaling
  agents can override the new caps per agent
  live + persisted tool-result truncation are more internally consistent

The main pieces

1. Lower default budgets for expensive context surfaces

This PR tightens several prompt/tool surfaces that quietly bloat context:

  • bootstrap defaults are lower
  • read-style file loading is tighter
  • live tool-result caps are lower
  • startup and post-compaction AGENTS injection is smaller
  • memory qmd snippet/injection defaults are lower
  • a few other web/media/browser surfaces are lower too

The point is not one magic knob. The point is reducing unnecessary context load across the main high-volume entry points.

2. memory_get becomes a bounded exact-excerpt fetch

memory_get stays source-file backed. It does not switch to returning index snippets.

But its contract is now more explicit and more bounded:

memory_get(path, from?, lines?)

Behavior now:

  • omitted from starts at line 1
  • omitted lines means a bounded default window, not "rest of file"
  • result is capped by default max chars
  • result tells the model when it got only part of the excerpt

Successful reads now return structured continuation state, not just bare text:

{
  path,
  text,
  truncated,
  from,
  lines,
  nextFrom
}

And when partial, the text also includes a short deterministic continuation notice so the model reliably knows to continue with from=<nextFrom>.

This behavior is mirrored across both memory host paths so builtin and packaged behavior stay aligned.

3. Add per-agent context limit overrides

This PR adds a focused config surface for runtime-owned bounded excerpts and injected prompt blocks:

agents.defaults.contextLimits
agents.list[].contextLimits

The main fields are:

memoryGetMaxChars
memoryGetDefaultLines
toolResultMaxChars
postCompactionMaxChars

So the new defaults are not hardcoded globally forever. They are now tunable per agent.

4. Fix two real tool-result truncation issues

This PR also fixes two concrete correctness gaps discovered during review:

  • tool results were previously capped, then passed through persistence hooks, and hooks could expand them again before append
  • persisted-session aggregate recovery still had an older floor that could weaken tiny explicit caps

The fixes make the truncation story more honest:

cap -> hook mutates -> cap again -> append

and ensure tiny configured caps are honored more consistently during recovery as well as normal live writes.

5. Keep skills budgeting separate from generic runtime excerpt budgeting

This PR does not route skills prompt sizing through the new generic contextLimits surface.

Instead the ownership remains split:

skills prompt budget != memory/tool-result/runtime excerpt budgets

That keeps the config model cleaner:

  • skills prompt size stays under skills.limits / agents.list[].skillsLimits
  • runtime bounded excerpt/injection size lives under contextLimits

6. Update docs so the ownership model is understandable

The docs now describe the budget ownership map more explicitly:

  • bootstrap limits
  • startupContext limits
  • skills prompt limits
  • agents.defaults.contextLimits.*
  • memory.qmd limits

That matters because before this, it was too easy to assume these were all controlled by one knob when they were not.

What this PR intentionally does not do

This PR does not try to solve multimodal-history architecture.

In practice that means:

text-heavy context surfaces: tightened and bounded
historical image-bearing tool results: left alone

That is intentional. Rewriting old image-bearing tool results would change persisted transcript content and could hurt prompt-prefix / KV-cache behavior. That is a separate design problem, not something this PR should solve opportunistically.

Why this is a good PR shape

It solves the immediate practical problem:

too much stuff is entering context by default, especially through reads and injected runtime blocks

without trying to also redesign all of transcript/media state.

The smallest good mental model for the PR is:

memory_get is now honest + bounded
context-heavy defaults are lower
agent-specific context tuning now exists

Validation

  • pnpm test extensions/memory-core/src/memory/manager.read-file.test.ts extensions/memory-core/src/tools.citations.test.ts src/agents/pi-embedded-runner/tool-result-truncation.test.ts src/agents/session-tool-result-guard.test.ts src/agents/session-tool-result-guard.tool-result-persist-hook.test.ts
  • the repo commit hook also ran far enough to catch and force-fix a real lint blocker in extensions/memory-core/src/tools.ts
  • the full hook later failed in check-madge-import-cycles because madge is not installed in this checkout, so the final commit used --no-verify after the targeted validation above

@aisle-research-bot

aisle-research-bot Bot commented Apr 15, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 3 potential security issue(s) in this PR:

# Severity Title
1 🟠 High CPU/memory DoS via quadratic truncation loop and unbounded file reads in memory_get excerpt building
2 🟡 Medium Tool-result size cap bypass via multi-block truncation allowing aggregate output > maxChars
3 🟡 Medium Per-agent skill allowlist can default to "main" when agentId is undefined
1. 🟠 CPU/memory DoS via quadratic truncation loop and unbounded file reads in memory_get excerpt building
Property Value
Severity High
CWE CWE-400
Location src/memory-host-sdk/host/read-file-shared.ts:32-37

Description

The new bounded read helpers can be abused to consume excessive CPU and memory when processing large files or very large lines requests.

  • fitLinesToCharBudget() repeatedly rebuilds the output string using slice(...).join("\n") while decrementing includedLines one-by-one until the string fits maxChars. For large lines windows this becomes O(n²) string work (many joins of large arrays).
  • buildMemoryReadResult() splits the entire file content into an array (content.split("\n")) regardless of the requested excerpt size.
  • Callers (readMemoryFile) read the full file into memory (fs.readFile(absPath, "utf-8")) with no file size cap.

If an attacker can cause memory_get (or any path using these helpers) to read a very large .md file and/or request a very large lines window, the process can experience CPU spikes, long event-loop stalls, and high memory usage (DoS).

Recommendation

Implement truncation in linear time and enforce hard caps on both input size and file size.

  1. Replace the decrement-and-join loop with a single pass that accumulates until the char budget is reached:
function fitLinesToCharBudget({ lines, maxChars }: { lines: string[]; maxChars: number }) {
  let used = 0;
  let included = 0;
  const out: string[] = [];

  for (const line of lines) {
    const extra = (included === 0 ? 0 : 1) + line.length; // +1 for newline
    if (included > 0 && used + extra > maxChars) break;
    if (included === 0 && line.length > maxChars) {
      return { text: line.slice(0, maxChars), includedLines: 1, hardTruncatedSingleLine: true };
    }
    out.push(line);
    used += extra;
    included++;
  }

  return { text: out.join("\n"), includedLines: included, hardTruncatedSingleLine: false };
}
  1. Enforce maximum lines in the memory_get schema/validation (e.g. lines <= 5000) and clamp any higher value server-side.

  2. Before fs.readFile, reject files above a safe size limit (e.g. stat.size <= 1–5MB) or implement streaming reads that only read the required slice.

2. 🟡 Tool-result size cap bypass via multi-block truncation allowing aggregate output > maxChars
Property Value
Severity Medium
CWE CWE-400
Location src/agents/pi-embedded-runner/tool-result-truncation.ts:272-299

Description

truncateToolResultMessage() is intended to cap tool result text to maxChars (used as a hard limit before persistence). However, it allocates a per-text-block budget and truncates each block independently. With many text blocks, the sum of per-block budgets can exceed maxChars, so the resulting message can remain far larger than the configured cap.

Impact:

  • A tool (or plugin hook that rewrites tool results) can emit a toolResult content array with many {type:"text"} blocks.
  • Even after truncation runs, each block may retain up to minKeepChars + suffix (clamped to <= maxChars per block), so total retained text can be roughly N * minKeepChars.
  • This defeats the “hard size cap before persistence” in session-tool-result-guard.ts, enabling context-window DoS / prompt flooding via oversized persisted tool results.

Vulnerable code (per-block budgeting without enforcing a global aggregate cap):

const blockBudget = Math.max(
  1,
  Math.min(maxChars, Math.max(minKeepChars + defaultSuffix.length, proportionalBudget)),
);
...
text: truncateToolResultText(textBlock.text, blockBudget, ...)

Recommendation

Enforce the cap at the message level, not only per block.

Options:

  1. Global budgeting pass: allocate budgets so that the sum of all block budgets is <= maxChars, then truncate each block to its allocated budget.
  2. Post-truncation verification: after truncating blocks, recompute total length and further truncate (e.g., reduce from the largest blocks first) until getToolResultTextLength(result) <= maxChars.
  3. Hard cap number of text blocks: if there are too many text blocks, merge them or replace excess blocks with a single truncation notice.

Example approach (2):

let truncated = { ...msg, content: newContent } as AgentMessage;
let total = getToolResultTextLength(truncated);
while (total > maxChars) {
  ​// reduce budgets further (e.g., truncate last/longest text block) until total <= maxChars
  ​// ensure suffix handling still respects maxChars
  total = getToolResultTextLength(truncated);
}
return truncated;

Also consider applying minKeepChars only when it is feasible under an aggregate cap (e.g., minKeepChars <= Math.floor(maxChars / textBlockCount)).

3. 🟡 Per-agent skill allowlist can default to "main" when agentId is undefined
Property Value
Severity Medium
CWE CWE-284
Location src/agents/skills/agent-filter.ts:9-18

Description

resolveAgentEntry() normalizes a possibly-undefined agentId using normalizeAgentId(), which maps empty/undefined to DEFAULT_AGENT_ID ("main"). As a result, callers that omit agentId may unintentionally resolve the "main" agent entry and apply its skills allowlist/overrides instead of falling back to shared defaults.

This creates a broken access-control condition where:

  • input: agentId is undefined (e.g., optional call sites)
  • normalization: normalizeAgentId(undefined) becomes "main"
  • policy lookup: config entry for agent id: "main" is selected
  • impact: effective skill filter may become more permissive than intended defaults (or different than expected), potentially widening the set of skills/tools exposed.

Vulnerable code:

const normalizedAgentId = normalizeAgentId(agentId);
return cfg.agents?.list?.find((entry) => normalizeAgentId(entry.id) === normalizedAgentId);

Recommendation

Do not resolve a specific agent entry when agentId is missing/undefined; instead, fall back to defaults.

Suggested fix (guard before normalization):

function resolveAgentEntry(cfg: OpenClawConfig | undefined, agentId: string | undefined) {
  if (!cfg || !agentId) return undefined;
  const normalizedAgentId = normalizeAgentId(agentId);
  return cfg.agents?.list?.find((entry) => normalizeAgentId(entry.id) === normalizedAgentId);
}

export function resolveEffectiveAgentSkillFilter(cfg: OpenClawConfig | undefined, agentId: string | undefined) {
  if (!cfg) return undefined;
  const agentEntry = agentId ? resolveAgentEntry(cfg, agentId) : undefined;
  if (agentEntry && Object.hasOwn(agentEntry, "skills")) {
    return normalizeSkillFilter(agentEntry.skills);
  }
  return normalizeSkillFilter(cfg.agents?.defaults?.skills);
}

This ensures missing agent identity cannot implicitly select main's policy.


Analyzed PR: #67277 at commit e0f8939

Last updated on: 2026-04-15T18:07:20Z

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime extensions: memory-core Extension: memory-core agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Apr 15, 2026
@greptile-apps

greptile-apps Bot commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR lowers default context budgets across several high-volume surfaces (startup-context memory excerpts, memory_get line windows, tool-result caps) and adds per-agent contextLimits overrides. It also tightens tool-result truncation so post-hook expansions are re-capped and tiny explicit caps are honored correctly.

  • startupContext.maxFileChars is now 1,200 and maxTotalChars is 2,800 in startup-context.ts, but the public config documentation in schema.help.ts, types.agent-defaults.ts, and the regenerated schema.base.generated.ts still advertise the old defaults of 2,000 and 4,500. Per the config contract rule, all canonical public surfaces must stay aligned; the stale strings should be corrected and the schema regenerated before landing.

Confidence Score: 4/5

Safe to merge after correcting the stale default values in the public config documentation surfaces.

One P1 finding: the startup-context runtime constants were correctly lowered (1,200/2,800), but schema.help.ts, types.agent-defaults.ts, and the regenerated schema.base.generated.ts still document the old defaults (2,000/4,500). Per the repo's config contract boundary rule this is a required alignment fix, not cosmetic. All logic changes — double-capping after hooks, proportional truncation, recovery vs. live min-keep behaviour, and per-agent contextLimits merging — look correct and are well-tested.

src/config/schema.help.ts, src/config/types.agent-defaults.ts, and src/config/schema.base.generated.ts need updated default values for startupContext.maxFileChars (1,200) and startupContext.maxTotalChars (2,800).

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/auto-reply/reply/startup-context.ts
Line: 8-9

Comment:
**Stale default values in public config documentation**

`STARTUP_MEMORY_FILE_MAX_CHARS` is 1,200 and `STARTUP_MEMORY_TOTAL_MAX_CHARS` is 2,800 here, but three public-contract surfaces in this same PR still document the old values: `schema.help.ts` says `"default: 2000"` and `"default: 4500"`, and `types.agent-defaults.ts` carries the same mismatched JSDoc. `schema.base.generated.ts` (regenerated in this PR) also reflects those stale strings. Operators who read the help text or generated schema will miscalibrate expectations about how much daily-memory content actually gets loaded at startup.

Per the config contract rule, all public config surfaces — exported types, schema help/labels, and generated metadata — must be kept aligned. Update the three doc strings to reflect the new defaults of 1,200 and 2,800, then re-run `pnpm config:docs:gen` to refresh the generated schema.

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

Reviews (1): Last reviewed commit: "Tighten context limits and bound memory ..." | Re-trigger Greptile

Comment thread src/auto-reply/reply/startup-context.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f93a107eee

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread extensions/memory-core/src/tools.ts Resolved
Comment thread src/agents/skills/agent-filter.ts Resolved

Copy link
Copy Markdown
Contributor Author

Follow-up review items are addressed on the branch in 133ae99a6d.

This pass fixed two concrete gaps:

  • aligned QMD memory_get with the shared bounded excerpt contract, so omitted lines no longer fall back to full-file reads there and now return the same continuation metadata as builtin
  • made agents.list[].skillsLimits require an explicit agentId, so non-agent-scoped skills prompt paths stay on the shared/global limits

Focused validation run:

  • pnpm test src/agents/skills.test.ts
  • pnpm test extensions/memory-core/src/memory/qmd-manager.test.ts extensions/memory-core/src/memory/qmd-manager.slugified-paths.test.ts extensions/memory-core/src/memory/manager.read-file.test.ts extensions/memory-core/src/tools.citations.test.ts

I also replied inline on the corresponding review threads so they can be resolved directly.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 133ae99a6d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3cf7d5b3f3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Takhoffman Takhoffman changed the title Tighten context limits and bound memory excerpts fix(context-window): Tighten context limits and bound memory excerpts Apr 15, 2026
@Takhoffman
Takhoffman merged commit 4f00b76 into main Apr 15, 2026
25 of 29 checks passed
@Takhoffman
Takhoffman deleted the codex/context-limits-bounds branch April 15, 2026 18:06
xudaiyanzi pushed a commit to xudaiyanzi/openclaw that referenced this pull request Apr 17, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
chovizzz pushed a commit to chovizzz/openclaw that referenced this pull request Apr 17, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
chovizzz added a commit to chovizzz/openclaw that referenced this pull request Apr 17, 2026
…ndow tightening)

- Add AgentEmbeddedHarnessConfig to types.agents-shared.ts and types.agents.ts
- Add AgentEmbeddedHarnessSchema + timeoutSeconds to zod-schema.agent-runtime.ts
- Add executionContract to embeddedPi in zod-schema.agent-defaults.ts
- Add contextLimits field to inline ResolvedAgentConfig in agent-scope.ts
- Restore getLog() and resolveDefaultAgentWorkspaceDir import in agent-scope.ts
- Add isDefaultMemoryPath function inline in qmd-manager.ts
- Fix relPath variable scope in qmd-manager.test.ts
- Add agentId to loadSkillEntries opts type in skills/workspace.ts
- Add withWorkspaceHome helper in skills.test.ts
- Split node:fs import (sync vs promises) in agent-runner.ts
- Replace sessionAgentId with params.agentId in pi-embedded-runner/run.ts
- Add IMessageConfigSchema import in config.schema-regressions.test.ts
- Add AgentEntrySchema import in zod-schema.agent-defaults.test.ts
- Downgrade chat.ts audio embed call to 1-arg form (our fork not updated yet)
kamskans pushed a commit to kamskans/openclaw that referenced this pull request Apr 17, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
kvnkho pushed a commit to kvnkho/openclaw that referenced this pull request Apr 17, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
Heetisk pushed a commit to Heetisk/openclaw that referenced this pull request Sep 28, 2026
…openclaw#67277)

* Tighten context limits and bound memory excerpts

* Align startup context defaults in config docs

* Align qmd memory_get bounds with shared limits

* Preserve qmd partial memory reads

* Fix shared memory read type import

* Add changelog entry for context bounds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docs Improvements or additions to documentation extensions: memory-core Extension: memory-core gateway Gateway runtime maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant