Skip to content

feat: expose prompt-cache runtime context to context engines#62179

Merged
jalehman merged 5 commits into
openclaw:mainfrom
jalehman:codex/prompt-cache-context-engine
Apr 7, 2026
Merged

feat: expose prompt-cache runtime context to context engines#62179
jalehman merged 5 commits into
openclaw:mainfrom
jalehman:codex/prompt-cache-context-engine

Conversation

@jalehman

@jalehman jalehman commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Problem: context engines only receive messages, token budget, and runtime context, so they cannot inspect OpenClaw prompt-cache telemetry when deciding post-turn maintenance or compaction.
  • Why it matters: engines like lossless-claw need resolved cache retention, normalized last-call usage, and cache-break observations to make cache-aware decisions without duplicating embedded-runner logic.
  • What changed: added a typed runtimeContext.promptCache payload, populated it in the embedded runner for afterTurn(), and forwarded it into compact() on the existing recovery paths that already have the attempt result.
  • What did NOT change (scope boundary): no compaction policy changed, no lossless-claw behavior changed, and no expiry timestamps are invented for providers where OpenClaw cannot know them confidently.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #
  • Related #
  • This PR fixes a bug or regression

Root Cause (if applicable)

  • Root cause: N/A
  • Missing detection / guardrail: N/A
  • Contributing context (if known): N/A

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-engine.test.ts, src/agents/pi-embedded-runner/run.timeout-triggered-compaction.test.ts, and the existing buildAfterTurnRuntimeContext tests in src/agents/pi-embedded-runner/run/attempt.test.ts.
  • Scenario the test should lock in: afterTurn() receives prompt-cache info when available, the field stays absent/partial when unavailable, retention and cache-break observations are threaded through correctly, and compact() receives the same payload on the current recovery paths.
  • Why this is the smallest reliable guardrail: the behavior is owned by the embedded-runner/context-engine seam, so extending the existing attempt helper and recovery-path harnesses exercises the actual plumbing without adding broad integration coverage.
  • Existing test that already covers this (if any): existing buildAfterTurnRuntimeContext coverage remains in place and stays compatible with callers that ignore the new field.
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

None.

Diagram (if applicable)

Before:
[embedded runner finishes turn] -> [afterTurn(runtimeContext without prompt-cache data)]

After:
[embedded runner finishes turn]
  -> [resolve effective retention + normalize last-call usage + finalize cache observation]
  -> [afterTurn(runtimeContext.promptCache)]
  -> [retry/timeout compaction path reuses same promptCache payload]

Security Impact (required)

  • New permissions/capabilities? (No)
  • Secrets/tokens handling changed? (No)
  • New/changed network calls? (No)
  • Command/tool execution surface changed? (No)
  • Data access scope changed? (No)
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: local Node/pnpm repo workflow
  • Model/provider: N/A
  • Integration/channel (if any): embedded runner / context-engine seam
  • Relevant config (redacted): none required beyond test defaults

Steps

  1. Run pnpm test src/agents/pi-embedded-runner/run/attempt.spawn-workspace.context-engine.test.ts src/agents/pi-embedded-runner/run.timeout-triggered-compaction.test.ts.
  2. Run pnpm test src/agents/pi-embedded-runner/run/attempt.test.ts -t "buildAfterTurnRuntimeContext".
  3. Confirm the prompt-cache payload appears only where expected and existing callers still pass.

Expected

  • Targeted tests pass.
  • runtimeContext.promptCache is available to context engines when the embedded runner has cache telemetry.
  • Existing behavior is unchanged for engines that ignore the new field.

Actual

  • Matched expected results locally.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

  • Verified scenarios: ran the targeted attempt/context-engine and timeout-compaction tests, plus the focused buildAfterTurnRuntimeContext coverage, against the final committed tree.
  • Edge cases checked: missing cache data leaves promptCache absent, effective retention is the resolved value, and cache-break observations carry through when the heuristic reports a meaningful drop.
  • What you did not verify: no broader end-to-end model-provider run, and no lossless-claw compaction policy changes in this PR.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? (Yes)
  • Config/env changes? (No)
  • Migration needed? (No)
  • If yes, exact upgrade steps:

