-
Notifications
You must be signed in to change notification settings - Fork 1
chore: comprehensive repository improvements and infrastructure enhancements #3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
- Add .coderabbit.yaml with security-focused configuration - Configure path-specific instructions for different code areas - Add auto-approval for small, safe changes - Include ContextForge Memory-specific review prompts - Add comprehensive setup guide for CodeRabbit AI - Optimize for security, performance, and code quality reviews
Security fixes: - Fix pip version constraint from >=25.0 to >=25.2 (GHSA-4xh5-x5gv-qwph) - Add explicit starlette==0.48.0 to requirements.txt - Pin fastapi to exact version 0.119.0 for reproducibility CI workflow improvements: - Remove duplicate dependency installation (safety/pip-audit now in requirements.txt) - Remove ad-hoc dependency upgrades from CI - Replace deprecated 'safety check' with 'safety scan' - Use continue-on-error instead of shell || true for cleaner JSON output Performance optimizations: - Remove unused _score computation in search function - Fix redundant query embedding computation in sort key - Reuse precomputed query_vec instead of recomputing for each item Code quality: - Add safety-results.json and audit-results.json to .gitignore - Remove committed safety-results.json artifact file - Ensure all dependencies are properly pinned for reproducibility All CodeRabbit AI suggestions have been implemented.
- Remove .coderabbit.yaml (system-specific configuration) - Remove CODERABBIT_SETUP.md (setup documentation) - Keep CodeRabbit AI integration but use default settings - Configuration should be managed at user/organization level, not in repo
- Remove unused score function from main.py (dead code) - Fix flake8 line length issues in Python client - Fix markdownlint issues across all markdown files: - Break long lines to comply with 80-character limit - Add proper spacing around headings and lists - Fix code block spacing issues - All linting tools now pass without errors
- Move tone from review.tone to top-level tone_instructions - Move path_instructions under reviews section - Replace ignore.paths with reviews.path_filters using ! prefix - Remove unsupported custom sections (behavior, security, performance, integrations, custom_prompts) - Restructure to match official CodeRabbit schema requirements - Preserve all review guidance content in properly formatted structure
- Combine identical instructions for *.md and docs/**/* into single entry - Use **/*.md pattern to cover all markdown files - Remove duplication while preserving all review instructions
- Recommend enabling gitleaks, semgrep, checkov in CodeRabbit UI - Add IaC/container/K8s review instructions under path_instructions - Keep path fields as strings to satisfy linter
…yaml - Replace 8 identical path instruction blocks with single canonical rule - Use brace-expanded glob to cover all original patterns: - **/*.tf, **/Dockerfile, **/Dockerfile.* - **/docker-compose.yml, **/docker-compose.*.yml - helm/**/*, k8s/**/*, kubernetes/**/* - Preserve original instruction text for Infrastructure-as-Code security
- Add pluggable embeddings providers (hash fallback, ST, OpenAI) - Add in-memory cosine vector index and session TTL store - Add summarizers (heuristic, OpenAI) - Add v1 endpoints: embed, store, search, checkpoint, restore - Add openapi/openapi-v1.yaml - Update Python/TS clients with v1 helpers - Update README for v1 overview Note: follow-up will address remaining lint (line length).
- Feature request template: fix checklist formatting - PR template: heading level for Description, add spacing before commands - README: add production considerations and v1 feature note
- Document MemoryItem fields (descriptions, lengths, enums) - Add request/response descriptions and min/max constraints - Provide examples, bounds for search and restore requests - Clarify vector shapes and formats
- Python: context manager, retryable request wrapper, custom exceptions, input validations - TS: timeout+retry with AbortController, custom error types, richer typings
- Lock-protected per-session lazy cleanup and expiry heap - Background thread to evict expired sessions; stop() API and __del__ guard - Tests for filtering, lazy cleanup, and background expiry
- VectorIndex contract tightened; input validation and error semantics - InMemoryCosineIndex: dimensionality checks, deterministic ordering, positive top_k - OpenAI embeddings: retry/backoff for transient errors; clearer context errors - Base contracts documented; summarizers refined for boundaries and truncation
- Add pydantic validators and constraints to v1 models - Structured startup/shutdown logs; warn about ephemeral storage - Safer API key checking with secrets.compare_digest - Thread-pooled file I/O for store/search/restore; top_k bounds; error handling
- Replace os.environ with monkeypatch.setenv in tests/test_summarize_and_phase.py - Add pytest dev deps in venv for local runs - Run black formatting across src, clients, tests - Update related files accordingly
…tion\n\n- Add .pre-commit-config.yaml with black, ruff, prettier, detect-secrets, commitizen, pre-push hooks\n- Add .prettierrc and .prettierignore for TypeScript and docs formatting\n- Add pyproject.toml for black/ruff and commitizen config\n- Add GitHub Actions workflow to run pre-commit, pytest smoke, and pip-audit\n- Update CONTRIBUTING.md with pre-commit install and usage instructions
…make targets, badges\n\n- Add pytest.ini with pythonpath=src\n- Add detect-secrets baseline and wire into pre-commit\n- Add caching to pre-commit workflow; add semgrep workflow\n- Add Makefile targets: setup, precommit, test\n- Add README CI badge, PR template\n- Add scheduled workflows: pre-commit autoupdate, pip-audit
…system - Add requirements-dev.txt with pinned dev dependencies (pre-commit, commitizen, pip-audit, pytest, ruff, black) - Fix pip-audit workflow: pin pip-audit to v2.9.0 and pip to v24.3.1, add contents:read permissions - Fix pre-commit-autoupdate workflow: add contents:write permissions for least-privilege access - Update Makefile: use requirements-dev.txt, remove || true from lint/format targets for fail-fast behavior - Fix README.md: update GitHub Actions badge URL to use correct org/repo (VirtualAgentics/ConextForge_memory) These changes improve supply-chain security, CI reproducibility, and developer experience.
- Fixed missing return statement in embed method that was causing linter error - Added unreachable code path with proper error handling for linter compliance - Added comprehensive documentation and configuration updates - Updated client libraries and API specifications - Enhanced project structure with new documentation and configuration files
- Fix MD024 linting error by making duplicate headings unique - Rename 'Environment Variables' to 'Storing Secrets in Environment Variables' - Rename 'Best Practices' to 'Secrets Storage Best Practices' - Rename 'Error Handling' to 'Validation Error Handling' - Remove extra blank lines to fix MD012 warning - Update various configuration files and documentation
CI Configuration Alignment: - Consolidate CI workflows into single ci.yml with 4 jobs (lint, test, security, pre-commit) - Standardize Python version to 3.12 across all CI jobs - Add full pytest suite to CI with proper environment variables - Enforce strict security policy (fail on security issues) - Align linting scope to match local development (src, clients/python, tests) - Fix CF_API_KEY requirement with testing mode detection - Add asyncio configuration to pytest.ini Environment Variables Documentation: - Create comprehensive .env.example with all 17 environment variables - Document variables by category (Core, Embeddings, Backfill, Search, Client) - Update configuration guide with .env usage instructions - Add environment setup to development quick start guide - Update README with environment configuration section - Fix .gitignore to allow .env.example while excluding personal .env files Testing Improvements: - Add session-scoped test environment setup in conftest.py - Update Makefile smoke test to use test environment variables - All tests now pass without manual CF_API_KEY setup Breaking Changes: None - Maintains backward compatibility - All existing functionality preserved - Enhanced developer experience with better documentation
- Add comprehensive clean target that removes build artifacts, cache files, and virtual environment - Include clean in .PHONY declaration for reliable execution - Clean target removes: dist/, build/, *.egg-info/, .coverage, .pytest_cache/, __pycache__ directories, *.pyc/*.pyo files, and .venv directory - Provides user feedback during cleanup process
- Replace three separate find commands with single consolidated command - Maintains same functionality for __pycache__ dirs and .pyc/.pyo files - Preserves error suppression behavior with 2>/dev/null || true - Improves efficiency by reducing directory traversals from 3 to 1
- Add pip install -e . to all CI jobs to fix module import errors - Fix ruff UP035 error: import Generator from collections.abc - Apply black formatting changes - Add pragma allowlist comments for test secrets in detect-secrets - Fix pytest module path issues by installing package in development mode
- Add proper package definition to pyproject.toml for pip install -e . - Fix end-of-file issue in CI workflow - Update .secrets.baseline with latest line numbers - Define project dependencies and build system configuration
- Change imports from src.contextforge_memory to contextforge_memory - This allows tests to work with pip install -e . in CI - Update .secrets.baseline with latest line numbers from detect-secrets
- Add mypy type checking to pre-commit hooks - Install mypy and essential type stubs in dev dependencies - Configure mypy with --ignore-missing-imports and --no-strict-optional - This will catch type issues locally before commits
- Restore test_optimization.py with proper performance tests - Restore test_threadpool_config.py with comprehensive threadpool tests - Restore test_simple_imports.py with import validation tests - Fix import paths to use src.contextforge_memory prefix - Maintain all original test functionality while fixing syntax errors - Ensure tests are comprehensive and properly structured
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 10
♻️ Duplicate comments (8)
clients/python/pytest.ini (1)
3-11: Critical: Python code in pytest.ini won't execute.Lines 3-11 contain Python code embedded in an INI configuration file. pytest.ini is parsed as INI syntax, not executed as Python. This code will be ignored, and the
CF_PYTEST_QUIETenvironment variable won't affect verbosity.Move this code to
clients/python/conftest.py:+# clients/python/conftest.py +import os + +def pytest_cmdline_preparse(config, args): + if os.getenv("CF_PYTEST_QUIET") == "1": + # remove -v if present and add -q + while "-v" in args: + args.remove("-v") + if "-q" not in args: + args.append("-q")Then update
pytest.inito remove lines 3-11:[pytest] pythonpath = . -# conftest.py -import os -def pytest_cmdline_preparse(config, args): - if os.getenv("CF_PYTEST_QUIET") == "1": - # remove -v if present and add -q - while "-v" in args: - args.remove("-v") - if "-q" not in args: - args.append("-q") markers = smoke: marks tests as smoke tests (quick validation tests).github/workflows/semgrep.yml (2)
21-22: Pin Semgrep version for deterministic builds.Installing Semgrep without a version pin (
pip install --upgrade semgrep) causes non-deterministic security scans. Different versions may produce different findings, breaking reproducibility.Pin to a specific version:
- name: Install Semgrep - run: python3 -m pip install --upgrade semgrep + run: python3 -m pip install --upgrade semgrep==1.95.0Verify the latest stable version on PyPI and update accordingly.
20-22: Consider adding pip caching to speed up workflow.The workflow installs Semgrep on every run without caching. Adding Python setup with pip cache would reduce installation time, especially important given the 30-minute timeout.
Add caching before installation:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 + - uses: actions/setup-python@0b93645e9fea7318ecaed2b359559ac225c90a2b # v5.3.0 + with: + python-version: '3.11' + cache: 'pip' - name: Install Semgrep run: python3 -m pip install --upgrade semgrep==1.95.0.github/scripts/test_vulnerability_scripts.py (1)
189-220: Patch the function where it's used for proper test isolation.Lines 189, 200, and 212 patch
subprocess.runat the global module level, which doesn't isolate calls insidecreate_security_issue. This can lead to incorrect test behavior.Patch where the function is imported:
- @patch("subprocess.run") + @patch("create_security_issue.subprocess.run") def test_create_github_issue_failure(self, mock_run): """Test handling GitHub issue creation failure.""" from subprocess import CalledProcessError mock_run.side_effect = CalledProcessError(1, "gh", stderr="Error") result = create_security_issue.create_github_issue( "Test Title", "Test Body", ["label1"] ) self.assertEqual(result, 1) - @patch("subprocess.run") + @patch("create_security_issue.subprocess.run") def test_create_github_issue_timeout(self, mock_run): """Test handling GitHub issue creation timeout.""" from subprocess import TimeoutExpired mock_run.side_effect = TimeoutExpired("gh", 30) result = create_security_issue.create_github_issue( "Test Title", "Test Body", ["label1"] ) self.assertEqual(result, 1) mock_run.assert_called_once() - @patch("subprocess.run") + @patch("create_security_issue.subprocess.run") def test_create_github_issue_file_not_found(self, mock_run): """Test handling GitHub CLI not found.""" mock_run.side_effect = FileNotFoundError() result = create_security_issue.create_github_issue( "Test Title", "Test Body", ["label1"] ) self.assertEqual(result, 1) mock_run.assert_called_once().github/workflows/ci.yml (1)
39-50: MyPy coverage limited to src directory.The MyPy strict check (line 47) only runs when
src/**/*.pychanges. This misses type errors inclients/python/**/*.py, which could propagate issues to downstream users. Per coding guidelines, Python client code should have comprehensive type checking.Expand the path filter to include the Python client:
- name: Check for changes in Python source files uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 id: src-changes with: filters: | src: - 'src/**/*.py' + - 'clients/python/**/*.py' - name: MyPy strict mode check (new code) if: steps.src-changes.outputs.src == 'true' run: | echo "Running MyPy strict mode check..." - mypy --strict src/ --show-error-codes + mypy --strict src/ clients/python/ --show-error-codes.github/workflows/typescript-client.yml (1)
130-143: Simplify redundant NPM token validation.The token check on lines 130-143 is redundant since
npm publish(line 146) will fail anyway ifNPM_TOKENis missing. This adds workflow complexity without functional benefit.Consider removing the validation step:
- - name: Check for NPM token - id: check_npm_token - run: | - if [ -n "$NPM_TOKEN" ]; then - echo "✅ NPM token is available" - echo "has_token=true" >> $GITHUB_OUTPUT - else - echo "❌ NPM_TOKEN secret is not configured" - echo "This workflow requires NPM_TOKEN to be set in repository secrets to publish packages." - echo "Please add NPM_TOKEN to your repository secrets and try again." - exit 1 - fi - env: - NPM_TOKEN: ${{ secrets.NPM_TOKEN }} - - name: Publish to npm run: npm publish env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}The native
npm publisherror message is sufficient.clients/typescript/tests/contextforgeClient.test.ts (1)
70-76: Inconsistent header assertion for health() endpoint.Line 74 asserts
Content-Type: application/jsonheader for the health endpoint, but health() sends no body. While harmless, this assertion is semantically incorrect. The test at lines 55-61 correctly checks for absence ofx-api-keywithout checking Content-Type.Update to match the correct pattern:
await clientWhitespace.health(); expect(mockFetch).toHaveBeenCalledWith( `${baseUrl}/v0/health`, expect.objectContaining({ - headers: { 'Content-Type': 'application/json' } // No x-api-key header + headers: expect.not.objectContaining({ 'x-api-key': expect.anything() }) }) );Apply the same fix to lines 87-92 for the
clientUndefinedtest.clients/typescript/contextforgeClient.ts (1)
111-157: Restore baseUrl validation.Line 117 only strips trailing slashes but doesn't validate the URL or protocol. Per previous review and coding guidelines, validate baseUrl using
new URL(baseUrl)and verifyprotocolis'http:'or'https:'before normalizing.Apply this diff to restore validation:
constructor(baseUrl: string, apiKey?: string, timeoutMs?: number, retryConfig?: Partial<RetryConfig>, logger?: { warn: (message: string, data?: any) => void; error: (message: string, data?: any) => void; info?: (message: string, data?: any) => void; debug?: (message: string, data?: any) => void; }) { + // Validate baseUrl + try { + const url = new URL(baseUrl); + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new TypeError('Invalid baseUrl: must be an absolute http(s) URL'); + } + } catch (error) { + throw new TypeError('Invalid baseUrl: must be an absolute http(s) URL'); + } + this.baseUrl = baseUrl.replace(/\/$/, "");
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
⛔ Files ignored due to path filters (24)
.cursor/rules/cicd.mdcis excluded by none and included by none.cursor/rules/general.mdcis excluded by none and included by none.cursor/rules/testing.mdcis excluded by none and included by none.gitignoreis excluded by none and included by noneCHANGELOG.mdis excluded by!**/*.mdand included by noneCONTRIBUTING.mdis excluded by!**/*.mdand included byCONTRIBUTING.mdREADME.mdis excluded by!**/*.mdand included by noneREPOSITORY_IMPROVEMENTS.mdis excluded by!**/*.mdand included by noneclients/python/README.mdis excluded by!**/*.mdand included byclients/**clients/typescript/CHANGELOG.mdis excluded by!**/*.mdand included byclients/**docs/api-reference.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/ci-cd.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/deployment.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/development.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/pr-automation.mdis excluded by!docs/**,!**/*.mdand included by nonepyrightconfig.jsonis excluded by none and included by nonescripts/apply_cr_suggestions.pyis excluded by none and included by nonescripts/compile_pr_comments.pyis excluded by none and included by nonescripts/resolve_applied_suggestions.pyis excluded by none and included by nonetest_import_optimization.pyis excluded by none and included by nonetest_optimization.pyis excluded by none and included by nonetest_simple_imports.pyis excluded by none and included by nonetest_threadpool_config.pyis excluded by none and included by nonetests/test_pr_scripts.pyis excluded by none and included by none
📒 Files selected for processing (11)
.github/scripts/analyze_vulnerabilities.py(1 hunks).github/scripts/create_security_issue.py(1 hunks).github/scripts/test_vulnerability_scripts.py(1 hunks).github/workflows/ci.yml(3 hunks).github/workflows/semgrep.yml(1 hunks).github/workflows/typescript-client.yml(1 hunks)Makefile(1 hunks)clients/python/pytest.ini(1 hunks)clients/typescript/contextforgeClient.ts(2 hunks)clients/typescript/jest.config.js(1 hunks)clients/typescript/tests/contextforgeClient.test.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
.github/**/*
⚙️ CodeRabbit configuration file
.github/**/*: Verify least-privilege permissions, pinned actions SHAs, secret usage, concurrency/cancellation,
and fast-fail patterns. Suggest caching and matrix splits where build times benefit.
Files:
.github/workflows/semgrep.yml.github/workflows/ci.yml.github/scripts/create_security_issue.py.github/scripts/test_vulnerability_scripts.py.github/workflows/typescript-client.yml.github/scripts/analyze_vulnerabilities.py
clients/typescript/**
⚙️ CodeRabbit configuration file
clients/typescript/**: Ensure strict typing, accurate DTOs from OpenAPI, consistent error shapes, and robust timeout/retry semantics.
Prefer fetch/axios configurations with sane defaults; avoid throwing ambiguous any-typed errors.
Files:
clients/typescript/tests/contextforgeClient.test.tsclients/typescript/jest.config.jsclients/typescript/contextforgeClient.ts
clients/python/**
⚙️ CodeRabbit configuration file
clients/python/**: Ensure session reuse, timeouts, and exception taxonomy maps cleanly for downstream users.
Check docstrings and typing for public functions; verify parity with OpenAPI.
Files:
clients/python/pytest.ini
🧬 Code graph analysis (5)
clients/typescript/tests/contextforgeClient.test.ts (1)
clients/typescript/src/index.ts (4)
MemoryItem(1-8)NetworkError(42-50)HTTPError(28-40)RequestTimeoutError(21-26)
.github/scripts/create_security_issue.py (1)
.github/scripts/analyze_vulnerabilities.py (2)
_validate_path(20-54)main(181-260)
.github/scripts/test_vulnerability_scripts.py (2)
.github/scripts/analyze_vulnerabilities.py (5)
extract_vulnerabilities(84-101)filter_high_critical_vulnerabilities(104-120)create_vulnerability_summary(123-140)load_audit_results(57-81)save_summary(143-178).github/scripts/create_security_issue.py (3)
load_vulnerability_summary(86-123)create_issue_body(126-191)create_github_issue(194-229)
clients/typescript/contextforgeClient.ts (1)
clients/typescript/src/index.ts (5)
RequestTimeoutError(21-26)HTTPError(28-40)NetworkError(42-50)RetryConfig(55-59)ContextForgeClient(88-554)
.github/scripts/analyze_vulnerabilities.py (1)
.github/scripts/create_security_issue.py (1)
main(232-281)
🪛 actionlint (1.7.8)
.github/workflows/typescript-client.yml
81-81: unknown permission scope "run". all available permission scopes are "actions", "attestations", "checks", "contents", "deployments", "discussions", "id-token", "issues", "models", "packages", "pages", "pull-requests", "repository-projects", "security-events", "statuses"
(permissions)
82-82: expected scalar node for string value but found mapping node with "!!map" tag
(syntax-check)
82-82: "" is invalid for permission of scope "run". available values are "read", "write" or "none"
(permissions)
🪛 Biome (2.1.2)
clients/typescript/tests/contextforgeClient.test.ts
[error] 61-61: expected , but instead found ;
Remove ;
(parse)
[error] 162-162: expected , but instead found )
Remove )
(parse)
[error] 162-162: expected , but instead found ;
Remove ;
(parse)
clients/typescript/jest.config.js
[error] 33-33: Expected a semicolon or an implicit semicolon after a statement, but found none
An explicit or implicit semicolon is expected here...
...Which is required to end this statement
(parse)
[error] 38-42: Expected a statement but instead found '],
coverageDirectory: 'coverage',
coverageReporters: ['text', 'lcov', 'html'],
setupFilesAfterEnv: ['/tests/setup.ts']
}'.
Expected a statement here.
(parse)
clients/typescript/contextforgeClient.ts
[error] 191-191: Expected a class parameters but instead found 'error'.
Expected a class parameters here.
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: Expected an identifier, a string literal, a number literal, a private field name, or a computed name but instead found '.'.
Expected an identifier, a string literal, a number literal, a private field name, or a computed name here.
(parse)
[error] 192-192: Illegal use of reserved keyword private as an identifier in strict mode
(parse)
[error] 193-193: Expected an identifier, a string literal, a number literal, a private field name, or a computed name but instead found '/'.
Expected an identifier, a string literal, a number literal, a private field name, or a computed name here.
(parse)
[error] 502-502: expected , but instead found !==
Remove !==
(parse)
[error] 502-502: expected , but instead found summary
Remove summary
(parse)
[error] 502-502: expected , but instead found !==
Remove !==
(parse)
[error] 505-505: expected , but instead found !==
Remove !==
(parse)
[error] 505-505: expected , but instead found summary
Remove summary
(parse)
[error] 505-505: expected , but instead found .
Remove .
(parse)
[error] 505-505: expected , but instead found trim
Remove trim
(parse)
[error] 505-505: expected , but instead found (
Remove (
(parse)
[error] 505-505: Expected a class method body but instead found '==='.
Expected a class method body here.
(parse)
[error] 506-506: Expected a parameter but instead found ''summary must be a non-empty string when provided''.
Expected a parameter here.
(parse)
[error] 520-520: Expected a semicolon or an implicit semicolon after a statement, but found none
An explicit or implicit semicolon is expected here...
...Which is required to end this statement
(parse)
[error] 520-520: expected , but instead found :
Remove :
(parse)
[error] 520-520: Expected a semicolon or an implicit semicolon after a statement, but found none
An explicit or implicit semicolon is expected here...
...Which is required to end this statement
(parse)
[error] 520-520: Expected an expression but instead found ']'.
Expected an expression here.
(parse)
[error] 520-520: Expected a statement but instead found '>'.
Expected a statement here.
(parse)
[error] 536-536: Illegal return statement outside of a function
(parse)
[error] 538-538: Expected a statement but instead found '}'.
Expected a statement here.
(parse)
[error] 191-191: Duplicate class member name "error"
(lint/suspicious/noDuplicateClassMembers)
[error] 502-502: Duplicate parameter name.
The parameter overrides a preceding parameter by using the same name.
(lint/suspicious/noDuplicateParameters)
[error] 505-505: Duplicate class member name "if"
(lint/suspicious/noDuplicateClassMembers)
[error] 505-505: Duplicate parameter name.
The parameter overrides a preceding parameter by using the same name.
(lint/suspicious/noDuplicateParameters)
🪛 checkmake (0.2.2)
Makefile
[warning] 27-27: Target body for "venv" exceeds allowed length of 5 (6).
(maxbodylength)
🔇 Additional comments (17)
Makefile (1)
38-40: LGTM: Editable install correctly added.The setup target now installs the package in editable mode (line 40), which addresses the previous review comment and ensures the src-layout package is available to tests and other targets.
.github/workflows/ci.yml (1)
158-167: No issues found. Bothget_embedding_dimensionand_embed_textare defined and accessible fromcontextforge_memory.main. The import on line 158 will resolve correctly..github/scripts/analyze_vulnerabilities.py (8)
1-18: LGTM: Clean imports and documentation.The module uses standard library only and includes clear documentation of purpose.
20-54: LGTM: Robust path validation with TOCTOU awareness.The function properly constrains paths to CWD and temp directories. The TOCTOU risk noted in line 76 is appropriately acknowledged.
57-82: LGTM: Secure file loading with proper error handling.Path validation, explicit encoding, and contextual error messages demonstrate best practices.
84-101: LGTM: Comprehensive format handling.The function now correctly handles pip-audit's dependencies[].vulns[] format along with legacy formats, addressing previous review feedback.
104-120: LGTM: Robust severity filtering.Case-insensitive comparison and defensive .get() usage prevent errors on missing or inconsistent severity fields.
123-140: LGTM: Clear summary structure.The function produces a well-defined summary format consumed by downstream issue creation logic.
143-178: LGTM: Atomic writes with proper error handling.The temp-file-then-replace pattern prevents corruption, and separate exception handling for I/O vs. serialization errors provides clear diagnostics.
181-264: LGTM: Well-structured main workflow with proper exit codes.Comprehensive exception handling, structured logging with context, and correct exit codes (0 for clean, 1 for vulnerabilities/errors) integrate cleanly with CI/CD pipelines.
clients/typescript/contextforgeClient.ts (7)
1-19: LGTM: Clear type definitions and constants.MAX_MEMORY_TEXT_LENGTH and type definitions align with API contracts and are used consistently in validation logic.
21-71: LGTM: Well-structured error types and retry configuration.Custom error classes with typed properties enable precise error handling and align with TypeScript best practices.
159-190: LGTM: Robust retry logic with exponential backoff.The jittered backoff and status-based retry decisions (5xx, 429, 408) follow best practices and correctly address previous feedback.
281-315: LGTM: Comprehensive item validation.Thorough validation of all required fields, format patterns, length constraints, and optional metadata prevents malformed data from reaching the API.
317-397: LGTM: Consistent v0 API implementation.All v0 methods include input validation, proper error handling through fetchWithRetry, and appropriate authentication headers.
399-500: LGTM: Well-implemented v1 API methods.Comprehensive validation, required authentication via authHeaders(true), and clear documentation align with API contracts and coding guidelines.
509-537: v1Restore implementation is correct, but depends on fixing structural errors.The v1Restore method has proper input validation and error handling. However, compilation will fail due to earlier structural errors (missing JSDoc opener at line 191, orphaned code at lines 502-507, and incorrect shouldRetry call at line 250).
- Fix 56 TypeScript errors related to Jest globals (describe, it, expect, beforeEach) - Add explicit Jest imports to test files for proper type recognition - Create jest-globals.d.ts with proper Jest type references - Fix tsconfig.json in tests directory to resolve rootDir conflicts - Clean up duplicate content in jest.config.js and package.json - Fix Python linting issues with duplicate imports and isinstance syntax - All 14 tests now pass with proper TypeScript support
- Fix YAML syntax errors in cache-pip action - Update pip-audit scheduled workflow - Fix OpenAPI v1 specification YAML structure
- Fix Codecov action SHA to correct commit hash - Fix semgrep configuration format (separate --config flags) - Add missing prepare.js script for TypeScript client - Resolve all CI job failures
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 5
♻️ Duplicate comments (4)
clients/python/contextforge_memory_client/__init__.py (1)
228-229: Runtime TypeError: isinstance requires tuple, not union type.Line 228 uses PEP 604 union syntax with
isinstance, which raisesTypeErrorat runtime. Theisinstancebuilt-in requires a tuple of types, not a union.Apply this diff to fix:
- elif isinstance(exc, httpx.ConnectError | httpx.NetworkError): + elif isinstance(exc, (httpx.ConnectError, httpx.NetworkError)): return TransientAPIError(f"Network error: {exc}")clients/typescript/tests/contextforgeClient.test.ts (2)
85-91: Fix incorrect header assertion for health() call.Same issue as the previous test: health() sends no body, so don't assert
Content-Type.Apply this diff:
await clientUndefined.health(); expect(mockFetch).toHaveBeenCalledWith( `${baseUrl}/v0/health`, expect.objectContaining({ - headers: { 'Content-Type': 'application/json' } // No x-api-key header + headers: expect.not.objectContaining({ 'x-api-key': expect.anything() }) }) );
61-75: Fix incorrect header assertion for health() call.The health() endpoint sends no body, so asserting
Content-Typeis incorrect. Only verify thatx-api-keyis absent.Apply this diff:
await clientWhitespace.health(); expect(mockFetch).toHaveBeenCalledWith( `${baseUrl}/v0/health`, expect.objectContaining({ - headers: { 'Content-Type': 'application/json' } // No x-api-key header + headers: expect.not.objectContaining({ 'x-api-key': expect.anything() }) }) );Per TypeScript client guidelines for accurate DTOs and error shapes.
clients/typescript/package.json (1)
32-32: Add missing rimraf devDependency.The clean script uses
rimrafbut it's not listed indevDependencies. This will cause the script to fail.Add to devDependencies:
"devDependencies": { "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-terser": "^0.4.4", "@rollup/plugin-typescript": "^11.1.5", "@types/jest": "^29.5.8", "@typescript-eslint/eslint-plugin": "^6.12.0", "@typescript-eslint/parser": "^6.12.0", "eslint": "^8.54.0", "husky": "^8.0.3", "jest": "^29.7.0", "prettier": "^3.1.0", + "rimraf": "^6.0.1", "rollup": "^4.6.1", "ts-jest": "^29.1.1", "typescript": "^5.3.2" },
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
⛔ Files ignored due to path filters (1)
test_optimization.pyis excluded by none and included by none
📒 Files selected for processing (11)
.github/actions/cache-pip/action.yml(1 hunks).github/workflows/pip-audit-scheduled.yml(1 hunks).github/workflows/typescript-client.yml(1 hunks)clients/python/contextforge_memory_client/__init__.py(1 hunks)clients/python/pytest.ini(1 hunks)clients/python/test_import.py(1 hunks)clients/typescript/jest.config.js(1 hunks)clients/typescript/package.json(1 hunks)clients/typescript/tests/contextforgeClient.test.ts(1 hunks)clients/typescript/tests/jest-globals.d.ts(1 hunks)clients/typescript/tests/tsconfig.json(1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
clients/typescript/**
⚙️ CodeRabbit configuration file
clients/typescript/**: Ensure strict typing, accurate DTOs from OpenAPI, consistent error shapes, and robust timeout/retry semantics.
Prefer fetch/axios configurations with sane defaults; avoid throwing ambiguous any-typed errors.
Files:
clients/typescript/tests/tsconfig.jsonclients/typescript/tests/jest-globals.d.tsclients/typescript/tests/contextforgeClient.test.tsclients/typescript/jest.config.jsclients/typescript/package.json
.github/**/*
⚙️ CodeRabbit configuration file
.github/**/*: Verify least-privilege permissions, pinned actions SHAs, secret usage, concurrency/cancellation,
and fast-fail patterns. Suggest caching and matrix splits where build times benefit.
Files:
.github/actions/cache-pip/action.yml.github/workflows/typescript-client.yml.github/workflows/pip-audit-scheduled.yml
clients/python/**
⚙️ CodeRabbit configuration file
clients/python/**: Ensure session reuse, timeouts, and exception taxonomy maps cleanly for downstream users.
Check docstrings and typing for public functions; verify parity with OpenAPI.
Files:
clients/python/test_import.pyclients/python/pytest.iniclients/python/contextforge_memory_client/__init__.py
🧬 Code graph analysis (3)
clients/typescript/tests/contextforgeClient.test.ts (4)
clients/python/contextforge_memory_client/__init__.py (2)
ContextForgeClient(163-380)MemoryItem(27-30)clients/typescript/contextforgeClient.ts (5)
ContextForgeClient(91-538)MemoryItem(4-11)NetworkError(45-53)HTTPError(31-43)RequestTimeoutError(24-29)clients/typescript/src/index.ts (5)
ContextForgeClient(88-554)MemoryItem(1-8)NetworkError(42-50)HTTPError(28-40)RequestTimeoutError(21-26)src/contextforge_memory/main.py (1)
MemoryItem(704-743)
clients/python/test_import.py (1)
clients/python/contextforge_memory_client/__init__.py (6)
ContextForgeClient(163-380)ContextForgeAPIError(40-45)PermanentAPIError(55-59)RetryConfig(66-160)TimeoutAPIError(62-63)TransientAPIError(48-52)
clients/python/contextforge_memory_client/__init__.py (3)
clients/typescript/contextforgeClient.ts (6)
MemoryItem(4-11)RetryConfig(58-62)NetworkError(45-53)HTTPError(31-43)health(327-332)search(354-375)clients/typescript/src/index.ts (6)
MemoryItem(1-8)RetryConfig(55-59)NetworkError(42-50)HTTPError(28-40)health(306-311)search(333-359)src/contextforge_memory/main.py (4)
MemoryItem(704-743)SearchResponse(767-770)health(1255-1257)search(1666-1749)
🔇 Additional comments (6)
.github/workflows/pip-audit-scheduled.yml (1)
69-76: Good: artifact upload is now guarded withif: always().Results are correctly preserved on both success and failure, so audit data won't vanish when pip-audit or analysis steps fail.
clients/typescript/tests/tsconfig.json (1)
1-11: LGTM!Test TypeScript configuration correctly extends the parent test config and includes appropriate type definitions for Jest and Node environments.
clients/typescript/tests/jest-globals.d.ts (1)
1-4: LGTM!Standard Jest type declaration file following TypeScript conventions.
clients/typescript/package.json (1)
1-31: Package manifest looks well-structured.The dual ESM/CJS exports, cross-platform scripts (except missing rimraf dependency flagged separately), and metadata are correctly configured.
Also applies to: 33-86
clients/typescript/tests/contextforgeClient.test.ts (1)
95-261: Comprehensive test coverage for client methods and error handling.The test suite appropriately covers success paths, input validation, and error scenarios (network, HTTP, timeout) with proper retry configuration for error tests.
clients/typescript/jest.config.js (1)
1-31: LGTM!Jest configuration correctly uses the ESM preset for ts-jest, enables proper mock cleanup, and configures comprehensive coverage collection.
There was a problem hiding this 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
♻️ Duplicate comments (2)
.github/workflows/semgrep.yml (1)
20-24: Pin Semgrep version and enable pip caching for deterministic, efficient builds.Two unresolved improvements from prior review feedback remain:
Non-deterministic Semgrep installation (Line 22): The
--upgradeflag installs the latest available version on each run, undermining build reproducibility and creating potential security scanning inconsistencies across runs.Missing pip caching (Lines 20–22): Without caching, pip downloads Semgrep and dependencies on every run despite the 30-minute timeout, wasting time and resources.
Apply this diff to add Python setup with caching and pin the Semgrep version:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4 + - uses: actions/setup-python@0a9ff469c0b25ad82f2337349e1f4d53ff537de6 # v5 + with: + python-version: '3.11' + cache: 'pip' - name: Install Semgrep - run: python3 -m pip install --upgrade semgrep + run: python3 -m pip install semgrep==1.40.0Verify the latest stable Semgrep version on PyPI and update the version specifier accordingly.
.github/workflows/ci.yml (1)
40-50: Extend MyPy type checking to include the Python client library.The path filter (lines 44–45) only triggers MyPy when
src/**/*.pychanges, excludingclients/python/**/*.py. The clients/python directory contains production code (contextforge_memory_client/__init__.py,__init__.py) that should be type-checked. Changes to the client library may introduce type errors that go undetected.Extend the filter to include the client library:
with: filters: | src: - 'src/**/*.py' + clients_python: + - 'clients/python/**/*.py'Then update the MyPy conditional:
- - name: MyPy strict mode check (new code) - if: steps.src-changes.outputs.src == 'true' + - name: MyPy strict mode check (new code) + if: steps.src-changes.outputs.src == 'true' || steps.src-changes.outputs.clients_python == 'true'Alternatively, remove the conditional to always run MyPy across both directories.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (3)
.github/workflows/ci.yml(3 hunks).github/workflows/semgrep.yml(1 hunks)clients/typescript/scripts/prepare.js(1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
.github/**/*
⚙️ CodeRabbit configuration file
.github/**/*: Verify least-privilege permissions, pinned actions SHAs, secret usage, concurrency/cancellation,
and fast-fail patterns. Suggest caching and matrix splits where build times benefit.
Files:
.github/workflows/semgrep.yml.github/workflows/ci.yml
clients/typescript/**
⚙️ CodeRabbit configuration file
clients/typescript/**: Ensure strict typing, accurate DTOs from OpenAPI, consistent error shapes, and robust timeout/retry semantics.
Prefer fetch/axios configurations with sane defaults; avoid throwing ambiguous any-typed errors.
Files:
clients/typescript/scripts/prepare.js
🔇 Additional comments (3)
.github/workflows/semgrep.yml (1)
8-10: Concurrency and permissions configuration looks good.The workflow correctly implements cancel-in-progress to prevent redundant runs and uses minimal, appropriate permissions for the security scanning operations.
clients/typescript/scripts/prepare.js (1)
1-12: LGTM: Clean preparation script structure.The shebang, comments, and use of Node.js built-in modules are appropriate. Synchronous operations are acceptable for a prepare script that runs once before installation. The informational logging provides good visibility into the preparation process.
Also applies to: 20-20
.github/workflows/ci.yml (1)
1-210: Action pinning, permissions, and security practices are well-configured.All GitHub Actions are pinned to specific commit SHAs (checkout, setup-python, codecov, cache, paths-filter, upload-artifact). Permissions follow the least-privilege principle (contents:read, security-events:write). Secret handling includes pragma allowlist comments. Caching strategies are in place for both pip and pre-commit. The
.secrets.baselinecheck (lines 203–206) enforces proper review of secret baseline changes. The security job usescontinue-on-error: trueto permit graceful handling of findings.
- Fix infinite recursion in OpenAI embedding dimension detection - Prevent TypeScript publish job from running on pull requests - Use default embedding dimension to avoid recursion loops - Add conditional execution for publish job (release/workflow_dispatch only)
There was a problem hiding this 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
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (1)
.github/workflows/typescript-client.yml(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
.github/**/*
⚙️ CodeRabbit configuration file
.github/**/*: Verify least-privilege permissions, pinned actions SHAs, secret usage, concurrency/cancellation,
and fast-fail patterns. Suggest caching and matrix splits where build times benefit.
Files:
.github/workflows/typescript-client.yml
🔇 Additional comments (5)
.github/workflows/typescript-client.yml (5)
3-4: Permissions follow least-privilege principle.Both global (lines 3-4) and job-level (line 81) permissions are correctly set to
contents: readonly. The previous review flagged and has been resolved.Also applies to: 80-81
39-41: YAML structure correctly fixed.The
defaults:block is now properly a sibling topermissionsandsteps(not nested within permissions), resolving the previous critical syntax error. This ensuresworking-directoryapplies correctly to run steps.Also applies to: 82-84
44-45: Action SHAs are pinned.Both
actions/checkout@b4ffde...andactions/setup-node@1d0ff...use pinned SHAs, reducing supply-chain attack surface.Also applies to: 87-88, 90-91
132-145: Minor: Redundant npm token check.The "Check for NPM token" step (lines 132-145) validates presence and exits if missing. Since
npm publishwill fail anyway withoutNODE_AUTH_TOKEN(line 150), this step is redundant, though it does provide clearer error messaging. This was flagged in previous reviews as a minor UX preference. You can simplify by removing this step and relying on npm's native failure, or keep it as-is for explicit user guidance.
47-52: Review comment verified and accurate.The workflow file confirms both jobs use identical
cache-dependency-path: './clients/typescript/package-lock.json', the lock file exists at the specified path and is committed to git. npm cache consistency across test and publish jobs is correctly configured.
- Fix semgrep command syntax (add --output flag and scanning root) - Update OpenAI embedding tests to match new default dimension behavior - Skip sentence-transformers test when dependency not available - Fix retry test to match placeholder implementation behavior - Update test expectations for unknown model dimension handling
- Remove tests/test_pr_scripts.py as PR automation is internal tooling - Revert changes to PR scripts that were made for test compatibility - Clean up debug files created during troubleshooting - PR automation scripts should not be part of the main program test suite
|
@coderabbitai resolve |
✅ Actions performedComments resolved and changes approved. |
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 13
♻️ Duplicate comments (22)
clients/typescript/LICENSE (1)
3-3: Verify and update the copyright holder.A previous review flagged that the copyright holder "bofh" should be verified. Based on the PR metadata, this package is authored by VirtualAgentics (as shown in the PR URL and organization context), yet the LICENSE names "bofh" as the holder. Please confirm the correct copyright owner and update the LICENSE accordingly to ensure distribution compliance and proper attribution.
clients/typescript/scripts/prepare.js (1)
14-18: Add error handling for directory creation failures.The
fs.mkdirSync()call lacks error handling and will throw unhandled exceptions on permission issues, disk full, or invalid paths, breaking npm install and CI builds.Apply this diff to add graceful error handling:
const distDir = path.join(__dirname, '..', 'dist'); -if (!fs.existsSync(distDir)) { - fs.mkdirSync(distDir, { recursive: true }); - console.log('Created dist directory'); -} +try { + if (!fs.existsSync(distDir)) { + fs.mkdirSync(distDir, { recursive: true }); + console.log('Created dist directory'); + } +} catch (error) { + console.error('Failed to create dist directory:', error.message); + process.exit(1); +}.github/workflows/semgrep.yml (1)
21-22: Pin Semgrep version for deterministic security scanning.The
--upgradeflag combined with no version pin causes non-deterministic builds. Different workflow runs will install different Semgrep versions, undermining reproducibility and potentially producing inconsistent security scan results across runs.Apply this diff to pin Semgrep to the current latest version:
- name: Install Semgrep - run: python3 -m pip install --upgrade semgrep + run: python3 -m pip install semgrep==1.140.0Version 1.140.0 is the latest version on PyPI (uploaded Oct 17, 2025) and ensures deterministic behavior across all workflow runs.
Makefile (1)
68-68: Consider removing PYTHONPATH=src for consistency.Similar to the
runtarget, verify ifPYTHONPATH=srcis necessary here given the editable install at line 40.clients/typescript/tsconfig.json (1)
30-37: Address redundant exclude patterns flagged in previous review.As noted in the previous review, lines 35-36 (
"**/*.test.ts","**/*.spec.ts") are redundant since line 34 already excludes"tests/**/*". If test files only exist undertests/, these glob patterns should be removed for clarity.Apply this diff if test files are only in
tests/:"exclude": [ "node_modules", "dist", "scripts", - "tests/**/*", - "**/*.test.ts", - "**/*.spec.ts" + "tests/**/*" ].github/actions/cache-pip/action.yml (4)
9-11: CRITICAL: Fix requirements-files input format - cache key never invalidates.The comma-separated default is treated as a single literal string by
hashFiles(), so the cache key${{ hashFiles('requirements.txt,requirements-dev.txt') }}hashes that exact string instead of the file contents. The cache never invalidates when requirements change.Convert to newline-delimited format and use
replace()in the key expression:requirements-files: description: 'Comma-separated list of requirements files to hash' required: false - default: 'requirements.txt,requirements-dev.txt' + default: | + requirements.txt + requirements-dev.txtThen update line 30:
- key: ${{ runner.os }}-pip-${{ inputs.python-version != '' && format('{0}-', inputs.python-version) || '' }}${{ hashFiles(inputs.requirements-files) }} + key: ${{ runner.os }}-pip-${{ inputs.python-version != '' && format('{0}-', inputs.python-version) || '' }}${{ hashFiles(format('{0}', inputs.requirements-files)) }}As per coding guidelines.
13-15: CRITICAL: Fix cache-paths input format - actions/cache treats comma as literal.The comma-separated path string is treated as a single literal path
~/.cache/pip,<additional>instead of separate entries. This breaks caching.Convert to newline-delimited format:
cache-paths: description: 'Comma-separated list of cache paths' required: false - default: '~/.cache/pip' + default: | + ~/.cache/pipAs per coding guidelines.
25-25: CRITICAL: Pin actions/cache to commit SHA for supply-chain security.Per coding guidelines for
.github/**/*, all actions must be pinned to specific commit SHAs to prevent supply-chain attacks. The@v4tag alone allows silent updates.Apply this diff:
- uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4As per coding guidelines.
27-29: CRITICAL: Path block must be newline-delimited - current logic creates invalid path.The path block concatenates inputs as-is. If
additional-pathsis non-empty, the YAML produces a malformed path entry. The conditional on line 29 doesn't prevent an empty string from appearing as a cache path.Apply this diff to filter empty additional-paths:
path: | ${{ inputs.cache-paths }} - ${{ inputs.additional-paths }} + ${{ inputs.additional-paths != '' && inputs.additional-paths || '' }}As per coding guidelines.
.github/workflows/pip-audit-scheduled.yml (1)
25-31: Refactor to use composite cache-pip action - reduces duplication.The workflow duplicates pip caching logic instead of reusing the
.github/actions/cache-pipcomposite action defined in this PR. This violates DRY and makes future cache updates require changes in multiple places.Replace with the composite action:
- - name: Cache pip packages - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 - with: - path: ~/.cache/pip - key: ${{ runner.os }}-pip-${{ hashFiles('.github/workflows/requirements/pip-audit.txt') }} - restore-keys: | - ${{ runner.os }}-pip- + - name: Cache pip packages + uses: ./.github/actions/cache-pip + with: + requirements-files: | + .github/workflows/requirements/pip-audit.txtNote: This suggestion assumes the cache-pip action issues are resolved first.
.github/scripts/test_vulnerability_scripts.py (2)
200-210: Patch target should be create_security_issue.subprocess.run for isolation.The test patches
subprocess.runglobally instead of where it's imported in the module under test. This doesn't properly isolate the call insidecreate_security_issue.- @patch("subprocess.run") + @patch("create_security_issue.subprocess.run") def test_create_github_issue_timeout(self, mock_run):
212-220: Patch target should be create_security_issue.subprocess.run for isolation.Same issue as the timeout test - patch where subprocess is imported in the module under test.
- @patch("subprocess.run") + @patch("create_security_issue.subprocess.run") def test_create_github_issue_file_not_found(self, mock_run):clients/typescript/package.json (1)
32-32: MAJOR: rimraf used but not declared in devDependencies.The clean script invokes
rimraf(line 32) butrimrafis missing from devDependencies (lines 64-78). This breaks the script on fresh installs.Add rimraf to devDependencies:
"devDependencies": { "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-terser": "^0.4.4", "@rollup/plugin-typescript": "^11.1.5", "@types/jest": "^29.5.8", "@typescript-eslint/eslint-plugin": "^6.12.0", "@typescript-eslint/parser": "^6.12.0", "eslint": "^8.54.0", "husky": "^8.0.3", "jest": "^29.7.0", "prettier": "^3.1.0", + "rimraf": "^6.0.0", "rollup": "^4.6.1", "ts-jest": "^29.1.1", "typescript": "^5.3.2" },.github/scripts/create_security_issue.py (1)
109-113: Critical: Remove duplicate _validate_path block.Lines 109-113 are an exact duplicate of lines 104-108, calling
_validate_path(filepath)twice consecutively with identical error handling. This is a merge artifact that should be removed.Apply this diff:
try: resolved_path = _validate_path(filepath) except ValueError as e: logger.error(f"Invalid filepath {filepath}: {e}") return None - try: - resolved_path = _validate_path(filepath) - except ValueError as e: - logger.error(f"Invalid filepath {filepath}: {e}") - return None if not resolved_path.exists(): return Noneclients/typescript/contextforgeClient.ts (4)
111-157: Restore baseUrl validation.The constructor accepts any string for
baseUrlwithout validation. Non-HTTP(S) or malformed URLs (e.g.,'ftp://foo','invalid') will pass through and fail later infetchwith a generic error, making debugging harder for callers.Apply this diff to add upfront validation:
constructor(baseUrl: string, apiKey?: string, timeoutMs?: number, retryConfig?: Partial<RetryConfig>, logger?: { warn: (message: string, data?: any) => void; error: (message: string, data?: any) => void; info?: (message: string, data?: any) => void; debug?: (message: string, data?: any) => void; }) { + // Validate baseUrl + try { + const url = new URL(baseUrl); + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + throw new TypeError('Invalid baseUrl: must use http or https protocol'); + } + } catch (error) { + throw new TypeError(`Invalid baseUrl: must be an absolute http(s) URL. ${error instanceof Error ? error.message : String(error)}`); + } + this.baseUrl = baseUrl.replace(/\/$/, "");
191-191: Critical: Missing JSDoc comment opener.Line 191 is missing the opening
/**for the JSDoc comment, causing parse errors that will prevent compilation.Apply this diff:
+ /** * Parses error response body for better error messages.
250-250: Remove unused lastResponse argument.Line 250 calls
this.shouldRetry(lastError, lastResponse)but the method signature at line 175 only accepts one parameter:shouldRetry(error: Error): boolean. This causes a TypeScript error.Apply this diff:
- if (attempt < this.retryConfig.maxRetries && lastError !== undefined && this.shouldRetry(lastError, lastResponse)) { + if (attempt < this.retryConfig.maxRetries && lastError !== undefined && this.shouldRetry(lastError)) {
502-507: Critical: Orphaned validation code in class body.Lines 502-507 contain validation logic that's not inside any method, making this syntactically invalid TypeScript and causing parse errors.
This validation appears to belong in a
v1Checkpointmethod that accepts asummaryparameter, but that method is missing. Either:
- The v1Checkpoint method implementation is missing from this file, or
- This validation was accidentally left outside the method during editing.
Remove this orphaned code from the class body. If a v1Checkpoint method is needed, implement it properly with this validation inside:
- - if (summary !== undefined && typeof summary !== 'string') { - throw new Error('summary must be a string when provided'); - } - if (summary !== undefined && summary.trim() === '') { - throw new Error('summary must be a non-empty string when provided'); - } -If implementing v1Checkpoint:
async v1Checkpoint(summary: string): Promise<void> { // Runtime validation if (summary !== undefined && typeof summary !== 'string') { throw new Error('summary must be a string when provided'); } if (summary !== undefined && summary.trim() === '') { throw new Error('summary must be a non-empty string when provided'); } // Implementation here const response = await this.fetchWithRetry(`${this.baseUrl}/v1/checkpoint`, { method: "POST", headers: this.authHeaders(true), body: JSON.stringify({ summary }), }); return response.json(); }clients/python/contextforge_memory_client/__init__.py (2)
211-232: Critical: isinstance union syntax causes runtime TypeError.Line 228 uses
isinstance(exc, httpx.ConnectError | httpx.NetworkError), which raisesTypeError: isinstance() arg 2 must be a type, a tuple of types, or a unionat runtime in Python <3.10, and even in 3.10+ this syntax is not supported by isinstance.Apply this diff:
- elif isinstance(exc, httpx.ConnectError | httpx.NetworkError): + elif isinstance(exc, (httpx.ConnectError, httpx.NetworkError)): return TransientAPIError(f"Network error: {exc}")
3-5: Docstring overclaims v1 support.The module docstring states "supporting both v0 (hash-based) and v1 (embedding-based) endpoints," but only v0 is implemented (see
health()andsearch()use/v0/endpoints). Update the docstring to reflect current functionality or add v1 methods before release.Apply this diff:
"""ContextForge Memory API Python Client Library. This module provides a Python client for the ContextForge Memory API, -supporting both v0 (hash-based) and v1 (embedding-based) endpoints. +supporting v0 (hash-based) endpoints. Support for v1 (embedding-based) +endpoints is planned for a future release. """clients/python/pyproject.toml (1)
44-48: Critical: Repository URLs point to non-existent slug.The URLs use
ContextForge_memory, but the PR and repository live atConextForge_memory. These links will 404 on PyPI, breaking documentation navigation and issue tracking for users.Apply this diff:
[project.urls] -Homepage = "https://github.com/VirtualAgentics/ContextForge_memory" -Repository = "https://github.com/VirtualAgentics/ContextForge_memory" -Documentation = "https://github.com/VirtualAgentics/ContextForge_memory/tree/main/clients/python" -"Bug Tracker" = "https://github.com/VirtualAgentics/ContextForge_memory/issues" +Homepage = "https://github.com/VirtualAgentics/ConextForge_memory" +Repository = "https://github.com/VirtualAgentics/ConextForge_memory" +Documentation = "https://github.com/VirtualAgentics/ConextForge_memory/tree/main/clients/python" +"Bug Tracker" = "https://github.com/VirtualAgentics/ConextForge_memory/issues"clients/python/test_import.py (1)
64-98: Optional: Consolidate duplicate assertions.Lines 78-84 and 93-97 duplicate checks from
test_all_exports_available(lines 47-61). The unique value here is the__version__validation (lines 75-77). Removing duplicates reduces maintenance overhead.Apply this diff to focus on unique assertions:
def test_version_export() -> None: + """Test that __version__ is exposed and is a string.""" import contextforge_memory_client as cmc - from contextforge_memory_client import ( - ContextForgeAPIError, - ContextForgeClient, - PermanentAPIError, - RetryConfig, - TimeoutAPIError, - TransientAPIError, - ) - # __version__ should be exposed as a string on the package assert hasattr(cmc, "__version__") assert isinstance(cmc.__version__, str) - # Verify all classes are importable - assert ContextForgeClient is not None - assert ContextForgeAPIError is not None - assert TransientAPIError is not None - assert PermanentAPIError is not None - assert TimeoutAPIError is not None - assert RetryConfig is not None - - # Validate that ContextForgeClient and RetryConfig are classes - assert isinstance(ContextForgeClient, type) - assert isinstance(RetryConfig, type) - - # Verify ContextForgeClient has expected methods - assert hasattr(ContextForgeClient, "__init__") - - # Validate that error types are subclasses of Exception - assert issubclass(ContextForgeAPIError, Exception) - assert issubclass(TransientAPIError, Exception) - assert issubclass(PermanentAPIError, Exception) - assert issubclass(TimeoutAPIError, Exception)
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
⛔ Files ignored due to path filters (84)
.coderabbit.yamlis excluded by none and included by none.cursor/instructions.mdis excluded by!**/*.mdand included by none.cursor/roadmap.mdis excluded by!**/*.mdand included by none.cursor/rules/cicd.mdcis excluded by none and included by none.cursor/rules/fastapi.mdcis excluded by none and included by none.cursor/rules/general.mdcis excluded by none and included by none.cursor/rules/performance.mdcis excluded by none and included by none.cursor/rules/python.mdcis excluded by none and included by none.cursor/rules/security.mdcis excluded by none and included by none.cursor/rules/testing.mdcis excluded by none and included by none.cursor/rules/typescript.mdcis excluded by none and included by none.editorconfigis excluded by none and included by none.env.exampleis excluded by none and included by none.eslintignoreis excluded by none and included by none.github/DEPENDENCY_POLICY.mdis excluded by!**/*.mdand included by.github/**.github/ISSUE_TEMPLATE/bug_report.mdis excluded by!**/*.mdand included by.github/**.github/ISSUE_TEMPLATE/feature_request.mdis excluded by!**/*.mdand included by.github/**.github/ISSUE_TEMPLATE/pull_request_template.mdis excluded by!**/*.mdand included by.github/**.github/PULL_REQUEST_TEMPLATE.mdis excluded by!**/*.mdand included by.github/**.gitignoreis excluded by none and included by none.pre-commit-config.yamlis excluded by none and included by none.prettierignoreis excluded by none and included by none.prettierrcis excluded by none and included by none.secrets.baselineis excluded by none and included by noneCHANGELOG.mdis excluded by!**/*.mdand included by noneCODE_OF_CONDUCT.mdis excluded by!**/*.mdand included by noneCONTRIBUTING.mdis excluded by!**/*.mdand included byCONTRIBUTING.mdCURSOR_RULES_UPDATE_SUMMARY.mdis excluded by!**/*.mdand included by noneENHANCEMENT_SUMMARY.mdis excluded by!**/*.mdand included by noneLICENSEis excluded by none and included by noneREADME.mdis excluded by!**/*.mdand included by noneREPOSITORY_IMPROVEMENTS.mdis excluded by!**/*.mdand included by noneSECURITY_BASELINE_REVIEW.mdis excluded by!**/*.mdand included by noneTEST_REFACTORING_SUMMARY.mdis excluded by!**/*.mdand included by noneclients/python/README.mdis excluded by!**/*.mdand included byclients/**clients/typescript/CHANGELOG.mdis excluded by!**/*.mdand included byclients/**clients/typescript/JEST_TYPES_TROUBLESHOOTING.mdis excluded by!**/*.mdand included byclients/**clients/typescript/README.mdis excluded by!**/*.mdand included byclients/**clients/typescript/package-lock.jsonis excluded by!**/package-lock.jsonand included byclients/**demo_lazy_dimension.pyis excluded by none and included by nonedocs/adr/ADR-0001-product-scope-and-api-contracts.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/api-reference.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/architecture.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/ci-cd.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/configuration.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/deployment.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/development.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/pr-automation.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/renovate.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/security.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/test-documentation.mdis excluded by!docs/**,!**/*.mdand included by nonedocs/testing-strategy.mdis excluded by!docs/**,!**/*.mdand included by noneexample_usage.pyis excluded by none and included by nonemypy.iniis excluded by none and included by nonepyrightconfig.jsonis excluded by none and included by nonepytest.iniis excluded by none and included by nonerenovate.jsonis excluded by none and included by nonerequirements-dev.inis excluded by none and included by nonescripts/apply_cr_suggestions.pyis excluded by none and included by nonescripts/compile_pr_comments.pyis excluded by none and included by nonescripts/resolve_applied_suggestions.pyis excluded by none and included by nonetest_chained_hashing.pyis excluded by none and included by nonetest_file_lock_enhancement.pyis excluded by none and included by nonetest_fixes.pyis excluded by none and included by nonetest_import_optimization.pyis excluded by none and included by nonetest_optimization.pyis excluded by none and included by nonetest_optional_imports.pyis excluded by none and included by nonetest_platform_file_lock.pyis excluded by none and included by nonetest_simple_imports.pyis excluded by none and included by nonetest_strict_provider_detailed.pyis excluded by none and included by nonetest_threadpool_config.pyis excluded by none and included by nonetest_vector_dimension_fix.pyis excluded by none and included by nonetests/conftest.pyis excluded by none and included by nonetests/test_analyze_vulnerabilities.pyis excluded by none and included by nonetests/test_backfill_integration.pyis excluded by none and included by nonetests/test_backfill_public_api.pyis excluded by none and included by nonetests/test_backfill_scanning.pyis excluded by none and included by nonetests/test_embeddings_validation.pyis excluded by none and included by nonetests/test_session_store.pyis excluded by none and included by nonetests/test_session_store_accessor.pyis excluded by none and included by nonetests/test_summarize_and_phase.pyis excluded by none and included by nonetsconfig.eslint.jsonis excluded by none and included by nonetsconfig.jsonis excluded by none and included by nonevulnerability_summary.jsonis excluded by none and included by none
📒 Files selected for processing (42)
.github/actions/cache-pip/action.yml(1 hunks).github/dependabot.yml(2 hunks).github/scripts/__init__.py(1 hunks).github/scripts/analyze_vulnerabilities.py(1 hunks).github/scripts/create_security_issue.py(1 hunks).github/scripts/test_vulnerability_scripts.py(1 hunks).github/workflows/ci.yml(3 hunks).github/workflows/pip-audit-scheduled.yml(1 hunks).github/workflows/requirements/pip-audit.txt(1 hunks).github/workflows/semgrep.yml(1 hunks).github/workflows/typescript-client.yml(1 hunks)Makefile(1 hunks)clients/python/__init__.py(1 hunks)clients/python/contextforge_client.py(0 hunks)clients/python/contextforge_memory_client/__init__.py(1 hunks)clients/python/pyproject.toml(1 hunks)clients/python/pytest.ini(1 hunks)clients/python/test_import.py(1 hunks)clients/typescript/.eslintignore(1 hunks)clients/typescript/.eslintrc.js(1 hunks)clients/typescript/.eslintrc.test.js(1 hunks)clients/typescript/.gitignore(1 hunks)clients/typescript/.husky/_(1 hunks)clients/typescript/.husky/pre-commit(1 hunks)clients/typescript/.husky/pre-push(1 hunks)clients/typescript/.huskyrc(1 hunks)clients/typescript/.prettierrc(1 hunks)clients/typescript/LICENSE(1 hunks)clients/typescript/contextforgeClient.ts(2 hunks)clients/typescript/examples/basic-usage.ts(1 hunks)clients/typescript/jest.config.js(1 hunks)clients/typescript/package.json(1 hunks)clients/typescript/rollup.config.js(1 hunks)clients/typescript/scripts/dev.js(1 hunks)clients/typescript/scripts/prepare.js(1 hunks)clients/typescript/src/index.ts(1 hunks)clients/typescript/tests/contextforgeClient.test.ts(1 hunks)clients/typescript/tests/jest-globals.d.ts(1 hunks)clients/typescript/tests/setup.ts(1 hunks)clients/typescript/tests/tsconfig.json(1 hunks)clients/typescript/tsconfig.json(1 hunks)clients/typescript/tsconfig.test.json(1 hunks)
💤 Files with no reviewable changes (1)
- clients/python/contextforge_client.py
🧰 Additional context used
📓 Path-based instructions (3)
.github/**/*
⚙️ CodeRabbit configuration file
.github/**/*: Verify least-privilege permissions, pinned actions SHAs, secret usage, concurrency/cancellation,
and fast-fail patterns. Suggest caching and matrix splits where build times benefit.
Files:
.github/scripts/test_vulnerability_scripts.py.github/actions/cache-pip/action.yml.github/dependabot.yml.github/workflows/requirements/pip-audit.txt.github/workflows/typescript-client.yml.github/workflows/ci.yml.github/workflows/semgrep.yml.github/scripts/analyze_vulnerabilities.py.github/workflows/pip-audit-scheduled.yml.github/scripts/__init__.py.github/scripts/create_security_issue.py
clients/typescript/**
⚙️ CodeRabbit configuration file
clients/typescript/**: Ensure strict typing, accurate DTOs from OpenAPI, consistent error shapes, and robust timeout/retry semantics.
Prefer fetch/axios configurations with sane defaults; avoid throwing ambiguous any-typed errors.
Files:
clients/typescript/package.jsonclients/typescript/LICENSEclients/typescript/tests/tsconfig.jsonclients/typescript/jest.config.jsclients/typescript/tsconfig.jsonclients/typescript/tests/contextforgeClient.test.tsclients/typescript/scripts/dev.jsclients/typescript/tests/setup.tsclients/typescript/tsconfig.test.jsonclients/typescript/examples/basic-usage.tsclients/typescript/tests/jest-globals.d.tsclients/typescript/contextforgeClient.tsclients/typescript/rollup.config.jsclients/typescript/src/index.tsclients/typescript/scripts/prepare.js
clients/python/**
⚙️ CodeRabbit configuration file
clients/python/**: Ensure session reuse, timeouts, and exception taxonomy maps cleanly for downstream users.
Check docstrings and typing for public functions; verify parity with OpenAPI.
Files:
clients/python/pytest.iniclients/python/pyproject.tomlclients/python/test_import.pyclients/python/__init__.pyclients/python/contextforge_memory_client/__init__.py
🪛 Biome (2.1.2)
clients/typescript/contextforgeClient.ts
[error] 191-191: Expected a class parameters but instead found 'error'.
Expected a class parameters here.
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: expected a semicolon to end the class property, but found none
(parse)
[error] 191-191: Expected an identifier, a string literal, a number literal, a private field name, or a computed name but instead found '.'.
Expected an identifier, a string literal, a number literal, a private field name, or a computed name here.
(parse)
[error] 192-192: Illegal use of reserved keyword private as an identifier in strict mode
(parse)
[error] 193-193: Expected an identifier, a string literal, a number literal, a private field name, or a computed name but instead found '/'.
Expected an identifier, a string literal, a number literal, a private field name, or a computed name here.
(parse)
[error] 502-502: expected , but instead found !==
Remove !==
(parse)
[error] 502-502: expected , but instead found summary
Remove summary
(parse)
[error] 502-502: expected , but instead found !==
Remove !==
(parse)
[error] 505-505: expected , but instead found !==
Remove !==
(parse)
[error] 505-505: expected , but instead found summary
Remove summary
(parse)
[error] 505-505: expected , but instead found .
Remove .
(parse)
[error] 505-505: expected , but instead found trim
Remove trim
(parse)
[error] 505-505: expected , but instead found (
Remove (
(parse)
[error] 505-505: Expected a class method body but instead found '==='.
Expected a class method body here.
(parse)
[error] 506-506: Expected a parameter but instead found ''summary must be a non-empty string when provided''.
Expected a parameter here.
(parse)
[error] 520-520: Expected a semicolon or an implicit semicolon after a statement, but found none
An explicit or implicit semicolon is expected here...
...Which is required to end this statement
(parse)
[error] 520-520: expected , but instead found :
Remove :
(parse)
[error] 520-520: Expected a semicolon or an implicit semicolon after a statement, but found none
An explicit or implicit semicolon is expected here...
...Which is required to end this statement
(parse)
[error] 520-520: Expected an expression but instead found ']'.
Expected an expression here.
(parse)
[error] 520-520: Expected a statement but instead found '>'.
Expected a statement here.
(parse)
[error] 536-536: Illegal return statement outside of a function
(parse)
[error] 538-538: Expected a statement but instead found '}'.
Expected a statement here.
(parse)
[error] 191-191: Duplicate class member name "error"
(lint/suspicious/noDuplicateClassMembers)
[error] 502-502: Duplicate parameter name.
The parameter overrides a preceding parameter by using the same name.
(lint/suspicious/noDuplicateParameters)
[error] 505-505: Duplicate class member name "if"
(lint/suspicious/noDuplicateClassMembers)
[error] 505-505: Duplicate parameter name.
The parameter overrides a preceding parameter by using the same name.
(lint/suspicious/noDuplicateParameters)
🪛 checkmake (0.2.2)
Makefile
[warning] 27-27: Target body for "venv" exceeds allowed length of 5 (6).
(maxbodylength)
🔇 Additional comments (43)
.github/dependabot.yml (3)
10-10: Timezone change is sound.The "Etc/UTC" identifier is the canonical IANA timezone representation and is functionally equivalent to "UTC" but more explicit and deterministic for tooling.
26-26: Empty ignore list with policy reference is a solid pattern.Defaulting to
ignore: [](ignore nothing) and externalizing exclusions to a documented policy file makes dependency governance explicit and auditable. This aligns well with the PR's CI/CD hardening goals.
25-26: The dependency policy file exists and is properly documented.Verification confirms
.github/DEPENDENCY_POLICY.mdis present with clear documentation outlining the policy overview, exclusion criteria (breaking changes, security vulnerabilities, active review, experimental dependencies), and the process for adding exclusions. The reference in.github/dependabot.ymlat lines 25-26 is valid and accurate, providing good maintainability for future reviewers..github/scripts/__init__.py (1)
1-6: LGTM! Clear package documentation.The module docstring appropriately describes the package purpose and scope for CI/CD automation scripts.
clients/typescript/tests/jest-globals.d.ts (1)
1-4: LGTM! Standard Jest type declarations.The triple-slash reference and explanatory comments are appropriate for providing Jest types to the TypeScript test suite.
clients/typescript/.prettierrc (1)
1-11: LGTM! Reasonable Prettier configuration.The formatting rules are consistent and follow standard TypeScript conventions. The 100-character print width and LF line endings align well with the project's cross-platform nature.
clients/typescript/.eslintignore (1)
1-17: LGTM! Appropriate ESLint ignore patterns.The ignore patterns correctly exclude build outputs, dependencies, scripts, and configuration files from linting, following standard TypeScript project conventions.
clients/typescript/.gitignore (1)
1-84: LGTM! Comprehensive .gitignore coverage.The ignore patterns are thorough and cover all standard Node.js/TypeScript project artifacts, including dependencies, build outputs, IDE files, caches, and framework-specific directories.
clients/typescript/.husky/_ (1)
1-36: LGTM! Standard Husky hook wrapper.The script correctly implements the Husky hook lifecycle with proper debug logging, environment variable checks, re-entrance guards, and exit code handling. The implementation follows Husky conventions.
.github/workflows/requirements/pip-audit.txt (1)
4-8: pip-audit 2.9.0 hash verified; pip 25.2 requires manual verification.pip-audit 2.9.0 wheel hash (348b16e60895749a0839875d7cc27ebd692e1584ebe5d5cb145941c8e25a80bd) matches the official PyPI digest. Both versions are valid and current. However, verify the pip 25.2 hash (6d67a2b4e7f14d8b31b8b52648866fa717f45a1eb70e83002f4331d07e953717) against PyPI to confirm it matches the official release, as the web search result did not include that specific hash.
Makefile (1)
27-33: LGTM: Robust venv initialization.The venv target properly handles missing or broken virtual environments and ensures pip is upgraded. The static analysis warning about body length (6 lines) is pedantic and can be safely ignored for this workflow-critical target.
clients/typescript/.huskyrc (1)
1-2: LGTM: Standard Husky configuration.The configuration properly initializes Husky by exporting the
HUSKY=1environment variable, enabling Husky hooks in the TypeScript client package.clients/typescript/tsconfig.test.json (1)
1-15: LGTM: Well-structured test configuration.The test TypeScript configuration appropriately:
- Extends the base config for consistency
- Sets
noEmit: true(correct for test-only compilation)- Includes both source and test files for type checking
- Excludes build artifacts
The include patterns (
src/**/*.tsandtests/**/*.ts) correctly ensure tests can reference source types while maintaining separation.clients/typescript/tests/setup.ts (1)
14-17: Good test isolation with afterEach cleanup.Using
jest.resetAllMocks()ensures deterministic test isolation by clearing mock history, implementations, and return values between tests. This is the correct choice for preventing test interdependencies.clients/typescript/tsconfig.json (2)
24-24: Verify composite: true is intentional without references.Setting
composite: truetypically indicates this is part of a TypeScript project references setup, but noreferencesarray is present in the config. Composite projects are designed for multi-project builds with explicit dependencies.If this isn't part of a project references setup, consider removing
composite: true:"noUnusedLocals": true, "noUnusedParameters": true, - "exactOptionalPropertyTypes": true, - "composite": true + "exactOptionalPropertyTypes": trueIf it is intentional, verify that dependent projects properly reference this one.
1-25: Strong TypeScript configuration for strict type safety.The compiler options demonstrate excellent practices per coding guidelines:
- Strict mode enabled with granular strict checks
- ES2020 target with modern module system
- Proper interop settings for Node ecosystem
- Declaration generation for library consumers
- Unused code detection enabled
This aligns well with the PR's goal of enhanced type safety.
clients/typescript/.husky/pre-commit (1)
1-4: Pre-commit script verified.The
pre-commitscript is defined inclients/typescript/package.jsonand correctly configured to runnpm run lint && npm run format:check. The Husky hook is properly set up.clients/typescript/.husky/pre-push (1)
1-4: No issues found. Thepre-pushscript is properly defined.The verification confirms that
npm run pre-pushis defined inclients/typescript/package.jsonas"npm run test:smoke". The Husky hook will execute without runtime failures.clients/typescript/.eslintrc.test.js (1)
1-11: LGTM - Clean test ESLint configuration.The test override correctly extends the base config, points to the test tsconfig, and enables Jest globals. Well structured.
clients/typescript/examples/basic-usage.ts (2)
53-63: LGTM - Robust numeric validation with bounds checking.The validation correctly handles NaN, non-finite, and negative values with sensible defaults. Well done.
145-159: LGTM - Comprehensive error handling with type guards.The error handling properly uses instanceof checks and handles both typed errors (RequestTimeoutError, HTTPError, NetworkError) and generic Error cases. The originalError handling on lines 154-159 is defensive and correct.
clients/typescript/.eslintrc.js (1)
1-45: LGTM - Strict TypeScript ESLint configuration.The config enforces strong type safety with explicit return types, no-any, and strict boolean expressions. Test overrides correctly point to the test tsconfig and enable Jest globals. Well structured per coding guidelines.
clients/typescript/scripts/dev.js (1)
34-54: LGTM - Robust timeout parsing with bounds and validation.The timeout parsing correctly handles invalid inputs, applies sensible defaults, and clamps to a maximum. The warning messages are helpful.
.github/workflows/pip-audit-scheduled.yml (2)
56-62: LGTM - Vulnerability analysis step with proper exit code capture.The step correctly runs the analysis script, captures the exit code, and outputs it for conditional steps. Well structured.
69-76: LGTM - Artifact upload runs regardless of job outcome.The
if: always()ensures audit results are preserved even when prior steps fail. This is correct and was properly addressed from past reviews..github/scripts/test_vulnerability_scripts.py (1)
20-111: LGTM - Comprehensive test coverage for vulnerability analysis functions.The test suite covers extraction, filtering, summary creation, file I/O, and error paths with appropriate assertions. Good use of tempfile for safe testing.
clients/typescript/jest.config.js (1)
1-31: LGTM! Jest configuration is well-structured.The ESM preset, TypeScript globals, test isolation settings, and coverage configuration are all properly configured. Past syntax issues have been resolved.
clients/typescript/tests/contextforgeClient.test.ts (1)
1-262: LGTM! Comprehensive test coverage.The test suite thoroughly covers constructor validation, API methods, error handling, and edge cases. Past syntax errors have been resolved, and the tests properly validate client behavior including retry logic, timeout handling, and API key normalization.
clients/typescript/rollup.config.js (1)
1-53: LGTM! Clean dual-format build configuration.The Rollup config properly generates both CommonJS and ES Module builds with appropriate plugin configurations, sourcemaps, and minification. Type declarations are correctly emitted only in the ESM build to avoid duplication.
.github/scripts/analyze_vulnerabilities.py (1)
1-264: LGTM! Robust vulnerability analysis with comprehensive format support.The script properly handles multiple pip-audit output formats, including the newer
dependencies[].vulns[]structure. Path validation prevents traversal attacks, and the error handling with structured logging provides clear diagnostics..github/workflows/ci.yml (1)
1-210: LGTM! Comprehensive CI workflow with proper security hardening.The workflow properly separates lint, test, security, and pre-commit concerns. Action SHAs are pinned, pip is pinned to 25.2 for security, and artifacts are uploaded for security audit results. The multi-version Python matrix ensures compatibility.
clients/typescript/src/index.ts (1)
1-554: LGTM! Production-ready client with robust error handling.The TypeScript client implementation is comprehensive with:
- Proper input validation for all methods
- Exponential backoff with jitter for retries
- Type-safe error classes (RequestTimeoutError, HTTPError, NetworkError)
- URL protocol validation and API key normalization
- Thorough MemoryItem validation including namespace pattern enforcement
The retry logic correctly handles network errors, timeouts, and retryable HTTP status codes while avoiding retries on 4xx client errors. As per coding guidelines for
clients/typescript/**.clients/python/__init__.py (1)
1-31: LGTM! Clean package entry point.The re-export pattern, version handling with fallback, and
__all__definition follow Python packaging best practices. The approach ensures graceful degradation if the package metadata is unavailable.clients/python/pyproject.toml (1)
50-105: Tool configurations look solid.Package discovery, type marker (
py.typed), and linter/formatter configs follow best practices. The ANN401 exception for__init__.pyis appropriate for re-export modules.clients/python/test_import.py (2)
7-42: Comprehensive client structure validation.Testing importability, type checks, lifecycle methods (
close,__enter__,__exit__,__del__), and API methods (health,search) ensures the public surface is stable.
100-152: Thorough RetryConfig validation.Testing default values, types, and custom initialization ensures the retry configuration behaves correctly. Good coverage of the public API contract.
clients/python/contextforge_memory_client/__init__.py (6)
26-38: API types appropriately flexible.Using
total=FalseforMemoryItemandNotRequired[int]forSearchResponse.totalallows the client to handle server responses without over-constraining. Good alignment with backend flexibility.
40-64: Clean exception taxonomy.The error hierarchy (base, transient, permanent, timeout) provides clear semantics for retry decisions and downstream error handling. Well-designed for client resilience.
As per coding guidelines
66-161: Robust retry configuration with validation.Input validation with coercion (int/float/bool) and bounds checking prevents misconfiguration. The jitter string handling (
"true","1", etc.) adds flexibility for environment-driven config.
166-210: Session reuse and timeout handling look correct.The client initializes a single
httpx.Clientinstance (session reuse per coding guidelines) and properly handles resource cleanup on initialization errors. Modern httpx versions (>=0.25.0 per dependencies) accepttimeout=Noneto mean no timeout, so no guard is needed.As per coding guidelines
246-304: Retry logic and header handling are correct.Headers are properly merged (lines 254-259) and passed to every request (line 263), ensuring authentication headers are sent. Retry logic correctly distinguishes transient vs. permanent errors and logs structured retry attempts.
306-380: Resource management and API methods are well-implemented.Lifecycle methods ensure proper cleanup,
health()provides basic connectivity checks, andsearch()includes thorough input validation (non-empty strings, top_k bounds 1-50) aligned with other client implementations. Good adherence to coding guidelines for public API surface.As per coding guidelines
clients/python/pytest.ini (1)
2-2: CI correctly uses editable install, but verify thatpythonpathsetting applies.Pytest searches for pytest.ini upward from the common ancestor directory of test arguments. When CI runs
pytest tests/from the repository root, it will discover the first matching configuration file in that directory or its parents. If a configuration file exists at the repository root, it takes precedence and becomes the rootdir.CI correctly uses
pip install -e .for editable installation, which ensures package imports work. However, verify that thepythonpath = .setting inclients/python/pytest.iniactually applies during CI runs:
- Confirm whether pytest.ini or another config file exists at the repository root that might take precedence.
- If the tests directory is at the repository root, the repository root's config file (if present) will be used instead of
clients/python/pytest.ini.
- Add option detection and parsing for CodeRabbit comments with multiple resolution options - Implement intelligent auto-selection heuristics (recommended keywords, numbered options, simpler changes) - Add configuration file support for user override of auto-selected options - Update main processing loop to handle multiple options with auto-selection and user override - Add options config generation during preview mode - Enhance reporting to include option labels and multi-option detection summary - Update documentation with comprehensive multi-option handling guide - Maintain backward compatibility with single-option comments - Test implementation with realistic CodeRabbit comment formats The script now intelligently handles comments like: **Option 1: Rename to test-backfill** **Option 2: Run all tests** Auto-selects the best option and allows user override via .cr/options_config.json
- Enhanced docs/pr-automation.md with comprehensive multi-option handling documentation - Added supported option formats section - Added AI auto-selection algorithm details - Added multi-option detection explanation - Added enhanced reporting examples - Added backward compatibility section - Updated README.md PR automation section with new multi-option features - Added AI auto-selection, user override, enhanced reporting highlights - Added example workflow with options config review - Updated CHANGELOG.md with multi-option handling feature details - Fixed markdown linting issues (duplicate headings, code block language, list formatting)
- Update Makefile to filter resolved comments during GitHub API fetch using jq
- Add check-jq dependency check
- Filter out comments with resolved_at field and reply comments
- Add pr_cleanup target for manual tracking file cleanup
- Add persistent tracking to scripts/apply_cr_suggestions.py
- Track successfully applied comments per-PR in .cr/processed_comments_pr{PR}.json
- Skip previously processed comments in subsequent runs
- Automatic cleanup of tracking files older than 30 days
- Per-PR tracking files (gitignored) for multiple PR support
- Update .gitignore to explicitly ignore tracking files
- Update documentation in docs/pr-automation.md and README.md
- Add resolved comment filtering section with usage examples
- Document tracking file locations and cleanup procedures
- Update PR automation workflow with filtering features
Benefits:
- No duplicate suggestion applications across multiple runs
- Safe to run multiple times on same PR
- Automatic cleanup prevents accumulation of old tracking files
- Handles multiple PRs independently
- Clean repository (tracking files are gitignored)
|
@coderabbitai resolve |
✅ Actions performedComments resolved and changes approved. |
- Enhanced patch generation system ready - Preview mode completed successfully - 40 comments processed, 42 patches generated - All patches validated with git apply --check - Multi-option selection working correctly - Ready for live application with backup system
Comprehensive Repository Improvements and Infrastructure Enhancements
This PR implements extensive improvements across the entire codebase including infrastructure enhancements, CI/CD improvements, type safety upgrades, comprehensive testing, and complete client library infrastructure.
📊 Overview
This PR includes 111 commits spanning multiple categories of improvements:
🚀 Key Features Implemented
1. Platform-Safe File Locking
fcntl.flockon Unix/Linux andmsvcrt.lockingon Windows2. Complete TypeScript Client Infrastructure
3. Optional Provider Imports with Strict Mode
CF_STRICT_PROVIDER_INITenvironment variableHAS_OPENAIandHAS_SENTENCE_TRANSFORMERSdetection4. Automatic Backfill System
/v0/backfilland/v0/backfill-statsfor monitoring5. Enhanced Type Safety & Code Quality
py.typedmarkers throughout🔧 Infrastructure & CI/CD Improvements
GitHub Actions Security & Reliability
Development Workflow
Code Quality & Security
📋 Detailed Changes by Category
Infrastructure & CI/CD (49 fixes)
Features (10 implementations)
Type Safety & Code Quality
Documentation & Testing
Security & Compliance
🧪 Testing Infrastructure
Test Coverage
Test Commands
📚 Documentation Updates
API Documentation
Development Documentation
Architecture Documentation
🔧 Configuration & Environment
New Environment Variables
CF_STRICT_PROVIDER_INIT: Enable strict provider validationMakefile Enhancements
make type-check: Run MyPy type checkingmake test-all: Run comprehensive test suitemake test-api: Run API-specific testsmake test-integration: Run integration testsmake clean: Clean build artifacts and temporary files🚀 Performance Impact
Positive Improvements
🔒 Security Considerations
Enhanced Security
📦 Breaking Changes
None - All changes are backward compatible and maintain existing functionality.
🎯 Future Considerations
✅ Checklist
📊 Commit Summary
This PR includes 111 commits following conventional commit standards:
Major Categories:
🔗 Related Issues
This PR addresses multiple enhancement areas:
Summary by CodeRabbit
New Features
Security
Documentation
Tests / CI