Skip to content

test: add 54 unit tests for IdeationEngine and Analyzers#518

Open
nikolasdehor wants to merge 2 commits intoSynkraAI:mainfrom
nikolasdehor:test/ideation-engine-coverage
Open

test: add 54 unit tests for IdeationEngine and Analyzers#518
nikolasdehor wants to merge 2 commits intoSynkraAI:mainfrom
nikolasdehor:test/ideation-engine-coverage

Conversation

@nikolasdehor
Copy link
Contributor

@nikolasdehor nikolasdehor commented Feb 25, 2026

Descrição

Suite de testes abrangente para o módulo ideation-engine — o maior módulo sem cobertura (832 linhas, 6 classes).

Cobertura

Classe Testes O que cobre
IdeationEngine 31 constructor, calculatePriority, isKnownGotcha, countByArea, formatSuggestion, formatMarkdown, ideate, save
PerformanceAnalyzer 3 sync ops detection, threshold, error handling
SecurityAnalyzer 3 hardcoded secrets, eval usage, dependency vulns
CodeQualityAnalyzer 2 large files, excessive console.log
ArchitectureAnalyzer 2 circular deps, layer violations
Total 54

Destaques

Bugs encontrados

Nota técnica

Requer --transform='{}' por ausência de babel.config.js no projeto (o jest.config padrão usa babel-jest como transform, mas o config não existe). Isso afeta TODOS os testes que carregam módulos em .aios-core/core/ideation/.

PASS tests/core/ideation/ideation-engine.test.js
Tests: 54 passed, 54 total

Summary by CodeRabbit

  • Tests
    • Added a comprehensive Jest test suite for the ideation engine covering constructor behavior, priority calculations, gotcha detection, counting by area, suggestion/Markdown formatting, orchestration (filtering, sorting, per-area summaries), save behavior and file outputs, individual analyzer detections, memory interactions, and extensive edge-case and failure-mode scenarios with I/O mocking.

Cobre IdeationEngine (orquestrador) + PerformanceAnalyzer,
SecurityAnalyzer, CodeQualityAnalyzer, UXAnalyzer e ArchitectureAnalyzer.

Testes incluem:
- calculatePriority: quick-wins, effort multipliers, defaults
- isKnownGotcha: word overlap detection, edge cases
- countByArea: aggregação por área
- formatSuggestion/formatMarkdown: output formatting
- ideate: orquestração, filtragem de gotchas, save
- Analyzers: detecção de sync ops, secrets, eval, vulns, etc.

NOTA: Requer --transform='{}' por falta de babel.config no projeto.
Copilot AI review requested due to automatic review settings February 25, 2026 22:26
@vercel
Copy link

vercel bot commented Feb 25, 2026

@nikolasdehor is attempting to deploy a commit to the Pedro Valério Lopez's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link

coderabbitai bot commented Feb 25, 2026

Walkthrough

Adds a comprehensive Jest test suite for the ideation-engine module (new tests covering constructor, analyzers, formatting, orchestration, memory, and save behavior; mocks for execSync, fs, and memory).

Changes

Cohort / File(s) Summary
Ideation Engine Test Suite
tests/core/ideation/ideation-engine.test.js
New comprehensive Jest tests that mock GotchasMemory, child_process.execSync, and fs; validate IdeationEngine constructor, calculatePriority, isKnownGotcha, countByArea, formatSuggestion/formatMarkdown, ideate orchestration (filtering, sorting, error paths, memory interactions), save behavior (dir creation and JSON/Markdown outputs), and individual analyzer behaviors (Performance, Security, CodeQuality, Architecture) including many edge cases.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Suggested labels

core, tests

Suggested reviewers

  • Pedrovaleriolopez
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding 54 unit tests for the IdeationEngine and Analyzer classes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adiciona uma suíte de testes unitários para o módulo .aios-core/core/ideation/ideation-engine.js, cobrindo o IdeationEngine (orquestração/formatters/salvamento) e validando o comportamento dos analyzers principais sem executar I/O real (mock de execSync e fs).

Changes:

  • Cria tests/core/ideation/ideation-engine.test.js com cobertura para IdeationEngine (constructor, calculatePriority, isKnownGotcha, countByArea, formatSuggestion, formatMarkdown, ideate, save).
  • Inclui testes para PerformanceAnalyzer, SecurityAnalyzer, CodeQualityAnalyzer e ArchitectureAnalyzer usando execSync mockado.
  • Mock de gotchas-memory para isolar o carregamento do ideation-engine durante os testes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +34 to +40