Risks and Mitigations

  • Risk: compact() only receives prompt-cache info on recovery paths that already have an attempt result.
    • Mitigation: this keeps the change additive and aligned with the current call graph; broader compaction-context sourcing can be added later if an engine needs it.
  • Risk: expiresAt is intentionally absent for Anthropic/OpenAI because OpenClaw cannot know it confidently.
    • Mitigation: the new type makes the field optional so engines can branch on real availability instead of guessed data.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M maintainer Maintainer-authored PR labels Apr 6, 2026
@jalehman
jalehman force-pushed the codex/prompt-cache-context-engine branch from a0d1f1c to 8f3d3ab Compare April 6, 2026 23:15
@greptile-apps

greptile-apps Bot commented Apr 6, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a typed runtimeContext.promptCache payload to the embedded runner's context-engine seam, populates it via buildContextEnginePromptCacheInfo after each turn, and threads it into compact() on both the timeout and overflow recovery paths. The design is clean: the helper correctly gates each field behind explicit presence checks, the ContextEnginePromptCacheInfo type is additive and backwards-compatible, and the PromptCacheChangeCodeContextEnginePromptCacheObservationChangeCode mapping is 1-to-1. The main coverage gap is that the overflow compaction path (which received the same promptCache forwarding) has no new targeted test, while the timeout path does.

Confidence Score: 5/5

Safe to merge; all findings are P2 style suggestions.

No P0 or P1 issues found. The implementation is type-safe, additive, and backwards-compatible. The single P2 note is a test-coverage gap on the overflow path, which mirrors working code that is already covered on the timeout path.

No files require special attention before merging.

Comments Outside Diff (1)

  1. src/agents/pi-embedded-runner/run.ts, line 921-966 (link)

    P2 Overflow compaction path lacks test coverage for promptCache forwarding

    The timeout-triggered compaction path received a dedicated test asserting that attempt.promptCache is forwarded into runtimeContext (see run.timeout-triggered-compaction.test.ts), but the symmetric overflow compaction path at this block (overflowCompactionRuntimeContext) has no corresponding new test in run.overflow-compaction.test.ts. The logic is identical, so a gap here means the overflow path's forwarding could silently regress.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/agents/pi-embedded-runner/run.ts
    Line: 921-966
    
    Comment:
    **Overflow compaction path lacks test coverage for `promptCache` forwarding**
    
    The timeout-triggered compaction path received a dedicated test asserting that `attempt.promptCache` is forwarded into `runtimeContext` (see `run.timeout-triggered-compaction.test.ts`), but the symmetric overflow compaction path at this block (`overflowCompactionRuntimeContext`) has no corresponding new test in `run.overflow-compaction.test.ts`. The logic is identical, so a gap here means the overflow path's forwarding could silently regress.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/pi-embedded-runner/run.ts
Line: 921-966

Comment:
**Overflow compaction path lacks test coverage for `promptCache` forwarding**

The timeout-triggered compaction path received a dedicated test asserting that `attempt.promptCache` is forwarded into `runtimeContext` (see `run.timeout-triggered-compaction.test.ts`), but the symmetric overflow compaction path at this block (`overflowCompactionRuntimeContext`) has no corresponding new test in `run.overflow-compaction.test.ts`. The logic is identical, so a gap here means the overflow path's forwarding could silently regress.

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

Reviews (1): Last reviewed commit: "Context engine: plumb prompt cache runti..." | Re-trigger Greptile

@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: a0d1f1c301

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +2049 to +2051
const lastCallUsage = normalizeUsage(
(lastAssistant as { usage?: UsageLike } | undefined)?.usage,
);

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.

P2 Badge Derive prompt-cache usage from current turn only

lastCallUsage is computed from the most recent assistant message in the entire snapshot, not from messages produced by the current attempt. When a turn exits before producing a new assistant message (for example preflight overflow/skip-prompt paths or early prompt failures), this picks a prior-turn assistant and forwards stale usage as runtimeContext.promptCache.lastCallUsage, which can mislead context engines during post-turn maintenance and recovery compaction decisions. Restrict the lookup to messages added in this attempt (e.g. after prePromptMessageCount) or use current-attempt usage data when no new assistant exists.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Apr 7, 2026

