diff --git a/backend/tests/problemSolverParser.unit.test.js b/backend/tests/problemSolverParser.unit.test.js index a98e35e9..8361c6a9 100644 --- a/backend/tests/problemSolverParser.unit.test.js +++ b/backend/tests/problemSolverParser.unit.test.js @@ -248,6 +248,27 @@ describe("parseSolverOutput", () => { expect(result.raw).not.toContain("\r"); }); + it("does not start a section at a heading word used inside prose", () => { + const output = [ + "## Approach", + "We decode the string in two steps using a stack.", + "", + "## Steps", + "1. Push digits.", + "", + "## Code", + "```python", + "def solve(s):", + " return s", + "```", + ].join("\n"); + + const { sections } = parseSolverOutput(output); + + expect(sections.steps).toBe("1. Push digits."); + expect(sections.code).toContain("def solve(s):"); + }); + it("finds code using the implementation alias", () => { const output = `## Approach\nBinary search.\n\n## Implementation\n\`\`\`javascript\n// using alias\n\`\`\``; const result = parseSolverOutput(output); diff --git a/backend/utils/problemSolverParser.js b/backend/utils/problemSolverParser.js index b04f601b..7ba65023 100644 --- a/backend/utils/problemSolverParser.js +++ b/backend/utils/problemSolverParser.js @@ -46,8 +46,11 @@ function buildSolverPrompt({ problem, language = DEFAULT_LANGUAGE, constraints = } function extractSection(text, heading) { + // The heading has to be the whole line ("## Steps", "**Steps**", "Steps:"). + // Unanchored, "steps" or "code" also matched inside prose such as "we + // decode the string in two steps", and the section started mid-sentence. const headingPattern = new RegExp( - `(?:#{1,3}\\s*\\**|\\**)[ ]*${heading}[ ]*\\**(?:\\s*:)?`, + `^ {0,3}(?:#{1,3}[ \\t]*)?\\**[ ]*${heading}[ ]*:?[ ]*\\**(?:[ \\t]*:)?[ \\t]*$`, "i" );