Skip to content

feat: add session agent metadata#306

Open
flamerged wants to merge 5 commits into
rohitg00:mainfrom
flamerged:feat/session-agent-metadata
Open

feat: add session agent metadata#306
flamerged wants to merge 5 commits into
rohitg00:mainfrom
flamerged:feat/session-agent-metadata

Conversation

@flamerged
Copy link
Copy Markdown

@flamerged flamerged commented May 12, 2026

Summary

  • add optional Session.agent and Session.metadata fields for client/model/role attribution
  • accept agent, metadata, convenience agent fields, and common role/agent_type/source aliases on POST /agentmemory/session/start
  • capture Claude Code model, agent_type, and source in the SessionStart hook payload
  • redact secret-like values from custom session metadata and normalize durable event session metadata before storage
  • surface agent/model/custom metadata in the viewer dashboard and Sessions tab
  • include compact session attribution in mem::search, mem::smart-search, and mem::context so recalled context names the originating client/model/role
  • preserve role-only attribution labels and degrade search session attribution gracefully when session reads fail

Notes

This is a focused first slice of session metadata support. It stores and returns metadata on sessions, makes identity visible in the UI, and carries attribution into agent-facing recall/context output. Update/filter APIs can land as a follow-up without changing the stored shape.

Refs #259

CodeRabbit Follow-up

  • fixed role-only session labels in sessionAttributionLabel()
  • made mem::search treat failed session lookups as missing attribution instead of failing the whole search
  • moved test/search.test.ts to the repo-standard vi.mock("iii-sdk") test harness pattern

Tests

  • npm run build
  • node --check <(awk '/<script nonce/{flag=1;next}/<\\/script>/{flag=0}flag' src/viewer/index.html) && git diff --check
  • npm test -- --run test/session-metadata.test.ts test/search.test.ts test/smart-search.test.ts test/context-slots.test.ts test/context-injection.test.ts
  • SANDBOX_HOME=$(mktemp -d); env -i HOME="$SANDBOX_HOME" USERPROFILE="$SANDBOX_HOME" PATH="$PATH" AGENTMEMORY_URL="http://127.0.0.1:9" AGENTMEMORY_PROBE_TIMEOUT_MS="10" npm test; rc=$?; rm -rf "$SANDBOX_HOME"; exit $rc

Summary by CodeRabbit

  • New Features

    • Sessions now capture and display agent identity (client, model, role/source) and optional session metadata; search, context, and UI show richer per-session attribution and a human-readable source label.
  • Documentation

    • README and API docs updated with session-start request example, optional metadata fields, and notes about compact session attribution.
  • Tests

    • Added/updated tests for metadata normalization, redaction, attribution, context injection, and search/smart-search integration.

Review Change Stack

Signed-off-by: flamerged <34665379+flamerged@users.noreply.github.com>
@vercel
Copy link
Copy Markdown

vercel Bot commented May 12, 2026

@flamerged 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

coderabbitai Bot commented May 12, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 56b65fcc-57a0-4f76-9dc1-62e3f3f70561

📥 Commits

Reviewing files that changed from the base of the PR and between 0f3e0c9 and d760fd9.

📒 Files selected for processing (5)
  • README.md
  • src/functions/search.ts
  • src/types.ts
  • src/viewer/index.html
  • test/search.test.ts
✅ Files skipped from review due to trivial changes (1)
  • README.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/types.ts
  • src/functions/search.ts
  • test/search.test.ts

📝 Walkthrough

Walkthrough

Session-start flow extended to optionally capture agent identity, model, and custom metadata. Client hooks send these fields; server APIs/events normalize, validate, and redact metadata before storing. Attribution helpers, search/context enrichment, viewer UI, README, and tests were updated to surface the new session attribution data.

Changes

Session metadata capture