@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: 09b03925ec

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +2085 to +2087
observation: promptCacheObservation,
lastCacheTouchAt: readLastCacheTtlTimestamp(sessionManager),
});

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.

P2 Badge Filter cache-touch timestamp to the active cache context

lastCacheTouchAt is sourced from readLastCacheTtlTimestamp(sessionManager) without checking whether that TTL entry matches the current provider/model, so a prior Anthropic/Gemini turn can leak a stale timestamp into runtimeContext.promptCache for a later turn on a different model/provider. This makes cache-aware engines think the current cache was touched recently when it was not, which can skew compaction/maintenance decisions after provider switches.

Useful? React with 👍 / 👎.

Comment on lines +2063 to +2065
const lastCallUsage =
normalizeUsage((currentAttemptAssistant as { usage?: UsageLike } | undefined)?.usage) ??
normalizeUsage(attemptUsage);

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.

P2 Badge Avoid using turn-aggregate usage as last-call usage

When no current-attempt assistant message is found, lastCallUsage falls back to attemptUsage, but attemptUsage is a turn aggregate (getUsageTotals) rather than the most recent API call. In compaction/retry flows this can combine multiple model calls, so runtimeContext.promptCache.lastCallUsage over-reports the latest call and violates the field’s own contract, which can mislead context engines that use per-call cache-read deltas.

Useful? React with 👍 / 👎.

@100yenadmin

100yenadmin commented Apr 7, 2026

Copy link
Copy Markdown
Contributor

Nice work @jalehman this is clean and well-scoped. The ContextEnginePromptCacheInfo type is exactly the right surface for cache-aware engine behavior.

A few observations from review:

What I like:

  • findCurrentAttemptAssistantMessage() properly avoids stale prior-turn usage by slicing from prePromptMessageCount. The test that locks this in is particularly valuable — a subtle bug source.
  • expiresAt field on the type is forward-looking even though nothing populates it yet. Smart to reserve the slot.
  • Clean scope boundary: no compaction policy changed, just data plumbing. Makes it easy to review in isolation.

Potential edge cases to consider:

  1. retention: "in_memory" and "24h" these are in the type union but I don't see them sourced from resolveCacheRetention() in the current codebase. Are these planned for future providers, or should they be gated behind the existing "none" | "short" | "long" until a provider actually uses them?

  2. lastCacheTouchAt from readLastCacheTtlTimestamp this reads the session manager's custom entries in reverse. If a session has many entries, this is O(n) on every turn. Probably fine for now, but worth noting if sessions grow very long-lived as it is likely to be the case for a higher number of users of LCM tools.

  3. Compaction path threading the timeout-recovery and overflow paths both spread attempt.promptCache into the compaction runtime context. Should the budget-triggered compaction path (from preflight) also receive this, or is that intentionally excluded since preflight happens before any API call?

Why this matters to us: We're working on a cache keep-warm feature (#62475) that fires minimal max_tokens: 1 pings between turns to prevent cache TTL expiry. This PR's observation.broke + lastCacheTouchAt signals are exactly the dirty-flag mechanism we need — if compaction invalidates the prefix, the keep-warm timer knows to cancel. We'd build on top of this.

Happy to help test or address any reviewer feedback if useful.

jalehman added 4 commits April 7, 2026 08:48
Add a typed prompt-cache payload to the context-engine runtime context and populate it from the embedded runner's resolved retention, last-call usage, cache-break observation, and cache-touch metadata. Also pass the same payload through the retry compaction runtime context when a run attempt already has it.

Regeneration-Prompt: |
  Expose OpenClaw prompt-cache telemetry to context engines in a narrow,
  additive way without changing compaction policy. Keep the public change on
  the OpenClaw side only: add a typed promptCache payload to the context-engine
  runtime context, thread it into afterTurn, and also into compact where the
  existing run loop already has the data cheaply available.

  Use OpenClaw's resolved cache retention, not raw config. Use last-call usage
  for the new payload, not accumulated retry or tool-loop totals. Reuse the
  existing prompt-cache observability result and tracked change causes instead
  of inventing a new heuristic. If cache-touch metadata is already available
  from the cache-TTL bookkeeping, include it; do not invent expiry timestamps
  for providers where OpenClaw cannot know them confidently.

  Keep the interface backward-compatible for engines that ignore the new field.
  Add focused tests around the existing attempt/context-engine helpers and the
  compaction runtime-context propagation path rather than broad new integration
  coverage.
