From f838f854dd2a95061e99db97ccb38954457d3d93 Mon Sep 17 00:00:00 2001 From: Bryan Ramirez-Gonzalez Date: Wed, 14 Oct 2026 23:32:54 -0700 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20handle=20ask=20ai=20answers=20that?= =?UTF-8?q?=20don't=20match=20the=20metadata=20format=20=F0=9F=90=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The model sometimes wraps the metadata JSON in a ```json code fence, which made parseAnswerForMemberProfile fail with "Failed to parse thread metadata into JSON." instead of showing the answer. - Strip the code fence with stripCodeFence before parsing the metadata. - Show output without any metadata as an answer with no sources. - Report the raw output when it still can't be parsed. - Tell the model not to put the JSON in a code block. - Add tests for parseAnswerForMemberProfile. --- packages/core/src/modules/slack/slack.test.ts | 317 ++++++++++++++++++ packages/core/src/modules/slack/slack.ts | 81 +++-- 2 files changed, 371 insertions(+), 27 deletions(-) create mode 100644 packages/core/src/modules/slack/slack.test.ts diff --git a/packages/core/src/modules/slack/slack.test.ts b/packages/core/src/modules/slack/slack.test.ts new file mode 100644 index 000000000..9eb7a775e --- /dev/null +++ b/packages/core/src/modules/slack/slack.test.ts @@ -0,0 +1,317 @@ +import { beforeEach, describe, expect, spyOn, test } from 'bun:test'; +import dedent from 'dedent'; + +import { slack } from '@/modules/slack/instances'; +import { + type ChatbotAnswerSegment, + parseAnswerForMemberProfile, +} from '@/modules/slack/slack'; + +const METADATA = dedent` + { + "threads": [ + { "channelId": "C123", "threadId": "1700000000.000100", "number": 1 }, + { "channelId": "C456", "threadId": "1700000000.000200", "number": 2 } + ], + "ok": true + } +`; + +const ANSWER = + 'Quant firms usually recruit in the summer [ref:1]. ' + + 'Some open applications in July [ref:2].'; + +const PERMALINK = 'https://colorstack-family.slack.com/archives/C123/p1'; + +const EXPECTED_SEGMENTS: ChatbotAnswerSegment[] = [ + { type: 'text', content: 'Quant firms usually recruit in the summer ' }, + { type: 'reference', number: 1 }, + { type: 'text', content: '. Some open applications in July ' }, + { type: 'reference', number: 2 }, + { type: 'text', content: '.' }, +]; + +beforeEach(() => { + spyOn(slack.chat, 'getPermalink').mockResolvedValue({ + ok: true, + permalink: PERMALINK, + }); + + // Silences the error reports from the failure cases. + spyOn(console, 'error').mockImplementation(() => {}); +}); + +describe(parseAnswerForMemberProfile.name, () => { + test('Should parse the documented format.', async () => { + const result = await parseAnswerForMemberProfile( + `${METADATA}\n---\n${ANSWER}` + ); + + expect(result).toEqual({ + ok: true, + data: { + answerSegments: EXPECTED_SEGMENTS, + threads: [ + { + authorFirstName: '', + authorLastName: '', + authorProfilePicture: '', + createdAt: '', + number: 1, + replyCount: 0, + text: '', + url: PERMALINK, + }, + { + authorFirstName: '', + authorLastName: '', + authorProfilePicture: '', + createdAt: '', + number: 2, + replyCount: 0, + text: '', + url: PERMALINK, + }, + ], + }, + }); + }); + + test('Should parse metadata wrapped in a code fence.', async () => { + const expected = await parseAnswerForMemberProfile( + `${METADATA}\n---\n${ANSWER}` + ); + + const result = await parseAnswerForMemberProfile( + '```json\n' + METADATA + '\n```\n---\n' + ANSWER + ); + + expect(result).toEqual(expected); + }); + + // This is the shape that the LLM returned for "What can you tell me about + // the P&G It Security Internship OA?" when no thread was relevant. + test('Should parse fenced metadata with no threads.', async () => { + const result = await parseAnswerForMemberProfile( + '```json\n{\n "threads": [],\n "ok": true\n}\n```\n---\n\n' + + "I wasn't able to find any specific information about the P&G IT " + + 'Security Internship OA in our Slack history.' + ); + + expect(result).toEqual({ + ok: true, + data: { + answerSegments: [ + { + type: 'text', + content: + "I wasn't able to find any specific information about the P&G " + + 'IT Security Internship OA in our Slack history.', + }, + ], + threads: [], + }, + }); + }); + + test('Should parse a delimiter with surrounding whitespace.', async () => { + const expected = await parseAnswerForMemberProfile( + `${METADATA}\n---\n${ANSWER}` + ); + + const result = await parseAnswerForMemberProfile( + `${METADATA}\r\n --- \r\n${ANSWER}` + ); + + expect(result).toEqual(expected); + }); + + test('Should parse a delimiter that is not on its own line.', async () => { + const expected = await parseAnswerForMemberProfile( + `${METADATA}\n---\n${ANSWER}` + ); + + const result = await parseAnswerForMemberProfile(`${METADATA}---${ANSWER}`); + + expect(result).toEqual(expected); + }); + + test('Should keep a "---" that is part of the answer.', async () => { + const result = await parseAnswerForMemberProfile( + `${METADATA}\n---\nFirst part [ref:1].\n\n---\n\nSecond part --- done.` + ); + + expect(result.ok && result.data.answerSegments).toEqual([ + { type: 'text', content: 'First part ' }, + { type: 'reference', number: 1 }, + { type: 'text', content: '.\n\n---\n\nSecond part --- done.' }, + ]); + }); + + test('Should return an answer with no sources if there are no threads.', async () => { + const result = await parseAnswerForMemberProfile( + `{ "threads": [], "ok": true }\n---\nI couldn't find that in our Slack history.` + ); + + expect(result).toEqual({ + ok: true, + data: { + answerSegments: [ + { + type: 'text', + content: "I couldn't find that in our Slack history.", + }, + ], + threads: [], + }, + }); + }); + + test('Should return an answer with no sources if there is no metadata.', async () => { + const output = "I couldn't find anything about the P&G OA in our Slack."; + + const result = await parseAnswerForMemberProfile(output); + + expect(result).toEqual({ + ok: true, + data: { + answerSegments: [{ type: 'text', content: output }], + threads: [], + }, + }); + }); + + test('Should keep the whole answer if there is no metadata but there is a divider.', async () => { + const output = dedent` + I couldn't find anything about the P&G OA in our Slack. + + --- + + In general, practice timed problems before taking an OA. + `; + + const result = await parseAnswerForMemberProfile(output); + + expect(result).toEqual({ + ok: true, + data: { + answerSegments: [{ type: 'text', content: output }], + threads: [], + }, + }); + }); + + test('Should ignore an empty metadata section.', async () => { + const result = await parseAnswerForMemberProfile( + "---\nI couldn't find that in our Slack history." + ); + + expect(result).toEqual({ + ok: true, + data: { + answerSegments: [ + { + type: 'text', + content: "I couldn't find that in our Slack history.", + }, + ], + threads: [], + }, + }); + }); + + test('Should fail if there is no metadata but the answer references a thread.', async () => { + const result = await parseAnswerForMemberProfile( + 'Quant firms usually recruit in the summer [ref:1].' + ); + + expect(result).toEqual({ + ok: false, + code: 400, + error: 'The answer contains invalid thread references.', + }); + }); + + test('Should fail if the answer references a thread not in the metadata.', async () => { + const result = await parseAnswerForMemberProfile( + `${METADATA}\n---\nSee this thread [ref:3].` + ); + + expect(result).toEqual({ + ok: false, + code: 400, + error: 'The answer contains invalid thread references.', + }); + }); + + test('Should fail if the metadata is not valid JSON.', async () => { + const output = '{ "threads": [], "ok": true, }\n---\nAnswer.'; + + const result = await parseAnswerForMemberProfile(output); + + expect(result).toEqual({ + ok: false, + code: 400, + error: 'Failed to parse thread metadata into JSON.', + }); + + expect(console.error).toHaveBeenCalledTimes(1); + + expect(console.error).toHaveBeenCalledWith( + expect.objectContaining({ + context: { output }, + message: 'Failed to parse thread metadata into JSON.', + }) + ); + }); + + test('Should fail if there is text before the metadata.', async () => { + const output = `Here is my response:\n\n${METADATA}\n---\n${ANSWER}`; + + const result = await parseAnswerForMemberProfile(output); + + expect(result).toEqual({ + ok: false, + code: 400, + error: 'Failed to parse thread metadata into JSON.', + }); + + expect(console.error).toHaveBeenCalledWith( + expect.objectContaining({ context: { output } }) + ); + }); + + test('Should fail if the metadata is missing its closing brace.', async () => { + const result = await parseAnswerForMemberProfile( + '{ "threads": [\n---\nAnswer.' + ); + + expect(result).toEqual({ + ok: false, + code: 400, + error: 'Failed to parse thread metadata into JSON.', + }); + }); + + test('Should fail if the metadata is not formatted correctly.', async () => { + const result = await parseAnswerForMemberProfile( + '{ "ok": false }\n---\nAnswer.' + ); + + expect(result).toEqual({ + ok: false, + code: 400, + error: 'The metadata section is not formatted correctly.', + }); + }); + + test('Should fail if there is metadata but no delimiter.', async () => { + const result = await parseAnswerForMemberProfile(`${METADATA}\n${ANSWER}`); + + expect(result).toEqual({ + ok: false, + code: 400, + error: 'Missing metadata section or answer section from response.', + }); + }); +}); diff --git a/packages/core/src/modules/slack/slack.ts b/packages/core/src/modules/slack/slack.ts index 0dc7f988d..249180e4b 100644 --- a/packages/core/src/modules/slack/slack.ts +++ b/packages/core/src/modules/slack/slack.ts @@ -10,6 +10,7 @@ import { createEmbedding, getChatCompletion, rerankDocuments, + stripCodeFence, } from '@/infrastructure/ai'; import { job } from '@/infrastructure/bull'; import { track } from '@/infrastructure/mixpanel'; @@ -18,6 +19,7 @@ import { cache, ONE_HOUR_IN_SECONDS } from '@/infrastructure/redis'; import { sendSlackNotification } from '@/modules/notifications/use-cases/send-slack-notification'; import { slack } from '@/modules/slack/instances'; import { IS_PRODUCTION } from '@/shared/env'; +import { ColorStackError } from '@/shared/errors'; import { fail, type Result, success } from '@/shared/utils/core'; // Constants @@ -464,7 +466,7 @@ const MEMBER_PROFILE_SYSTEM_PROMPT = dedent` Your response must follow this exact format: - 1. First, output a JSON object with this EXACT structure: + 1. First, output a JSON object (not in a code block) with this EXACT structure: { "threads": [ { "channelId": "...", "threadId": "...", "number": 1 }, @@ -692,47 +694,75 @@ const MetadataSection = z.object({ * @param output - Raw output from the LLM. * @returns The parsed answer with thread references. */ -async function parseAnswerForMemberProfile( +export async function parseAnswerForMemberProfile( output: string ): Promise> { // PART I: Split the output into the metadata section and the answer section, // parse the metadata section into JSON and validate it with Zod. - const [metadataSection, ...answerParts] = output.split('---'); + // We report the raw output whenever we can't parse it, since the output + // isn't stored anywhere else and is needed to debug the failure. + function failToParse(error: string): Result { + new ColorStackError().withMessage(error).withContext({ output }).report(); - if (!metadataSection || answerParts.length === 0) { - return fail({ - code: 400, - error: 'Missing metadata section or answer section from response.', - }); + return fail({ code: 400, error }); } - let metadataJSON: any = {}; + // The metadata section is everything before the first "---" delimiter. Note + // that the answer itself can contain a "---" (ie: a Markdown divider). + const delimiterIndex = output.indexOf('---'); + const hasDelimiter = delimiterIndex !== -1; + + const metadataSection = hasDelimiter + ? output.slice(0, delimiterIndex) + : output; + + const answerSection = hasDelimiter ? output.slice(delimiterIndex + 3) : ''; + + let answer: string; + let threadsMetadata: z.infer['threads'] = []; + + if (!metadataSection.includes('{')) { + // There is no JSON at all, which means that the LLM answered without + // referencing any threads (ie: it couldn't find the answer in our Slack + // history). Instead of failing, we show it as an answer with no sources. + // If it references a thread anyway, the validation in PART III fails. + answer = metadataSection.trim() ? output : answerSection; + } else { + if (!hasDelimiter) { + return failToParse( + 'Missing metadata section or answer section from response.' + ); + } - try { - metadataJSON = JSON.parse(metadataSection.trim()); - } catch (error) { - return fail({ - code: 400, - error: 'Failed to parse thread metadata into JSON.', - }); - } + let metadataJSON: unknown; - const metadataResult = MetadataSection.safeParse(metadataJSON); + // The LLM sometimes wraps the JSON in a code fence (ie: ```json) even + // though we ask it not to, which would otherwise break `JSON.parse`. + try { + metadataJSON = JSON.parse(stripCodeFence(metadataSection)); + } catch (error) { + return failToParse('Failed to parse thread metadata into JSON.'); + } - if (!metadataResult.success) { - return fail({ - code: 400, - error: 'The metadata section is not formatted correctly.', - }); + const metadataResult = MetadataSection.safeParse(metadataJSON); + + if (!metadataResult.success) { + return failToParse('The metadata section is not formatted correctly.'); + } + + threadsMetadata = metadataResult.data.threads; + answer = answerSection; } + answer = answer.trim(); + // PART II: Fetch the Slack permalink for each thread and return the threads // with their respective URLs. This will allow us to actually have the user // click on the thread and see the actual context of the thread. const threads = await Promise.all( - metadataResult.data.threads.map(async (thread) => { + threadsMetadata.map(async (thread) => { const [{ permalink }, slackMessage] = await Promise.all([ slack.chat.getPermalink({ channel: thread.channelId, @@ -785,9 +815,6 @@ async function parseAnswerForMemberProfile( // PART III: Validate that all the references in the answer are valid. Ensures // that the LLM didn't hallucinate and that the references actually exist. - // Combine all parts after the "---" delimiter. - const answer = answerParts.join('---').trim(); - // Next, we need to validate that all the references in the answer are valid. // We do this by finding all the references in the answer and then checking // that each reference corresponds to a thread in the metadata. From 069eb7eb71d2ddb3e1169ffde5d6a29285a5792e Mon Sep 17 00:00:00 2001 From: Bryan Ramirez-Gonzalez Date: Sun, 22 Nov 2026 17:29:52 -0800 Subject: [PATCH 2/2] fix: report only the metadata section when ask ai parsing fails --- packages/core/src/modules/slack/slack.test.ts | 36 +++++++++++++++++-- packages/core/src/modules/slack/slack.ts | 29 ++++++++++----- 2 files changed, 55 insertions(+), 10 deletions(-) diff --git a/packages/core/src/modules/slack/slack.test.ts b/packages/core/src/modules/slack/slack.test.ts index 9eb7a775e..062b4919c 100644 --- a/packages/core/src/modules/slack/slack.test.ts +++ b/packages/core/src/modules/slack/slack.test.ts @@ -259,7 +259,7 @@ describe(parseAnswerForMemberProfile.name, () => { expect(console.error).toHaveBeenCalledWith( expect.objectContaining({ - context: { output }, + context: { metadataSection: '{ "threads": [], "ok": true, }' }, message: 'Failed to parse thread metadata into JSON.', }) ); @@ -277,7 +277,9 @@ describe(parseAnswerForMemberProfile.name, () => { }); expect(console.error).toHaveBeenCalledWith( - expect.objectContaining({ context: { output } }) + expect.objectContaining({ + context: { metadataSection: `Here is my response:\n\n${METADATA}` }, + }) ); }); @@ -313,5 +315,35 @@ describe(parseAnswerForMemberProfile.name, () => { code: 400, error: 'Missing metadata section or answer section from response.', }); + + expect(console.error).toHaveBeenCalledWith( + expect.objectContaining({ context: {} }) + ); + }); + + // The answer is built from members' Slack messages, so it should never end + // up in an error report. + test('Should never report the answer when it fails.', async () => { + const answer = 'Jordan Smith (jordan@example.com) got the offer.'; + + const outputs = [ + `{ "threads": [], "ok": true, }\n---\n${answer}`, + `Here is my response:\n\n${METADATA}\n---\n${answer}`, + `{ "ok": false }\n---\n${answer}`, + `${METADATA}\n${answer}`, + `${METADATA}\n\n${answer}\n\n| Company | Offer |\n|---|---|`, + ]; + + for (const output of outputs) { + const result = await parseAnswerForMemberProfile(output); + + expect(result.ok).toBe(false); + } + + expect(console.error).toHaveBeenCalledTimes(outputs.length); + + for (const [error] of (console.error as any).mock.calls) { + expect(JSON.stringify(error.context)).not.toContain('Jordan'); + } }); }); diff --git a/packages/core/src/modules/slack/slack.ts b/packages/core/src/modules/slack/slack.ts index 249180e4b..d9fcde7e8 100644 --- a/packages/core/src/modules/slack/slack.ts +++ b/packages/core/src/modules/slack/slack.ts @@ -700,14 +700,6 @@ export async function parseAnswerForMemberProfile( // PART I: Split the output into the metadata section and the answer section, // parse the metadata section into JSON and validate it with Zod. - // We report the raw output whenever we can't parse it, since the output - // isn't stored anywhere else and is needed to debug the failure. - function failToParse(error: string): Result { - new ColorStackError().withMessage(error).withContext({ output }).report(); - - return fail({ code: 400, error }); - } - // The metadata section is everything before the first "---" delimiter. Note // that the answer itself can contain a "---" (ie: a Markdown divider). const delimiterIndex = output.indexOf('---'); @@ -719,6 +711,27 @@ export async function parseAnswerForMemberProfile( const answerSection = hasDelimiter ? output.slice(delimiterIndex + 3) : ''; + // We report the metadata section whenever we can't parse it, since it isn't + // stored anywhere else and is needed to debug the failure. We never report + // the answer, since it's built from members' Slack messages and can include + // personal details. Without a delimiter, the "metadata section" is the whole + // output, so we don't report it at all. We also cut it off at the JSON's + // closing brace, in case the LLM left out the delimiter and the "---" we + // split on is actually part of the answer (ie: a Markdown table). + function failToParse(error: string): Result { + const reportedSection = metadataSection.slice( + 0, + metadataSection.lastIndexOf('}') + 1 + ); + + new ColorStackError() + .withMessage(error) + .withContext(hasDelimiter ? { metadataSection: reportedSection } : {}) + .report(); + + return fail({ code: 400, error }); + } + let answer: string; let threadsMetadata: z.infer['threads'] = [];