Repository navigation
fix(context-window): Tighten context limits and bound memory excerpts - #67277
Conversation
🔒 Aisle Security AnalysisWe found 3 potential security issue(s) in this PR:
1. 🟠 CPU/memory DoS via quadratic truncation loop and unbounded file reads in memory_get excerpt building
DescriptionThe new bounded read helpers can be abused to consume excessive CPU and memory when processing large files or very large
If an attacker can cause RecommendationImplement truncation in linear time and enforce hard caps on both input size and file size.
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 };
}
2. 🟡 Tool-result size cap bypass via multi-block truncation allowing aggregate output > maxChars
Description
Impact:
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, ...)RecommendationEnforce the cap at the message level, not only per block. Options:
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 3. 🟡 Per-agent skill allowlist can default to "main" when agentId is undefined
Description
This creates a broken access-control condition where:
Vulnerable code: const normalizedAgentId = normalizeAgentId(agentId);
return cfg.agents?.list?.find((entry) => normalizeAgentId(entry.id) === normalizedAgentId);RecommendationDo not resolve a specific agent entry when 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 Analyzed PR: #67277 at commit Last updated on: 2026-04-15T18:07:20Z |
Greptile SummaryThis 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
Confidence Score: 4/5Safe 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 AIThis 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 |
There was a problem hiding this comment.
💡 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".
|
Follow-up review items are addressed on the branch in This pass fixed two concrete gaps:
Focused validation run:
I also replied inline on the corresponding review threads so they can be resolved directly. |
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
💡 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".
…bounds # Conflicts: # CHANGELOG.md
…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
…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
…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)
…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
…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
…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
…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
…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
…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
…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
…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
…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
What this PR is doing
This is a broad "make context loading less wasteful by default, without removing capability" pass.
The core idea is:
The main pieces
1. Lower default budgets for expensive context surfaces
This PR tightens several prompt/tool surfaces that quietly bloat context:
The point is not one magic knob. The point is reducing unnecessary context load across the main high-volume entry points.
2.
memory_getbecomes a bounded exact-excerpt fetchmemory_getstays source-file backed. It does not switch to returning index snippets.But its contract is now more explicit and more bounded:
Behavior now:
fromstarts at line 1linesmeans a bounded default window, not "rest of file"Successful reads now return structured continuation state, not just bare text:
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:
The main fields are:
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:
The fixes make the truncation story more honest:
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
contextLimitssurface.Instead the ownership remains split:
That keeps the config model cleaner:
skills.limits/agents.list[].skillsLimitscontextLimits6. Update docs so the ownership model is understandable
The docs now describe the budget ownership map more explicitly:
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:
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:
without trying to also redesign all of transcript/media state.
The smallest good mental model for the PR is:
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.tsextensions/memory-core/src/tools.tscheck-madge-import-cyclesbecausemadgeis not installed in this checkout, so the final commit used--no-verifyafter the targeted validation above