Regeneration-Prompt: |
  Fix PR openclaw#62179 so context-engine prompt-cache metadata uses only the current attempt's usage. The review comment pointed out that early exits could reuse a prior turn's assistant usage when no new assistant message was produced. Restrict the prompt-cache lastCallUsage lookup to assistant messages added after prePromptMessageCount, and fall back to current-attempt usage totals instead of stale snapshot history. Also repair the PR's new context-engine test typings and add a regression test for the stale prior-turn case. Two import-only fixes in doctor-state-integrity and config/talk were already broken on origin/main, but they blocked build/check and the gateway-watch regression harness, so include the minimum unblocking imports as well.
@jalehman
jalehman force-pushed the codex/prompt-cache-context-engine branch from 624d5f5 to fa96c07 Compare April 7, 2026 15:55
@aisle-research-bot

aisle-research-bot Bot commented Apr 7, 2026

Copy link
Copy Markdown

🔒 Aisle Security Analysis

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

# Severity Title
1 🟡 Medium Untrusted session custom entry can spoof cache-ttl timestamp to bypass context pruning (resource exhaustion)
1. 🟡 Untrusted session custom entry can spoof cache-ttl timestamp to bypass context pruning (resource exhaustion)
Property Value
Severity Medium
CWE CWE-345
Location src/agents/pi-embedded-runner/cache-ttl.ts:85-93

Description

The cache-ttl based pruning logic trusts the latest openclaw.cache-ttl custom entry from the session without bounding or validating the timestamp.

  • readLastCacheTtlTimestamp() returns data.timestamp from session entries when it is a finite number.
  • contextPruningExtension then skips pruning whenever Date.now() - lastTouch < ttlMs.
  • If an attacker can tamper with or inject session JSONL custom entries (the session transcript format supports customType: "openclaw.cache-ttl"), they can set timestamp far in the future to make Date.now() - lastTouch negative, causing pruning to be skipped indefinitely.
  • Result: unbounded prompt/context growth and increased token usage/cost (denial of service / cost-amplification), and altered pruning behavior.

Vulnerable code:

const ts = typeof data?.timestamp === "number" ? data.timestamp : null;
if (ts && Number.isFinite(ts)) {
  last = ts;
  break;
}

This value is later used in TTL logic:

if (ttlMs > 0 && Date.now() - lastTouch < ttlMs) {
  return undefined;
}

Recommendation

Treat session-provided timestamps as untrusted input.

  • Reject non-sensical values (e.g., in the future beyond a small clock-skew allowance) and negative/zero values.
  • Optionally clamp to Date.now() or ignore entries outside an acceptable window.
  • Consider storing this bookkeeping in a trusted location not writable via session transcript edits, or add integrity protection (e.g., HMAC/signature) if the transcript can be modified by untrusted actors.

Example hardening in readLastCacheTtlTimestamp:

const now = Date.now();
const ts = typeof data?.timestamp === "number" ? data.timestamp : null;
if (typeof ts === "number" && Number.isFinite(ts)) {// allow up to 5 minutes of skew
  const maxAllowed = now + 5 * 60 * 1000;
  if (ts > 0 && ts <= maxAllowed) {
    last = ts;
    break;
  }
}

And/or defensively handle in the TTL check:

const safeLastTouch = Math.min(lastTouch, Date.now());
if (Date.now() - safeLastTouch < ttlMs) return;

Analyzed PR: #62179 at commit 5231c8d

Last updated on: 2026-04-07T16:15:05Z

@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: fa96c07a8e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +298 to +300
.slice(Math.max(0, params.prePromptMessageCount))
.toReversed()
.find((message) => message.role === "assistant");

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.

P2 Badge Derive current-call usage without relying on pre-compaction index