Layer / File(s) Summary
Type contracts for session metadata
src/types.ts
Session now includes optional agent (AgentIdentity) and metadata (SessionMetadata) fields. New AgentIdentity interface and SessionMetadata type alias added.
Metadata normalization and validation
src/functions/session-metadata.ts, test/session-metadata.test.ts
New normalizeSessionMetadata(body) validates agent/metadata types, accepts nested or top-level convenience agent fields, redacts secrets in metadata via stringify/parse, and returns normalized result or an error. Tests cover normalization, convenience fields, aliasing, validation errors, and redaction.
Client-side session-start hooks
plugin/scripts/session-start.mjs, src/hooks/session-start.ts, test/context-injection.test.ts
Hook and plugin sanitize optional model/agent_type/source via nonEmptyString, compose agent with client and conditional fields, and extend POST body to /agentmemory/session/start. Integration test verifies the expanded payload is posted.
Server-side session handlers
src/triggers/api.ts, src/triggers/events.ts
api::session::start calls normalizeSessionMetadata, returns 400 on validation error, and conditionally populates Session with model/agent/metadata. event::session::started accepts expanded payload and sets optional fields when present (warnings on invalid metadata).
Session attribution helpers
src/functions/session-attribution.ts
New helpers compute compact session attribution objects, readable labels, and formatted session headings used by context, search, and UI.
Search & smart-search enrichment
src/functions/search.ts, src/functions/smart-search.ts
Search and smart-search load Sessions in parallel and attach session attribution to compact/expanded results; narrative output includes a per-item Source: line using the attribution label.
Context rendering
src/functions/context.ts
Context "summary" and "observation" blocks now use formatSessionHeading(...) to include computed session attribution labels.
Viewer UI: identity badges and metadata panel
src/viewer/index.html
Added CSS and JS helpers to render agent/model identity badges, a grid-based identity panel, and sorted/limited metadata entries in Dashboard, Sessions list, and Session Detail; Session Detail also shows raw s.agent JSON when present.
Tests
test/*
Added and updated tests: normalization unit tests, session-start hook integration test, context slot attribution tests, search and smart-search expectations extended for session fields.
API and capture documentation
README.md
README updated to list model and agent identity in captured SessionStart fields and to document POST /agentmemory/session/start accepting optional session metadata with example JSON payload.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I hopped through hooks to learn each name,

models whispered, agents staked their claim,
secrets masked and metadata trimmed,
badges bloom where sessions once dimmed,
I nibble logs and thump—a tiny fame.

🚥 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 'feat: add session agent metadata' accurately describes the main change—adding optional session agent and metadata fields—and aligns directly with the PR's core objective of capturing and surfacing agent identity alongside session data.
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.

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

Signed-off-by: flamerged <34665379+flamerged@users.noreply.github.com>
Copy link
Copy Markdown

@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.

Actionable comments posted: 2

🤖 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.

Inline comments:
In `@src/functions/session-metadata.ts`:
- Around line 17-20: The helper asRecord currently treats null like undefined
which suppresses the "must be an object when provided" validation for
metadata/agent; change asRecord so it returns undefined only for undefined and
returns null for an explicit null input (i.e., separate the checks: if value ===
undefined return undefined; if value === null return null) so callers
(validation around metadata and agent) can detect explicit null and emit the
intended errors.

In `@src/triggers/events.ts`:
- Around line 12-19: The code stores data.metadata and data.agent directly which
skips the normalization and secret-redaction logic used by api::session::start;
update the event handler in events.ts to run the same normalization/redaction
routine used by api::session::start on data.metadata and data.agent before
persisting them (i.e., import and call the session start normalization/redaction
helper or extract that logic into a shared helper and use it here) so that
metadata and agent values are normalized and secrets are redacted consistently
when sessions are created via events.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 44c5e84a-d3d3-4132-be4a-4f000ba940e5

📥 Commits

Reviewing files that changed from the base of the PR and between 292e9f6 and ed2bd51.

📒 Files selected for processing (9)
  • README.md
  • plugin/scripts/session-start.mjs
  • src/functions/session-metadata.ts
  • src/hooks/session-start.ts
  • src/triggers/api.ts
  • src/triggers/events.ts
  • src/types.ts
  • test/context-injection.test.ts
  • test/session-metadata.test.ts

Comment thread src/functions/session-metadata.ts
Comment thread src/triggers/events.ts
Copy link
Copy Markdown

@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.

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@src/viewer/index.html`:
- Around line 1091-1097: The sessionAgentLabel function only reads
agent.agentType and agent.sessionSource; update identity extraction logic (in
sessionAgentLabel and the related sessionAgent function) to also check for
alternative keys role and agent_type for agent type and source and source for
sessionSource (e.g., prefer agent.agentType || agent.role || agent.agent_type
and agent.sessionSource || agent.source) so role/source and agent_type/source
appear in the parts array and render as badges/panel fields.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ffc1f8c3-00c0-4a8b-a091-359fe7b634a7

📥 Commits

Reviewing files that changed from the base of the PR and between ed2bd51 and 8130764.

📒 Files selected for processing (1)
  • src/viewer/index.html

Comment thread src/viewer/index.html
@flamerged flamerged marked this pull request as draft May 12, 2026 17:55
Signed-off-by: flamerged <34665379+flamerged@users.noreply.github.com>
@flamerged flamerged marked this pull request as ready for review May 12, 2026 18:51
Copy link
Copy Markdown

@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.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/functions/search.ts (1)

128-133: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid failing the entire search when session lookup rejects

loadSession() currently lets kv.get() rejections bubble, and Promise.all on session enrichment can fail the whole request. This should degrade to null session attribution instead.

Suggested patch
       const loadSession = async (sessionId: string): Promise<Session | null> => {
         if (sessionCache.has(sessionId)) return sessionCache.get(sessionId)!
-        const s = await kv.get<Session>(KV.sessions, sessionId)
+        const s = await kv.get<Session>(KV.sessions, sessionId).catch(() => null)
         sessionCache.set(sessionId, s ?? null)
         return s ?? null
       }

Also applies to: 164-166

🤖 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/search.ts` around lines 128 - 133, The session lookup currently
lets kv.get(...) rejections bubble through loadSession and can cause the
surrounding Promise.all (session enrichment) to reject; update loadSession to
catch any errors from kv.get and treat failures as a missing session by
logging/ignoring the error, setting sessionCache.set(sessionId, null), and
returning null so enrichment degrades gracefully; apply the same defensive
try/catch pattern wherever kv.get is used for session reads (the other instance
around lines 164-166) so those calls also return null on error instead of
throwing.
test/search.test.ts (1)

11-51: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Adopt the required iii-sdk mock pattern instead of custom local SDK/KV mocks.

This test currently uses bespoke mockSdk()/mockKV() helpers, which diverges from the repository’s required test harness pattern. Please switch to vi.mock("iii-sdk") and provide the expected mocked sdk.trigger and kv.get/set/list there, matching the established test style.

As per coding guidelines, test/**/*.test.ts must “use vi.mock("iii-sdk") with mock sdk.trigger, kv.get/set/list” and “follow existing patterns from test/crystallize.test.ts.”

