Skip to content

refactor(api): optimize api-handlers.ts and client.ts#11

Merged
ZeR020 merged 6 commits into
mainfrom
refactor/api-handlers-optimization
May 7, 2026
Merged

refactor(api): optimize api-handlers.ts and client.ts#11
ZeR020 merged 6 commits into
mainfrom
refactor/api-handlers-optimization

Conversation

@ZeR020

@ZeR020 ZeR020 commented May 7, 2026

Copy link
Copy Markdown
Owner

Changes

  • Centralized safe transforms: Extracted safeToISOString() and safeJSONParse() from both api-handlers.ts and client.ts into src/services/utils/safe-transforms.ts — eliminates 60+ lines of duplication
  • Optimized tag lookup: getProjectPathFromTag() now uses extractScopeFromTag() to scope shard search instead of iterating all project shards
  • Fixed mutable migration state: Replaced module-level let migrationProgress with MigrationProgressTracker class — proper encapsulation, thread-safety, JSON serialization

Impact

  • -80 lines across api-handlers.ts and client.ts (net reduction after adding utils module)
  • Eliminates code duplication between two core modules
  • Improves shard lookup efficiency for project path resolution
  • Fixes shared mutable state in migration progress tracking

Testing

  • TypeScript compilation: clean
  • All 173 tests pass

Requesting @coderabbitai full review for additional optimization opportunities in this module and across the codebase.

Summary by CodeRabbit

  • Refactor

    • Centralized safer data-handling utilities to improve robustness of memory listing, search backfill, and deletion flows.
    • Improved tag routing and migration progress tracking with structured progress reporting.
    • Safer parsing and timestamp formatting of stored metadata to reduce runtime errors.
  • Chores

    • Added and tuned repository review automation, linting and check settings; enabled automated draft reviews and auto-replies, and adjusted integrations and timeouts for review tooling.

Copilot AI review requested due to automatic review settings May 7, 2026 11:30
@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown

Review Change Stack
No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 11ab5dfc-bef6-4891-aac3-f8ef69efd3fa

📥 Commits

Reviewing files that changed from the base of the PR and between 3c95d0b and 39dab05.

📒 Files selected for processing (1)
  • src/services/utils/safe-transforms.ts

📝 Walkthrough

Walkthrough

Adds shared safe-transform helpers, replaces local helpers with imports in client and API handlers, applies safe JSON parsing across memory list/search/delete/backfill flows, updates tag-to-shard selection, refactors migration progress into a class, and adds .coderabbit.yaml review configuration.

Changes

Safe Transformation Utilities and Refactoring

Layer / File(s) Summary
Shared Safe Transformation Utilities
src/services/utils/safe-transforms.ts
Exports safeToISOString (converts unknown timestamp with fallback to current time) and safeJSONParse (safely parses JSON, returns undefined on failure).
Client Utility Consolidation
src/services/client.ts
Removes local safeToISOString/safeJSONParse definitions and imports them from ./utils/safe-transforms.js.
Safe Metadata Parsing in API Handlers
src/services/api-handlers.ts
Imports safe transformation helpers and applies safeJSONParse across memory listing, deletion (cascade), search, and backfill to extract linkedPromptId and set metadata with explicit typing.
Shard Selection Logic Update
src/services/api-handlers.ts
getProjectPathFromTag now derives scope/hash from the tag and computes shards via shardManager.getAllShards(scope, hash) instead of a fixed shard list.
Migration Progress Tracking Refactor
src/services/api-handlers.ts
Introduces MigrationProgressTracker class with reset() and toJSON(); handler returns serialized migration progress via migrationProgress.toJSON().
CodeRabbit Configuration
.coderabbit.yaml
Configures review profiles, path filters (excluding generated/build/dependency dirs), path-specific instructions for src/**/*.ts and tests/**/*.ts, enables markdownlint and GitHub checks, disables shellcheck/ruff, and configures auto-review and integrations.

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides clear sections covering Changes, Impact, and Testing, but deviates from the repository's required template structure and is missing several checklist items. Use the repository's standard PR template with Description, Type of Change, Checklist, Testing, and Related Issues sections. Include required checklist confirmations for typecheck, test, build, code style, and documentation updates.
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: refactoring and optimizing api-handlers.ts and client.ts by extracting shared utilities and improving efficiency.
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/api-handlers-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: 4