findCurrentAttemptAssistantMessage slices from prePromptMessageCount, but the same attempt can run SDK compaction that rewrites history and shrinks messagesSnapshot (the code later notes compaction can restructure messages). In that case the start index is past the end of the compacted snapshot, so the slice is empty and lastCallUsage is dropped even though this attempt produced an assistant response. That under-reports runtimeContext.promptCache.lastCallUsage specifically in compaction/retry flows where cache-aware engines need accurate per-call telemetry.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot removed the commands Command implementations label Apr 7, 2026
jalehman added a commit to Martian-Engineering/lossless-claw that referenced this pull request Apr 7, 2026
Persist prompt-cache telemetry after turns and use it to gate incremental
leaf compaction. Hot cache sessions now defer best-effort incremental
passes unless raw history pressure is clearly above target, while cold
cache sessions can run bounded catch-up passes in a single maintenance
cycle. Full threshold sweeps keep their existing behavior.

Also add cacheAwareCompaction config/schema support, docs, a changeset,
and regression coverage for hot/cold/unknown prompt-cache behavior.

Regeneration-Prompt: |
  Implement the cache-aware incremental compaction spec for lossless-claw
  using the new prompt-cache telemetry exposed by the dependent OpenClaw
  branch tied to openclaw/openclaw#62179. Persist lightweight per-
  conversation cache telemetry after each turn, classify sessions as hot,
  cold, or unknown, and use that state to decide whether afterTurn()
  should run incremental leaf compaction. Preserve the existing full-sweep
  compaction behavior, but let cold-cache sessions do a bounded number of
  extra leaf passes to catch up while hot-cache sessions defer passes
  unless raw history pressure is clearly above target. Add the minimal
  config surface for enabling the feature and setting the cold-cache pass
  cap, keep the plugin manifest and docs in sync, and cover the behavior
  with focused engine and config tests.
