- Update test_inject_profiling_used_frameworks, test_async_run_and_parse,
test_pickle_patcher to use new inject_profiling_into_existing_test API
(test_string param removed)
- Add parse_line_profile_results function to parse_line_profile_test_output
module (imported by main's PythonFunctionOptimizer and test_instrument_tests)
Merges the omni-main-java branch which synced main into omni-java,
including JavaFunctionOptimizer, removal of is_java()/is_python() guards,
protocol dispatch for parse_test_xml, and deletion of concolic_testing.py.
The optimization adds `@lru_cache(maxsize=4096)` to `format_runtime_comment`, which is called once per annotated line (2484 hits in the profiler) with frequently repeated input tuples—particularly when multiple test cases measure identical nanosecond pairs or when performance data clusters around similar values. Without caching, each call re-executes `format_perf`, `performance_gain`, and two `format_time` calls, accounting for 78% of `format_runtime_comment`'s total time (9.55ms) and 63.5% of `add_runtime_comments`'s wall time (17.7ms). With caching, cache hits eliminate these formatting steps entirely, reducing the hot-path line from 7120ns to 4292ns per hit—a 39.7% per-call improvement that compounds across thousands of invocations to yield the observed 111% speedup.
The optimization replaced 34 repeated string interpolations of `{iter_id}_{call_counter}` with a single pre-computed `id_pair` variable, reducing per-call runtime from ~24ms to ~13ms (87% faster). Line profiler shows the list-building return statement consumed 38.9% of original time (~42ms) versus 41.2% optimized (~47ms absolute), but the absolute wall-clock improvement came from eliminating redundant f-string evaluations: each of the 34 format operations that previously recalculated `f"{iter_id}_{call_counter}"` now references a cached result, cutting allocation overhead. Tests across 1000+ iterations confirm identical output with consistent speedup ranging from 44–92% depending on input size.
JavaScriptFunctionOptimizer.replace_function_and_helpers_with_optimized_code
imports from codeflash.languages.code_replacer, but the file was never
ported to omni-java. Copied from main.
Fixes PYTHON-CLI-44S.
Fix 10 failing tests: remove wrong assertions expecting import statements
inside extracted class code, use substring matching for UserDict class
signature, and rewrite click-dependent tests as project-local equivalents.
Add tests for resolve_instance_class_name, enhanced extract_init_stub_from_class,
and enrich_testgen_context instance resolution.
Move Path import out of TYPE_CHECKING block (TC004) since it is used at runtime, and replace missing safe_relative_to call with inline try/except pattern matching the rest of the PR.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Drop the /simplify step that caused unprompted refactors and scope
creep in PR reviews. Also add prek pre-commit rule to project config
so the PR bot and all contributors see it.
Use self.default_file_extension in format_code and a treesitter_language
property in validate_syntax so TypeScriptSupport inherits both methods
from JavaScriptSupport instead of duplicating them.
When testsRoot overlaps moduleRoot (common in JS/TS monorepos like Ghost
where both point to "src"), the directory-based filter incorrectly
excluded ALL source files. Switch to filename/directory pattern matching
(*.test.*, *.spec.*, __tests__/) when roots overlap, preserving the
existing directory-based filter for standard layouts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Use instrumented class name in _cf_mod/_cf_cls markers to disambiguate
existing vs generated tests sharing the same original class name
- Encode line number in invocation IDs (L{line}_{counter}) for deterministic
call-site identification in inline runtime comments
- Rewrite add_runtime_comments() to annotate each call line with inline
performance data instead of a summary block at top
- Strip assertions before instrumenting so both modes share the same base source
- Update test expected strings for new marker format
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Reverts ed2594bf which added --pool=forks to Vitest commands and
changed capture.js to use process.stdout.write and Vitest worker API.
These changes broke JS E2E tests (CJS, ESM, TS class) by altering
how all JS tests run, not just Vitest benchmarking.
Two fixes discovered during end-to-end testing:
1. _ensure_codeflash_vitest_config() reused existing configs that lacked
pool: 'forks', causing benchmarking to fall back to wall-clock timing
on re-runs. Now checks for the required setting and regenerates if
missing.
2. ESM projects require explicit .js file extensions in import specifiers
(e.g., `import foo from './lib/foo.js'`). The verifier stripped the
extension but never added .js back for ESM, causing
ERR_MODULE_NOT_FOUND in Mocha ESM projects like axios.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
The AI backend generates vitest/jest-style imports for Mocha projects.
Our sanitize_mocha_imports() stripped ESM `import { ... } from 'vitest'`,
but process_generated_test_strings() runs BEFORE postprocessing and calls
ensure_module_system_compatibility() which converts these to CJS requires.
Result: `const { ... } = require('vitest')` survived sanitization.
Added regexes for the CJS variants of vitest and @jest/globals requires.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Root cause: Vitest performance tests reported "20.0 seconds over 1 loop"
(JUnit XML wall-clock fallback) instead of actual per-function nanosecond
timing. This was a chain of two issues:
1. **stdout interception**: Vitest's default `threads` pool intercepts
process.stdout.write() and console.log(), preventing timing markers
from flowing to the parent process. Fixed by adding `--pool=forks`
to all Vitest commands and config files. The `forks` pool uses child
processes where stdout flows directly to the parent.
2. **test name detection**: Even after markers flowed through (43,000+
found in stdout), the parser couldn't match them to JUnit XML
testcases because all markers had "unknown" as the test name. This
happened because Vitest doesn't inject `beforeEach` as a global
(unlike Jest), so capture.js's Jest-style hook to set
`currentTestName` never fired.
Fixed by adding Vitest-specific test name detection in capture.js:
- Primary: `expect.getState().currentTestName` (full describe path)
- Fallback: `__vitest_worker__.current.fullTestName`
- Defense-in-depth: parser fallback matches "unknown" markers to
the first testcase when no name match is found
Result: cheerio's `isHtml` went from "20.0s / 1 loop" to
"902μs / 20,853 loops" with proper speedup analysis.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Three related fixes for Mocha test generation in CommonJS projects:
1. inject_test_globals() now accepts module_system param — emits
`require('node:assert/strict')` for CJS instead of ESM import syntax
2. ensure_module_system_compatibility() now converts ESM→CJS even when
the source has mixed imports (was skipping when both ESM and CJS were
detected, leaving the ESM import from inject_test_globals unconverted)
3. New sanitize_mocha_imports() strips vitest/jest/@jest/globals imports
that the AI sometimes generates for Mocha projects — Mocha provides
describe/it/before*/after* as globals
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Ship a zero-dependency jest-reporter.js inside the codeflash runtime package
instead of requiring the external jest-junit npm package. This ensures the
reporter is always available when codeflash is installed, fixing Jest-based
projects (Strapi, Moleculer) that failed because jest-junit wasn't installed.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Nested functions are now skipped by FunctionVisitor, and
discover_functions no longer swallows parse/IO errors — callers
handle them. Update test expectations accordingly.
Remove the AST-based discovery path for Python, routing all languages
through the unified CST-based `_find_all_functions_via_language_support`.
Delete dead code: `find_functions_with_return_statement`,
`_find_all_functions_in_python_file`, `function_has_return_statement`,
`function_is_a_property`, and associated constants. Fix FunctionVisitor
to skip nested functions and exclude @property/@cached_property, and let
parse errors propagate for correct empty-dict behavior on invalid files.
When testsRoot overlaps moduleRoot (common in JS/TS monorepos like Ghost
where both point to "src"), the directory-based filter incorrectly
excluded ALL source files. Switch to filename/directory pattern matching
(*.test.*, *.spec.*, __tests__/) when roots overlap, preserving the
existing directory-based filter for standard layouts.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
When a user targets a function that exists in the file but is not exported,
show a clear message suggesting they add an export statement, instead of
the generic "function not found" error.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Allow init_js_project(), should_modify_package_json_config(), and
collect_js_setup_info() to run without interactive prompts when
skip_confirm=True. Uses auto-detected defaults instead of prompting.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add NotImplementedError guard in all 3 test dispatchers (behavioral,
benchmarking, line-profile) for frameworks other than jest and vitest.
Previously, mocha and other frameworks silently fell through to Jest,
causing confusing failures. Now users get a clear error message.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Resolve `module.exports = varName` where varName is an object literal
containing methods. For patterns like `const utils = { match() {} };
module.exports = utils;`, the individual methods are now recognized as
exported. This fixes function discovery for CJS libraries like Moleculer.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Post-process find_functions() to mark functions as exported when they appear
in named export clauses like `export { joinBy }`. This fixes discovery for
TypeScript codebases (e.g., Strapi) that define const arrow functions and
export them via a separate export statement.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
parse_code_and_prune_cst now returns cst.Module instead of str.
add_needed_imports_from_module accepts cst.Module | str, skipping re-parse
when a Module is passed. This eliminates the string round-trip that caused
comments to migrate from statement leading_lines to Module.header,
resulting in comments appearing above imports instead of at their
original position.