Skip to content

Remove duplicated blocks from AI sources (3 of 4), fix three bugs found on the way - #33

Merged
drzo merged 2 commits into
mainfrom
claude/loving-archimedes-r7fcwy
Nov 21, 2026
Merged

drzo merged 2 commits into
mainfrom
claude/loving-archimedes-r7fcwy

Conversation

@drzo

@drzo drzo commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

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

  • Bug fix (non-breaking change which fixes an issue)
  • Code refactoring

Related Issues

Related to #29

Changes Made

Refactor

  • 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. The header gains the two private declarations.
  • koboldcpp_provider.cpp: one JSON string escaper, one finishRequest() for latency / empty-reply / parse-error handling, and one reader per endpoint.
  • rwkv_wrapper.cpp: findWeight(), previousTokenOrZeros() and mixWithPrevious().
  • unified_rag_manager.cpp: queryNarrativeBackend() and queryGeneralBackend().
  • All seven files are then formatted and made cpplint-clean.

The two headers are a different case: please look at this one. In ai_code_generator.hpp and ai_refactoring_engine.hpp the detector flags the list of override declarations that the Template* and AIEnhanced* 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 the AIEnhanced* 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 the Template* classes into their own headers; say so and I will do that instead.

Bug fixes

  • EnhancedAIManager::switch_provider called list_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 throw Json::LogicError out of complete() and chat(). It is now reported as a failed response with an error message.
  • CodeContext::cursorPosition, line and column had no initial value, and the code generator and refactoring engine passed line and column to 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.sh passes.

  • 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 ctest run 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.cpp and unified_rag_manager.cpp are 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.
  • Found and not fixed here, because they change what is sent or cannot be tested:
    • koboldcpp_provider.cpp puts stop_sequences entries and chat role names into the request JSON unescaped, and does not escape control characters other than \n, \r, \t in prompts, so a request body can be invalid JSON.
    • unified_rag_manager.cpp checks top_k after adding a result, so top_k == 0 still returns one result.

Generated by Claude Code

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
@drzo
drzo marked this pull request as ready for review November 21, 2026 18:39
Copilot AI balanced review requested due to automatic review settings November 21, 2026 18:39
@drzo
drzo merged commit 8899d2b into main Nov 21, 2026
53 of 54 checks passed

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 5 potential issues.

Devin Review

@@ -190,17 +194,19 @@ bolt::drawkern::AIInferenceResponse EnhancedAIManager::complete_code(const std::
return response;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 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)

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +20 to +22
// 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 =

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +165 to +171
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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +135 to +156
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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Plain comments for new API docs

The new generator and refactoring override comments use plain // instead of the required Doxygen syntax.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +14 to +19
const std::string& language, size_t maxSuggestions) {
CodeContext aiContext;
aiContext.content = prompt;
aiContext.language = language;
aiContext.cursorPosition = prompt.length();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Conflicting indentation requirements

New helper bodies follow the formatter’s four-space setting, while the contributor guide requires two spaces.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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()) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants