Repository navigation
Remove duplicated blocks from AI sources (3 of 4), fix three bugs found on the way - #33
Conversation
Third batch of the files left unformatted because the copy/paste detector rejects them. - ai_code_generator.cpp: requestCompletions(), firstCompletionLabel() and makeUnavailableResult() replace repeated provider calls and "not available" results. - enhanced_ai_manager.cpp: chat() uses session_history_snapshot() and chat_with_direct_inference() instead of repeating those blocks. - koboldcpp_provider.cpp: one JSON string escaper, one finishRequest() for latency / empty-reply / parse-error handling, and one reader per endpoint. Requests and results were compared before and after against a local server with canned replies and are byte-identical. - rwkv_wrapper.cpp: findWeight(), previousTokenOrZeros() and mixWithPrevious(). - unified_rag_manager.cpp: queryNarrativeBackend() and queryGeneralBackend(). ai_code_generator.hpp and ai_refactoring_engine.hpp are a different case. What the detector flags there is the list of override declarations that the Template* and AIEnhanced* classes each have to repeat; C++ offers nothing to factor out short of moving a class to another header. Those declarations are unchanged. Each override in the AIEnhanced* classes now carries a one-line comment saying what it does, which is also what stops the detector matching the two lists. The declarations themselves are still repeated. rwkv_wrapper.cpp and unified_rag_manager.cpp are not part of the build (the latter did not compile before either: same errors, none new), so their changes are checked by the linters and by reading only. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011vmiZ7F3rQu7dith9sQw71
- EnhancedAIManager::switch_provider called list_providers() four times and compared iterators from the different temporary vectors it returned, which is undefined behaviour. Take one copy and search that. - KoboldCppProvider: a reply that is valid JSON but not an object (a bare array, string or number) made the reply reader throw Json::LogicError out of complete() and chat(). Report it as a failed response with an error message instead. - CodeContext::cursorPosition, line and column had no initial value; the code generator and refactoring engine passed line and column to the provider uninitialised. Default them to 0. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011vmiZ7F3rQu7dith9sQw71
| @@ -190,17 +194,19 @@ bolt::drawkern::AIInferenceResponse EnhancedAIManager::complete_code(const std:: | |||
| return response; | |||
There was a problem hiding this comment.
🔍 Missing regression tests for three fixes
The PR adds no tests for switch_provider, non-object KoboldCpp replies, or default completion coordinates. The testing guide calls for coverage of edge cases and errors.
(Refers to this code)
Was this helpful? React with 👍 or 👎 to provide feedback.
| // there is no state for the layer. | ||
| ggml_tensor* previousTokenOrZeros(ggml_context* ctx, const RWKVState* state, int layer_idx, int n_embd) { | ||
| ggml_tensor* last_x = |
There was a problem hiding this comment.
🔍 RWKV build coverage is unclear
The PR lists the RWKV wrapper as unbuilt, but the llama.cpp build option includes it in bolt_lib. The test report does not identify that option’s setting.
Was this helpful? React with 👍 or 👎 to provide feedback.
| result.error = "JSON parse error: " + errors; | ||
| } else if (!root.isObject()) { | ||
| // Valid JSON, but not the object every endpoint replies with (for | ||
| // example a bare array or string). Looking up members in it throws. | ||
| result.success = false; | ||
| result.error = "Unexpected response from server: not a JSON object"; | ||
| } else { |
There was a problem hiding this comment.
🔍 Malformed nested replies still throw
finishRequest rejects non-object roots, but readOpenAICompletionReply still throws when the first choice is a number. The chat and native readers also assume object entries.
Was this helpful? React with 👍 or 👎 to provide feedback.
| public: | ||
| AIEnhancedCodeGenerator(); | ||
| explicit AIEnhancedCodeGenerator(std::unique_ptr<AICompletionProvider> provider); | ||
|
|
||
| void setAIProvider(std::unique_ptr<AICompletionProvider> provider); | ||
|
|
||
| // AICodeGenerator interface | ||
| GeneratedCode generateFunction( | ||
| const std::string& description, | ||
| const CodeGenerationContext& context = {} | ||
| ) override; | ||
|
|
||
| GeneratedCode generateClass( | ||
| const std::string& className, | ||
| const std::string& description, | ||
| const CodeGenerationContext& context = {} | ||
| ) override; | ||
|
|
||
| GeneratedCode generateMethod( | ||
| const std::string& methodName, | ||
| const std::string& description, | ||
| const std::string& className, | ||
| const CodeGenerationContext& context = {} | ||
| ) override; | ||
|
|
||
| GeneratedCode generateTemplate( | ||
| const std::string& templateType, | ||
| const CodeGenerationContext& context = {} | ||
| ) override; | ||
|
|
||
| std::string generateDocumentation( | ||
| const std::string& code, | ||
| const CodeGenerationContext& context = {} | ||
| ) override; | ||
|
|
||
| std::string explainCode( | ||
| const std::string& code, | ||
| const CodeGenerationContext& context = {} | ||
| ) override; | ||
|
|
||
|
|
||
| // AICodeGenerator interface. Unless noted, a call asks the AI provider first when it is ready, and the template | ||
| // generator answers when the provider has nothing and fallback is enabled. | ||
|
|
||
| // A function matching the description. | ||
| GeneratedCode generateFunction(const std::string& description, const CodeGenerationContext& context = {}) override; | ||
|
|
||
| // A class called className. | ||
| GeneratedCode generateClass(const std::string& className, const std::string& description, | ||
| const CodeGenerationContext& context = {}) override; | ||
|
|
||
| // A method called methodName for the class className. | ||
| GeneratedCode generateMethod(const std::string& methodName, const std::string& description, | ||
| const std::string& className, const CodeGenerationContext& context = {}) override; | ||
|
|
||
| // Never uses the AI provider: always produced by the template generator, whatever the fallback setting. | ||
| GeneratedCode generateTemplate(const std::string& templateType, const CodeGenerationContext& context = {}) override; |
There was a problem hiding this comment.
🔍 Plain comments for new API docs
The new generator and refactoring override comments use plain // instead of the required Doxygen syntax.
Was this helpful? React with 👍 or 👎 to provide feedback.
| const std::string& language, size_t maxSuggestions) { | ||
| CodeContext aiContext; | ||
| aiContext.content = prompt; | ||
| aiContext.language = language; | ||
| aiContext.cursorPosition = prompt.length(); | ||
|
|
There was a problem hiding this comment.
🔍 Conflicting indentation requirements
New helper bodies follow the formatter’s four-space setting, while the contributor guide requires two spaces.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
🟡 Changes recommended
The new non-object JSON response branch lacks regression coverage for complete() and chat() in both API modes, because existing tests exit through the empty-response path without exercising JSON parsing.
1 open issue
What changed in this PR
This PR continues the AI code cleanup from #29, following #31 and #32. It extracts duplicated implementation blocks for lint compliance and separately fixes three correctness issues.
Changes:
- Introduces shared helpers for code generation, chat history, KoboldCpp responses, RWKV operations, and RAG queries.
- Fixes provider-list iterator misuse, rejects non-object JSON replies, and initializes code-context coordinates.
- Formats the affected code and documents repeated override declarations without changing their signatures.
| File | Description |
|---|---|
src/bolt/ai/unified_rag_manager.cpp |
Extracts narrative and semantic result-conversion helpers. |
src/bolt/ai/rwkv_wrapper.cpp |
Shares weight lookup, prior-token lookup, and tensor-mixing logic. |
src/bolt/ai/koboldcpp_provider.cpp |
Consolidates request/response handling and rejects non-object JSON replies. |
src/bolt/ai/enhanced_ai_manager.cpp |
Shares direct-chat helpers and fixes provider-list iterator misuse. |
src/bolt/ai/ai_code_generator.cpp |
Consolidates completion requests and unavailable results. |
include/bolt/ai/enhanced_ai_manager.hpp |
Declares the new private chat helpers. |
include/bolt/ai/ai_refactoring_engine.hpp |
Documents unchanged overrides and standardizes formatting and guards. |
include/bolt/ai/ai_completion_provider.hpp |
Defaults cursor position, line, and column to zero. |
include/bolt/ai/ai_code_generator.hpp |
Documents unchanged overrides and standardizes formatting and guards. |
Review effort: Balanced
| std::string errors; | ||
| if (!parseJson(response_str, root, errors)) { | ||
| result.error = "JSON parse error: " + errors; | ||
| } else if (!root.isObject()) { |

Description
Third of four pull requests that refactor the files left unformatted because the linter's copy/paste detector rejects them (previous: #31, #32). This batch covers seven AI files, and fixes three bugs found while reading them.
Two commits, meant to be read separately: the refactor (no behaviour change intended) and the bug fixes (deliberate behaviour changes).
Type of Change
Related Issues
Related to #29
Changes Made
Refactor
ai_code_generator.cpp:requestCompletions(),firstCompletionLabel()andmakeUnavailableResult()replace repeated provider calls and "not available" results.enhanced_ai_manager.cpp:chat()usessession_history_snapshot()andchat_with_direct_inference()instead of repeating those blocks. The header gains the two private declarations.koboldcpp_provider.cpp: one JSON string escaper, onefinishRequest()for latency / empty-reply / parse-error handling, and one reader per endpoint.rwkv_wrapper.cpp:findWeight(),previousTokenOrZeros()andmixWithPrevious().unified_rag_manager.cpp:queryNarrativeBackend()andqueryGeneralBackend().The two headers are a different case: please look at this one. In
ai_code_generator.hppandai_refactoring_engine.hppthe detector flags the list ofoverridedeclarations that theTemplate*andAIEnhanced*classes each have to repeat. C++ gives nothing to factor out there short of moving a class into another header. The declarations are unchanged. Each override in theAIEnhanced*classes now has a one-line comment saying what it does, and those comments are also what stops the detector matching the two lists. So the detector passes, but the declarations are still repeated. If you would rather have a structural fix, the option is to move theTemplate*classes into their own headers; say so and I will do that instead.Bug fixes
EnhancedAIManager::switch_providercalledlist_providers()four times and compared iterators from the different temporary vectors it returned, which is undefined behaviour. It now takes one copy and searches that.KoboldCppProvider: a reply that is valid JSON but not an object (a bare array, string or number) made the reply reader throwJson::LogicErrorout ofcomplete()andchat(). It is now reported as a failed response with an error message.CodeContext::cursorPosition,lineandcolumnhad no initial value, and the code generator and refactoring engine passedlineandcolumnto the provider uninitialised. They now default to 0.Testing
All existing tests pass
Manual testing performed
Locally on Linux (GCC): 98/98 CTest tests, including the 13 KoboldCpp suites and the 15 tests labelled AI;
scripts/smoke_test.shpasses.KoboldCpp refactor: the old and new provider were each run against a local HTTP server with canned replies in both API modes; the requests sent and the results returned were byte-identical. The code generator was compared the same way with a mock provider.
clang-format 15.0.7, cpplint 1.6.1 and jscpd 3.5.3 report nothing on the changed files.
Not covered by a test: the three bug fixes have no dedicated test in this PR.
One parallel
ctestrun during verification reported 1 of 98 failed; nine further runs all passed and I could not identify which test it was. It coincided with another test run on the same machine, and several tests still write to fixed paths under/tmp, which is the likeliest cause. Noted here rather than hidden.Reviewer Notes
rwkv_wrapper.cppandunified_rag_manager.cppare not part of the build (the latter did not compile before either: same errors, none new). Their changes are checked by the linters and by reading only.koboldcpp_provider.cppputsstop_sequencesentries and chat role names into the request JSON unescaped, and does not escape control characters other than\n,\r,\tin prompts, so a request body can be invalid JSON.unified_rag_manager.cppcheckstop_kafter adding a result, sotop_k == 0still returns one result.Generated by Claude Code