beforeEach(() => {
jest.clearAllMocks();
execSyncSpy.mockReturnValue('');
engine = new IdeationEngine({
rootPath: '/fake/project',
gotchasMemory: null,
});
Copy link

Copilot AI Feb 25, 2026

Choose a reason for hiding this comment

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

jest.clearAllMocks() não reseta implementações; como alguns testes alteram fs.existsSync.mockReturnValue(false), esse estado pode vazar para testes seguintes dentro do mesmo describe('IdeationEngine'). Para manter isolamento e evitar flakiness/ordem-dependência, reconfigure explicitamente os retornos padrão dos spies de fs (ex.: existsSync voltar a true) no beforeEach, ou use uma estratégia que resete implementações (com re-spy em seguida).

Copilot uses AI. Check for mistakes.
Comment on lines +376 to +381
engine.analyzers.security.analyze = jest.fn().mockRejectedValue(
new Error('analysis failed'),
);

const result = await engine.ideate({ focus: 'security', save: false });
expect(result.allSuggestions.length).toBe(0);
Copy link

Copilot AI Feb 25, 2026

Choose a reason for hiding this comment

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

Este teste força um analyze() rejeitar e o IdeationEngine.ideate() vai emitir console.warn(...) (comportamento esperado). Para evitar ruído no output do Jest/CI, vale mockar console.warn localmente (e restaurar depois) ou no beforeEach deste bloco.

Suggested change
engine.analyzers.security.analyze = jest.fn().mockRejectedValue(
new Error('analysis failed'),
);
const result = await engine.ideate({ focus: 'security', save: false });
expect(result.allSuggestions.length).toBe(0);
const originalWarn = console.warn;
console.warn = jest.fn();
try {
engine.analyzers.security.analyze = jest.fn().mockRejectedValue(
new Error('analysis failed'),
);
const result = await engine.ideate({ focus: 'security', save: false });
expect(result.allSuggestions.length).toBe(0);
} finally {
console.warn = originalWarn;
}

Copilot uses AI. Check for mistakes.
Copy link

@coderabbitai coderabbitai bot left a 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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/core/ideation/ideation-engine.test.js`:
- Around line 13-16: Replace the current null mock with a constructor-shaped
mock so tests catch import/export mismatches: update the jest.mock for
gotchas-memory to return a module object that provides a class constructor named
GotchasMemory and also exposes that constructor as the default export (so
ideation-engine's `new GotchasMemory()` and any default-import usage both
behave). Locate the jest.mock call in the test file (mocking gotchas-memory) and
return an object with GotchasMemory: class { /* empty stub */ } and default: the
same class.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 63db79b and 149e379.

📒 Files selected for processing (1)
  • tests/core/ideation/ideation-engine.test.js

1. Mock gotchas-memory com shape de constructor em vez de null —
   funciona com import atual (sem destructuring) e com fix SynkraAI#519
   (com destructuring). Captura mismatch de import/export.

2. Reconfigurar spies de fs no beforeEach (existsSync, mkdirSync,
   writeFileSync) para evitar leak de estado entre testes após
   clearAllMocks limpar as implementações.

3. Suprimir console.warn no teste de analyzer rejection para
   evitar ruído no output do CI.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
tests/core/ideation/ideation-engine.test.js (1)

386-395: Harden console.warn spy cleanup with try/finally.

If an assertion fails before cleanup, console.warn can stay mocked and affect later tests. Prefer guaranteed restoration.

🔧 Suggested change
-    test('captura erros de analyzers sem propagar', async () => {
-      const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
-      engine.analyzers.security.analyze = jest.fn().mockRejectedValue(
-        new Error('analysis failed'),
-      );
-
-      const result = await engine.ideate({ focus: 'security', save: false });
-      expect(result.allSuggestions.length).toBe(0);
-      warnSpy.mockRestore();
-    });
+    test('captura erros de analyzers sem propagar', async () => {
+      const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
+      try {
+        engine.analyzers.security.analyze = jest.fn().mockRejectedValue(
+          new Error('analysis failed'),
+        );
+
+        const result = await engine.ideate({ focus: 'security', save: false });
+        expect(result.allSuggestions.length).toBe(0);
+      } finally {
+        warnSpy.mockRestore();
+      }
+    });

As per coding guidelines, "Verify error handling is comprehensive."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/core/ideation/ideation-engine.test.js` around lines 386 - 395, The test
"captura erros de analyzers sem propagar" currently mocks console.warn via
warnSpy but can leak the mock if an assertion throws; wrap the body that calls
engine.ideate and assertions in a try/finally so warnSpy.mockRestore() is always
executed. Locate the test block (the test function that sets warnSpy via
jest.spyOn and stubs engine.analyzers.security.analyze) and move/make the
mockRestore call into a finally clause after the await engine.ideate(...) and
expect(...) so console.warn is restored regardless of test outcome.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tests/core/ideation/ideation-engine.test.js`:
- Around line 386-395: The test "captura erros de analyzers sem propagar"
currently mocks console.warn via warnSpy but can leak the mock if an assertion
throws; wrap the body that calls engine.ideate and assertions in a try/finally
so warnSpy.mockRestore() is always executed. Locate the test block (the test
function that sets warnSpy via jest.spyOn and stubs
engine.analyzers.security.analyze) and move/make the mockRestore call into a
finally clause after the await engine.ideate(...) and expect(...) so
console.warn is restored regardless of test outcome.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 149e379 and c496dd6.

📒 Files selected for processing (1)
  • tests/core/ideation/ideation-engine.test.js

@Pedrovaleriolopez
Copy link
Contributor

Aguardando Dependência

@nikolasdehor Este PR depende do #521 (fix: destructuring import GotchasMemory) que ainda precisa de rebase. Uma vez que o #521 for mergeado, este PR pode ser atualizado e mergeado.

Status: Aprovado, aguardando resolução da dependência #521.

— Gage (DevOps)

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.

3 participants