Skip to content

docs(plan): life app-prompt caching — Increment B + Phase 3 (review-only) - #81

Open
cryptolir wants to merge 4 commits into
mainfrom
docs/life-caching-increment-b
Open

cryptolir wants to merge 4 commits into
mainfrom
docs/life-caching-increment-b

Conversation

@cryptolir

Copy link
Copy Markdown
Owner

Follow-up design to #77 (rev4) now that Increment A shipped (#80, gateway:v2026.06.20.1). Review-only — do NOT merge to deploy.

Increment A captured the per-turn size win (~8 KB/turn). This plan covers the deferred caching lever (the multi-turn win):

  • Phase 0 — Measure (gate): (1) does Venice return cached_tokens > 0 on turn 2+ of a stable-prefix session? (2) is the shared framework+bootstrap prefix cross-user stable today (it isn't — APP_PROFILE sits inside # Project Context)? Privacy-safe via cache-trace digests + a one-line response-usage log. Decides the Phase 3 path.
  • Increment B — make the prefix cacheable: APP_PROFILE dedicated render-slot (after # Project Context, before ## Runtime; not a hook reorder — Codex 4533385398 P2) + per-session bootstrap memoization keyed on (sessionKey, promptMode, app-variant mtime/hash, config version) (Codex 4536644504 feat(gateway): add usage report rpc #3). Threaded through the shared resolveAppPromptContext so attempt/compact can't drift; fix(bootstrap): inject app_profile on the first turn of a new app session #71 first-turn greeting preserved.
  • Phase 3 — caching on (gated on Phase 0): Venice implicit (automatic if it caches) vs Option A (generalize the openai-completions cache_control injector for Venice) vs Option B (route claude-opus-4-6 via an Anthropic endpoint).

Expected impact: no further size change; the multi-turn win — shared prefix re-billed ~10% after turn 1 on long coaching chats. Telegram/owner unaffected.

🤖 Generated with Claude Code

…→ stabilize → cache)

Follow-up to #77 (rev4) after Increment A (#80) shipped. Review-only design
proposal for the deferred cache-prefix work: Phase 0 measurement (does Venice
cache implicitly? is the shared prefix cross-user stable?), Increment B
(APP_PROFILE dedicated render-slot + per-session bootstrap memoization with
cache-key invalidation), Phase 3 caching (Venice implicit vs Option A injector
vs Option B Anthropic endpoint). Not implemented; do NOT merge to deploy.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

@cryptolir cryptolir left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review for Claude on cryptolir/openclaw#81 at 4558663.

Findings:

  • [P1] Phase 0's privacy-safe digest capture does not match current cache-trace behavior. With OPENCLAW_CACHE_TRACE_SYSTEM=0, cache-trace.ts suppresses both raw system and systemDigest, so the proposed cross-user system-prefix comparison will produce no digest. It also only has a whole-system digest today, not a shared-prefix digest split before APP_PROFILE/Runtime. Please update the plan so Phase 0 explicitly adds always-on redacted digest fields, e.g. sharedPrefixDigest / perUserBlockDigest, emitted even when raw prompt/system content is disabled.
  • [P2] The memoization scope needs to account for bootstrap hooks. Today resolveBootstrapFilesForRun includes applyBootstrapHookOverrides(...); memoizing the whole resolveBootstrapContextForRun result with only session/config/app-file keys can freeze hook-generated context for the rest of the session. The plan should specify either memoizing only the static bootstrap file load/filter/app-variant span and rerunning hooks every turn, or requiring hook output to declare cache keys/TTL. Add a freshness test for dynamic hook output, not only AGENTS.app.md edits.

The rest of the plan direction looks sound: moving APP_PROFILE into a dedicated render slot through resolveAppPromptContext is the right shape, and preserving run/compact parity is the key implementation constraint.

1. **Does Venice cache a stable prefix at all?** (decides whether Phase 3 needs Option A/B, or is automatic.) Capture the model **response `usage.cached_tokens`** on turn 2+ of a single app session whose prefix is unchanged. > 0 ⇒ Venice caches implicitly; 0 ⇒ it does not. _(Needs a multi-turn app session; capture token counts only — no prompt/message content.)_
2. **Is the shared prefix currently NOT stable across users?** (confirms Increment B is necessary + sizes the win.) Use `cache-trace` digests: compare the system-prompt prefix digest for **two different app users** — today they differ (APP_PROFILE inside Project Context); after Increment B the framework+bootstrap prefix digest should be **identical** across users, with only the trailing per-user block differing.

Privacy-safe capture: `cache-trace` logs digests (hashes), not content; set the content flags off (`OPENCLAW_CACHE_TRACE_MESSAGES/PROMPT/SYSTEM=0`) and add a one-line `usage.cached_tokens`/`promptTokens` log line at the openai-completions response boundary for question 1. Output: a 3-row table (prompt tokens, prefix-stable-across-users y/n, turn-2 `cached_tokens` y/n, p50 latency) → **decides Phase 3 path**. If Venice doesn't cache, Increment B still has no payoff alone → Phase 3 Option A/B is required for any win.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] This measurement recipe currently will not produce the digest it asks Claude to compare. In cache-trace.ts, systemDigest is only computed inside the includeSystem branch, so setting OPENCLAW_CACHE_TRACE_SYSTEM=0 suppresses both the raw system prompt and its digest. Also, the existing digest is for the whole system prompt, not the shared prefix before APP_PROFILE/Runtime. Please make Phase 0 explicitly add redacted digest-only fields such as sharedPrefixDigest and perUserBlockDigest that are emitted even when raw content flags are off.

## Increment B — make the prefix cacheable (openclaw PR → roll life-only)

1. **Dedicated APP_PROFILE render slot** (Codex 4533385398 P2 — a real render split, not a hook reorder): add an `appProfileContext` input to `buildAgentSystemPrompt`, rendered as its **own section AFTER `# Project Context`, immediately before `## Runtime`**. Stop appending `APP_PROFILE.md` into the bootstrap-file list (`appendAppProfileBootstrapFile` → feed the render input instead). Thread it through the shared `resolveAppPromptContext` so **both** `attempt.ts` and `compact.ts` populate it identically. Net effect: the framework+bootstrap prefix becomes **identical across all app users** (cacheable cross-user), and the per-user block sits _after_ it. Preserve the #71 first-turn `appUserIdFromSessionKey` resolution (APP_PROFILE stays outside any memo span). Tests: APP_PROFILE **absent** from `# Project Context`, appears **exactly once** after the shared prefix and before `## Runtime`; greets-by-name on turn 1 intact; compaction parity (`compact.ts` byte-identical to `attempt.ts` for the same inputs).
2. **Per-session bootstrap memoization** (Codex 4536644504 #3): memoize `resolveBootstrapContextForRun` keyed on `(sessionKey, promptMode, app-variant file mtime+size [or content hash], config version)`, with **APP_PROFILE + scoped skills kept OUTSIDE** the memoized span. Editing/rolling back `AGENTS.app.md`/`SOUL.app.md` or the `appSkills` allowlist misses the cache and re-resolves; conservative fallback = new-session-only / short TTL. Test: edit `AGENTS.app.md` mid-session → next turn reflects it (no stale prefix).

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] This memoization target is too broad unless the hook boundary is specified. Current resolveBootstrapFilesForRun runs applyBootstrapHookOverrides(...) before returning, so memoizing resolveBootstrapContextForRun with only session/config/app-file keys can freeze any hook-generated bootstrap context for the rest of the session. Please either memoize only the static load/filter/app-variant portion and rerun hooks every turn, or require bootstrap hooks to contribute cache keys/TTL, with a test that dynamic hook output refreshes.

[P1] Phase 0 digest recipe corrected: cache-trace systemDigest is gated behind
includeSystem and is whole-system, so SYSTEM=0 kills it. Add always-on,
content-independent sharedPrefixDigest/perUserBlockDigest split at the
APP_PROFILE/Runtime boundary. [P2] Narrow memoization to the static load→filter
→app-variant span only; re-run applyBootstrapHookOverrides + APP_PROFILE every
turn (hooks declare their own cache key/TTL if needed). Add a dynamic-hook
freshness test. Still review-only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cryptolir

Copy link
Copy Markdown
Owner Author

Rev2 (5c34a23433) addresses both findings — verified against live source first.

[P1] Digest recipe corrected. Confirmed systemDigest is computed only inside the includeSystem branch (cache-trace.ts:196–198) and digests the whole system prompt → OPENCLAW_CACHE_TRACE_SYSTEM=0 would produce no digest, and even on it wouldn't isolate the shared prefix. Phase 0 now adds always-on, content-independent sharedPrefixDigest (framework + lean bootstrap, up to the APP_PROFILE/## Runtime boundary) and perUserBlockDigest (trailing per-user block), emitted even when raw prompt/system content is off. Question 2 = compare sharedPrefixDigest across two app users. Noted that this makes Phase 0 a tiny code change (the digest split), not pure-config.

[P2] Memo scope narrowed. Confirmed resolveBootstrapFilesForRun runs applyBootstrapHookOverrides(...) before returning. The memo now covers only the static loadWorkspaceBootstrapFiles → filterBootstrapFilesForSession → applyAppBootstrapVariants span; applyBootstrapHookOverrides + APP_PROFILE re-run every turn outside it (a hook needing caching must declare its own key/TTL). Added a dynamic-hook freshness test (hook output changing turn-to-turn must still surface) alongside the AGENTS.app.md-edit test.

Critical files updated to name cache-trace.ts (the digest fields) and the narrowed bootstrap-files.ts memo boundary. Still review-only — no code implemented.

@cryptolir cryptolir left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rev2 review for Claude on cryptolir/openclaw#81 at 5c34a23.

Good: rev2 addresses the two prior findings from review 4536945369: the cache-trace digest work is now explicitly a tiny code change with digest-only fields, and the bootstrap memoization boundary now keeps hooks outside the memo.

Remaining finding:

  • [P1] The revised sharedPrefixDigest gate is internally inconsistent. The doc defines sharedPrefixDigest as the hash of the prompt up to the APP_PROFILE/Runtime boundary, i.e. excluding the per-user APP_PROFILE block. But current appendAppProfileBootstrapFile(...) appends APP_PROFILE after the hook-adjusted bootstrap files, so a digest that stops before APP_PROFILE should already be cross-user stable today. The doc still says this digest should differ today and become identical only after Increment B. Please split the measurement into two explicit digests: one for the current whole/pre-runtime prompt shape that proves APP_PROFILE makes the assembled prompt differ today, and one for the candidate cacheable prefix that excludes APP_PROFILE. Otherwise Phase 0 can report the wrong conclusion and either understate the need for Increment B or measure the wrong cache target.

Non-blocking wording cleanup: perUserBlockDigest / Phase 3 says “APP_PROFILE + scoped skills,” but app skills currently render in the early ## Skills section and are agent-scoped, not per-user. Either keep scoped skills in the shared prefix and make the per-user block just APP_PROFILE, or explicitly add moving scoped skills to Increment B.


Privacy-safe capture (P1 — corrected): the existing `systemDigest` is gated behind `includeSystem` and is whole-system, so it can't answer question 2 with content off. So Phase 0 adds two **always-on, content-independent** digest fields to `cache-trace.ts`, emitted even when `OPENCLAW_CACHE_TRACE_MESSAGES/PROMPT/SYSTEM=0`:

- `sharedPrefixDigest` — hash of the assembled system prompt **up to the APP_PROFILE/`## Runtime` boundary** (framework + lean app bootstrap = the cache target).

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] This digest boundary conflicts with the expected result below. If sharedPrefixDigest stops before APP_PROFILE, then with the current code it should already be stable across users because appendAppProfileBootstrapFile(...) appends APP_PROFILE after the static/hook-adjusted bootstrap files. To prove the current problem, Phase 0 needs a separate whole/pre-runtime digest that includes APP_PROFILE, plus a candidate cacheable-prefix digest that excludes it. Otherwise the gate can measure the wrong thing.


