Skip to content

refactor(plugin): optimize plugin entry, config, and supporting services#15

Merged
ZeR020 merged 3 commits into
mainfrom
refactor/plugin-entry-config-optimization
May 7, 2026
Merged

refactor(plugin): optimize plugin entry, config, and supporting services#15
ZeR020 merged 3 commits into
mainfrom
refactor/plugin-entry-config-optimization

Conversation

@ZeR020

@ZeR020 ZeR020 commented May 7, 2026

Copy link
Copy Markdown
Owner

Summary

Optimization pass over plugin entry point (index.ts), configuration (config.ts), auto-capture, user memory learning, user prompt manager, and web server modules.

Changes

src/services/auto-capture.ts

  • Extract shared AUTO_CAPTURE_SYSTEM_PROMPT_TEMPLATE and AUTO_CAPTURE_ANALYSIS_PROMPT constants to eliminate ~100 lines of duplicated prompt text between the opencode provider path and the manual API provider path

src/services/user-memory-learning.ts

  • Extract shared USER_PROFILE_SYSTEM_PROMPT constant to eliminate ~10 lines of duplicated prompt text between the two provider paths

src/services/user-prompt/user-prompt-manager.ts

  • Cache 20 prepared statements in constructor for all hot-path queries (save, get last uncaptured, delete, mark captured, claim, reset claim, count uncaptured, get uncaptured, count unanalyzed, get for user learning, mark user learning, get linked memory IDs, delete old, link memory, get by ID, get captured, search prompts)
  • Add fast paths for single-item batch operations to use cached single-item statements instead of dynamic SQL

src/services/web-server.ts

  • Move localHosts Set to module-level LOCAL_HOSTS constant to avoid recreating on every HTTP request
  • Move sensitive keys array to module-level SENSITIVE_KEYS Set for O(1) PII redaction lookups instead of O(n) Array#includes

src/index.ts

  • Optimize formatMemoriesForCompaction to use array join() instead of repeated string concatenation in a loop
  • Remove redundant language interpolation from help command descriptions (reduces per-call string allocations)

Verification

  • Typecheck: ✅ clean
  • Tests: same pass/fail profile as main (39 pass, 20 fail — pre-existing failures unrelated to these changes)

Summary by CodeRabbit

  • Refactor

    • Simplified how help text and prompts are assembled to make memory search descriptions clearer and session restoration more consistent.
    • Improved background handling of user-profile and capture prompts and optimized prompt/query preparation for faster, more reliable operations.
    • Centralized local-access detection and privacy handling on the server.
  • Bug Fixes

    • Improved redaction of sensitive personal information in responses.

- Extract shared system prompt templates in auto-capture.ts and user-memory-learning.ts
  to eliminate 200+ line duplication between opencode and manual provider paths
- Cache 20 prepared statements in UserPromptManager constructor for all hot-path queries
  (save, get, delete, mark captured, claim, user learning, cleanup, search, link)
- Use module-level LOCAL_HOSTS Set and SENSITIVE_KEYS Set in web-server.ts
  to avoid recreating on every request
- Optimize formatMemoriesForCompaction to use array join instead of string concatenation
- Add fast paths for single-item batch operations in user-prompt-manager
Copilot AI review requested due to automatic review settings May 7, 2026 11:47
@ZeR020

ZeR020 commented May 7, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown
✅ Actions performed

Full review triggered.

@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR extracts prompt-template helpers, centralizes web-server loopback/PII constants, precompiles SQL statements in UserPromptManager and updates its methods to use them, and makes minor index help-text and memory-formatting refactors.

Changes

Code Refactoring and Optimization

