Skip to content

feat(context,smart-search): inject insights into session context and smart search results (#457)#615

Open
mengqiuzhen wants to merge 1 commit into
rohitg00:mainfrom
mengqiuzhen:feat/insights-context-search
Open

feat(context,smart-search): inject insights into session context and smart search results (#457)#615
mengqiuzhen wants to merge 1 commit into
rohitg00:mainfrom
mengqiuzhen:feat/insights-context-search

Conversation

@mengqiuzhen
Copy link
Copy Markdown

@mengqiuzhen mengqiuzhen commented May 23, 2026

Summary

mem::context (SessionStart injection) and mem::smart-search (hybrid
search) loaded lessons but skipped insights — the higher-order reflections
synthesised by mem::reflect. Insights sat in KV reachable only via the
explicit memory_insight_list / memory_insight_search MCP tools, never
surfacing automatically in context or search results.

Diff

  • src/functions/context.ts (+34/-1): parallel-load KV.insights
    alongside lessons; filter non-deleted, project-scoped; sort by
    confidence descending; cap at 8; render as ## Insights block.
  • src/functions/smart-search.ts (+41/-4): add recallInsights()
    helper calling mem::insight-search with minConfidence 0.3; run in
    parallel with hybrid search and lesson recall; attach results as
    insights field on the compact response. Reuses CompactLessonResult
    type.

Both follow the existing lessons pattern exactly: same cap strategy,
token-budget loop, recency sort, and best-effort catch semantics.

Validation

  • Type safety verified: Insight interface fields all match; KV.insights
    scope defined; mem::insight-search payload signature matches handler.
  • Reviewed: 0 Critical, 0 Major findings.
  • npm install blocked by pre-existing arborist bug on Windows (@node-rs/jieba
    • @anthropic-ai/claude-agent-sdk optional deps trigger npm 10/11
      canDedupe crash). Unrelated to this change. CI runs ubuntu+macos only.
  • Existing tests do not reference insights — this is additive, no test
    assertion changes needed.

🤖 Generated with Claude Code

Summary by CodeRabbit

New Features

  • Insights are now integrated into agent memory context, retrieved and displayed with confidence ratings, titles, and content previews (capped at 8 results, sorted by confidence)
  • Smart search now includes insight-based recall alongside observation and lesson searches, with results returned in a unified format

Review Change Stack

…smart search results (rohitg00#457)

## Summary
`mem::context` (SessionStart injection) and `mem::smart-search` (hybrid
search) loaded lessons but skipped insights — the higher-order reflections
synthesised by `mem::reflect`. Insights sat in KV reachable only via the
explicit `memory_insight_list` / `memory_insight_search` MCP tools, never
surfacing automatically in context or search results.

## Diff
- **src/functions/context.ts** (+34/-1): parallel-load `KV.insights`
  alongside lessons; filter non-deleted, project-scoped; sort by
  confidence descending; cap at 8; render as `## Insights` block.
- **src/functions/smart-search.ts** (+41/-4): add `recallInsights()`
  helper calling `mem::insight-search` with minConfidence 0.3; run in
  parallel with hybrid search and lesson recall; attach results as
  `insights` field on the compact response. Reuses `CompactLessonResult`
  type — insight fields map cleanly onto it.

Both follow the existing lessons pattern exactly: same cap strategy,
token-budget loop, recency sort, and best-effort catch semantics.

## Validation
- TypeScript type safety verified: `Insight` interface (types.ts:757)
  fields all match; `KV.insights` scope defined (schema.ts:38);
  `mem::insight-search` payload signature matches handler (reflect.ts:361).
- Reviewer agent passed: 0 Critical, 0 Major. Two Minor observations
  (M1: `includeInsights` param, M2: `ContextBlock.type` — both addressable
  in follow-up).
- npm install blocked by pre-existing arborist bug on Windows
  (@node-rs/jieba + @anthropic-ai/claude-agent-sdk optional deps trigger
  npm 10/11 canDedupe crash). Unrelated to this change. CI runs
  ubuntu+macos only per `.github/workflows/ci.yml`.
- Existing tests do not reference insights — this is purely additive, no
  test assertion changes needed.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@vercel
Copy link
Copy Markdown

vercel Bot commented May 23, 2026

Someone is attempting to deploy a commit to the rohitg00's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 23, 2026

📝 Walkthrough

Walkthrough

Agent memory context and smart-search functions now retrieve insights in parallel with existing data. The context handler aggregates insights into the memory prompt with filtering, sorting, and formatting; smart-search performs insight recall alongside hybrid search and lesson recall, extending the response payload to include insights when available.

Changes

Insight Retrieval and Integration

Layer / File(s) Summary
Insight context block
src/functions/context.ts
Insight type is imported; context construction fetches insights from KV in parallel; a new "Insights" block filters by deletion and project scope, sorts by confidence, caps at 8 results, formats each as a bullet with truncated content and recency metadata, and participates in token-budget tracking.
Insight smart-search integration
src/functions/smart-search.ts
Insight type is imported; smart-search handler runs recallInsights in parallel with hybrid search and lesson recall as best-effort; response payload optionally includes insights field; new recallInsights helper calls mem::insight-search, validates shape, maps insights to lesson-result format with content preview, and returns empty array on error.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related issues

  • #590: This PR directly implements the insight retrieval and rendering feature requested for both mem::context and mem::smart-search handlers, extending context generation and search responses with filtered and formatted insight data.

Poem

🐰 Insights flutter like carrots in the wind,
Smart search now recalls their whispered grin,
Context blocks woven from confidence and time,
Eight filtered morsels in perfect rhyme,
Memory blooms where wisdom can be found!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main changes: injecting insights into both session context and smart search results across two files (context.ts and smart-search.ts).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
src/functions/smart-search.ts (1)

85-88: ⚡ Quick win

Drop this WHAT-style comment and let naming carry intent.

This comment explains mechanics already visible in the code path; prefer clearer local naming over explanatory prose.

As per coding guidelines, "Avoid code comments explaining WHAT — use clear naming instead".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/functions/smart-search.ts` around lines 85 - 88, Remove the WHAT-style
block comment and instead make the intent explicit via names: delete the
three-line comment and ensure the parallel calls are named/encapsulated with
clear identifiers (e.g., runObservationHybridSearch, runLessonRecall,
runInsightRecall or a helper like performParallelBestEffortLookups) and use
descriptive result variable names (e.g., observationResults,
lessonRecallResults, insightRecallResults) so the code reads self-documentingly
without the explanatory comment.
src/functions/context.ts (1)

137-140: ⚡ Quick win

Remove WHAT-style inline commentary in this block.

Please replace this explanatory block comment with self-descriptive naming (or keep only intent-level rationale if needed).

As per coding guidelines, "Avoid code comments explaining WHAT — use clear naming instead".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/functions/context.ts` around lines 137 - 140, Remove the WHAT-style
explanatory block comment and instead make the code self-descriptive: replace
the multi-line comment about "Insights — higher-order reflections..." with
either a short intent-level comment (one line) or better, rename the related
symbol(s) such as the insights collection/variable and any helper like
mem::reflect to a self-descriptive identifier (e.g., insights, reflectInsights,
cappedInsights) so the purpose is clear from names; keep only a brief rationale
about the 8-item cap or token-budget behavior if needed (mentioning "8-item cap
for token-budget trimming") and delete the rest of the inline WHAT commentary.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/functions/context.ts`:
- Around line 137-140: Remove the WHAT-style explanatory block comment and
instead make the code self-descriptive: replace the multi-line comment about
"Insights — higher-order reflections..." with either a short intent-level
comment (one line) or better, rename the related symbol(s) such as the insights
collection/variable and any helper like mem::reflect to a self-descriptive
identifier (e.g., insights, reflectInsights, cappedInsights) so the purpose is
clear from names; keep only a brief rationale about the 8-item cap or
token-budget behavior if needed (mentioning "8-item cap for token-budget
trimming") and delete the rest of the inline WHAT commentary.

In `@src/functions/smart-search.ts`:
- Around line 85-88: Remove the WHAT-style block comment and instead make the
intent explicit via names: delete the three-line comment and ensure the parallel
calls are named/encapsulated with clear identifiers (e.g.,
runObservationHybridSearch, runLessonRecall, runInsightRecall or a helper like
performParallelBestEffortLookups) and use descriptive result variable names
(e.g., observationResults, lessonRecallResults, insightRecallResults) so the
code reads self-documentingly without the explanatory comment.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 66bed8b9-6123-4557-a229-04ff95bdb8a6

📥 Commits

Reviewing files that changed from the base of the PR and between 3551241 and dfa2849.

📒 Files selected for processing (2)
  • src/functions/context.ts
  • src/functions/smart-search.ts

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