- **If Phase 0 shows Venice caches implicitly** → Increment B's now-stable prefix captures the win automatically; no provider change needed.
- **If not** (owner decision): **Option A** — generalize pi-ai's openai-completions `cache_control` injector behind a per-model flag and test whether Venice honors it (keeps Venice; cheapest). **Option B** — route `claude-opus-4-6` to an Anthropic-API endpoint so the existing `cacheRetention` path works (cost + data-routing sign-off).
- Either way: **2 breakpoints** — after the shared prefix (framework + lean app bootstrap, identical across all life app users) and after the per-user block (APP_PROFILE + scoped skills).

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: “APP_PROFILE + scoped skills” does not match the current render order or the Increment B steps. App skills render in the early ## Skills section and are agent-scoped, so they should either remain part of the shared prefix, or the plan should explicitly move them into the per-user block and add tests for that.

@cryptolir
cryptolir force-pushed the docs/life-caching-increment-b branch from a1be656 to d58d987 Compare June 20, 2026 10:36
…ontract + premise

[P1] Verified appendAppProfileBootstrapFile appends APP_PROFILE last
(app-profile-context.ts:170), so the cross-user shared prefix already exists
today and sharedPrefixDigest (excl APP_PROFILE) is already stable — it can't
prove the problem. Phase 0 digest contract corrected to preRuntimeDigest (incl
APP_PROFILE, differs per-user today) + sharedPrefixDigest (excl, the cacheable
candidate) + cacheablePrefixBytes. Honestly reframed Increment B: it secures
cross-turn byte-stability (memo) + clean APP_PROFILE separation, NOT a
cross-user-prefix extension; Phase 3 (provider caching) is the dominant lever.
Non-blocking: scoped skills are agent-scoped/shared → shared prefix, per-user
block = APP_PROFILE only (fixed throughout). Still review-only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cryptolir
cryptolir force-pushed the docs/life-caching-increment-b branch from d58d987 to 209f1fb Compare June 20, 2026 10:36
@cryptolir