Layer / File(s) Summary
Prompt Template Extraction
src/services/auto-capture.ts, src/services/user-memory-learning.ts
New reusable prompt template functions (AUTO_CAPTURE_SYSTEM_PROMPT_TEMPLATE, AUTO_CAPTURE_ANALYSIS_PROMPT, USER_PROFILE_SYSTEM_PROMPT) are introduced to parameterize system prompts and avoid inline duplication.
Web Server Constants
src/services/web-server.ts
LOCAL_HOSTS and SENSITIVE_KEYS sets are defined for consistent loopback detection and PII redaction key checking; redactPII and request-locality/auth logic now use them.
Database Prepared Statements Setup
src/services/user-prompt/user-prompt-manager.ts
Adds escapeLikePattern, a typed this.stmts map, and initializes all prepared statements in the constructor for reuse.
Auto-Capture Template Integration
src/services/auto-capture.ts
generateSummary and provider execution paths now call the extracted auto-capture prompt helpers and pass prompts as separate arguments.
User Learning Template Integration
src/services/user-memory-learning.ts
Structured-output and external provider paths now call USER_PROFILE_SYSTEM_PROMPT(!!existingProfile) instead of building inline system prompt strings.
DB Method Usage Updates
src/services/user-prompt/user-prompt-manager.ts
All DB methods (save, fetch, delete, update, count, batch operations, search, link) now execute precompiled statements from this.stmts and preserve prior empty-list/single-id behaviors.
Help Text and Formatting
src/index.ts
tool.memory help "search" description simplified to Search memories via keywords (MATCH USER LANGUAGE: ... ); formatMemoriesForCompaction refactored to accumulate sections in an array and join with newlines.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • ZeR020/opencode-mem0#9: Overlapping edits touching the same modules (index, auto-capture, user-memory-learning, user-prompt manager, web-server), suggesting related refactor work.

Poem

🐰 I stitched prompts into tidy strings,

Prepared the SQL that softly sings,
Constants gathered, neat and small,
The code hops lighter — one and all,
A little carrot for the reviewers' rings.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

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.
Description check ❓ Inconclusive The description includes a detailed summary, organized changes per file, and verification results, though it does not follow the provided template structure with Type of Change checkboxes, Testing section, or Related Issues. Align the description format with the repository template by adding Type of Change section, explicit Testing details, and Related Issues/Fixes reference for consistency.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main optimization focus across multiple services (plugin entry, config, supporting services) and accurately reflects the changeset.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/plugin-entry-config-optimization

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 (1)
src/services/user-prompt/user-prompt-manager.ts (1)

83-83: ⚡ Quick win

Three prepared statements duplicate already-declared ones — reuse the existing statements.

The refactor introduces three unnecessary duplicate prepared statements:

New (duplicate) Identical to
markMultipleCaptured (line 83) markCaptured (line 67)
markMultipleUserLearning (lines 96-98) markUserLearningCaptured (lines 93-95)
getByIds (line 118) getById (line 105)

Each is only ever used in the single-item fast paths of markMultipleAsCaptured, markMultipleAsUserLearningCaptured, and getPromptsByIds. Removing the duplicates and pointing the fast paths at the already-existing statements reduces both the stmts surface area and the number of prepared statement handles held against the DB connection.

♻️ Proposed fix

Remove the three duplicate declarations from the stmts type and initializer:

-    markMultipleCaptured: ReturnType<DatabaseType["prepare"]>;
     markMultipleUserLearning: ReturnType<DatabaseType["prepare"]>;
     ...
-    getByIds: ReturnType<DatabaseType["prepare"]>;
-      markMultipleCaptured: this.db.prepare(`UPDATE user_prompts SET captured = 1 WHERE id = ?`),
       ...
-      markMultipleUserLearning: this.db.prepare(
-        `UPDATE user_prompts SET user_learning_captured = 1 WHERE id = ?`
-      ),
       ...
-      getByIds: this.db.prepare(`SELECT * FROM user_prompts WHERE id = ?`),

Then update the three fast-path call sites:

 // markMultipleAsCaptured
-      this.stmts.markMultipleCaptured.run(promptIds[0]);
+      this.stmts.markCaptured.run(promptIds[0]);

 // markMultipleAsUserLearningCaptured
-      this.stmts.markMultipleUserLearning.run(promptIds[0]);
+      this.stmts.markUserLearningCaptured.run(promptIds[0]);

 // getPromptsByIds
-      const row = this.stmts.getByIds.get(ids[0]) as any;
+      const row = this.stmts.getById.get(ids[0]) as any;

Also applies to: 96-98, 118-118

