Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: use shared JSON extraction for LLM responses (#6793)

[._.]/ Adam Eivy34bb10f3597a
diff --git a/server/lib/jsonExtract.test.js b/server/lib/jsonExtract.test.js
index 4ec2bea313..f6e7a3dd83 100644
--- a/server/lib/jsonExtract.test.js
+++ b/server/lib/jsonExtract.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import { findAllBalancedBlocks, findBalancedBlocks, tryParseWithRepair, extractJson } from './jsonExtract.js';
+import { BRAIN_DIGEST_ECHO_FIXTURE } from '../test/fixtures/brainDigestEcho.js';
describe('jsonExtract.findBalancedBlocks', () => {
it('returns the single top-level brace-balanced block', () => {
@@ -233,6 +234,15 @@ describe('jsonExtract.extractJson', () => {
expect(value.stylePrompt).toBe('painterly');
});
+ it('skips a fenced echoed schema before the real caller response', () => {
+ const { value } = extractJson(BRAIN_DIGEST_ECHO_FIXTURE.raw, {
+ skipInnerFence: true,
+ shapePredicate: (candidate) => candidate && typeof candidate === 'object'
+ && Array.isArray(candidate.topActions),
+ });
+ expect(value).toEqual(BRAIN_DIGEST_ECHO_FIXTURE.actual);
+ });
+
it('falls back to the first parseable block when shapePredicate matches nothing', () => {
// If the predicate is too strict to match anything, the first valid
// block is still returned so callers can decide whether to accept
diff --git a/server/lib/postRhetoric.js b/server/lib/postRhetoric.js
index 319ed97616..bd71aaa712 100644
--- a/server/lib/postRhetoric.js
+++ b/server/lib/postRhetoric.js
@@ -1,5 +1,6 @@
import { z } from 'zod';
import { EFFORT_LEVELS } from './providerModels.js';
+import { extractJson } from './jsonExtract.js';
export const RHETORIC_MODE_IDS = Object.freeze([
'meter',
@@ -174,14 +175,18 @@ export function buildRhetoricReferencePrompt(referenceSet = RHETORIC_REFERENCE_S
].join('\n\n');
}
-export function parseRhetoricJson(content) {
+export function parseRhetoricJson(content, shapePredicate) {
if (!content || typeof content !== 'string') throw new Error('Empty rhetoric evaluator response');
- let json = content.trim();
- const fenced = json.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (fenced) json = fenced[1].trim();
- const object = json.match(/(\{[\s\S]*\})/);
- if (object) json = object[1];
- return JSON.parse(json);
+ const { value, lastError } = extractJson(content, {
+ // The evaluator prompt itself contains a fenced shape example. Walk all
+ // balanced candidates so a CLI prompt echo cannot become the score.
+ skipInnerFence: true,
+ shapePredicate,
+ });
+ if (value === undefined) {
+ throw new Error(`Failed to parse rhetoric evaluator response: ${lastError?.message || 'No JSON found'}`);
+ }
+ return value;
}
export function scoreRhetoricReference(value, referenceSet = RHETORIC_REFERENCE_SET) {
diff --git a/server/services/agentContentGenerator.js b/server/services/agentContentGenerator.js
index 5065539559..693e248831 100644
--- a/server/services/agentContentGenerator.js
+++ b/server/services/agentContentGenerator.js
@@ -6,34 +6,30 @@
*/
import * as agentActivity from './agentActivity.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';
+import { extractJson } from '../lib/jsonExtract.js';
/**
* Parse JSON from AI response text (handles markdown blocks, extra text)
*/
-export function parseAIJsonResponse(text) {
- let jsonStr = text.trim();
-
- if (!jsonStr) {
+export function parseAIJsonResponse(text, shapePredicate, promptToStrip = '') {
+ if (typeof text !== 'string' || !text.trim()) {
throw new Error('AI returned empty response');
}
-
- // Extract from markdown code blocks
- const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (jsonMatch) {
- jsonStr = jsonMatch[1].trim();
- }
-
- // Extract just the JSON object
- const objectMatch = jsonStr.match(/\{[\s\S]*\}/);
- if (objectMatch) {
- jsonStr = objectMatch[0];
+ // CLI/TUI providers may echo the complete prompt before their answer. It
+ // contains the same valid-looking output example, so remove that exact
+ // prefix before candidate walking when the caller has it available.
+ const source = promptToStrip && text.includes(promptToStrip)
+ ? text.replace(promptToStrip, '')
+ : text;
+ const { value, lastError } = extractJson(source, {
+ skipInnerFence: true,
+ shapePredicate,
+ });
+ if (!value) {
+ throw new Error(`AI returned invalid JSON${lastError ? `: ${lastError.message}` : ''}`);
}
-
- const parsed = safeJSONParse(jsonStr, null, { logError: true, context: 'AI JSON response' });
- if (!parsed) throw new Error('AI returned invalid JSON');
- return parsed;
+ return value;
}
/**
@@ -127,7 +123,10 @@ Respond with ONLY a valid JSON object (no markdown, no explanation):
prompt, providerId, model, 'agent-content-post'
);
- const generated = parseAIJsonResponse(responseText);
+ const generated = parseAIJsonResponse(responseText, (value) => (
+ value && typeof value === 'object' && !Array.isArray(value)
+ && typeof value.title === 'string' && typeof value.content === 'string'
+ ), prompt);
if (!generated.title || !generated.content) {
throw new Error('Generated post missing title or content');
@@ -197,7 +196,10 @@ Respond with ONLY a valid JSON object (no markdown, no explanation):
prompt, providerId, model, 'agent-content-comment'
);
- const generated = parseAIJsonResponse(responseText);
+ const generated = parseAIJsonResponse(responseText, (value) => (
+ value && typeof value === 'object' && !Array.isArray(value)
+ && typeof value.content === 'string'
+ ), prompt);
if (!generated.content) {
throw new Error('Generated comment missing content');
@@ -261,7 +263,10 @@ Respond with ONLY a valid JSON object (no markdown, no explanation):
prompt, providerId, model, 'agent-content-reply'
);
- const generated = parseAIJsonResponse(responseText);
+ const generated = parseAIJsonResponse(responseText, (value) => (
+ value && typeof value === 'object' && !Array.isArray(value)
+ && typeof value.content === 'string'
+ ), prompt);
if (!generated.content) {
throw new Error('Generated reply missing content');
diff --git a/server/services/agentPersonalityGenerator.js b/server/services/agentPersonalityGenerator.js
index f223c00773..1c67047291 100644
--- a/server/services/agentPersonalityGenerator.js
+++ b/server/services/agentPersonalityGenerator.js
@@ -6,6 +6,7 @@
*/
import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';
+import { extractJson } from '../lib/jsonExtract.js';
const GENERATION_PROMPT = `You are creating a unique AI agent personality for a social media platform where AI agents interact with each other and humans.
@@ -126,7 +127,7 @@ export async function generateAgentPersonality(seed = {}, providerId = null, mod
const selectedModel = effectiveModel || requestedModel;
// Parse the JSON response
- let responseText = text.trim();
+ const responseText = text.trim();
// Check for empty response
if (!responseText) {
@@ -134,24 +135,19 @@ export async function generateAgentPersonality(seed = {}, providerId = null, mod
throw new Error('AI returned empty response. The provider may be unavailable - try a different provider or try again.');
}
- // Extract JSON from response (handle markdown code blocks if present)
- let jsonStr = responseText;
- const jsonMatch = responseText.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (jsonMatch) {
- jsonStr = jsonMatch[1].trim();
- }
-
- // Also try to extract just the object if there's extra text
- const objectMatch = jsonStr.match(/\{[\s\S]*\}/);
- if (objectMatch) {
- jsonStr = objectMatch[0];
- }
-
- let generated;
- try {
- generated = JSON.parse(jsonStr);
- } catch (parseError) {
- console.error(`❌ Failed to parse generated personality: ${parseError.message} | response: ${responseText.substring(0, 500)}`);
+ const responseSource = fullPrompt && responseText.includes(fullPrompt)
+ ? responseText.replace(fullPrompt, '')
+ : responseText;
+ const { value: generated, lastError } = extractJson(responseSource, {
+ // This prompt contains a fenced schema example. Walking all balanced
+ // blocks lets a real response after an echoed prompt win.
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value)
+ && value.personality && typeof value.personality.style === 'string'
+ && typeof value.personality.tone === 'string',
+ });
+ if (!generated || typeof generated !== 'object' || Array.isArray(generated)) {
+ console.error(`❌ Failed to parse generated personality: ${lastError?.message || 'No JSON found'} | response: ${responseText.substring(0, 500)}`);
throw new Error('Failed to parse AI response as JSON. Please try again.');
}
diff --git a/server/services/brain.js b/server/services/brain.js
index cf6577e959..e62ec1cb73 100644
--- a/server/services/brain.js
+++ b/server/services/brain.js
@@ -14,7 +14,7 @@ import { getInstanceId, ensureInstanceId, UNKNOWN_INSTANCE_ID } from './instance
import { getActiveProvider, getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
import { validate } from '../lib/validation.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { extractJson } from '../lib/jsonExtract.js';
import { runPromptThroughProvider } from './promptRunner.js';
import { getDomainAutonomyMode } from './cosState.js';
import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
@@ -78,58 +78,49 @@ async function callAI(promptStageName, variables, providerOverride, modelOverrid
const { text, model: effectiveModel } = await runPromptThroughProvider({
provider: providerForCall, prompt, source: `brain-${promptStageName}`, model,
});
- return { content: text, model: effectiveModel || model, providerId: provider.id };
+ return { content: text, model: effectiveModel || model, providerId: provider.id, prompt };
}
/**
* Parse JSON from AI response (handles markdown code blocks)
*/
-function parseJsonResponse(content) {
+function parseJsonResponse(content, responseSchema = null, promptToStrip = '') {
if (!content || typeof content !== 'string') {
throw new Error('Empty or invalid AI response');
}
- let jsonStr = content.trim();
-
- // Remove markdown code blocks if present
- const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (jsonMatch) {
- jsonStr = jsonMatch[1].trim();
- }
-
- // Find JSON object
- const objectMatch = jsonStr.match(/\{[\s\S]*\}/);
- if (objectMatch) {
- jsonStr = objectMatch[0];
- }
-
- try {
- return JSON.parse(jsonStr);
- } catch (err) {
- throw new Error(`Failed to parse AI JSON response: ${err.message}`);
+ const shapePredicate = responseSchema
+ ? (value) => responseSchema.safeParse(value).success
+ : undefined;
+ const source = promptToStrip && content.includes(promptToStrip)
+ ? content.replace(promptToStrip, '')
+ : content;
+ const { value, lastError } = extractJson(source, {
+ // Brain prompts include fenced JSON examples. Walk all candidates so an
+ // echoed example cannot win before the actual answer.
+ skipInnerFence: true,
+ shapePredicate,
+ });
+ if (value === undefined) {
+ throw new Error(`Failed to parse AI JSON response: ${lastError?.message || 'No JSON found'}`);
}
+ return value;
}
/**
* Safe version of parseJsonResponse that returns null instead of throwing.
* Used in background classification where errors can't bubble to middleware.
*/
-function safeParseJsonResponse(content) {
+function safeParseJsonResponse(content, responseSchema = null, promptToStrip = '') {
if (!content || typeof content !== 'string') return null;
-
- let jsonStr = content.trim();
-
- const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (jsonMatch) {
- jsonStr = jsonMatch[1].trim();
- }
-
- const objectMatch = jsonStr.match(/\{[\s\S]*\}/);
- if (objectMatch) {
- jsonStr = objectMatch[0];
- }
-
- return safeJSONParse(jsonStr, null, { logError: true, context: 'brain-classifier' });
+ const source = promptToStrip && content.includes(promptToStrip)
+ ? content.replace(promptToStrip, '')
+ : content;
+ const shapePredicate = responseSchema
+ ? (value) => responseSchema.safeParse(value).success
+ : undefined;
+ const { value } = extractJson(source, { skipInnerFence: true, shapePredicate });
+ return value === undefined ? null : value;
}
/**
@@ -301,7 +292,7 @@ async function classifyInBackground(entryId, text, meta, providerOverride, model
if (aiResponse) {
console.log(`🧠 AI responded in ${elapsed}s for ${entryId}`);
- const parsed = safeParseJsonResponse(aiResponse);
+ const parsed = safeParseJsonResponse(aiResponse, classifierOutputSchema, aiResult.prompt);
if (parsed) {
const validationResult = classifierOutputSchema.safeParse(parsed);
if (validationResult.success) {
@@ -620,7 +611,7 @@ export async function runDailyDigest(providerOverride, modelOverride) {
modelOverride || meta.defaultModel
);
- const parsed = parseJsonResponse(aiResult.content);
+ const parsed = parseJsonResponse(aiResult.content, digestOutputSchema, aiResult.prompt);
const validationResult = digestOutputSchema.safeParse(parsed);
if (!validationResult.success) {
@@ -682,7 +673,7 @@ export async function runWeeklyReview(providerOverride, modelOverride) {
modelOverride || meta.defaultModel
);
- const parsed = parseJsonResponse(aiResult.content);
+ const parsed = parseJsonResponse(aiResult.content, reviewOutputSchema, aiResult.prompt);
const validationResult = reviewOutputSchema.safeParse(parsed);
if (!validationResult.success) {
diff --git a/server/services/brain.test.js b/server/services/brain.test.js
index d88aaeae81..0cf68bcada 100644
--- a/server/services/brain.test.js
+++ b/server/services/brain.test.js
@@ -141,6 +141,7 @@ import * as repoCloner from './repoCloner.js';
import * as storage from './brainStorage.js';
import { deleteMemoryAssets } from './chatgptImport.js';
import { getProviderById } from './providers.js';
+import { BRAIN_DIGEST_ECHO_FIXTURE } from '../test/fixtures/brainDigestEcho.js';
import {
captureThought,
resolveReview,
@@ -1296,6 +1297,24 @@ describe('brain service', () => {
expect(result.digestText).toBe('Summary');
});
+ it('skips an echoed schema object before the real digest response', async () => {
+ storage.getProjects.mockResolvedValue([{ id: 'p1', name: 'Proj', status: 'active' }]);
+ storage.getAdminItems.mockResolvedValue([]);
+ storage.getPeople.mockResolvedValue([]);
+ storage.getInboxLog.mockResolvedValue([]);
+
+ const mockProvider = { id: 'lmstudio', enabled: true, type: 'api', endpoint: 'http://localhost:1234/v1', defaultModel: 'test' };
+ getProviderById.mockResolvedValue(mockProvider);
+ runPromptThroughProvider.mockResolvedValue({
+ text: BRAIN_DIGEST_ECHO_FIXTURE.raw,
+ runId: 'test-run', model: 'test-model'
+ });
+ storage.createDigest.mockImplementation(async (data) => ({ id: 'd1', ...data }));
+
+ const result = await runDailyDigest();
+ expect(result.digestText).toBe(BRAIN_DIGEST_ECHO_FIXTURE.actual.digestText);
+ });
+
it('should throw on empty AI response', async () => {
storage.getProjects.mockResolvedValue([{ id: 'p1', name: 'Proj', status: 'active' }]);
storage.getAdminItems.mockResolvedValue([]);
diff --git a/server/services/digital-twin-analysis.js b/server/services/digital-twin-analysis.js
index 71b3509e5a..a389c6fc61 100644
--- a/server/services/digital-twin-analysis.js
+++ b/server/services/digital-twin-analysis.js
@@ -3,7 +3,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { extractJson } from '../lib/jsonExtract.js';
import { DIGITAL_TWIN_DIR, callProviderAI, now } from './digital-twin-helpers.js';
import { loadMeta, saveMeta, digitalTwinEvents } from './digital-twin-meta.js';
import { getDocuments } from './digital-twin-documents.js';
@@ -152,26 +152,34 @@ export async function detectContradictions(providerId, model) {
const result = await callProviderAI(provider, model, prompt);
if (!result.error && result.text) {
- return parseContradictionResponse(result.text);
+ return parseContradictionResponse(result.text, prompt);
}
return { issues: [], error: result.error || 'Failed to analyze contradictions' };
}
-function parseContradictionResponse(response) {
- // Try to extract JSON from the response
- const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
- if (jsonMatch) {
- const parsed = safeJSONParse(jsonMatch[1], null, { logError: true, context: 'contradiction analysis' });
- if (parsed) return { issues: parsed.issues || [], summary: parsed.summary };
- }
-
- // Fallback: try direct JSON parse
- if (response.trim().startsWith('{') || response.trim().startsWith('[')) {
- const parsed = safeJSONParse(response, null, { logError: true, context: 'contradiction analysis fallback' });
- if (parsed) return { issues: parsed.issues || parsed || [], summary: parsed.summary };
+function parseContradictionResponse(response, promptToStrip = '') {
+ const source = promptToStrip && typeof response === 'string' && response.includes(promptToStrip)
+ ? response.replace(promptToStrip, '')
+ : response;
+ // The legacy parser accepted a top-level array when the provider returned
+ // one directly. Check that form first so the object walker does not harvest
+ // the first item inside the array.
+ if (typeof source === 'string' && /^\s*(?:```(?:json)?\s*)?\[/.test(source)) {
+ const arrayResult = extractJson(source, { blockType: 'array', skipInnerFence: true });
+ if (Array.isArray(arrayResult.value)) return { issues: arrayResult.value, summary: undefined };
+ }
+ const { value: parsed } = extractJson(source, {
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object'
+ && (Array.isArray(value.issues) || typeof value.summary === 'string'),
+ });
+ if (parsed && typeof parsed === 'object') {
+ return {
+ issues: parsed.issues || parsed || [],
+ summary: parsed.summary,
+ };
}
-
return { issues: [], rawResponse: response };
}
@@ -197,26 +205,38 @@ export async function generateDynamicTests(providerId, model) {
const result = await callProviderAI(provider, model, prompt);
if (!result.error && result.text) {
- return parseGeneratedTests(result.text);
+ return parseGeneratedTests(result.text, prompt);
}
return { tests: [], error: result.error || 'Failed to generate tests' };
}
-function parseGeneratedTests(response) {
- // Try to extract JSON from the response
- const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
- if (jsonMatch) {
- const parsed = safeJSONParse(jsonMatch[1], null, { logError: true, context: 'generated tests' });
- if (parsed) return { tests: parsed.tests || parsed || [] };
- }
-
- // Fallback: try direct JSON parse
- if (response.trim().startsWith('{') || response.trim().startsWith('[')) {
- const parsed = safeJSONParse(response, null, { logError: true, context: 'generated tests fallback' });
- if (parsed) return { tests: parsed.tests || parsed || [] };
- }
-
+function parseGeneratedTests(response, promptToStrip = '') {
+ const source = promptToStrip && typeof response === 'string' && response.includes(promptToStrip)
+ ? response.replace(promptToStrip, '')
+ : response;
+ // Preserve direct top-level arrays; walking object blocks first would return
+ // the first test item rather than the collection.
+ if (typeof source === 'string' && /^\s*(?:```(?:json)?\s*)?\[/.test(source)) {
+ const arrayResult = extractJson(source, { blockType: 'array', skipInnerFence: true });
+ if (Array.isArray(arrayResult.value)) return { tests: arrayResult.value };
+ }
+ const { value: parsed } = extractJson(source, {
+ skipInnerFence: true,
+ shapePredicate: (value) => Array.isArray(value)
+ || (value && typeof value === 'object' && Array.isArray(value.tests)),
+ });
+ if (parsed && typeof parsed === 'object') {
+ return { tests: parsed.tests || parsed || [] };
+ }
+ // `extractJson` defaults to object blocks. Preserve the old direct-array
+ // response contract for providers that return a top-level list.
+ const arrayResult = extractJson(source, {
+ blockType: 'array',
+ skipInnerFence: true,
+ shapePredicate: Array.isArray,
+ });
+ if (Array.isArray(arrayResult.value)) return { tests: arrayResult.value };
return { tests: [], rawResponse: response };
}
@@ -242,27 +262,30 @@ export async function analyzeWritingSamples(samples, providerId, model) {
const result = await callProviderAI(provider, model, prompt);
if (!result.error && result.text) {
- return parseWritingAnalysis(result.text);
+ return parseWritingAnalysis(result.text, prompt);
}
return { error: result.error || 'Failed to analyze writing samples' };
}
-function parseWritingAnalysis(response) {
- // Try to extract JSON
- const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
- if (jsonMatch) {
- const parsed = safeJSONParse(jsonMatch[1], null, { logError: true, context: 'writing analysis' });
- if (parsed) {
- return {
- analysis: parsed.analysis || parsed,
- suggestedContent: parsed.suggestedContent || parsed.document || ''
- };
- }
+function parseWritingAnalysis(response, promptToStrip = '') {
+ const source = promptToStrip && typeof response === 'string' && response.includes(promptToStrip)
+ ? response.replace(promptToStrip, '')
+ : response;
+ const { value: parsed } = extractJson(source, {
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value)
+ && ('analysis' in value || 'suggestedContent' in value || 'document' in value),
+ });
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ return {
+ analysis: parsed.analysis || parsed,
+ suggestedContent: parsed.suggestedContent || parsed.document || ''
+ };
}
// Extract markdown content for document if present
- const mdMatch = response.match(/```markdown\s*([\s\S]*?)\s*```/);
+ const mdMatch = source.match(/```markdown\s*([\s\S]*?)\s*```/);
const suggestedContent = mdMatch ? mdMatch[1] : '';
return {
@@ -378,7 +401,7 @@ export async function analyzeTraits(providerId, model, forceReanalyze = false) {
return { error: result.error };
}
- const parsedTraits = parseTraitsResponse(result.text || '');
+ const parsedTraits = parseTraitsResponse(result.text || '', prompt);
if (parsedTraits.error) {
return parsedTraits;
}
@@ -402,19 +425,21 @@ export async function analyzeTraits(providerId, model, forceReanalyze = false) {
return { traits, analysisNotes: parsedTraits.analysisNotes };
}
-export function parseTraitsResponse(response) {
- const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
- const jsonStr = jsonMatch ? jsonMatch[1] : (response.trim().startsWith('{') ? response.trim() : null);
-
- if (!jsonStr) {
- return { error: 'Failed to parse traits response - no JSON found', rawResponse: response };
+export function parseTraitsResponse(response, promptToStrip = '') {
+ const source = promptToStrip && typeof response === 'string' && response.includes(promptToStrip)
+ ? response.replace(promptToStrip, '')
+ : response;
+ if (typeof source === 'string' && /^\s*(?:```(?:json)?\s*)?\[/.test(source)) {
+ return { error: 'Failed to parse traits response - invalid JSON', rawResponse: response };
}
-
- const parsed = safeJSONParse(jsonStr, null, { allowArray: false });
+ const { value: parsed } = extractJson(source, {
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value),
+ });
// A fenced ```json block can wrap a bare scalar (e.g. the model responds
- // with just `42`) — `allowArray: false` only rejects a root array, so guard
- // for a genuine object before treating it as a traits response.
- if (!parsed || typeof parsed !== 'object') {
+ // with just `42`; guard for a genuine object before treating it as a traits
+ // response.
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return { error: 'Failed to parse traits response - invalid JSON', rawResponse: response };
}
@@ -459,7 +484,7 @@ export async function calculateConfidence(providerId, model) {
const result = await callProviderAI(provider, model, prompt);
if (!result.error && result.text) {
- const parsed = parseConfidenceResponse(result.text);
+ const parsed = parseConfidenceResponse(result.text, prompt);
if (!parsed.error) {
const confidence = {
@@ -479,19 +504,17 @@ export async function calculateConfidence(providerId, model) {
return calculateLocalConfidence(twinContent, currentTraits, meta);
}
-function parseConfidenceResponse(response) {
- const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
- if (jsonMatch) {
- const parsed = safeJSONParse(jsonMatch[1], null, { logError: true, context: 'confidence response' });
- if (parsed) return parsed;
- }
-
- if (response.trim().startsWith('{')) {
- const parsed = safeJSONParse(response, null, { logError: true, context: 'confidence response fallback' });
- if (parsed) return parsed;
- }
-
- return { error: 'Failed to parse confidence response' };
+function parseConfidenceResponse(response, promptToStrip = '') {
+ const source = promptToStrip && typeof response === 'string' && response.includes(promptToStrip)
+ ? response.replace(promptToStrip, '')
+ : response;
+ const { value: parsed } = extractJson(source, {
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value),
+ });
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
+ ? parsed
+ : { error: 'Failed to parse confidence response' };
}
/**
diff --git a/server/services/digital-twin-enrichment.js b/server/services/digital-twin-enrichment.js
index 29663c3575..607b136d5f 100644
--- a/server/services/digital-twin-enrichment.js
+++ b/server/services/digital-twin-enrichment.js
@@ -3,7 +3,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { getActiveProvider, getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { extractJson } from '../lib/jsonExtract.js';
import { ENRICHMENT_CATEGORIES, SCALE_QUESTIONS, SCALE_WEIGHT, CONFIDENCE_BOOST } from './digital-twin-constants.js';
import { DIGITAL_TWIN_DIR, generateId, now, ensureSoulDir, callProviderAI, ensureDocumentInMeta } from './digital-twin-helpers.js';
import { loadMeta, saveMeta, digitalTwinEvents } from './digital-twin-meta.js';
@@ -458,9 +458,18 @@ Respond in JSON format:
const responseText = result.text || '';
- // Parse the JSON response
- const parsed = safeJSONParse(responseText.match(/```json\s*([\s\S]*?)\s*```/)?.[1] || '', null, { logError: true, context: 'enrichment analysis' });
- if (parsed) {
+ // Parse the JSON response. The prompt contains a fenced schema example;
+ // walk all balanced blocks so a provider echo cannot win over the answer.
+ const responseSource = prompt && responseText.includes(prompt)
+ ? responseText.replace(prompt, '')
+ : responseText;
+ const { value: parsed } = extractJson(responseSource, {
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value)
+ && ['itemAnalysis', 'patterns', 'personalityInsights', 'suggestedDocument']
+ .some((key) => key in value),
+ });
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return {
category,
items,
diff --git a/server/services/digital-twin-helpers.js b/server/services/digital-twin-helpers.js
index 45c59c195a..1462fdb17a 100644
--- a/server/services/digital-twin-helpers.js
+++ b/server/services/digital-twin-helpers.js
@@ -1,6 +1,6 @@
import { v4 as uuidv4 } from '../lib/uuid.js';
import { existsSync } from 'fs';
-import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
+import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { runPromptThroughProvider } from './promptRunner.js';
import { clearTombstone, tombstoneTimestamp, supersedingTimestamp } from '../lib/tombstones.js';
@@ -14,24 +14,6 @@ export function now() {
return new Date().toISOString();
}
-/**
- * Extract and parse the first JSON block from an AI response string.
- * Tries ```json fences first, then bare-object/array fallback.
- * Returns the parsed value or null.
- */
-export function extractJSON(response, context = 'response') {
- const fenceMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
- if (fenceMatch) {
- const parsed = safeJSONParse(fenceMatch[1], null, { logError: true, context });
- if (parsed) return parsed;
- }
- const trimmed = response.trim();
- if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
- return safeJSONParse(trimmed, null, { logError: true, context: `${context} fallback` });
- }
- return null;
-}
-
/**
* Parse a JSON-ish scorer response into { result, reasoning }. Tolerates both
* `"result": "x"` and `result: x` shapes. `verdicts` lists the recognized
diff --git a/server/services/digital-twin-image-identity.js b/server/services/digital-twin-image-identity.js
index 277775822c..13ea7533b0 100644
--- a/server/services/digital-twin-image-identity.js
+++ b/server/services/digital-twin-image-identity.js
@@ -15,7 +15,7 @@
*/
import { buildPrompt } from './promptService.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { extractJson } from '../lib/jsonExtract.js';
import { getProviderById } from './providers.js';
import { describeImageDataUrl } from './visionTest.js';
import { loadMeta } from './digital-twin-meta.js';
@@ -79,7 +79,7 @@ export async function analyzeIdentityImage({ imageDataUrl, providerId, model })
return { error: 'Vision model returned an empty response' };
}
- return parseIdentityImage(vision.text);
+ return parseIdentityImage(vision.text, prompt);
}
/**
@@ -139,23 +139,25 @@ function buildDocumentMarkdown({ summary, appearance, presentation, setting, exp
* synthesized so the save action has content even when the model omits
* `documentMarkdown`.
*/
-export function parseIdentityImage(response) {
- const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
- const jsonStr = jsonMatch
- ? jsonMatch[1]
- : (response.trim().startsWith('{') ? response.trim() : null);
-
- if (!jsonStr) {
- return { error: 'Failed to parse image analysis - no JSON found', rawResponse: response };
+export function parseIdentityImage(response, promptToStrip = '') {
+ const source = promptToStrip && typeof response === 'string' && response.includes(promptToStrip)
+ ? response.replace(promptToStrip, '')
+ : response;
+ if (typeof source === 'string' && /^\s*(?:```(?:json)?\s*)?\[/.test(source)) {
+ return { error: 'Failed to parse image analysis - invalid JSON', rawResponse: response };
}
-
- const parsed = safeJSONParse(jsonStr, null, {
- allowArray: false,
- logError: true,
- context: 'image identity analysis'
+ const result = extractJson(source, {
+ blockType: 'object',
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value)
+ && ['appearance', 'presentation', 'setting', 'expression', 'descriptors', 'summary', 'documentMarkdown']
+ .some((key) => key in value),
});
-
- if (!parsed) {
+ const parsed = result.value;
+ if (parsed === undefined && !/[{[]/.test(source || '')) {
+ return { error: 'Failed to parse image analysis - no JSON found', rawResponse: response };
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return { error: 'Failed to parse image analysis - invalid JSON', rawResponse: response };
}
diff --git a/server/services/digital-twin-import.js b/server/services/digital-twin-import.js
index 86f20b9985..0ce8a591fc 100644
--- a/server/services/digital-twin-import.js
+++ b/server/services/digital-twin-import.js
@@ -1,6 +1,7 @@
import { getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
import { safeJSONParse } from '../lib/fileUtils.js';
+import { extractJson } from '../lib/jsonExtract.js';
import { callProviderAI, now } from './digital-twin-helpers.js';
import { loadMeta } from './digital-twin-meta.js';
import { createDocument, updateDocument } from './digital-twin-documents.js';
@@ -288,7 +289,7 @@ async function analyzeWithPrompt(prompt, providerId, model, source, parsedData)
const result = await callProviderAI(provider, model, prompt);
if (!result.error && result.text) {
- return parseImportAnalysisResponse(result.text, source, parsedData);
+ return parseImportAnalysisResponse(result.text, source, parsedData, prompt);
}
return { error: result.error || 'Provider request failed' };
@@ -297,28 +298,31 @@ async function analyzeWithPrompt(prompt, providerId, model, source, parsedData)
/**
* Parse AI response for import analysis
*/
-function parseImportAnalysisResponse(response, source, parsedData) {
- const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
- if (jsonMatch) {
- const parsed = safeJSONParse(jsonMatch[1], null, { logError: true, context: 'import analysis' });
- if (parsed) {
- return {
- source,
- itemCount: Array.isArray(parsedData) ? parsedData.length : (parsedData.artists?.length || 0),
- ...parsed
- };
- }
+function parseImportAnalysisResponse(response, source, parsedData, promptToStrip = '') {
+ const responseSource = promptToStrip && typeof response === 'string' && response.includes(promptToStrip)
+ ? response.replace(promptToStrip, '')
+ : response;
+ if (typeof responseSource === 'string' && /^\s*(?:```(?:json)?\s*)?\[/.test(responseSource)) {
+ return {
+ source,
+ itemCount: Array.isArray(parsedData) ? parsedData.length : (parsedData.artists?.length || 0),
+ insights: { patterns: [], preferences: [] },
+ rawSummary: response
+ };
}
-
- if (response.trim().startsWith('{')) {
- const parsed = safeJSONParse(response, null, { logError: true, context: 'import analysis fallback' });
- if (parsed) {
- return {
- source,
- itemCount: Array.isArray(parsedData) ? parsedData.length : (parsedData.artists?.length || 0),
- ...parsed
- };
- }
+ const { value: parsed } = extractJson(responseSource, {
+ // Import prompts contain a fenced response shape. Walk all balanced
+ // candidates and prefer an analysis-shaped object after any prompt echo.
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value)
+ && ('insights' in value || 'suggestedDocuments' in value || 'rawSummary' in value),
+ });
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ return {
+ source,
+ itemCount: Array.isArray(parsedData) ? parsedData.length : (parsedData.artists?.length || 0),
+ ...parsed
+ };
}
return {
@@ -521,7 +525,7 @@ export async function analyzeAssessment(content, providerId, model) {
return { error: aiResponse.error };
}
- const parsed = parseTraitsResponse(aiResponse.text);
+ const parsed = parseTraitsResponse(aiResponse.text, analysisPrompt);
if (parsed.error) {
return { error: parsed.error };
}
diff --git a/server/services/digital-twin-style-comparison.js b/server/services/digital-twin-style-comparison.js
index 7721046edc..3078786276 100644
--- a/server/services/digital-twin-style-comparison.js
+++ b/server/services/digital-twin-style-comparison.js
@@ -16,7 +16,7 @@
import { getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { extractJson } from '../lib/jsonExtract.js';
import { callProviderAI } from './digital-twin-helpers.js';
import { getAllTwinContent } from './digital-twin-analysis.js';
@@ -78,7 +78,7 @@ export async function compareSpokenWrittenStyle({ spokenTranscript, writtenSampl
return { error: result.error || 'Failed to analyze spoken-vs-written style' };
}
- return { ...parseStyleComparison(result.text), writtenSource };
+ return { ...parseStyleComparison(result.text, prompt), writtenSource };
}
/**
@@ -87,23 +87,24 @@ export async function compareSpokenWrittenStyle({ spokenTranscript, writtenSampl
* analyzers). Arrays default to [] and objects to null so the client can
* distinguish "absent" from "present-but-empty".
*/
-export function parseStyleComparison(response) {
- const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
- const jsonStr = jsonMatch
- ? jsonMatch[1]
- : (response.trim().startsWith('{') ? response.trim() : null);
-
- if (!jsonStr) {
- return { error: 'Failed to parse comparison response - no JSON found', rawResponse: response };
+export function parseStyleComparison(response, promptToStrip = '') {
+ const source = promptToStrip && typeof response === 'string' && response.includes(promptToStrip)
+ ? response.replace(promptToStrip, '')
+ : response;
+ if (typeof source === 'string' && /^\s*(?:```(?:json)?\s*)?\[/.test(source)) {
+ return { error: 'Failed to parse comparison response - invalid JSON', rawResponse: response };
}
-
- const parsed = safeJSONParse(jsonStr, null, {
- allowArray: false,
- logError: true,
- context: 'spoken-written comparison'
+ const result = extractJson(source, {
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value)
+ && ['spokenProfile', 'writtenProfile', 'differences', 'summary', 'suggestedCommunicationProfile']
+ .some((key) => key in value),
});
-
- if (!parsed) {
+ const parsed = result.value;
+ if (parsed === undefined && !/[{[]/.test(source || '')) {
+ return { error: 'Failed to parse comparison response - no JSON found', rawResponse: response };
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
return { error: 'Failed to parse comparison response - invalid JSON', rawResponse: response };
}
diff --git a/server/services/localThinking.js b/server/services/localThinking.js
index b72dfba4e7..9828e17631 100644
--- a/server/services/localThinking.js
+++ b/server/services/localThinking.js
@@ -6,6 +6,7 @@
*/
import * as lmStudio from './lmStudioManager.js'
+import { extractJson } from '../lib/jsonExtract.js'
// Task complexity thresholds for escalation
@@ -100,15 +101,16 @@ Respond with:
stats.localSuccesses++
- // Parse local model response
- let analysis
- try {
- // Extract JSON from response
- const jsonMatch = result.content.match(/\{[\s\S]*\}/)
- analysis = jsonMatch ? JSON.parse(jsonMatch[0]) : null
- } catch (err) {
- analysis = null
- }
+ // Parse local model response. The prompt is echoed by some local/CLI
+ // providers, so use the shared balanced walker and prefer the analysis shape.
+ const analysisSource = typeof result.content === 'string' && result.content.includes(analysisPrompt)
+ ? result.content.replace(analysisPrompt, '')
+ : result.content
+ const { value: analysis } = extractJson(analysisSource, {
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value)
+ && typeof value.complexity === 'number',
+ })
if (!analysis) {
return {
@@ -248,20 +250,32 @@ Respond with JSON only:
return { success: false, error: result.error }
}
- try {
- const jsonMatch = result.content.match(/\{[\s\S]*\}/)
- const classification = jsonMatch ? JSON.parse(jsonMatch[0]) : null
+ const classificationSource = typeof result.content === 'string' && result.content.includes(classifyPrompt)
+ ? result.content.replace(classifyPrompt, '')
+ : result.content
+ const { value: classification } = extractJson(classificationSource, {
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value)
+ && typeof value.type === 'string' && typeof value.category === 'string'
+ && Array.isArray(value.tags) && typeof value.importance === 'number',
+ })
+ // Preserve the historical distinction: prose with no object braces returned
+ // a bare success, while an actually malformed object entered the parse
+ // failure branch with the raw response attached.
+ if (classification !== undefined) {
return {
success: true,
...classification
}
- } catch (err) {
- return {
- success: false,
- error: 'Could not parse classification',
- rawResponse: result.content
- }
+ }
+ if (!/[{]/.test(result.content || '')) {
+ return { success: true }
+ }
+ return {
+ success: false,
+ error: 'Could not parse classification',
+ rawResponse: result.content
}
}
diff --git a/server/services/meatspacePostLlm.js b/server/services/meatspacePostLlm.js
index 2527b7277b..8a4f529784 100644
--- a/server/services/meatspacePostLlm.js
+++ b/server/services/meatspacePostLlm.js
@@ -11,6 +11,7 @@
import { getActiveProvider, getProviderById } from './providers.js';
import { runPromptThroughProvider } from './promptRunner.js';
+import { extractJson } from '../lib/jsonExtract.js';
import {
LEGACY_POST_LLM_PROVENANCE,
POST_LLM_MAX_SEMANTIC_CANDIDATES,
@@ -74,26 +75,57 @@ export async function callAI(prompt, providerId, model, effort = null, source =
};
}
-export function parseJsonFromAI(content) {
+export function parseJsonFromAI(content, shapePredicate, promptToStrip = '') {
if (!content || typeof content !== 'string') throw new Error('Empty AI response');
- let jsonStr = content.trim();
- // Strip fenced code blocks
- const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (jsonMatch) jsonStr = jsonMatch[1].trim();
- // Extract first JSON object/array from surrounding text
- const objectMatch = jsonStr.match(/(\{[\s\S]*\})/);
- if (objectMatch) jsonStr = objectMatch[1];
- else {
- const arrayMatch = jsonStr.match(/(\[[\s\S]*\])/);
- if (arrayMatch) jsonStr = arrayMatch[1];
+
+ // POST responses are objects for most drills, but a few legacy providers
+ // return a top-level array. Walk both delimiters while preserving that
+ // public object-or-array contract. The optional predicate lets validators
+ // skip a prompt-echoed schema example before accepting the real payload.
+ const source = promptToStrip && content.includes(promptToStrip)
+ ? content.replace(promptToStrip, '')
+ : content;
+ const options = { skipInnerFence: true, shapePredicate };
+ // If the response itself is an array (possibly wrapped in one outer fence),
+ // inspect that container before walking nested object items.
+ if (/^\s*(?:```(?:json)?\s*)?\[/.test(source)) {
+ const topLevelArray = extractJson(source, { ...options, blockType: 'array' });
+ if (topLevelArray.value !== undefined
+ && (!shapePredicate || shapePredicate(topLevelArray.value))) {
+ return topLevelArray.value;
+ }
+ }
+ const objectResult = extractJson(source, options);
+ if (objectResult.value !== undefined
+ && (!shapePredicate || shapePredicate(objectResult.value))) {
+ return objectResult.value;
+ }
+ const arrayResult = extractJson(source, { ...options, blockType: 'array' });
+ if (arrayResult.value !== undefined
+ && (!shapePredicate || shapePredicate(arrayResult.value))) {
+ return arrayResult.value;
}
- return JSON.parse(jsonStr);
+
+ // No candidate matched the optional shape. Keep the old behavior of
+ // returning the first parseable value so the contract validator can report
+ // its detailed shape error to the caller.
+ const fallback = objectResult.value !== undefined ? objectResult.value : arrayResult.value;
+ if (fallback !== undefined) return fallback;
+ const error = objectResult.lastError || arrayResult.lastError;
+ throw new Error(`Failed to parse AI response: ${error?.message || 'No JSON found'}`);
}
async function generateValidatedPayload(type, count, prompt, providerId, model) {
const response = await callAI(prompt, providerId, model);
return {
- data: validatePostLlmGenerationPayload(type, parseJsonFromAI(response.text), count),
+ data: validatePostLlmGenerationPayload(type, parseJsonFromAI(response.text, (value) => {
+ try {
+ validatePostLlmGenerationPayload(type, value, count);
+ return true;
+ } catch {
+ return false;
+ }
+ }, prompt), count),
generation: buildPostLlmGeneratorProvenance(type, response.providerId, response.model),
};
}
@@ -503,7 +535,14 @@ async function semanticVerdicts(candidates, prompt, providerId, model, label) {
throw new Error(`Cannot score ${candidates.length} open-ended items in one bounded batch (max ${POST_LLM_MAX_SEMANTIC_CANDIDATES})`);
}
const response = await callAI(prompt, providerId, model);
- const parsed = validatePostLlmSemanticVerdicts(parseJsonFromAI(response.text), candidates, label);
+ const parsed = validatePostLlmSemanticVerdicts(parseJsonFromAI(response.text, (value) => {
+ try {
+ validatePostLlmSemanticVerdicts(value, candidates, label);
+ return true;
+ } catch {
+ return false;
+ }
+ }, prompt), candidates, label);
return {
verdicts: new Map(parsed.verdicts.map((verdict) => [`${verdict.responseIndex}:${verdict.itemIndex}`, verdict.valid])),
providerId: response.providerId,
@@ -769,8 +808,16 @@ export async function scoreLlmDrill(type, drillData, userResponses, timeLimitMs,
if (!builder) throw new Error(`Unsupported POST LLM scorer type: ${type}`);
console.log(`🧪 POST LLM scoring: ${type}`);
- const response = await callAI(builder(drillData, userResponses), providerId, model);
- const payload = validatePostLlmScorePayload(parseJsonFromAI(response.text), userResponses.length);
+ const scoringPrompt = builder(drillData, userResponses);
+ const response = await callAI(scoringPrompt, providerId, model);
+ const payload = validatePostLlmScorePayload(parseJsonFromAI(response.text, (value) => {
+ try {
+ validatePostLlmScorePayload(value, userResponses.length);
+ return true;
+ } catch {
+ return false;
+ }
+ }, scoringPrompt), userResponses.length);
const evaluation = evaluationWithProvenance(
type, drillData, payload, 'llm', response.providerId, response.model,
);
diff --git a/server/services/meatspacePostLlm.test.js b/server/services/meatspacePostLlm.test.js
index d359fc2a9c..f546336324 100644
--- a/server/services/meatspacePostLlm.test.js
+++ b/server/services/meatspacePostLlm.test.js
@@ -1028,6 +1028,25 @@ describe('AI response parsing', () => {
expect(result.questions[0].prompt).toBe('world');
});
+ it('skips an echoed generation schema before the real response', async () => {
+ const provider = {
+ id: 'test', enabled: true, type: 'api',
+ endpoint: 'http://localhost:9999', defaultModel: 'test'
+ };
+ getActiveProvider.mockResolvedValue(provider);
+ runPromptThroughProvider.mockImplementation(async ({ prompt }) => ({
+ // Some CLI providers echo the complete prompt, including its valid
+ // looking schema example, before printing the actual answer.
+ text: `${prompt}\n${JSON.stringify({
+ questions: [{ prompt: 'real-word', hints: 'real hint' }]
+ })}`,
+ runId: 'test-run', model: 'test-model'
+ }));
+
+ const result = await generateWordAssociation({ count: 1 });
+ expect(result.questions[0]).toEqual({ prompt: 'real-word', hints: 'real hint' });
+ });
+
it('throws on empty AI response', async () => {
const provider = {
id: 'test', enabled: true, type: 'api',
diff --git a/server/services/meatspacePostRhetoric.js b/server/services/meatspacePostRhetoric.js
index 68a94341b3..b5f280943b 100644
--- a/server/services/meatspacePostRhetoric.js
+++ b/server/services/meatspacePostRhetoric.js
@@ -24,14 +24,22 @@ export async function evaluateRhetoricAttempt({
effort,
}) {
const startedAt = Date.now();
+ const evaluatorPrompt = buildRhetoricEvaluatorPrompt({ mode, prompt, response });
const aiResponse = await callAI(
- buildRhetoricEvaluatorPrompt({ mode, prompt, response }),
+ evaluatorPrompt,
providerId,
model,
effort,
'meatspace-post-rhetoric-evaluator',
);
- const payload = validateRhetoricEvaluationPayload(mode, parseJsonFromAI(aiResponse.text));
+ const payload = validateRhetoricEvaluationPayload(mode, parseJsonFromAI(aiResponse.text, (value) => {
+ try {
+ validateRhetoricEvaluationPayload(mode, value);
+ return true;
+ } catch {
+ return false;
+ }
+ }, evaluatorPrompt));
const evaluation = rhetoricEvaluationSchema.parse({
...payload,
provenance: {
diff --git a/server/services/meatspacePostRhetoric.test.js b/server/services/meatspacePostRhetoric.test.js
index b344918a4b..04e3cd9a3a 100644
--- a/server/services/meatspacePostRhetoric.test.js
+++ b/server/services/meatspacePostRhetoric.test.js
@@ -50,5 +50,10 @@ describe('evaluateRhetoricAttempt', () => {
'high',
'meatspace-post-rhetoric-evaluator',
);
+ expect(parseJsonFromAI).toHaveBeenCalledWith(
+ '{}',
+ expect.any(Function),
+ expect.stringContaining('Return ONLY valid JSON'),
+ );
});
});
diff --git a/server/services/memoryClassifier.js b/server/services/memoryClassifier.js
index d5e779d9ce..4e1b0d60aa 100644
--- a/server/services/memoryClassifier.js
+++ b/server/services/memoryClassifier.js
@@ -10,6 +10,7 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { getStageTemplate } from './promptService.js';
import { atomicWrite, ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';
+import { extractJson } from '../lib/jsonExtract.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
import { readResponseJson } from '../lib/readResponseJson.js';
import { getMemories } from './memoryBackend.js';
@@ -279,26 +280,24 @@ async function callLLM(prompt, config) {
/**
* Parse LLM response to extract memories
*/
-function parseLLMResponse(response) {
- // Extract JSON from response (may be wrapped in markdown code blocks)
- const jsonMatch = response.match(/```(?:json)?\s*([\s\S]*?)```/) ||
- response.match(/(\{[\s\S]*\})/);
+function parseLLMResponse(response, promptToStrip = '') {
+ const source = promptToStrip && response?.includes(promptToStrip)
+ ? response.replace(promptToStrip, '')
+ : response;
+ const { value: parsed } = extractJson(source, {
+ // The classifier prompt includes a schema object. Walk all candidates and
+ // prefer the response shape so a prompt echo cannot look like an empty
+ // classification result.
+ skipInnerFence: true,
+ shapePredicate: (value) => value && typeof value === 'object' && !Array.isArray(value)
+ && Array.isArray(value.memories),
+ });
- if (!jsonMatch) {
+ if (parsed === undefined || !parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
console.log('⚠️ Could not find JSON in LLM response');
return { memories: [], rejected: [], parseError: true };
}
- let parsed;
- const jsonStr = jsonMatch[1].trim();
- // Validate JSON structure before parsing
- if (!jsonStr || !(jsonStr.startsWith('{') && jsonStr.endsWith('}'))) {
- console.log('⚠️ Extracted JSON appears malformed');
- return { memories: [], rejected: [], parseError: true };
- }
- parsed = safeJSONParse(jsonStr, null, { logError: true, context: 'memory classification' });
- if (!parsed) return { memories: [], rejected: [], parseError: true };
-
// Validate structure
if (!Array.isArray(parsed.memories)) {
return { memories: [], rejected: parsed.rejected || [], parseError: false };
@@ -377,7 +376,7 @@ export async function classifyMemories(task, agentOutput) {
};
}
- const result = parseLLMResponse(llmResponse);
+ const result = parseLLMResponse(llmResponse, prompt);
if (result.parseError) {
console.log(`⚠️ Failed to parse LLM response, raw: ${llmResponse.substring(0, 200)}`);
diff --git a/server/services/modelCapabilityTests.js b/server/services/modelCapabilityTests.js
index 9103780f24..f49518ec50 100644
--- a/server/services/modelCapabilityTests.js
+++ b/server/services/modelCapabilityTests.js
@@ -59,7 +59,7 @@ import {
applicableTests, getCapabilityTest,
scoreKeywords, scoreFictionScene, scoreStoryBeats, scoreSandboxRepair, rollUpVerdict,
} from '../lib/modelCapabilityTests.js';
-import { parseRhetoricJson, scoreRhetoricReference } from '../lib/postRhetoric.js';
+import { parseRhetoricJson, scoreRhetoricReference, RHETORIC_REFERENCE_SET } from '../lib/postRhetoric.js';
import { listRuntimeModels, runtimeEndpoint, runtimeApiKey } from './localModelAssessments.js';
import { runLocalLlmTest, runEndpointLlmTest } from './localLlmPlayground.js';
import { listProviders } from './providers.js';
@@ -249,7 +249,14 @@ const CHAT_TESTS = {
maxTokens: 5000,
message: (modelId) => `Scoring the rhetoric reference set with ${modelId}…`,
images: async () => undefined,
- score: (text) => scoreRhetoricReference(parseRhetoricJson(text)),
+ score: (text) => scoreRhetoricReference(parseRhetoricJson(text, (value) => {
+ const expected = new Set(RHETORIC_REFERENCE_SET.map(({ id }) => id));
+ return value && typeof value === 'object' && !Array.isArray(value)
+ && Array.isArray(value.evaluations)
+ && value.evaluations.length === expected.size
+ && value.evaluations.every((item) => item && expected.has(item.id)
+ && typeof item.score === 'number');
+ })),
},
};
diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.js
index 3aea666ad7..e813380826 100644
--- a/server/services/pm2Standardizer.js
+++ b/server/services/pm2Standardizer.js
@@ -4,7 +4,8 @@ import { join, basename, relative } from 'path';
import { exec, spawn } from '../lib/childProcess.js';
import { promisify } from 'util';
import { getActiveProvider, getProviderById } from './providers.js';
-import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
+import { tryReadFile } from '../lib/fileUtils.js';
+import { extractJson } from '../lib/jsonExtract.js';
import { runPromptThroughProvider } from './promptRunner.js';
import { getReservedPorts, getAllApps } from './apps.js';
import { PORTOS_APP_ID } from '../lib/appIdentity.js';
@@ -381,24 +382,26 @@ async function executeAnalysis(provider, prompt, cwd) {
/**
* Parse LLM response to extract JSON
*/
-function parseAnalysisResponse(response) {
- let jsonStr = response.trim();
-
- // Remove markdown code blocks if present
- const jsonMatch = jsonStr.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (jsonMatch) {
- jsonStr = jsonMatch[1].trim();
+function parseAnalysisResponse(response, promptToStrip = '') {
+ const source = promptToStrip && typeof response === 'string' && response.includes(promptToStrip)
+ ? response.replace(promptToStrip, '')
+ : response;
+ if (typeof source === 'string' && /^\s*(?:```(?:json)?\s*)?\[/.test(source)) {
+ throw new Error('Failed to parse LLM analysis response: expected an object');
}
-
- // Try to find JSON object
- const objectMatch = jsonStr.match(/\{[\s\S]*\}/);
- if (objectMatch) {
- jsonStr = objectMatch[0];
+ const { value, lastError } = extractJson(source, {
+ // The standardization prompt contains a JSON schema example; avoid the
+ // first fenced block heuristic and select the process-plan shape.
+ skipInnerFence: true,
+ shapePredicate: (candidate) => candidate && typeof candidate === 'object'
+ && !Array.isArray(candidate) && Array.isArray(candidate.processes),
+ });
+ // Preserve the legacy parser's falsy-value failure contract (null, false,
+ // zero, and empty strings are not usable analysis objects).
+ if (!value) {
+ throw new Error(`Failed to parse LLM analysis response${lastError ? `: ${lastError.message}` : ''}`);
}
-
- const parsed = safeJSONParse(jsonStr, null, { logError: true, context: 'PM2 standardizer analysis' });
- if (!parsed) throw new Error('Failed to parse LLM analysis response');
- return parsed;
+ return value;
}
/**
@@ -511,7 +514,7 @@ export async function analyzeApp(repoPath, providerId = null) {
console.log(`✅ Analysis response received in ${((Date.now() - startTime) / 1000).toFixed(1)}s`);
// Parse response
- const analysis = parseAnalysisResponse(response);
+ const analysis = parseAnalysisResponse(response, prompt);
// Deterministic safety net: even if the LLM ignored the avoid-list, remap any
// port that still collides with a taken/duplicate port before generating the file.
diff --git a/server/services/writersRoom/evaluator.js b/server/services/writersRoom/evaluator.js
index 5cf1c7a485..e3204d6cb9 100644
--- a/server/services/writersRoom/evaluator.js
+++ b/server/services/writersRoom/evaluator.js
@@ -8,8 +8,8 @@ import { join } from 'path';
import { readFile, readdir } from 'fs/promises';
import { PATHS, atomicWrite, ensureDir, safeJSONParse, tryReadFile, rmGuarded } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
-import { stripCodeFences } from '../aiProvider.js';
import { runStagedLLM } from '../stageRunner.js';
+import { extractJson as extractJsonShared } from '../../lib/jsonExtract.js';
import { extractBible } from '../bibleExtractor.js';
import { extractScenes, SOURCE_KIND } from '../sceneExtractor.js';
import { BIBLE_KIND } from '../../lib/storyBible.js';
@@ -60,13 +60,23 @@ const analysisPath = (workId, id) => join(analysisDir(workId), `${id}.json`);
// ---------- response parsing ----------
-function extractJson(text) {
+function extractJsonResponse(text, shapePredicate) {
+ // runStagedLLM parses returnsJson stages before handing the result to the
+ // shaper. Keep that object boundary accepted so the shared extractor only
+ // handles raw strings from direct callers; otherwise every JSON Writers
+ // Room pass would fail with "Empty AI response" after the migration.
+ if (text && typeof text === 'object') return text;
if (!text || typeof text !== 'string') throw new Error('Empty AI response');
- let str = stripCodeFences(text);
- // Some providers prepend explanation text; pull the first balanced object/array.
- const objMatch = str.match(/[{[][\s\S]*[\]}]/);
- if (objMatch) str = objMatch[0];
- return JSON.parse(str);
+ const { value, lastError } = extractJsonShared(text, {
+ // Writers Room prompts include fenced JSON schemas. Walk every candidate
+ // so a provider's echoed schema cannot become the analysis.
+ skipInnerFence: true,
+ shapePredicate,
+ });
+ if (value === undefined) {
+ throw new Error(`Failed to parse AI response${lastError ? `: ${lastError.message}` : ''}`);
+ }
+ return value;
}
// Strip a leading/trailing markdown code fence from a prose response — some
@@ -81,7 +91,10 @@ function stripProseFence(raw) {
export const SHAPERS = {
format: (raw) => ({ formattedBody: stripProseFence(raw) }),
evaluate: (raw) => {
- const parsed = extractJson(raw);
+ const parsed = extractJsonResponse(raw, (value) => value && typeof value === 'object'
+ && !Array.isArray(value)
+ && ['logline', 'summary', 'themes', 'strengths', 'issues', 'suggestions']
+ .some((key) => key in value));
return {
logline: typeof parsed.logline === 'string' ? parsed.logline : null,
summary: typeof parsed.summary === 'string' ? parsed.summary : null,
@@ -96,7 +109,9 @@ export const SHAPERS = {
// health signals (fat %, protected passage). Findings without a usable anchor
// quote or a recognized cut type are dropped — the applier can't act on them.
cuts: (raw) => {
- const parsed = extractJson(raw);
+ const parsed = extractJsonResponse(raw, (value) => value && typeof value === 'object'
+ && !Array.isArray(value) && (Array.isArray(value.findings)
+ || typeof value.fat_percentage === 'number'));
const rawFindings = Array.isArray(parsed.findings) ? parsed.findings : [];
return {
fatPercentage: typeof parsed.fat_percentage === 'number' ? parsed.fat_percentage : null,
diff --git a/server/services/writersRoom/evaluator.test.js b/server/services/writersRoom/evaluator.test.js
index ab0575c2c7..e54720e408 100644
--- a/server/services/writersRoom/evaluator.test.js
+++ b/server/services/writersRoom/evaluator.test.js
@@ -56,6 +56,11 @@ describe('SHAPERS.cuts', () => {
expect(shaped.findings).toEqual([]);
expect(shaped.fatPercentage).toBe(0);
});
+
+ it('accepts the parsed object returned by a returnsJson staged pass', () => {
+ const shaped = SHAPERS.cuts({ fat_percentage: 4, findings: [] });
+ expect(shaped).toMatchObject({ fatPercentage: 4, findings: [] });
+ });
});
describe('SHAPERS.revise', () => {
diff --git a/server/test/fixtures/brainDigestEcho.js b/server/test/fixtures/brainDigestEcho.js
new file mode 100644
index 0000000000..1d27d33e90
--- /dev/null
+++ b/server/test/fixtures/brainDigestEcho.js
@@ -0,0 +1,23 @@
+/**
+ * A provider transcript with a fenced prompt schema echoed before the real
+ * Brain digest response. Shared by the jsonExtract contract test and the
+ * migrated Brain caller so both pin the same regression shape.
+ */
+const echoedSchema = {
+ digestText: 'string',
+ topActions: 'array',
+ stuckThing: 'string',
+ smallWin: 'string',
+};
+
+const actual = {
+ digestText: 'Real digest summary',
+ topActions: ['Ship the fix'],
+ stuckThing: 'Nothing blocked',
+ smallWin: 'A passing regression test',
+};
+
+export const BRAIN_DIGEST_ECHO_FIXTURE = Object.freeze({
+ actual: Object.freeze(actual),
+ raw: `OpenAI Codex CLI v2.1.0\n[workdir, /tmp]\n\n\`\`\`json\n${JSON.stringify(echoedSchema)}\n\`\`\`\n${JSON.stringify(actual)}`,
+});