Copy link
Copy Markdown
Owner Author

Rev3 (209f1fb6b0) addresses the remaining P1 + the wording note — and the P1 surfaced a real premise correction, which I've made honestly rather than papered over.

[P1] Digest contract + premise. Verified in code: appendAppProfileBootstrapFile appends APP_PROFILE last (app-profile-context.ts:170 return [...files, contextFile]), so it's already the final file in # Project Context with only ## Runtime after it. Therefore:

  • A sharedPrefixDigest that stops before APP_PROFILE is already cross-user stable today — it can't "differ today, become identical after." You're right; the old contract measured the wrong thing.
  • Phase 0 now uses two explicit digests: preRuntimeDigest (includes APP_PROFILE → differs per user today, proving it's the variance) + sharedPrefixDigest (excludes it → the cacheable candidate, expected already-stable), plus cacheablePrefixBytes as the headline.
  • Honest consequence: the cross-user shared prefix already exists, so Increment B does not extend it. I've reframed it as a supporting refactor — cross-turn byte-stability (memoization) + pulling APP_PROFILE into a clean render slot (clean memo boundary, no run/compaction drift). The dominant lever is now explicitly Phase 3 (does the provider cache the already-stable prefix?). Context + Increment B headings updated to match.

Non-blocking wording. Fixed throughout: the agent-scoped ## Skills catalog is cross-user-identical → it stays in the shared prefix; the per-user block is APP_PROFILE only. Increment B does not move scoped skills. Phase 3 breakpoints + verification corrected accordingly.

Still review-only — no code implemented; life stays on v2026.06.20.1.

@cryptolir

Copy link
Copy Markdown
Owner Author

@codex review — rev3 (209f1fb6b0) of the Increment B + Phase 3 design plan (review-only).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

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: 209f1fb6b0

ℹ️ 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".


The DOMINANT question is provider caching; the digests confirm the prefix shape and size the levers. Three measurements:

1. **Does the provider cache a stable prefix at all?** (the gate — decides whether Phase 3 is automatic or needs Option A/B.) Capture the model **response `usage.cached_tokens`** on turn 2+ of a single app session whose prefix is unchanged. > 0 ⇒ caches implicitly; 0 ⇒ it does not. Add a one-line `usage.cached_tokens`/`promptTokens` log at the openai-completions response boundary (token counts only — no content).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Read cached tokens from nested usage details

If Phase 0 is implemented literally as usage.cached_tokens, OpenAI-compatible responses will report no hit even when caching works: cached counts are nested under usage.prompt_tokens_details.cached_tokens for chat completions, and this repo's Responses mock models the analogous input_tokens_details.cached_tokens shape in src/gateway/test-helpers.openai-mock.ts:17. That would make the gate incorrectly choose Option A/B whenever Venice already caches implicitly, so the plan should require reading the nested detail field (or the SDK-normalized cacheRead) instead of a top-level property.

Useful? React with 👍 / 👎.

> Scope note (rev3): the cross-user shared prefix already exists today (APP_PROFILE is appended last). Increment B does **not** extend it — it secures **cross-turn** byte-stability (memoization) and pulls APP_PROFILE into a first-class slot so the memo boundary is clean and the run/compaction paths can't drift. The big win is still **Phase 3** (provider caching).

1. **Dedicated APP_PROFILE render slot** (Codex 4533385398 P2 — a real render split, not a hook reorder): add an `appProfileContext` input to `buildAgentSystemPrompt`, rendered as its **own section AFTER `# Project Context`, immediately before `## Runtime`** (the same end-position it already occupies as the trailing file — this is a clean-separation refactor, not a reorder). Stop appending `APP_PROFILE.md` into the bootstrap-file list (`appendAppProfileBootstrapFile` → feed the render input instead) so APP_PROFILE is **out of the memoized bootstrap span**. Thread it through the shared `resolveAppPromptContext` so **both** `attempt.ts` and `compact.ts` populate it identically. Preserve the #71 first-turn `appUserIdFromSessionKey` resolution. Tests: APP_PROFILE **absent** from the `# Project Context` file list, appears **exactly once** after the shared prefix and before `## Runtime`; greets-by-name on turn 1 intact; compaction parity (`compact.ts` byte-identical to `attempt.ts` for the same inputs).
2. **Per-session memoization of the STATIC bootstrap span only** (Codex 4536644504 #3 + 4536945369 P2): memoize **just** `loadWorkspaceBootstrapFiles` → `filterBootstrapFilesForSession` → `applyAppBootstrapVariants` (the file I/O), keyed on `(sessionKey, promptMode, app-variant file mtime+size [or content hash], config version)`. **`applyBootstrapHookOverrides` and APP_PROFILE re-run every turn** (after the memoized span), so dynamic hook output and per-user context are never frozen. Editing/rolling back `AGENTS.app.md`/`SOUL.app.md` or the `appSkills` allowlist misses the cache and re-resolves; conservative fallback = new-session-only / short TTL. If a hook ever needs to be cached, it must declare its own cache key/TTL (not covered by the static-span memo). Tests: (a) edit `AGENTS.app.md` mid-session → next turn reflects it; (b) **dynamic-hook freshness** — a bootstrap hook whose output changes turn-to-turn still surfaces on every turn (proves hooks aren't memoized).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Key memoization on all bootstrap inputs

In app sessions this memoized span still reads canonical bootstrap files via loadWorkspaceBootstrapFiles and may keep BOOTSTRAP.md or canonical AGENTS.md/SOUL.md when an .app.md variant is absent or deleted, but the proposed key only mentions app-variant mtime/hash plus config. In that scenario, editing one of those canonical files mid-session will keep serving stale prompt context, so the cache key should include the selected canonical files and missing/present variant state for every file that can contribute to the static span.

Useful? React with 👍 / 👎.

@cryptolir cryptolir left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rev3 review for Claude on cryptolir/openclaw#81 at 209f1fb.

Findings:

  • [P2] Phase 0 should not read only a top-level usage.cached_tokens. OpenAI-compatible chat completions report cached tokens under usage.prompt_tokens_details.cached_tokens, and this repo’s Responses mock uses the analogous usage.input_tokens_details.cached_tokens shape. If the implementation checks only the top-level field, it can report a false zero and push the wrong Phase 3 provider decision. Please require the nested detail field or the SDK-normalized cache-read value.
  • [P2] The static bootstrap memo key needs every bootstrap input that can contribute, not just .app.md variant mtimes/hashes plus config. The memoized span still starts with loadWorkspaceBootstrapFiles, so canonical BOOTSTRAP.md and canonical AGENTS.md / SOUL.md when a variant is absent or deleted can be served stale mid-session. Please key on the selected canonical file mtimes/hashes plus variant present/missing state, prompt mode, session key, and config version; add an edit-canonical-file invalidation test alongside the app-variant edit test.

No remaining P1 from my pass. Rev3 fixes the earlier digest-premise issue: preRuntimeDigest includes APP_PROFILE, sharedPrefixDigest excludes it, and APP_PROFILE remains the only per-user block.

…ith #83

[P2] Phase 0 reads the NESTED cached-token field (usage.prompt_tokens_details
.cached_tokens / usage.input_tokens_details.cached_tokens), not the nonexistent
top-level usage.cached_tokens. [P2] Memo key covers all canonical bootstrap
inputs (BOOTSTRAP/AGENTS/SOUL mtimes/hashes + sessionKey + promptMode + config
version), not just .app.md variants. Memo span narrowed to load→filter only;
applyAppBootstrapVariants now runs post-hook + un-memoized (matching shipped
#83), so variant edits reflect automatically. Added an edit-canonical-file
invalidation test. Still review-only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@cryptolir

Copy link
Copy Markdown
Owner Author

Rev4 (e6a499a8f7) addresses both P2s. [P2] Phase 0 reads the nested cached-token field (usage.prompt_tokens_details.cached_tokens / usage.input_tokens_details.cached_tokens), not the nonexistent top-level usage.cached_tokens. [P2] Memo key now covers all canonical bootstrap inputs (BOOTSTRAP/AGENTS/SOUL mtimes/hashes + sessionKey + promptMode + config version); the memo span is narrowed to load → filter and applyAppBootstrapVariants runs post-hook + un-memoized — reconciled with the shipped #83 ordering, so variant edits reflect automatically. Added an edit-canonical-file invalidation test. Still review-only.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant