Skip to content

V4 enhancement#101

Merged
linfangw merged 3 commits into
mainfrom
v4_enhancement
Mar 9, 2026
Merged

V4 enhancement#101
linfangw merged 3 commits into
mainfrom
v4_enhancement

Conversation

@linfangw

@linfangw linfangw commented Mar 9, 2026

Copy link
Copy Markdown
Member

Summary

  • Problem: The context-digest and session-importance memory hooks re-summarized all sessions in a 7-day window on every /new, exceeding LLM timeout limits and writing error messages into context-digest.md; TUI /new did not notify the gateway, so hooks never triggered; session:end was defined but never emitted; X channel monitorXProvider crashed on startup; QVeris onboarding bundled web_search and tool-search config in a single step.
  • Why it matters: Long-term memory was silently broken — context-digest.md showed timeout errors and memory/important/ was never created. Every gateway restart showed an X channel crash-loop. The onboard flow was confusing users who wanted to configure web_search and tool-search independently.
  • What changed: context-digest now detects staleness (skips entirely when no sessions updated since last write) and uses incremental merge mode (1–2 new sessions → merge prompt instead of full rebuild). runOneShotLLM now uses an adaptive timeout scaled to prompt size instead of a static 90 s. Token budget raised from 24 K to 120 K chars (~30 K tokens). session-importance adds a short-session skip (< 3 user messages) and an already-classified guard. Fixed TUI /new to call resetSession, emit session:end after rotation, propagate storePath through hook context, inject monitorXProvider into the X channel runtime. QVeris web_search config moved to the setupSearch step as a first-class provider.
  • What did NOT change: Hook configuration keys (context-digest, session-importance), fallback (no-LLM) code paths, existing session file formats, and all other channels/commands are untouched.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor
  • 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 #

User-visible / Behavior Changes

  • context-digest.md now updates correctly on /new and /reset instead of writing a timeout error string.
  • memory/important/ is now created and populated for sessions that pass importance classification.
  • First /new after startup = full digest rebuild; subsequent /new with no new sessions = skip (zero LLM cost); 1–2 new sessions = incremental merge (much smaller prompt).
  • X channel no longer crash-loops on gateway startup (monitorXProvider was missing from the runtime).
  • qverisbot onboard: web_search provider setup is now a separate step; configuring QVeris tool-search no longer silently overwrites web_search settings.
  • LLM timeout is now proportional to prompt size (min ~30 s, max 5 min) instead of a fixed 90 s.
  • Sessions with fewer than 3 user messages are skipped by session-importance without calling the LLM.

Security Impact (required)

  • New permissions/capabilities? No
  • Secrets/tokens handling changed? No
  • New/changed network calls? No (same LLM calls, just fewer and with adaptive timeout)
  • Command/tool execution surface changed? No
  • Data access scope changed? No — hooks only read/write files already under the agent workspace directory (~/.openclaw/workspace/memory/)

Repro + Verification

Environment

  • OS: macOS 15.3
  • Runtime/container: Node 22, Bun
  • Model/provider: Any (hooks use the agent's configured primary model)
  • Integration/channel: TUI (openclaw-tui) + gateway
  • Relevant config: hooks.context-digest.enabled: true, hooks.session-importance.enabled: true

Steps

  1. Start gateway, open TUI session, have a multi-turn conversation (≥ 3 user messages).
  2. Run /new to start a new session.
  3. Check ~/.openclaw/workspace/memory/context-digest.md — should show a structured digest, not a timeout error.
  4. If the session contained keywords like remember, milestone, decision, or high code-block density, check ~/.openclaw/workspace/memory/important/ — a dated Markdown file should appear.
  5. Run /new a second time immediately — digest should be skipped (no new sessions since last write).

Expected

  • context-digest.md contains ## Topics Discussed, ## Key Decisions, ## Open Items / Action Items sections populated from the session.
  • memory/important/*.md created for substantive sessions.
  • Gateway logs show Context digest updated or Digest still fresh — skipping.

Actual (before fix)

  • context-digest.md contained Request timed out before a response was generated.
  • memory/important/ directory did not exist.
  • Gateway logs showed [default] channel exited: monitorXProvider is not a function on every X channel restart.

Evidence

  • Failing test/log before + passing after — all 37 memory hook tests + 26 gateway/TUI tests pass; pnpm build clean.
  • Trace/log snippets — manual verification confirmed context-digest.md populated correctly after fix.

Human Verification (required)

  • Verified scenarios: /new triggers full digest on first run; /new skips when no sessions changed; X channel no longer reports monitorXProvider is not a function; qverisbot onboard completes without listXAccountIds TypeError.
  • Edge cases checked: empty session store (digest shows "No conversations"), session with < 3 user messages (importance skipped), session already in important/ (already-classified guard fires).
  • What I did not verify: incremental LLM merge path end-to-end with a live model (only fallback path exercised in tests); performance on very large session stores (> 50 sessions).

Compatibility / Migration

  • Backward compatible? Yes
  • Config/env changes? No — existing hook config keys unchanged; new defaults are backward compatible.
  • Migration needed? No

Failure Recovery (if this breaks)

  • How to disable/revert quickly: Set hooks.context-digest.enabled: false and hooks.session-importance.enabled: false in config to disable both hooks without reverting code.
  • Files/config to restore: src/hooks/bundled/context-digest/handler.ts, src/hooks/bundled/session-importance/handler.ts, src/hooks/llm-memory-helpers.ts.
  • Known bad symptoms to watch for: context-digest.md not updating after /new; memory/important/ not being created for clearly important sessions; X channel crash-loop in gateway logs.

Risks and Mitigations

  • Risk: Incremental merge prompt may produce a degraded digest if the existing digest body is malformed or truncated.
    • Mitigation: generateDigestIncremental returns null on any failure, and the handler falls through to a full rebuild automatically.
  • Risk: Staleness check skips digest even when a session was manually edited outside the bot.
    • Mitigation: The check uses sessions.json updatedAt timestamps written by the gateway itself, which are only updated on actual session activity — manual file edits don't affect this.
  • Risk: Short-session skip (< 3 user messages) may miss a genuinely important 2-message exchange (e.g., "remember X" → reply).
    • Mitigation: Explicit intent keywords (remember, 记住, etc.) trigger an instant pass in the evaluator before the short-session check, so those cases are still captured.

linfangw added 3 commits March 9, 2026 12:05
Previously, promptQverisConfig bundled web_search provider setup
together with QVeris tool search enablement. This made the two
concerns hard to manage independently and the setupSearch step
had no QVeris option, making it easy to accidentally overwrite.

Now promptQverisConfig only handles tools.qveris (tool search),
and setupSearch lists QVeris Smart Search as a first-class provider
that reuses the shared QVeris API key without duplication.

Made-with: Cursor
@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the agent's memory management system by optimizing how context digests and session importance are handled. It addresses critical performance issues, such as LLM timeouts and redundant processing, by introducing adaptive timeouts, incremental updates, and intelligent skipping mechanisms. Additionally, it refines the user onboarding experience for QVeris integrations and resolves a stability issue in the X channel, leading to a more robust and efficient agent overall.

Highlights

  • Memory Hooks Enhancement: The context-digest hook now includes a staleness check to skip unnecessary re-summarizations and an incremental merge mode for efficiency. The session-importance hook adds a short-session skip and an already-classified guard to prevent redundant processing. Both hooks now run heavy processing in the background to avoid blocking user commands.
  • Adaptive LLM Timeout & Token Budget: The runOneShotLLM function now uses an adaptive timeout scaled to prompt size, replacing the static 90-second limit. The token budget for memory-related LLM prompts has been significantly increased from 24K to 120K characters (~30K tokens).
  • TUI /new Command Fix: The TUI /new command now correctly notifies the gateway about the ending of the previous session, ensuring that memory hooks (like context-digest and session-importance) are triggered to process the completed session.
  • QVeris Onboarding Refinement: The QVeris onboarding flow has been improved to separate web search configuration from tool search, preventing silent overwrites and providing a clearer user experience. QVeris is now a first-class web search provider option.
  • X Channel Stability Fix: The X channel no longer crash-loops on gateway startup due to a missing monitorXProvider function, improving the stability of the integration.
  • Hook Context Propagation: The storePath parameter is now consistently propagated through hook contexts, ensuring memory hooks have the necessary information to locate session data.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • release_notes/QVerisBot_2026.3.8.md
    • Added new release notes detailing memory enhancements, natural language model switching, and QVeris integration improvements.
  • src/auto-reply/reply/commands-core.ts
    • Added storePath to the parameters passed to emitResetCommandHooks and handleCommands to ensure memory hooks have access to the session store path.
  • src/auto-reply/reply/get-reply.ts
    • Included storePath in the parameters for emitResetCommandHooks within getReplyFromConfig.
  • src/commands/onboard-qveris.test.ts
    • Removed DEFAULT_QVERIS_WEB_SEARCH_TOOL_ID import.
    • Updated test descriptions and assertions to reflect that QVeris tool search onboarding no longer configures web search by default.
    • Added a new test case to verify that existing web search configurations are preserved when enabling QVeris tool search.
  • src/commands/onboard-qveris.ts
    • Removed DEFAULT_QVERIS_WEB_SEARCH_TOOL_ID constant.
    • Modified the promptQverisConfig function to clarify that QVeris web search is configured separately and to remove the automatic defaulting of web search to QVeris when enabling QVeris tools.
  • src/commands/onboard-search.test.ts
    • Updated SEARCH_PROVIDER_OPTIONS length expectation from 5 to 6.
    • Added 'qveris' to the expected values in SEARCH_PROVIDER_OPTIONS.
    • Added new test cases for QVeris web search provider to verify key storage, skipping key prompts when a global QVeris API key exists (either in config or environment variables), and falling through to a key prompt when no key is available.
  • src/commands/onboard-search.ts
    • Added 'QVeris Smart Search' as a new option to SEARCH_PROVIDER_OPTIONS.
    • Modified rawKeyValue to fall back to the global QVeris API key for the 'qveris' provider.
    • Added a case to applySearchKey to handle qveris specific API key storage.
    • Implemented logic in setupSearch to skip the API key prompt for QVeris if a global QVeris API key is already configured or available via environment variables.
  • src/gateway/server-methods/sessions.ts
    • Propagated storePath to the emitResetCommandHooks call during session reset.
    • Added logic to emit a session:end internal hook event after a session rotation (e.g., /new or /reset) to allow memory hooks to process the completed session.
  • src/gateway/server.sessions.gateway-server-sessions-a.test.ts
    • Updated test expectations for triggerInternalHook calls during session reset to account for the newly emitted session:end lifecycle event.
    • Added assertions to verify the content and context of the session:end event.
  • src/hooks/bundled/context-digest/handler.test.ts
    • Added a new test case to verify that the context digest handler correctly skips processing when no sessions have changed since the last update (staleness check).
  • src/hooks/bundled/context-digest/handler.ts
    • Refactored the core digest generation logic into a separate runDigest function to allow background execution.
    • Implemented a staleness check to skip digest generation if no sessions have been updated since the last digest write.
    • Introduced an incremental merge mode (generateDigestIncremental) for efficiency when only a few new sessions are present.
    • Updated session processing deduplication to use a hook-specific namespace.
    • Modified the main handler to run heavy work (transcript collection + LLM) in a fire-and-forget manner, with awaiting in test environments.
  • src/hooks/bundled/session-importance/handler.test.ts
    • Extended mock session data in various test cases to include more user and assistant messages, simulating longer conversations for importance evaluation.
  • src/hooks/bundled/session-importance/handler.ts
    • Refactored the core importance classification logic into a separate runClassification function for background execution.
    • Added an isAlreadyClassified guard to prevent re-processing sessions that have already been persisted as important.
    • Implemented a MIN_USER_MESSAGES threshold to skip importance analysis for short sessions with fewer than 3 user messages.
    • Updated session processing deduplication to use a hook-specific namespace.
    • Modified the main handler to run heavy work (transcript read + LLM) in a fire-and-forget manner, with awaiting in test environments.
  • src/hooks/llm-memory-helpers.ts
    • Increased MAX_DIGEST_PROMPT_CHARS from 24,000 to 120,000 and MAX_IMPORTANCE_PROMPT_CHARS from 16,000 to 60,000.
    • Modified shouldProcessSession and markSessionProcessed to accept an optional hookName for hook-specific deduplication.
    • Added parseDigestHeader function to extract metadata from existing context digest files.
    • Introduced computeAdaptiveTimeout to dynamically adjust LLM call timeouts based on prompt character count, with a maximum of 5 minutes.
    • Enhanced runOneShotLLM to use the adaptive timeout and to filter out LLM responses that appear to be error messages, returning null for fallback.
  • src/hooks/transcript-reader.ts
    • Increased default maxMessagesPerSession from 20 to 50 and maxTotalChars from 24,000 to 120,000 in collectRecentSessionTranscripts.
    • Added collectNewSessionsSince function to efficiently gather sessions updated after a specific timestamp, used for incremental digest generation.
  • src/plugins/runtime/runtime-channel.ts
    • Imported monitorXProvider from ../../x/monitor.js.
    • Injected monitorXProvider into the X channel runtime object.
  • src/plugins/runtime/types-channel.ts
    • Added monitorXProvider to the PluginRuntimeChannel['x'] type definition.
  • src/tui/tui-command-handlers.test.ts
    • Updated test expectations for resetSession calls in /new and /reset commands to reflect the new session:end event emission.
  • src/tui/tui-command-handlers.ts
    • Modified the /new command handler to explicitly call client.resetSession with the 'new' reason before generating a new session key, ensuring the previous session is properly ended and processed by hooks.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@linfangw linfangw merged commit 62bf697 into main Mar 9, 2026
2 of 9 checks passed
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.

2 participants