@jalehman
jalehman merged commit e46e32b into openclaw:main Apr 7, 2026
8 checks passed
jalehman added a commit to Martian-Engineering/lossless-claw that referenced this pull request Apr 7, 2026
…izing (#318)

* feat: add cache-aware incremental compaction

Persist prompt-cache telemetry after turns and use it to gate incremental
leaf compaction. Hot cache sessions now defer best-effort incremental
passes unless raw history pressure is clearly above target, while cold
cache sessions can run bounded catch-up passes in a single maintenance
cycle. Full threshold sweeps keep their existing behavior.

Also add cacheAwareCompaction config/schema support, docs, a changeset,
and regression coverage for hot/cold/unknown prompt-cache behavior.

Regeneration-Prompt: |
  Implement the cache-aware incremental compaction spec for lossless-claw
  using the new prompt-cache telemetry exposed by the dependent OpenClaw
  branch tied to openclaw/openclaw#62179. Persist lightweight per-
  conversation cache telemetry after each turn, classify sessions as hot,
  cold, or unknown, and use that state to decide whether afterTurn()
  should run incremental leaf compaction. Preserve the existing full-sweep
  compaction behavior, but let cold-cache sessions do a bounded number of
  extra leaf passes to catch up while hot-cache sessions defer passes
  unless raw history pressure is clearly above target. Add the minimal
  config surface for enabling the feature and setting the cold-cache pass
  cap, keep the plugin manifest and docs in sync, and cover the behavior
  with focused engine and config tests.

* feat: add dynamic leaf chunk sizing

Add the next compaction spec on top of cache-aware incremental compaction.
Incremental maintenance can now grow its working leaf chunk target in
busy sessions using internal low/medium/high activity bands, keep the
configured static leafChunkTokens value as the floor, and cap growth at a
bounded max. When cache-aware compaction is enabled and the prompt cache
is cold, incremental compaction now jumps to the max working chunk.

This also persists minimal refill telemetry alongside the existing
compaction telemetry, threads optional leaf chunk overrides through the
incremental compaction path, and retries with smaller chunk targets when a
provider rejects an oversized compaction request on token/context-window
limits. Full sweeps remain unchanged.

Regeneration-Prompt: |
  Implement the dynamic leafChunkTokens spec from the 2026-04-07 Pagedrop
  page on top of the existing cache-aware incremental compaction branch.
  Keep the feature default-off in v1. Reuse the static leafChunkTokens as
  the floor, add only a minimal dynamicLeafChunkTokens config object with
  enabled and max, and store lightweight per-conversation refill telemetry
  needed to derive a simple low/medium/high activity band with internal
  hysteresis. Use that band to choose a working incremental leaf chunk
  target, but keep full sweeps unchanged. If cache-aware compaction is
  enabled and the cache is cold, force incremental compaction to use the
  max working chunk. Clamp the working chunk against budget-derived limits,
  and if a provider still rejects an oversized chunk due to token/context
  window limits, retry with the next smaller chunk target instead of
  failing immediately. Update the plugin manifest, docs, migration/store
  schema, and regression tests for config parsing, trigger overrides,
  cold-cache max bumping, and retry fallback behavior.

* chore: add debug logs for compaction decisions

Add debug-level tracing around the new cache-aware incremental compaction and
dynamic leaf chunk sizing paths so live runs can be diagnosed without querying
SQLite directly. This logs telemetry updates, incremental decision inputs and
reasons, and leaf compaction start/result state, with focused engine coverage
for the new messages.

Regeneration-Prompt: |
  User asked for better observability for the two new incremental compaction
  features added on this branch: cache-aware prompt-cache handling and dynamic
  leaf chunk sizing. The requirement was to add debug logs, not info logs, and
  to explain how to enable those logs in a live OpenClaw instance.

  Inspect the new policy code in the LCM engine and add low-noise debug traces
  at the decision points that matter operationally: telemetry persistence after
  afterTurn, the incremental compaction decision with cache state / activity
  band / chosen chunk / reason / max passes, reset after a successful leaf
  compaction pass, and compactLeafAsync start/result. Preserve existing behavior
  and keep the logs structured enough to grep in production. Add focused tests
  that prove the debug logger is called for the hot-cache telemetry path, the
  hot-cache defer path, and the dynamic high-band chunk selection path.
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
…w#62179)

* Context engine: plumb prompt cache runtime context

Add a typed prompt-cache payload to the context-engine runtime context and populate it from the embedded runner's resolved retention, last-call usage, cache-break observation, and cache-touch metadata. Also pass the same payload through the retry compaction runtime context when a run attempt already has it.

Regeneration-Prompt: |
  Expose OpenClaw prompt-cache telemetry to context engines in a narrow,
  additive way without changing compaction policy. Keep the public change on
  the OpenClaw side only: add a typed promptCache payload to the context-engine
  runtime context, thread it into afterTurn, and also into compact where the
  existing run loop already has the data cheaply available.

  Use OpenClaw's resolved cache retention, not raw config. Use last-call usage
  for the new payload, not accumulated retry or tool-loop totals. Reuse the
  existing prompt-cache observability result and tracked change causes instead
  of inventing a new heuristic. If cache-touch metadata is already available
  from the cache-TTL bookkeeping, include it; do not invent expiry timestamps
  for providers where OpenClaw cannot know them confidently.

  Keep the interface backward-compatible for engines that ignore the new field.
  Add focused tests around the existing attempt/context-engine helpers and the
  compaction runtime-context propagation path rather than broad new integration
  coverage.

* Agents: fix prompt-cache afterTurn usage

Regeneration-Prompt: |
  Fix PR openclaw#62179 so context-engine prompt-cache metadata uses only the current attempt's usage. The review comment pointed out that early exits could reuse a prior turn's assistant usage when no new assistant message was produced. Restrict the prompt-cache lastCallUsage lookup to assistant messages added after prePromptMessageCount, and fall back to current-attempt usage totals instead of stale snapshot history. Also repair the PR's new context-engine test typings and add a regression test for the stale prior-turn case. Two import-only fixes in doctor-state-integrity and config/talk were already broken on origin/main, but they blocked build/check and the gateway-watch regression harness, so include the minimum unblocking imports as well.

* Agents: document prompt-cache context

* Agents: address prompt-cache review feedback

* Doctor: drop unused isRecord import
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
…w#62179)

* Context engine: plumb prompt cache runtime context

Add a typed prompt-cache payload to the context-engine runtime context and populate it from the embedded runner's resolved retention, last-call usage, cache-break observation, and cache-touch metadata. Also pass the same payload through the retry compaction runtime context when a run attempt already has it.

Regeneration-Prompt: |
  Expose OpenClaw prompt-cache telemetry to context engines in a narrow,
  additive way without changing compaction policy. Keep the public change on
  the OpenClaw side only: add a typed promptCache payload to the context-engine
  runtime context, thread it into afterTurn, and also into compact where the
  existing run loop already has the data cheaply available.

  Use OpenClaw's resolved cache retention, not raw config. Use last-call usage
  for the new payload, not accumulated retry or tool-loop totals. Reuse the
  existing prompt-cache observability result and tracked change causes instead
  of inventing a new heuristic. If cache-touch metadata is already available
  from the cache-TTL bookkeeping, include it; do not invent expiry timestamps
  for providers where OpenClaw cannot know them confidently.

  Keep the interface backward-compatible for engines that ignore the new field.
  Add focused tests around the existing attempt/context-engine helpers and the
  compaction runtime-context propagation path rather than broad new integration
  coverage.

* Agents: fix prompt-cache afterTurn usage

Regeneration-Prompt: |
  Fix PR openclaw#62179 so context-engine prompt-cache metadata uses only the current attempt's usage. The review comment pointed out that early exits could reuse a prior turn's assistant usage when no new assistant message was produced. Restrict the prompt-cache lastCallUsage lookup to assistant messages added after prePromptMessageCount, and fall back to current-attempt usage totals instead of stale snapshot history. Also repair the PR's new context-engine test typings and add a regression test for the stale prior-turn case. Two import-only fixes in doctor-state-integrity and config/talk were already broken on origin/main, but they blocked build/check and the gateway-watch regression harness, so include the minimum unblocking imports as well.

* Agents: document prompt-cache context

* Agents: address prompt-cache review feedback

* Doctor: drop unused isRecord import
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 9, 2026
…w#62179)

* Context engine: plumb prompt cache runtime context

Add a typed prompt-cache payload to the context-engine runtime context and populate it from the embedded runner's resolved retention, last-call usage, cache-break observation, and cache-touch metadata. Also pass the same payload through the retry compaction runtime context when a run attempt already has it.

Regeneration-Prompt: |
  Expose OpenClaw prompt-cache telemetry to context engines in a narrow,
  additive way without changing compaction policy. Keep the public change on
  the OpenClaw side only: add a typed promptCache payload to the context-engine
  runtime context, thread it into afterTurn, and also into compact where the
  existing run loop already has the data cheaply available.

  Use OpenClaw's resolved cache retention, not raw config. Use last-call usage
  for the new payload, not accumulated retry or tool-loop totals. Reuse the
  existing prompt-cache observability result and tracked change causes instead
  of inventing a new heuristic. If cache-touch metadata is already available
  from the cache-TTL bookkeeping, include it; do not invent expiry timestamps
  for providers where OpenClaw cannot know them confidently.

  Keep the interface backward-compatible for engines that ignore the new field.
  Add focused tests around the existing attempt/context-engine helpers and the
  compaction runtime-context propagation path rather than broad new integration
  coverage.

* Agents: fix prompt-cache afterTurn usage

Regeneration-Prompt: |
  Fix PR openclaw#62179 so context-engine prompt-cache metadata uses only the current attempt's usage. The review comment pointed out that early exits could reuse a prior turn's assistant usage when no new assistant message was produced. Restrict the prompt-cache lastCallUsage lookup to assistant messages added after prePromptMessageCount, and fall back to current-attempt usage totals instead of stale snapshot history. Also repair the PR's new context-engine test typings and add a regression test for the stale prior-turn case. Two import-only fixes in doctor-state-integrity and config/talk were already broken on origin/main, but they blocked build/check and the gateway-watch regression harness, so include the minimum unblocking imports as well.

* Agents: document prompt-cache context

* Agents: address prompt-cache review feedback

* Doctor: drop unused isRecord import
YoshiaKefasu pushed a commit to YoshiaKefasu/DennouAibou that referenced this pull request May 18, 2026
…w#62179)

* Context engine: plumb prompt cache runtime context

Add a typed prompt-cache payload to the context-engine runtime context and populate it from the embedded runner's resolved retention, last-call usage, cache-break observation, and cache-touch metadata. Also pass the same payload through the retry compaction runtime context when a run attempt already has it.

Regeneration-Prompt: |
  Expose OpenClaw prompt-cache telemetry to context engines in a narrow,
  additive way without changing compaction policy. Keep the public change on
  the OpenClaw side only: add a typed promptCache payload to the context-engine
  runtime context, thread it into afterTurn, and also into compact where the
  existing run loop already has the data cheaply available.

  Use OpenClaw's resolved cache retention, not raw config. Use last-call usage
  for the new payload, not accumulated retry or tool-loop totals. Reuse the
  existing prompt-cache observability result and tracked change causes instead
  of inventing a new heuristic. If cache-touch metadata is already available
  from the cache-TTL bookkeeping, include it; do not invent expiry timestamps
  for providers where OpenClaw cannot know them confidently.

  Keep the interface backward-compatible for engines that ignore the new field.
  Add focused tests around the existing attempt/context-engine helpers and the
  compaction runtime-context propagation path rather than broad new integration
  coverage.

* Agents: fix prompt-cache afterTurn usage

Regeneration-Prompt: |
  Fix PR openclaw#62179 so context-engine prompt-cache metadata uses only the current attempt's usage. The review comment pointed out that early exits could reuse a prior turn's assistant usage when no new assistant message was produced. Restrict the prompt-cache lastCallUsage lookup to assistant messages added after prePromptMessageCount, and fall back to current-attempt usage totals instead of stale snapshot history. Also repair the PR's new context-engine test typings and add a regression test for the stale prior-turn case. Two import-only fixes in doctor-state-integrity and config/talk were already broken on origin/main, but they blocked build/check and the gateway-watch regression harness, so include the minimum unblocking imports as well.

* Agents: document prompt-cache context

* Agents: address prompt-cache review feedback

* Doctor: drop unused isRecord import
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…w#62179)

* Context engine: plumb prompt cache runtime context

Add a typed prompt-cache payload to the context-engine runtime context and populate it from the embedded runner's resolved retention, last-call usage, cache-break observation, and cache-touch metadata. Also pass the same payload through the retry compaction runtime context when a run attempt already has it.

Regeneration-Prompt: |
  Expose OpenClaw prompt-cache telemetry to context engines in a narrow,
  additive way without changing compaction policy. Keep the public change on
  the OpenClaw side only: add a typed promptCache payload to the context-engine
  runtime context, thread it into afterTurn, and also into compact where the
  existing run loop already has the data cheaply available.

  Use OpenClaw's resolved cache retention, not raw config. Use last-call usage
  for the new payload, not accumulated retry or tool-loop totals. Reuse the
  existing prompt-cache observability result and tracked change causes instead
  of inventing a new heuristic. If cache-touch metadata is already available
  from the cache-TTL bookkeeping, include it; do not invent expiry timestamps
  for providers where OpenClaw cannot know them confidently.

  Keep the interface backward-compatible for engines that ignore the new field.
  Add focused tests around the existing attempt/context-engine helpers and the
  compaction runtime-context propagation path rather than broad new integration
  coverage.

* Agents: fix prompt-cache afterTurn usage

Regeneration-Prompt: |
  Fix PR openclaw#62179 so context-engine prompt-cache metadata uses only the current attempt's usage. The review comment pointed out that early exits could reuse a prior turn's assistant usage when no new assistant message was produced. Restrict the prompt-cache lastCallUsage lookup to assistant messages added after prePromptMessageCount, and fall back to current-attempt usage totals instead of stale snapshot history. Also repair the PR's new context-engine test typings and add a regression test for the stale prior-turn case. Two import-only fixes in doctor-state-integrity and config/talk were already broken on origin/main, but they blocked build/check and the gateway-watch regression harness, so include the minimum unblocking imports as well.

* Agents: document prompt-cache context

* Agents: address prompt-cache review feedback

* Doctor: drop unused isRecord import
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants