Skip to content

feat(cli): expose memory commands to cli from sdk - #155

Merged
murdore merged 1 commit into
juspay:releasefrom
punyamsingh:feature/expose-memory-tool-sdk-to-cli
Sep 9, 2025
Merged

murdore merged 1 commit into
juspay:releasefrom
punyamsingh:feature/expose-memory-tool-sdk-to-cli

Conversation

@punyamsingh

@punyamsingh punyamsingh commented Sep 8, 2025 •

Copy link
Copy Markdown
Member

Pull Request

Description

Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📚 Documentation update
  • 🧹 Code refactoring (no functional changes)
  • ⚡ Performance improvement
  • 🧪 Test coverage improvement
  • 🔧 Build/CI configuration change

Related Issues

  • Fixes #
  • Related to #

Changes Made

  • added support to expose commands regarding conversation memory in cli

AI Provider Impact

  • OpenAI
  • Anthropic
  • Google AI/Vertex
  • AWS Bedrock
  • Azure OpenAI
  • Hugging Face
  • Ollama
  • Mistral
  • All providers
  • No provider-specific changes

Component Impact

  • CLI
  • SDK
  • MCP Integration
  • Streaming
  • Tool Calling
  • Configuration
  • Documentation
  • Tests

Testing

  • Unit tests added/updated
  • Integration tests added/updated
  • E2E tests added/updated
  • Manual testing performed
  • All existing tests pass

Test Environment

  • OS:
  • Node.js version:
  • Package manager:

Performance Impact

  • No performance impact
  • Performance improvement
  • Minor performance impact (acceptable)
  • Significant performance impact (needs discussion)

Breaking Changes

not a breaking change

Screenshots/Demo

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • [] I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published

Additional Notes

Summary by CodeRabbit

  • New Features

    • Added “memory” CLI commands: stats, history , clear [sessionId] with multi-format output (JSON/text/table), --dry-run, quiet mode, and colorized UX.
    • Bash completion support for memory commands and subcommands.
  • Documentation

    • Added comprehensive docs and examples for the memory CLI and a reusable CLI-SDK command pattern.
    • Documented prior “Interactive Loop Mode” with session management, memory integration, and loop commands.

@coderabbitai

coderabbitai Bot commented Sep 8, 2025 •

Copy link
Copy Markdown

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Adds a new CLI "memory" command group (stats, history , clear [sessionId]) via a factory method and parser registration, documents the memory-CLI exposure and prior interactive loop mode, updates bash completion, and adjusts several type-only import paths. Notes duplicate insertions of memory handlers in commandFactory.ts.

Changes

Cohort / File(s) Summary
Docs: Memory CLI + Loop Status
memory-bank/activeContext.md, memory-bank/progress.md
Adds documentation blocks describing the Memory CLI commands and the prior Interactive Loop Mode completion, with usage, architecture notes, and file references.
CLI Factory: Memory Commands
src/cli/factories/commandFactory.ts
Adds createMemoryCommands() and three executors (executeMemoryStats, executeMemoryHistory, executeMemoryClear) with dry-run, multi-format output, error handling, and bash completion updates. Duplicate insertions of the memory factory and completion branches are present. Also adjusts a type import path.
CLI Parser Registration
src/cli/parser.ts
Registers the memory command group by calling CLICommandFactory.createMemoryCommands() in initializeCliParser() and replaces console.error with logger.error in yargs fail handler; adds logger import.
Loop Session: Type Import Update
src/cli/loop/session.ts
Adjusts type-only import path for ConversationMemoryConfig to ../../lib/types/conversation.js (no runtime change).
Global Session: Type Import Update
src/lib/session/globalSessionState.ts
Adjusts type import path for ConversationMemoryConfig to ../types/conversation.js (no runtime change).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant CLI as neurolink (yargs)
  participant CF as CLICommandFactory
  participant GS as globalSession
  participant SDK as NeuroLink SDK

  U->>CLI: neurolink memory [stats|history|clear] [args] [--dry-run] [--format]
  CLI->>CF: invoke memory handler
  CF->>CF: processOptions(args)
  alt Dry-run
    CF-->>U: mock result (json/text) via handleOutput
  else Real execution
    CF->>GS: getOrCreateNeuroLink()
    GS-->>CF: sdk instance
    alt stats
      CF->>SDK: getConversationStats()
      SDK-->>CF: stats
    else history
      CF->>SDK: getConversationHistory(sessionId)
      SDK-->>CF: history[]
    else clear
      CF->>SDK: clearAllConversations()/clearConversationSession(sessionId)
      SDK-->>CF: result
    end
    CF-->>U: formatted output (json/text/table)
  end
  note over CLI,CF: Bash completion suggests memory subcommands (stats, history, clear)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • murdore

Poem

I burrow through flags with a twitch of my nose,
Stats, history, clear—how the memory grows!
In dry-run meadows I safely hop,
JSON or tables, I neatly drop.
Bash crumbs guide my tiny trail—hooray, the CLI won't fail! 🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

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

Actionable comments posted: 1

🧹 Nitpick comments (6)
memory-bank/activeContext.md (1)

25-46: Unify “CURRENT STATUS” sections and fix chronology

You now have three “CURRENT STATUS” headers with different dates. Demote this block to “PREVIOUS STATUS” (date 2025-09-06) or mark it “Recent Update” to avoid conflicting “current” labels with the 2025-09-07 Redis section and the earlier loop section.

-## 🚀 **CURRENT STATUS: MEMORY CLI COMMANDS IMPLEMENTED** (2025-09-06)
+## 🚀 **PREVIOUS STATUS: MEMORY CLI COMMANDS IMPLEMENTED** (2025-09-06)

Also consider removing or demoting the earlier “CURRENT STATUS: INTERACTIVE LOOP MODE IMPLEMENTED” above for consistency.

src/cli/factories/commandFactory.ts (3)

1821-1880: Honor --format table for stats output

When users pass --format table, stats currently render as text. Support table by mapping the object to rows; also handle dry-run the same way for consistency.

   if (options.dryRun) {
-    const mockStats = {
+    const mockStats = {
       totalSessions: 5,
       totalTurns: 47,
       memoryUsage: "Active",
     };
-    if (spinner) {
+    if (spinner) {
       spinner.succeed(chalk.green("✅ Memory stats retrieved (dry-run)"));
     }
-    this.handleOutput(mockStats, options);
+    if (options.format === "table") {
+      const rows = [
+        { metric: "Total Sessions", value: mockStats.totalSessions },
+        { metric: "Total Turns", value: mockStats.totalTurns },
+        { metric: "Memory Status", value: mockStats.memoryUsage },
+      ];
+      this.handleOutput(rows, options);
+    } else {
+      this.handleOutput(mockStats, options);
+    }
     return;
   }
@@
-  if (options.format === "json") {
+  if (options.format === "json") {
     this.handleOutput(stats, options);
+  } else if (options.format === "table") {
+    const rows = [
+      { metric: "Total Sessions", value: stats.totalSessions },
+      { metric: "Total Turns", value: stats.totalTurns },
+      {
+        metric: "Memory Status",
+        value: stats.totalSessions > 0 ? "Active" : "Empty",
+      },
+    ];
+    this.handleOutput(rows, options);
   } else {
     logger.always(chalk.blue("📊 Conversation Memory Stats:"));
     logger.always(`   Total Sessions: ${stats.totalSessions}`);
     logger.always(`   Total Turns: ${stats.totalTurns}`);
     logger.always(
       `   Memory Status: ${stats.totalSessions > 0 ? "Active" : "Empty"}`,
     );
   }

1881-1963: Honor --format table for history output

For non-JSON, you always pretty-print text; users requesting --format table won’t get a table. Delegate to handleOutput when table is requested.

-  if (options.format === "json") {
+  if (options.format === "json") {
     this.handleOutput(history, options);
+  } else if (options.format === "table") {
+    const rows = history.map((m, i) => ({
+      index: i + 1,
+      role: m.role,
+      content: m.content,
+    }));
+    this.handleOutput(rows, options);
   } else {
     logger.always(
       chalk.blue(`💬 Conversation History (${argv.sessionId}):`),
     );
     for (const message of history) {
       const roleColor = message.role === "user" ? chalk.cyan : chalk.green;
       const roleLabel = message.role === "user" ? "User" : "Assistant";
       logger.always(`   [${roleColor(roleLabel)}]: ${message.content}`);
     }
   }

2086-2153: Completion: include memory in the “Available commands” footer

You added memory to top-level opts and its branch. The footer echo still omits memory; add it for consistency.

-echo "Available commands: generate, stream, batch, provider, status, models, mcp, discover, config, get-best-provider, completion"
+echo "Available commands: generate (gen), stream, batch, provider, status, models, mcp, discover, memory, config, get-best-provider, completion"
memory-bank/progress.md (2)

32-33: Clarify required vs optional args for subcommands.

Bracket notation shows clear [sessionId] but history <sessionId>. If history can default to the active session, note it; if not, add “(required)” to avoid ambiguity.


34-35: Document default output format and include a short JSON sample.

State the default (e.g., text) and add a minimal JSON example for stats to set expectations.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89b5012 and 47eb638.

📒 Files selected for processing (4)
  • memory-bank/activeContext.md (1 hunks)
  • memory-bank/progress.md (1 hunks)
  • src/cli/factories/commandFactory.ts (4 hunks)
  • src/cli/parser.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/cli/factories/commandFactory.ts (4)
src/lib/types/cli.ts (1)
  • BaseCommandArgs (13-24)
src/lib/session/globalSessionState.ts (1)
  • globalSession (110-110)
src/lib/utils/logger.ts (2)
  • logger (341-380)
  • error (223-225)
src/cli/errorHandler.ts (1)
  • handleError (11-69)
🔇 Additional comments (6)
src/cli/factories/commandFactory.ts (3)

633-704: Nice addition: coherent memory command group

Command structure and examples are clear. No blockers.


1965-2061: Behavior LGTM; JSON shape is stable and messages are clear

Clear all vs single-session handling, and dry-run shape look good.


1821-2061: SDK surface verification passed

All required NeuroLink SDK methods (getConversationStats, getConversationHistory, clearConversationSession, clearAllConversations) are implemented and exported—no further action needed.

src/cli/parser.ts (1)

172-174: Good integration point

Memory command group is registered in a sensible spot. Help/strict parsing will surface it correctly.

memory-bank/progress.md (2)

49-56: Enforce explicit confirmation for memory clear
neurolink memory clear currently wipes all sessions with no safeguard. Require --all (and optionally --force or an interactive confirmation) for destructive actions. Update docs accordingly:

-# Clear conversation history (all or specific session)
-neurolink memory clear                    # Clear all sessions
-neurolink memory clear session-123       # Clear specific session
+# Clear conversation history (all or specific session)
+# Destructive: requires explicit confirmation or flags
+neurolink memory clear --all [--force]    # Clear all sessions
+neurolink memory clear session-123        # Clear specific session

File: memory-bank/progress.md
Verify that the implementation supports these flags or add the necessary yargs options/confirmation prompt.


36-36: Ensure bash completion for memory commands
Single registration of createMemoryCommands at src/cli/parser.ts:173; no .completion() invocation detected—verify your completion script or parser wiring includes the memory subcommands (stats, history, clear) and there are no duplicate registrations.

Comment thread memory-bank/progress.md
@punyamsingh

Copy link
Copy Markdown
Member Author

@coderabbitai help

@coderabbitai

coderabbitai Bot commented Sep 8, 2025

Copy link
Copy Markdown

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

CodeRabbit commands

These commands are invoked using PR/Issue comments.

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve to resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit configuration file (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, support, documentation and community

  • Visit our status page to check the current availability of CodeRabbit.
  • Create a ticket on our support page for assistance with any issues or questions.
  • Visit our documentation site for detailed information on how to use CodeRabbit.
  • Join our Discord community to connect with other users and get help from the community.
  • Follow us on X/Twitter for updates and announcements.

@punyamsingh

Copy link
Copy Markdown
Member Author

please don't merge, fixing a build issue

@punyamsingh
punyamsingh force-pushed the feature/expose-memory-tool-sdk-to-cli branch from 47eb638 to be61b74 Compare September 8, 2025 13:35
@punyamsingh

Copy link
Copy Markdown
Member Author

this is ready to merge, build shouldn't fail now

@punyamsingh
punyamsingh force-pushed the feature/expose-memory-tool-sdk-to-cli branch from be61b74 to 3166bfd Compare September 8, 2025 17:33
@punyamsingh

Copy link
Copy Markdown
Member Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Sep 8, 2025

Copy link
Copy Markdown
✅ Actions performed

Full review triggered.

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

Actionable comments posted: 2

Caution

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

⚠️ Outside diff range comments (2)
src/cli/factories/commandFactory.ts (2)

186-191: Expose dry-run as --dry-run (keep --dryRun as alias).

Current code defines only dryRun. Users expect kebab-case. Accept both to avoid breaking changes and update completion opts.

-    dryRun: {
+    dryRun: {
       type: "boolean" as const,
       default: false,
-      description: "Test command without making actual API calls (for testing)",
-    },
+      description: "Test command without making actual API calls (for testing)",
+      alias: "dry-run",
+    },

Also update completion options below (see separate comment).


2086-2109: Completion: include both --dry-run and --dryRun.

Also aligns with doc fixes.

-                    'opts="--provider --model --temperature --maxTokens --system --format --output --timeout --delay --disableTools --enableAnalytics --enableEvaluation --debug --quiet --noColor --configFile --dryRun"'
+                    'opts="--provider --model --temperature --maxTokens --system --format --output --timeout --delay --disableTools --enableAnalytics --enableEvaluation --debug --quiet --noColor --configFile --dry-run --dryRun"'
♻️ Duplicate comments (1)
memory-bank/progress.md (1)

35-36: Standardize dry-run flag to kebab-case.

Replace --dryRun with --dry-run in bullets and examples. Also update the completion script and yargs option alias so both forms work.

- - ✅ **Dry-Run Integration**: All commands support `--dryRun` for safe testing
+ - ✅ **Dry-Run Integration**: All commands support `--dry-run` for safe testing
@@
-neurolink memory stats --dry-run
-neurolink memory clear --dry-run
+neurolink memory stats --dry-run
+neurolink memory clear --dry-run

Also applies to: 54-56

🧹 Nitpick comments (4)
memory-bank/activeContext.md (1)

24-47: Duplicate “CURRENT STATUS” headings — demote the older one.

Two adjacent “CURRENT STATUS” sections (Loop Mode and Memory CLI) are confusing. Make the Loop Mode one “PREVIOUS STATUS” to match the block already added below.

Apply:

-## 🚀 **CURRENT STATUS: INTERACTIVE LOOP MODE IMPLEMENTED** (2025-09-06)
+## 🚀 **PREVIOUS STATUS: INTERACTIVE LOOP MODE IMPLEMENTED** (2025-09-06)
src/cli/factories/commandFactory.ts (3)

274-275: Remove unsupported 'yaml' from the format union or add real support.

commonOptions.format permits only text/json/table, but processOptions types include "yaml". Drop it to avoid misleading types.

-      format: argv.format as "text" | "json" | "table" | "yaml" | undefined,
+      format: argv.format as "text" | "json" | "table" | undefined,

633-703: Scope memory command options to essentials.

Using buildOptions(y) exposes generation-only flags (provider, model, temperature) on memory commands. Limit to generic flags (format/output/debug/quiet/noColor/configFile/dry-run) for cleaner UX.

If you want, I can send a small patch introducing buildBasicOptions() and switch these three subcommands to it.


2181-2183: Completion: update final “Available commands” list.

Add the newly supported commands so users see them on load.

-'echo "Available commands: generate, stream, batch, provider, status, models, mcp, discover, config, get-best-provider, completion"';
+'echo "Available commands: generate, stream, batch, provider, status, models, mcp, discover, memory, config, get-best-provider, completion, ollama, sagemaker, loop"';
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89b5012 and 3166bfd.

📒 Files selected for processing (6)
  • memory-bank/activeContext.md (1 hunks)
  • memory-bank/progress.md (1 hunks)
  • src/cli/factories/commandFactory.ts (5 hunks)
  • src/cli/loop/session.ts (1 hunks)
  • src/cli/parser.ts (3 hunks)
  • src/lib/session/globalSessionState.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: test (18)
src/cli/factories/commandFactory.ts

[warning] 2007-2007:
Forbidden non-null assertion

🪛 GitHub Check: test (20)
src/cli/factories/commandFactory.ts

[warning] 2007-2007:
Forbidden non-null assertion

🪛 GitHub Actions: CI
src/cli/factories/commandFactory.ts

[warning] 1349-1349: Promise without error handling


[warning] 1454-1454: Promise without error handling


[warning] 1506-1506: Promise without error handling


[warning] 1732-1732: Promise without error handling

🔇 Additional comments (4)
src/cli/loop/session.ts (1)

6-6: Approve type-only import path change
No lingering types/conversationTypes.js imports found; types/conversation.js is referenced in 16 places.

src/lib/session/globalSessionState.ts (1)

3-3: LGTM on type import path update.

Matches the new types/conversation.js convention and is type-only.

src/cli/parser.ts (2)

8-8: Good move to use the shared logger.
Switching from console.error to logger.error makes CLI output consistent.


173-175: Memory command group registration looks correct.

Factory method is added in the right spot and won’t interfere with existing commands.

Comment thread memory-bank/activeContext.md
Comment thread src/cli/factories/commandFactory.ts
- added commands to expose commands regarding conversation memory in cli
@punyamsingh
punyamsingh force-pushed the feature/expose-memory-tool-sdk-to-cli branch from 3166bfd to b428fb3 Compare September 9, 2025 07:13
@murdore
murdore merged commit b9eb802 into juspay:release Sep 9, 2025
7 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