🤖 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/services/user-prompt/user-prompt-manager.ts` at line 83, Remove the three
duplicate prepared-statement declarations and reuse the existing ones: delete
the stmts entries markMultipleCaptured, markMultipleUserLearning, and getByIds
and stop initializing them; then update the fast-path call sites in
markMultipleAsCaptured to call the existing markCaptured statement, in
markMultipleAsUserLearningCaptured to call markUserLearningCaptured, and in
getPromptsByIds to call getById for the single-id fast path so the code uses the
already-declared prepared statements instead of creating duplicates.
🤖 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/services/user-prompt/user-prompt-manager.ts`:
- Around line 264-271: The searchPrompts method builds a LIKE pattern without
escaping user-supplied metacharacters, so queries with % or _ behave as
wildcards; modify searchPrompts to escape backslashes, % and _ in the query
(e.g. replace \ with \\ then % with \% and _ with \_) before surrounding with
%...% and passing to the statements, and update the prepared SQL for
stmts.searchPrompts and stmts.searchPromptsByProject to include "ESCAPE '\\'" so
the DB treats the backslash as the escape character; keep mapping via
rowToPrompt unchanged.

---

Nitpick comments:
In `@src/services/user-prompt/user-prompt-manager.ts`:
- Line 83: Remove the three duplicate prepared-statement declarations and reuse
the existing ones: delete the stmts entries markMultipleCaptured,
markMultipleUserLearning, and getByIds and stop initializing them; then update
the fast-path call sites in markMultipleAsCaptured to call the existing
markCaptured statement, in markMultipleAsUserLearningCaptured to call
markUserLearningCaptured, and in getPromptsByIds to call getById for the
single-id fast path so the code uses the already-declared prepared statements
instead of creating duplicates.
🪄 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 Plus

Run ID: 0e431ef0-b27c-4803-89be-3460027ec2c1

📥 Commits

Reviewing files that changed from the base of the PR and between 6e35f4e and 0ae41bd.

📒 Files selected for processing (5)
  • src/index.ts
  • src/services/auto-capture.ts
  • src/services/user-memory-learning.ts
  • src/services/user-prompt/user-prompt-manager.ts
  • src/services/web-server.ts

Comment thread src/services/user-prompt/user-prompt-manager.ts

Copilot AI 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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

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

🧹 Nitpick comments (1)
src/services/user-prompt/user-prompt-manager.ts (1)

239-245: ⚡ Quick win

Make linked-ID collection and deletion atomic.

These two statements can observe different row sets, so linkedMemoryIds can drift from deleted if matching prompts are modified between the select and delete. Wrapping them in one transaction would keep the returned IDs consistent with the rows actually removed.

🤖 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/services/user-prompt/user-prompt-manager.ts` around lines 239 - 245, The
select and delete in deleteOldPrompts currently run separately and can see
different row sets; wrap both this.stmts.getLinkedMemoryIds.all(cutoffTime) and
this.stmts.deleteOldPrompts.run(cutoffTime) inside a single database transaction
so the select and delete observe the same snapshot, capture the linkedMemoryIds
from the select and the result.changes from the delete within that transaction,
and return those values; ensure the transaction helper for your DB (e.g.,
db.transaction or similar) is used so failures rollback and errors are rethrown.
🤖 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/services/user-prompt/user-prompt-manager.ts`:
- Around line 239-245: The select and delete in deleteOldPrompts currently run
separately and can see different row sets; wrap both
this.stmts.getLinkedMemoryIds.all(cutoffTime) and
this.stmts.deleteOldPrompts.run(cutoffTime) inside a single database transaction
so the select and delete observe the same snapshot, capture the linkedMemoryIds
from the select and the result.changes from the delete within that transaction,
and return those values; ensure the transaction helper for your DB (e.g.,
db.transaction or similar) is used so failures rollback and errors are rethrown.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: e790b45a-45f3-412f-b6a1-fbb7c70dd72b

📥 Commits

Reviewing files that changed from the base of the PR and between 3a24813 and 15e7dde.

📒 Files selected for processing (1)
  • src/services/user-prompt/user-prompt-manager.ts

@ZeR020
ZeR020 merged commit a89b059 into main May 7, 2026
5 checks passed
@ZeR020
ZeR020 deleted the refactor/plugin-entry-config-optimization branch May 7, 2026 12:48
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