🤖 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 `@test/search.test.ts` around lines 11 - 51, Replace the local mock helpers
mockKV() and mockSdk() with the repository-standard vi.mock("iii-sdk") pattern:
remove mockKV and mockSdk, add vi.mock("iii-sdk") at the top of the test, and in
its factory return an object with sdk.trigger implemented (to dispatch to your
registered handlers) and kv.get, kv.set, kv.list, kv.delete implementations that
mirror the behavior currently in mockKV; follow the same mock shapes and call
signatures used in test/crystallize.test.ts so existing tests using sdk.trigger
and kv.get/set/list continue to work.
🤖 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.

Inline comments:
In `@src/functions/session-attribution.ts`:
- Around line 46-47: sessionAttributionLabel currently omits role when client is
absent; change the logic that builds the parts array so that when client is
present you push `${client}/${role}` (if role exists) and when client is missing
but role exists you push just `role`; update the block around parts.push in
sessionAttributionLabel to conditionally push client, client+role, or role so
role-only sessions get preserved.

---

Outside diff comments:
In `@src/functions/search.ts`:
- Around line 128-133: The session lookup currently lets kv.get(...) rejections
bubble through loadSession and can cause the surrounding Promise.all (session
enrichment) to reject; update loadSession to catch any errors from kv.get and
treat failures as a missing session by logging/ignoring the error, setting
sessionCache.set(sessionId, null), and returning null so enrichment degrades
gracefully; apply the same defensive try/catch pattern wherever kv.get is used
for session reads (the other instance around lines 164-166) so those calls also
return null on error instead of throwing.

In `@test/search.test.ts`:
- Around line 11-51: Replace the local mock helpers mockKV() and mockSdk() with
the repository-standard vi.mock("iii-sdk") pattern: remove mockKV and mockSdk,
add vi.mock("iii-sdk") at the top of the test, and in its factory return an
object with sdk.trigger implemented (to dispatch to your registered handlers)
and kv.get, kv.set, kv.list, kv.delete implementations that mirror the behavior
currently in mockKV; follow the same mock shapes and call signatures used in
test/crystallize.test.ts so existing tests using sdk.trigger and kv.get/set/list
continue to work.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9ab024ec-5a6c-466f-a5fd-f8b3fc0930c0

📥 Commits

Reviewing files that changed from the base of the PR and between 8130764 and 27b49f3.

📒 Files selected for processing (13)
  • README.md
  • src/functions/context.ts
  • src/functions/search.ts
  • src/functions/session-attribution.ts
  • src/functions/session-metadata.ts
  • src/functions/smart-search.ts
  • src/triggers/events.ts
  • src/types.ts
  • src/viewer/index.html
  • test/context-slots.test.ts
  • test/search.test.ts
  • test/session-metadata.test.ts
  • test/smart-search.test.ts
✅ Files skipped from review due to trivial changes (1)
  • README.md
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/session-metadata.test.ts
  • src/functions/session-metadata.ts
  • src/triggers/events.ts

Comment thread src/functions/session-attribution.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