Skip to content

fix(ideation): corrigir import de GotchasMemory como named export#519

Closed
nikolasdehor wants to merge 1 commit intoSynkraAI:mainfrom
nikolasdehor:fix/ideation-gotchas-import
Closed

fix(ideation): corrigir import de GotchasMemory como named export#519
nikolasdehor wants to merge 1 commit intoSynkraAI:mainfrom
nikolasdehor:fix/ideation-gotchas-import

Conversation

@nikolasdehor
Copy link
Contributor

@nikolasdehor nikolasdehor commented Feb 25, 2026

Problema

gotchas-memory.js exporta usando named exports:

module.exports = { GotchasMemory, GotchaCategory, Severity, Events, CONFIG };

Mas ideation-engine.js importa sem destructuring:

GotchasMemory = require('../memory/gotchas-memory');

Isso faz com que GotchasMemory receba o objeto do módulo inteiro em vez da classe. Na linha 30, new GotchasMemory() tenta instanciar o objeto do módulo → TypeError.

Correção

Aplicar destructuring no require:

({ GotchasMemory } = require('../memory/gotchas-memory'));

Testes

Rodei os 54 testes do ideation-engine (PR #518) com este fix aplicado — todos passam.

Closes #517

Summary by CodeRabbit

Release Notes

No user-visible changes in this release. This update includes internal code organization improvements to enhance maintainability.

gotchas-memory.js exporta { GotchasMemory } (named export) mas
ideation-engine.js usava require() sem destructuring, recebendo o
objeto do módulo em vez da classe. Isso causa TypeError ao tentar
instanciar com new GotchasMemory().

Corrige aplicando destructuring no require:
  ({ GotchasMemory } = require('../memory/gotchas-memory'))

Closes SynkraAI#517
Copilot AI review requested due to automatic review settings February 25, 2026 22:31
@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

The import statement for GotchasMemory in the ideation engine is corrected to use destructuring assignment, properly extracting the named export from the gotchas-memory module instead of assigning the entire export object.

Changes

Cohort / File(s) Summary
Import Statement Fix
.aios-core/core/ideation/ideation-engine.js
Changed GotchasMemory import from direct assignment to destructuring (({ GotchasMemory } = require(...))), correctly extracting the named export from gotchas-memory module to enable proper class instantiation.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main change: fixing the GotchasMemory import to use named export destructuring, which directly addresses the core issue in the changeset.
Linked Issues check ✅ Passed The code change fully implements the suggested correction from issue #517 by applying destructuring to the require statement, ensuring GotchasMemory receives the class instead of the module object.
Out of Scope Changes check ✅ Passed The pull request contains only the necessary import fix to address issue #517; no extraneous or out-of-scope changes are present.
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

Este PR corrige um bug no IdeationEngine onde o módulo gotchas-memory.js era importado como se fosse default export, apesar de ele expor GotchasMemory como named export. Isso causava falha ao tentar instanciar GotchasMemory e degradava silenciosamente a funcionalidade de filtragem de gotchas conhecidos (Issue #517).

Changes:

  • Ajusta o require de ../memory/gotchas-memory para usar destructuring e obter a classe GotchasMemory corretamente.

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

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
.aios-core/core/ideation/ideation-engine.js (4)

504-533: ⚠️ Potential issue | 🟠 Major

JSON.parse on npm audit output may throw on non-JSON content.

npm audit can prefix its JSON with deprecation warnings or other plain-text lines in some npm versions, making auditResult not strictly valid JSON. While the outer catch swallows any resulting SyntaxError, it also silently discards legitimate vulnerability data, defeating the purpose of this check.

🛡️ Proposed defensive parse
-      const audit = JSON.parse(auditResult);
+      // npm can prepend non-JSON warnings; extract only the JSON portion
+      const jsonStart = auditResult.indexOf('{');
+      if (jsonStart === -1) return findings;
+      const audit = JSON.parse(auditResult.slice(jsonStart));
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.aios-core/core/ideation/ideation-engine.js around lines 504 - 533, The
JSON.parse can fail on npm audit output with leading non-JSON lines; update
checkDependencyVulnerabilities to defensively extract the JSON payload from
auditResult (returned by execSync) before parsing — e.g., trim output, locate
the first '{' (or first '[') and parse the substring from that index, handle
empty or non-JSON results by returning no findings, and keep the outer try/catch
but avoid silently swallowing valid vulnerability data; refer to
checkDependencyVulnerabilities, execSync, auditResult and audit when
implementing this fix.

63-69: ⚠️ Potential issue | 🔴 Critical

summary.quickWins will always be 0 — mutation after spread does not propagate.

JavaScript evaluates object-literal properties left-to-right. In the expression:

{ ...f, area, priority: this.calculatePriority(f) }

...f is spread (snapshotting f's properties) before calculatePriority(f) is invoked. calculatePriority then mutates f.category = 'quick-win' on Line 126, but that mutation has no effect on the already-created snapshot. Consequently, no suggestion object in the suggestions array ever carries category: 'quick-win', and summary.quickWins (Line 97, filtered by s.category === 'quick-win') is always 0.

The fix is to either include category explicitly after calling calculatePriority, or move the category assignment outside the mutating function.

🐛 Proposed fix
-      const findings = await analyzer.analyze();
-      suggestions.push(
-        ...findings.map((f) => ({
-          ...f,
-          area,
-          priority: this.calculatePriority(f),
-        })),
-      );
+      const findings = await analyzer.analyze();
+      suggestions.push(
+        ...findings.map((f) => {
+          const priority = this.calculatePriority(f);
+          return {
+            ...f,           // spread after calculatePriority so mutated category is included
+            area,
+            priority,
+          };
+        }),
+      );

And in calculatePriority, return category explicitly rather than relying on side-effect mutation:

 calculatePriority(finding) {
   const impact = finding.impact || 0.5;
   const effortMultiplier = { low: 1.5, medium: 1.0, high: 0.6 }[finding.effort] || 1.0;

   if (finding.effort === 'low' && impact >= 0.7) {
-    finding.category = 'quick-win';
-    return impact * 1.5;
+    finding.category = 'quick-win'; // keep for callers that rely on the side-effect being spread after this call
+    return impact * 1.5;
   }

   return impact * effortMultiplier;
 }

As per coding guidelines, .aios-core/core/** is a CRITICAL PATH and requires thorough review of logic correctness.

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

In @.aios-core/core/ideation/ideation-engine.js around lines 63 - 69, The
suggestions mapping spreads f before calculatePriority mutates f, so category
set inside calculatePriority never makes it into the created suggestion objects
(causing summary.quickWins to be 0); fix by having calculatePriority return the
computed category (or compute category separately) and include that returned
category explicitly when building each suggestion in the mapping (e.g., call
this.calculatePriority(f) -> { priority, category } and then push { ...f, area,
priority, category }), or alternatively set category on the suggestion after
calling calculatePriority rather than relying on mutation; update usages of
calculatePriority accordingly.

283-313: ⚠️ Potential issue | 🟠 Major

Shell injection via unsanitised this.rootPath across all analyzer execSync calls.

this.rootPath is interpolated directly into shell command strings (e.g., Line 289, and equivalently on Lines 322, 353, 386, 559, 595, 623, 672, 705, 767, 800). A path containing shell metacharacters (;, $, backticks, spaces) would allow arbitrary command execution. Because rootPath defaults to process.cwd() but can also be supplied via config.rootPath (Line 24), any caller controlling that value can trigger injection.

Sanitise the path before interpolation, or use spawnSync with argument arrays to avoid shell interpretation entirely.

🛡️ Suggested approach — use spawnSync with argument arrays
-const { execSync } = require('child_process');
+const { spawnSync } = require('child_process');

Replace each execSync grep call with a spawnSync equivalent. Example for checkSyncOperations:

-      const result = execSync(
-        `grep -rn "readFileSync\\|writeFileSync\\|existsSync" --include="*.js" --include="*.ts" ${this.rootPath}/src ${this.rootPath}/.aios-core 2>/dev/null || true`,
-        { encoding: 'utf8', maxBuffer: 5 * 1024 * 1024 },
-      );
+      const proc = spawnSync(
+        'grep',
+        ['-rn', 'readFileSync|writeFileSync|existsSync', '--include=*.js', '--include=*.ts',
+         `${this.rootPath}/src`, `${this.rootPath}/.aios-core`],
+        { encoding: 'utf8', maxBuffer: 5 * 1024 * 1024 },
+      );
+      const result = proc.stdout || '';

As per coding guidelines, .aios-core/core/** requires input validation on public API methods.

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

In @.aios-core/core/ideation/ideation-engine.js around lines 283 - 313, The
execSync invocations (e.g., in checkSyncOperations) interpolate this.rootPath
into shell strings, enabling shell injection; replace those execSync grep calls
with child_process.spawnSync using argument arrays (pass grep pattern and
--include and paths as separate args) or else strictly sanitize/validate
this.rootPath (e.g., resolve with path.resolve and reject or escape any unsafe
metacharacters) before use; update the methods that call execSync
(checkSyncOperations and the other analyzer methods that use execSync) to
preserve encoding/maxBuffer behavior, capture stdout/stderr from spawnSync, and
handle errors explicitly instead of an empty catch so the analyzer remains safe
and robust.

470-501: ⚠️ Potential issue | 🟡 Minor

Missing maxBuffer on checkInsecurePatterns execSync call.

Line 475's execSync for eval usage omits a maxBuffer option. On large codebases the default 1 MB buffer can be exceeded, causing a silent exception that is swallowed by the catch block, meaning real eval() usages would go unreported.

🛡️ Proposed fix
       const evalResult = execSync(
         `grep -rn "\\beval\\s*(" --include="*.js" --include="*.ts" ${this.rootPath} 2>/dev/null || true`,
         {
           encoding: 'utf8',
+          maxBuffer: 5 * 1024 * 1024,
         },
       );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.aios-core/core/ideation/ideation-engine.js around lines 470 - 501, The
execSync call inside checkInsecurePatterns (the one that assigns evalResult) is
missing a maxBuffer option which can cause silent failures on large repos;
update that execSync invocation to include a sufficiently large maxBuffer (e.g.
10 * 1024 * 1024) in its options object (alongside encoding), and apply the same
maxBuffer addition to any other execSync calls in checkInsecurePatterns to avoid
swallowed exceptions and ensure findings are reported.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In @.aios-core/core/ideation/ideation-engine.js:
- Around line 504-533: The JSON.parse can fail on npm audit output with leading
non-JSON lines; update checkDependencyVulnerabilities to defensively extract the
JSON payload from auditResult (returned by execSync) before parsing — e.g., trim
output, locate the first '{' (or first '[') and parse the substring from that
index, handle empty or non-JSON results by returning no findings, and keep the
outer try/catch but avoid silently swallowing valid vulnerability data; refer to
checkDependencyVulnerabilities, execSync, auditResult and audit when
implementing this fix.
- Around line 63-69: The suggestions mapping spreads f before calculatePriority
mutates f, so category set inside calculatePriority never makes it into the
created suggestion objects (causing summary.quickWins to be 0); fix by having
calculatePriority return the computed category (or compute category separately)
and include that returned category explicitly when building each suggestion in
the mapping (e.g., call this.calculatePriority(f) -> { priority, category } and
then push { ...f, area, priority, category }), or alternatively set category on
the suggestion after calling calculatePriority rather than relying on mutation;
update usages of calculatePriority accordingly.
- Around line 283-313: The execSync invocations (e.g., in checkSyncOperations)
interpolate this.rootPath into shell strings, enabling shell injection; replace
those execSync grep calls with child_process.spawnSync using argument arrays
(pass grep pattern and --include and paths as separate args) or else strictly
sanitize/validate this.rootPath (e.g., resolve with path.resolve and reject or
escape any unsafe metacharacters) before use; update the methods that call
execSync (checkSyncOperations and the other analyzer methods that use execSync)
to preserve encoding/maxBuffer behavior, capture stdout/stderr from spawnSync,
and handle errors explicitly instead of an empty catch so the analyzer remains
safe and robust.
- Around line 470-501: The execSync call inside checkInsecurePatterns (the one
that assigns evalResult) is missing a maxBuffer option which can cause silent
failures on large repos; update that execSync invocation to include a
sufficiently large maxBuffer (e.g. 10 * 1024 * 1024) in its options object
(alongside encoding), and apply the same maxBuffer addition to any other
execSync calls in checkInsecurePatterns to avoid swallowed exceptions and ensure
findings are reported.

ℹ️ 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 961e4fc.

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

nikolasdehor added a commit to nikolasdehor/aios-core that referenced this pull request Feb 25, 2026
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.
@nikolasdehor
Copy link
Contributor Author

Fechando como duplicata — substituído pelo PR #521 que corrige o bug em todos os 3 módulos (ideation-engine, context-injector, subagent-dispatcher).

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.

bug: ideation-engine falha ao instanciar GotchasMemory (export named vs default)

2 participants