🤖 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/api-handlers.ts`:
- Around line 966-975: The toJSON() method currently returns a live reference to
this.errors which allows later mutations from handleRunTagMigrationBatch (which
pushes into this.errors) to modify any stored snapshots (e.g., used by
handleGetTagMigrationProgress); change toJSON() to return a shallow copy of the
errors array (e.g., [...this.errors] or this.errors.slice()) so callers receive
an immutable snapshot while leaving the internal this.errors modifiable.
- Around line 337-350: The code parses memory.metadata into metadata once but
calls safeJSONParse(memory.metadata) again when building the return value; reuse
the existing metadata variable instead. Update the return object's deletedPrompt
expression to reference the already-parsed metadata (cast to Record<string,
unknown>)?.promptId rather than calling safeJSONParse a second time, leaving the
earlier logic that deletes the linked prompt via
userPromptManager.deletePrompt(linkedPromptId) and the existing calls to
vectorSearch.deleteVector(db, id, shard) and
shardManager.decrementVectorCount(shard.id) unchanged.
- Around line 614-625: Extract the parsed metadata into a local variable to
avoid calling safeJSONParse(m.metadata) twice inside the object literal: before
building the object, assign const parsedMetadata = safeJSONParse(m.metadata) as
Record<string, unknown> and then use parsedMetadata for the metadata field and
for linkedPromptId ((parsedMetadata)?.promptId as string | undefined); update
references in the object (metadata, linkedPromptId) accordingly and ensure types
remain the same.

In `@src/services/utils/safe-transforms.ts`:
- Line 11: The ternary assigning numValue is redundant because both branches
call Number(timestamp); replace the ternary expression in the assignment to
numValue with a single Number(timestamp) call (i.e., set numValue =
Number(timestamp)); update references around the assignment in
safe-transforms.ts (look for the numValue variable and the timestamp parameter)
so the code is simpler and avoids the dead branch.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: e60afdae-5879-4dd7-a0fc-1e29b7b32f54

📥 Commits

Reviewing files that changed from the base of the PR and between 6e35f4e and 2e56837.

📒 Files selected for processing (4)
  • .coderabbit.yaml
  • src/services/api-handlers.ts
  • src/services/client.ts
  • src/services/utils/safe-transforms.ts

Comment thread src/services/api-handlers.ts Outdated
Comment thread src/services/api-handlers.ts Outdated
Comment thread src/services/api-handlers.ts
Comment thread src/services/utils/safe-transforms.ts Outdated

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.

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/services/utils/safe-transforms.ts`:
- Around line 6-21: safeToISOString currently converts non-number string
timestamps to NaN and silently returns the current time, corrupting valid string
timestamps from raw DB results; update safeToISOString to detect when timestamp
is a string and attempt to parse it as a Date (e.g., new Date(timestamp)) and if
that produces a valid date return its toISOString(), otherwise keep existing
fallbacks (numeric conversion, negative check, catch-all current time).
Reference the function safeToISOString and the local variable timestamp when
adding the string-type guard and parsed Date validity check.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 256c50f4-4d74-48a4-b9ea-ec2e9b49f56c

📥 Commits

Reviewing files that changed from the base of the PR and between 2e56837 and bd808ea.

📒 Files selected for processing (2)
  • src/services/api-handlers.ts
  • src/services/utils/safe-transforms.ts

Comment thread src/services/utils/safe-transforms.ts

@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

🤖 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/utils/safe-transforms.ts`:
- Around line 7-26: The outer try-catch in safeToISOString is unnecessary and
should be removed: delete the surrounding try { ... } catch { return new
Date().toISOString(); } so the function relies on the existing inner checks
(null/undefined guard, Number() -> isNaN/negative check, string parse via new
Date(...).getTime()) and returns new Date().toISOString() for invalid inputs;
keep all current branches that handle numeric, string, and invalid timestamps
unchanged and ensure the final return uses new Date(numValue).toISOString() for
valid numeric inputs.
- Line 13: The check "numValue < 0" in the numeric timestamp validation inside
safe-transforms.ts incorrectly rejects valid pre-1970 timestamps and causes
silent fallback/corruption; remove the "< 0" condition so the branch only checks
isNaN(numValue), i.e., change the conditional from "isNaN(numValue) || numValue
< 0" to just "isNaN(numValue)", keep the existing string-parsing fallback
behavior intact (so negative numeric timestamps are accepted and parsed as
dates), and run/update any tests around the function that uses numValue to
ensure historical dates are preserved.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: bf62a3a6-a7cb-4c44-82a7-a05aeae36e46

📥 Commits

Reviewing files that changed from the base of the PR and between bd808ea and 3c95d0b.

📒 Files selected for processing (1)
  • src/services/utils/safe-transforms.ts

Comment thread src/services/utils/safe-transforms.ts Outdated
Comment thread src/services/utils/safe-transforms.ts Outdated
@ZeR020

ZeR020 commented May 7, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

I pushed commit 39dab05 to address the remaining safeToISOString findings: removed the outer try/catch, stopped rejecting negative numeric timestamps, preserved valid string timestamp parsing, and kept invalid values falling back safely. Please re-review PR #11.

@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

@ZeR020 Sure! I'll kick off a fresh review of PR #11 now, picking up commit 39dab05 and all the safeToISOString refinements you described — removal of the outer try/catch, acceptance of negative numeric timestamps, preserved valid string parsing, and safe fallback for invalid values.

[review]

@ZeR020
ZeR020 merged commit 1aeac99 into main May 7, 2026
5 checks passed
@ZeR020
ZeR020 deleted the refactor/api-handlers-optimization branch May 7, 2026 12:56
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