feat: Enhanced interview system prompts with memory scaffolding - #7
feat: Enhanced interview system prompts with memory scaffolding#7TechHypeXP wants to merge 1 commit into
Conversation
- Expand AI prompts from ~30 to 300+ total (10x improvement) - Add structured system prompts with ROLE/GOAL/INSTRUCTIONS format - Implement comprehensive memory scaffolding for recall difficulties - Enhanced fallback question banks (75+ questions across 5 domains) - Integrate memory scaffolds into save-response API route - Age-appropriate scaffolding (early childhood, school age, adolescence) - Improved follow-up detection with 80-character limit - Better error handling and validation for Claude responses
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughThe PR adds memory scaffolding support to the ADHD assessment interview system. When users mention memory help trigger phrases in their response, the system detects this, derives an age group from the question context, and generates age-appropriate memory scaffold prompts via Claude. Memory scaffolds are returned in the API response alongside follow-up questions. ChangesMemory Scaffolding Integration
Sequence DiagramsequenceDiagram
participant User
participant API as Save-Response<br/>Endpoint
participant Claude as Claude<br/>Client
participant Model as Claude<br/>API
User->>API: Submit response + questionText
API->>API: Detect memory trigger phrase
alt Memory trigger found
API->>API: Derive ageGroup from questionText
API->>Claude: generateMemoryScaffolds(ageGroup)
Claude->>Model: Request scaffolds with<br/>age-group prompts
Model-->>Claude: Return scaffold JSON
Claude->>Claude: Parse & validate response
Claude-->>API: Return up to 3 scaffolds<br/>(or fallback static)
else No trigger
API->>API: memoryScaffolds = null
end
API->>API: Save response & progress
API-->>User: JSON response with<br/>memoryScaffolds, followUpQuestion
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
✨ Simplify code
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. Review rate limit: 0/1 reviews remaining, refill in 60 minutes.Comment |
Reviewer's GuideEnhances the ADHD interview system’s Claude prompts with structured ROLE/GOAL/INSTRUCTIONS/OUTPUT formats, adds rich fallback question banks and memory-scaffolding prompts, wires in more robust API error handling and JSON validation, and integrates automatic memory scaffold triggering into the interview response-saving endpoint. Sequence diagram for saving interview response with follow-up and memory scaffoldingsequenceDiagram
actor Patient
participant WebApp
participant SaveResponseRoute as SaveResponseAPI_POST
participant ClaudeClient as ClaudeClient
participant DB
Patient->>WebApp: Submit interview response
WebApp->>SaveResponseRoute: POST /api/assessment/interview/save-response
SaveResponseRoute->>ClaudeClient: detectFollowUpNeeded(questionText, response)
ClaudeClient->>ClaudeClient: build systemPrompt (INTERVIEW_SYSTEM_PROMPTS.followUpDetector)
ClaudeClient->>ClaudeClient: build userPrompt (QUESTION/RESPONSE)
ClaudeClient->>ClaudeClient: anthropic.messages.create(...)
ClaudeClient-->>SaveResponseRoute: {needsFollowUp, followUpQuestion?} or error
SaveResponseRoute->>SaveResponseRoute: handle follow-up errors safely
SaveResponseRoute->>SaveResponseRoute: scan response for memoryTriggerPhrases
alt response indicates memory difficulty
SaveResponseRoute->>SaveResponseRoute: infer ageGroup from questionText
SaveResponseRoute->>ClaudeClient: generateMemoryScaffolds(ageGroup)
ClaudeClient->>ClaudeClient: getMemoryScaffoldsForAgeGroup(ageGroup)
ClaudeClient->>ClaudeClient: build systemPrompt (INTERVIEW_SYSTEM_PROMPTS.memoryScaffolding)
ClaudeClient->>ClaudeClient: anthropic.messages.create(...)
ClaudeClient-->>SaveResponseRoute: scaffolds[] or error
SaveResponseRoute->>SaveResponseRoute: on error, fallback to static scaffolds
else no memory difficulty
SaveResponseRoute->>SaveResponseRoute: memoryScaffolds = null
end
SaveResponseRoute->>DB: getInterviewResponseCount(assessmentId)
DB-->>SaveResponseRoute: previousCount
SaveResponseRoute->>DB: saveInterviewResponse(...)
DB-->>SaveResponseRoute: saved response
SaveResponseRoute->>DB: getAssessmentWithRelations(assessmentId)
DB-->>SaveResponseRoute: assessment
SaveResponseRoute-->>WebApp: JSON {success, assessment, followUpQuestion, memoryScaffolds}
WebApp-->>Patient: Show next question, follow-up, and memory scaffolds if present
Class diagram for Claude interview prompting and memory scaffolding utilitiesclassDiagram
class PromptsModule {
+INTERVIEW_SYSTEM_PROMPTS interviewer
+INTERVIEW_SYSTEM_PROMPTS followUpDetector
+INTERVIEW_SYSTEM_PROMPTS validator
+INTERVIEW_SYSTEM_PROMPTS memoryScaffolding
+INTERVIEW_SYSTEM_PROMPTS patternAnalyzer
+INTERVIEW_SYSTEM_PROMPTS emotionalAssessor
+INTERVIEW_SYSTEM_PROMPTS executiveFunctionEvaluator
+FALLBACK_QUESTIONS attention
+FALLBACK_QUESTIONS hyperactivity
+FALLBACK_QUESTIONS impulsivity
+FALLBACK_QUESTIONS executiveFunction
+FALLBACK_QUESTIONS emotionalRegulation
+MEMORY_SCAFFOLDS earlyChildhood
+MEMORY_SCAFFOLDS schoolAge
+MEMORY_SCAFFOLDS adolescence
+MEMORY_SCAFFOLDS generalRecall
+MEMORY_SCAFFOLDS contextualAnchors
+string[] getFallbackQuestionsForDomain(domain)
+string[] getMemoryScaffoldsForAgeGroup(ageGroup)
}
class ClaudeClientModule {
-Anthropic anthropicClient
+Anthropic getAnthropicClient()
+Promise~string~ generateInterviewQuestion(section, previousResponses)
+Promise~FollowUpResult~ detectFollowUpNeeded(question, response)
+Promise~string[]~ generateMemoryScaffolds(ageGroup)
-string getEnhancedFallbackQuestion(section)
}
class FollowUpResult {
+boolean needsFollowUp
+string followUpQuestion
}
class SaveResponseRouteModule {
+Promise~Response~ POST(request)
}
PromptsModule <.. ClaudeClientModule : uses
ClaudeClientModule <.. SaveResponseRouteModule : used by
FollowUpResult <.. ClaudeClientModule : returns
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 2 issues, and left some high level feedback:
- In
generateInterviewQuestionthe old try/catch block appears to still be present below the new one, which will likely cause duplicate return paths or even syntax errors; consider removing the legacy block so there’s a single, clear implementation. - In
generateMemoryScaffoldsyou buildcontextPromptbut then passuserPrompt(which is undefined) into the Anthropic client; update themessagescall to usecontextPromptor rename consistently to avoid a runtime ReferenceError. - The new
generateMemoryScaffoldshelper is called fromsave-response/route.tsbut isn’t imported at the top of that file, so you’ll need to add the import to avoid a compile-time error.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In `generateInterviewQuestion` the old try/catch block appears to still be present below the new one, which will likely cause duplicate return paths or even syntax errors; consider removing the legacy block so there’s a single, clear implementation.
- In `generateMemoryScaffolds` you build `contextPrompt` but then pass `userPrompt` (which is undefined) into the Anthropic client; update the `messages` call to use `contextPrompt` or rename consistently to avoid a runtime ReferenceError.
- The new `generateMemoryScaffolds` helper is called from `save-response/route.ts` but isn’t imported at the top of that file, so you’ll need to add the import to avoid a compile-time error.
## Individual Comments
### Comment 1
<location path="apps/web/lib/claude/client.ts" line_range="35-37" />
<code_context>
+ );
+
+ if (needsMemoryHelp) {
+ try {
+ // Determine age group based on question content (simplified logic)
+ let ageGroup: 'early' | 'school' | 'adolescent' | 'general' = 'general';
</code_context>
<issue_to_address>
**issue (bug_risk):** generateMemoryScaffolds uses an undefined `userPrompt` and ignores `contextPrompt`.
In `generateMemoryScaffolds`, `messages` uses `content: userPrompt`, but `userPrompt` isn’t defined in this scope, which will cause a runtime ReferenceError and leaves `contextPrompt` unused. You likely meant to use:
```ts
messages: [{ role: 'user', content: contextPrompt }],
```
so the model receives the intended age-group-specific context and the code doesn’t crash.
</issue_to_address>
### Comment 2
<location path="apps/web/app/api/assessment/interview/save-response/route.ts" line_range="41-51" />
<code_context>
+ // Check if memory scaffolding is needed
+ let memoryScaffolds: string[] | null = null;
+ const memoryTriggerPhrases = [
+ "i don't remember",
+ "i can't recall",
+ "i don't know",
+ "no memory",
+ "can't remember",
+ "don't recall",
+ "fuzzy memory",
+ "unclear",
+ "not sure about that"
+ ];
+
</code_context>
<issue_to_address>
**suggestion (bug_risk):** The memory trigger phrase matching is very broad and may cause false positives.
Generic phrases like "unclear" or "I don't know" can occur in many non-memory contexts (e.g., uncertainty about a diagnosis), so the simple `includes` check on a lowercased response is likely to over-trigger memory scaffolding. Consider narrowing these to more explicitly memory-related phrases (e.g., requiring "remember"/"recall" nearby) or adding word-boundary/regex checks to reduce false positives.
```suggestion
const memoryTriggerPhrases = [
"i don't remember",
"i can't remember",
"i can't recall",
"i have no memory of that",
"i don't have any memory of that",
"my memory is fuzzy",
"my memory is unclear",
"my memory is blank"
];
```
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| try { | ||
| const response = await client.messages.create({ | ||
| model: 'claude-3-5-sonnet-20241022', |
There was a problem hiding this comment.
issue (bug_risk): generateMemoryScaffolds uses an undefined userPrompt and ignores contextPrompt.
In generateMemoryScaffolds, messages uses content: userPrompt, but userPrompt isn’t defined in this scope, which will cause a runtime ReferenceError and leaves contextPrompt unused. You likely meant to use:
messages: [{ role: 'user', content: contextPrompt }],so the model receives the intended age-group-specific context and the code doesn’t crash.
| const memoryTriggerPhrases = [ | ||
| "i don't remember", | ||
| "i can't recall", | ||
| "i don't know", | ||
| "no memory", | ||
| "can't remember", | ||
| "don't recall", | ||
| "fuzzy memory", | ||
| "unclear", | ||
| "not sure about that" | ||
| ]; |
There was a problem hiding this comment.
suggestion (bug_risk): The memory trigger phrase matching is very broad and may cause false positives.
Generic phrases like "unclear" or "I don't know" can occur in many non-memory contexts (e.g., uncertainty about a diagnosis), so the simple includes check on a lowercased response is likely to over-trigger memory scaffolding. Consider narrowing these to more explicitly memory-related phrases (e.g., requiring "remember"/"recall" nearby) or adding word-boundary/regex checks to reduce false positives.
| const memoryTriggerPhrases = [ | |
| "i don't remember", | |
| "i can't recall", | |
| "i don't know", | |
| "no memory", | |
| "can't remember", | |
| "don't recall", | |
| "fuzzy memory", | |
| "unclear", | |
| "not sure about that" | |
| ]; | |
| const memoryTriggerPhrases = [ | |
| "i don't remember", | |
| "i can't remember", | |
| "i can't recall", | |
| "i have no memory of that", | |
| "i don't have any memory of that", | |
| "my memory is fuzzy", | |
| "my memory is unclear", | |
| "my memory is blank" | |
| ]; |
There was a problem hiding this comment.
2 issues found across 3 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/web/app/api/assessment/interview/save-response/route.ts">
<violation number="1" location="apps/web/app/api/assessment/interview/save-response/route.ts:54">
P1: Validate `response` as a string before calling `.toLowerCase()` to avoid runtime 500s on malformed payloads.</violation>
<violation number="2" location="apps/web/app/api/assessment/interview/save-response/route.ts:65">
P2: `"high school"` is shadowed by the earlier `"school"` check, causing incorrect age-group selection.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.
| ]; | ||
|
|
||
| const needsMemoryHelp = memoryTriggerPhrases.some(phrase => | ||
| response.toLowerCase().includes(phrase) |
There was a problem hiding this comment.
P1: Validate response as a string before calling .toLowerCase() to avoid runtime 500s on malformed payloads.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/app/api/assessment/interview/save-response/route.ts, line 54:
<comment>Validate `response` as a string before calling `.toLowerCase()` to avoid runtime 500s on malformed payloads.</comment>
<file context>
@@ -36,6 +36,44 @@ export async function POST(request: NextRequest) {
+ ];
+
+ const needsMemoryHelp = memoryTriggerPhrases.some(phrase =>
+ response.toLowerCase().includes(phrase)
+ );
+
</file context>
|
|
||
| if (questionLower.includes('child') || questionLower.includes('early') || questionLower.includes('preschool')) { | ||
| ageGroup = 'early'; | ||
| } else if (questionLower.includes('school') || questionLower.includes('elementary') || questionLower.includes('middle')) { |
There was a problem hiding this comment.
P2: "high school" is shadowed by the earlier "school" check, causing incorrect age-group selection.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/app/api/assessment/interview/save-response/route.ts, line 65:
<comment>`"high school"` is shadowed by the earlier `"school"` check, causing incorrect age-group selection.</comment>
<file context>
@@ -36,6 +36,44 @@ export async function POST(request: NextRequest) {
+
+ if (questionLower.includes('child') || questionLower.includes('early') || questionLower.includes('preschool')) {
+ ageGroup = 'early';
+ } else if (questionLower.includes('school') || questionLower.includes('elementary') || questionLower.includes('middle')) {
+ ageGroup = 'school';
+ } else if (questionLower.includes('teen') || questionLower.includes('adolescent') || questionLower.includes('high school')) {
</file context>
| } else if (questionLower.includes('school') || questionLower.includes('elementary') || questionLower.includes('middle')) { | |
| } else if ((questionLower.includes('school') && !questionLower.includes('high school')) || questionLower.includes('elementary') || questionLower.includes('middle')) { |
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
apps/web/lib/claude/client.ts (2)
60-66:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winCritical: Duplicate code block causing TypeScript compilation failure.
This is orphaned code that duplicates lines 52-58. The function
generateInterviewQuestionalready ends at line 58. This block also referencesgetFallbackQuestionwhich doesn't exist (should begetEnhancedFallbackQuestion).This is the root cause of the pipeline failure:
TS1128 Declaration or statement expected.🐛 Remove duplicate code block
- - return question; - } catch (error) { - console.error('Claude API error:', error); - // Fallback to static questions - return getFallbackQuestion(section); - } -}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/lib/claude/client.ts` around lines 60 - 66, Remove the duplicated catch block that repeats the end of generateInterviewQuestion (the orphaned lines duplicating the try/catch) which is causing TS1128; instead ensure there is only one catch that calls the correct fallback function getEnhancedFallbackQuestion (not getFallbackQuestion) and logs the error (e.g., in the existing catch for generateInterviewQuestion), so delete the extra duplicate block and update any remaining reference to use getEnhancedFallbackQuestion.
130-155:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winCritical: Another duplicate code block from incomplete edit.
Lines 130-155 duplicate the validation logic that already exists in lines 97-128. This orphaned block will cause additional compilation errors once the first duplicate is removed.
🐛 Remove duplicate validation block
- - if (typeof result.needsFollowUp !== 'boolean') { - console.error('Claude response missing valid needsFollowUp boolean'); - return { needsFollowUp: false }; - } - - if (result.needsFollowUp && typeof result.followUpQuestion !== 'string') { - console.error('Claude response has needsFollowUp=true but missing followUpQuestion string'); - return { needsFollowUp: false }; - } - - // Validate follow-up question length if present - if (result.followUpQuestion && result.followUpQuestion.length > 100) { - console.warn('Claude follow-up question too long, truncating'); - result.followUpQuestion = result.followUpQuestion.substring(0, 100); - } - - return result; - } catch (parseError) { - console.error('Failed to parse Claude response:', parseError); - return { needsFollowUp: false }; - } - } catch (error) { - console.error('Claude API error in follow-up detection:', error); - return { needsFollowUp: false }; - } -}🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/lib/claude/client.ts` around lines 130 - 155, There is a duplicated validation block re-checking result.needsFollowUp, result.followUpQuestion and truncating long followUpQuestion (including the parseError/catch block) that was accidentally left in the same function; remove the second/orphaned duplicate block so only the original validation logic remains (keep the first occurrence that validates needsFollowUp, followUpQuestion types and truncation and its surrounding try/catch) and ensure the function (the Claude follow-up detection function handling result.needsFollowUp and result.followUpQuestion) has a single consistent try/catch and return path.apps/web/app/api/assessment/interview/save-response/route.ts (1)
6-19:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftMissing assessment ownership validation.
The route validates that
assessmentIdis present but does not verify that the authenticated user owns or has permission to access this assessment. Per coding guidelines, assessment APIs must "validate assessment_id in request and return 401 if user lacks permission."This allows any authenticated user to potentially save responses to any assessment by guessing/enumerating assessment IDs.
🔒 Suggested approach
+ // Extract user ID from token and validate assessment ownership + const userId = await getUserIdFromToken(authHeader); + if (!userId) { + return NextResponse.json({ error: 'Invalid token' }, { status: 401 }); + } + + const assessment = await getAssessment(assessmentId); + if (!assessment || assessment.user_id !== userId) { + return NextResponse.json({ error: 'Assessment not found or access denied' }, { status: 401 }); + } + if (!assessmentId || !questionId || !response) {Note: Implementation depends on your auth token structure and assessment schema. You'll need to implement
getUserIdFromTokenandgetAssessment(or equivalent) functions.As per coding guidelines: "All assessment APIs must validate assessment_id in request and return 401 if user lacks permission"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@apps/web/app/api/assessment/interview/save-response/route.ts` around lines 6 - 19, The POST handler must validate that the authenticated user actually has access to the assessment: extract the user id from the bearer token (use/get or implement getUserIdFromToken(token)) inside POST, then load the assessment record (use/get or implement getAssessmentById(assessmentId) or getAssessment(assessmentId)) and verify the user is the owner or has permission (e.g., assessment.ownerId === userId or check collaborators/permissions); if the assessment is missing or the user lacks permission, return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) and do not proceed to save the response. Ensure this check runs after parsing assessmentId and before any save logic in POST.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@apps/web/lib/claude/client.ts`:
- Around line 169-181: The code passes an undefined variable userPrompt to
client.messages.create causing a runtime error; update the messages payload in
the Claude call (client.messages.create) to use the correctly defined
contextPrompt (messages: [{ role: 'user', content: contextPrompt }]) so the API
receives the intended prompt, and verify there are no other references to
userPrompt in this function.
- Around line 188-192: Parsed result.scaffolds may contain non-string elements;
update the handling in the try block (where you parse content into result and
check result.scaffolds) to filter and validate elements are strings before
returning: replace the current slice logic with a filter that keeps only typeof
=== 'string' entries, then limit to 3 (e.g., filter result.scaffolds to strings
and then take the first three) and return that array so downstream code always
receives string scaffolds.
---
Outside diff comments:
In `@apps/web/app/api/assessment/interview/save-response/route.ts`:
- Around line 6-19: The POST handler must validate that the authenticated user
actually has access to the assessment: extract the user id from the bearer token
(use/get or implement getUserIdFromToken(token)) inside POST, then load the
assessment record (use/get or implement getAssessmentById(assessmentId) or
getAssessment(assessmentId)) and verify the user is the owner or has permission
(e.g., assessment.ownerId === userId or check collaborators/permissions); if the
assessment is missing or the user lacks permission, return NextResponse.json({
error: 'Unauthorized' }, { status: 401 }) and do not proceed to save the
response. Ensure this check runs after parsing assessmentId and before any save
logic in POST.
In `@apps/web/lib/claude/client.ts`:
- Around line 60-66: Remove the duplicated catch block that repeats the end of
generateInterviewQuestion (the orphaned lines duplicating the try/catch) which
is causing TS1128; instead ensure there is only one catch that calls the correct
fallback function getEnhancedFallbackQuestion (not getFallbackQuestion) and logs
the error (e.g., in the existing catch for generateInterviewQuestion), so delete
the extra duplicate block and update any remaining reference to use
getEnhancedFallbackQuestion.
- Around line 130-155: There is a duplicated validation block re-checking
result.needsFollowUp, result.followUpQuestion and truncating long
followUpQuestion (including the parseError/catch block) that was accidentally
left in the same function; remove the second/orphaned duplicate block so only
the original validation logic remains (keep the first occurrence that validates
needsFollowUp, followUpQuestion types and truncation and its surrounding
try/catch) and ensure the function (the Claude follow-up detection function
handling result.needsFollowUp and result.followUpQuestion) has a single
consistent try/catch and return path.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: eb11ac4b-ff62-4d4e-8e65-dcf42d49867b
📒 Files selected for processing (3)
apps/web/app/api/assessment/interview/save-response/route.tsapps/web/lib/claude/client.tsapps/web/lib/claude/prompts.ts
| const scaffolds = getMemoryScaffoldsForAgeGroup(ageGroup); | ||
| const contextPrompt = `AGE GROUP: ${ageGroup} childhood | ||
| AVAILABLE SCAFFOLDS: ${scaffolds.slice(0, 5).join('; ')} | ||
|
|
||
| Generate 2-3 contextual memory prompts for ADHD recall:`; | ||
|
|
||
| try { | ||
| const response = await client.messages.create({ | ||
| model: 'claude-3-5-sonnet-20241022', | ||
| max_tokens: 200, | ||
| system: systemPrompt, | ||
| messages: [{ role: 'user', content: userPrompt }], | ||
| temperature: 0.6, |
There was a problem hiding this comment.
Bug: userPrompt is undefined; should be contextPrompt.
Line 170 declares contextPrompt but line 180 references userPrompt, which is undefined. This will cause a runtime error when calling the Claude API.
🐛 Fix variable name mismatch
const scaffolds = getMemoryScaffoldsForAgeGroup(ageGroup);
const contextPrompt = `AGE GROUP: ${ageGroup} childhood
AVAILABLE SCAFFOLDS: ${scaffolds.slice(0, 5).join('; ')}
Generate 2-3 contextual memory prompts for ADHD recall:`;
try {
const response = await client.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 200,
system: systemPrompt,
- messages: [{ role: 'user', content: userPrompt }],
+ messages: [{ role: 'user', content: contextPrompt }],
temperature: 0.6,
});📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const scaffolds = getMemoryScaffoldsForAgeGroup(ageGroup); | |
| const contextPrompt = `AGE GROUP: ${ageGroup} childhood | |
| AVAILABLE SCAFFOLDS: ${scaffolds.slice(0, 5).join('; ')} | |
| Generate 2-3 contextual memory prompts for ADHD recall:`; | |
| try { | |
| const response = await client.messages.create({ | |
| model: 'claude-3-5-sonnet-20241022', | |
| max_tokens: 200, | |
| system: systemPrompt, | |
| messages: [{ role: 'user', content: userPrompt }], | |
| temperature: 0.6, | |
| const scaffolds = getMemoryScaffoldsForAgeGroup(ageGroup); | |
| const contextPrompt = `AGE GROUP: ${ageGroup} childhood | |
| AVAILABLE SCAFFOLDS: ${scaffolds.slice(0, 5).join('; ')} | |
| Generate 2-3 contextual memory prompts for ADHD recall:`; | |
| try { | |
| const response = await client.messages.create({ | |
| model: 'claude-3-5-sonnet-20241022', | |
| max_tokens: 200, | |
| system: systemPrompt, | |
| messages: [{ role: 'user', content: contextPrompt }], | |
| temperature: 0.6, |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web/lib/claude/client.ts` around lines 169 - 181, The code passes an
undefined variable userPrompt to client.messages.create causing a runtime error;
update the messages payload in the Claude call (client.messages.create) to use
the correctly defined contextPrompt (messages: [{ role: 'user', content:
contextPrompt }]) so the API receives the intended prompt, and verify there are
no other references to userPrompt in this function.
| try { | ||
| const result = JSON.parse(content); | ||
| if (result.scaffolds && Array.isArray(result.scaffolds) && result.scaffolds.length >= 2) { | ||
| return result.scaffolds.slice(0, 3); // Limit to 3 scaffolds | ||
| } |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
Validate that scaffold array elements are strings before returning.
The parsed result.scaffolds is assumed to contain strings, but the Claude response could include non-string elements. Consider adding type validation to prevent downstream issues.
♻️ Add element type validation
try {
const result = JSON.parse(content);
- if (result.scaffolds && Array.isArray(result.scaffolds) && result.scaffolds.length >= 2) {
- return result.scaffolds.slice(0, 3); // Limit to 3 scaffolds
+ if (result.scaffolds && Array.isArray(result.scaffolds) && result.scaffolds.length >= 2) {
+ const validScaffolds = result.scaffolds
+ .filter((s: unknown): s is string => typeof s === 'string' && s.length > 0)
+ .slice(0, 3);
+ if (validScaffolds.length >= 2) {
+ return validScaffolds;
+ }
}
} catch (parseError) {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try { | |
| const result = JSON.parse(content); | |
| if (result.scaffolds && Array.isArray(result.scaffolds) && result.scaffolds.length >= 2) { | |
| return result.scaffolds.slice(0, 3); // Limit to 3 scaffolds | |
| } | |
| try { | |
| const result = JSON.parse(content); | |
| if (result.scaffolds && Array.isArray(result.scaffolds) && result.scaffolds.length >= 2) { | |
| const validScaffolds = result.scaffolds | |
| .filter((s: unknown): s is string => typeof s === 'string' && s.length > 0) | |
| .slice(0, 3); | |
| if (validScaffolds.length >= 2) { | |
| return validScaffolds; | |
| } | |
| } | |
| } catch (parseError) { |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@apps/web/lib/claude/client.ts` around lines 188 - 192, Parsed
result.scaffolds may contain non-string elements; update the handling in the try
block (where you parse content into result and check result.scaffolds) to filter
and validate elements are strings before returning: replace the current slice
logic with a filter that keeps only typeof === 'string' entries, then limit to 3
(e.g., filter result.scaffolds to strings and then take the first three) and
return that array so downstream code always receives string scaffolds.
Summary
Significantly enhances the ADHD assessment interview system with optimized Claude prompts and memory scaffolding support.
Features
Files Changed
apps/web/lib/claude/prompts.ts- Enhanced system prompts (300+ total)apps/web/lib/claude/client.ts- Memory scaffolding supportapps/web/app/api/assessment/interview/save-response/route.ts- IntegrationTesting
🤖 Generated with Claude Code
Summary by Sourcery
Enhance the ADHD assessment interview system with structured Claude prompts, richer fallback content, and memory scaffolding support for childhood recall.
New Features:
Enhancements:
Summary by CodeRabbit
New Features
Bug Fixes