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

fix: parse calendar and animation review responses reliably (#9926)

[._.]/ Adam Eivy61e2796e434a
diff --git a/server/services/calendarGoogleSync.js b/server/services/calendarGoogleSync.js
index da2398c0dd..d392a0913c 100644
--- a/server/services/calendarGoogleSync.js
+++ b/server/services/calendarGoogleSync.js
@@ -5,7 +5,7 @@ import { mutateCache, logCalendarTouchpoints, recordCalendarActivity } from './c
import { getAllProviders } from './providers.js';
import { getSettings } from './settings.js';
import { pickCliProvider, runCliProviderPrompt } from '../lib/cliProviderRun.js';
-import { safeJSONParse } from '../lib/fileUtils.js';
+import { extractJson } from '../lib/jsonExtract.js';
import { selectMeetingUrl } from '../lib/meetingUrl.js';
import { ServerError } from '../lib/errorHandler.js';
@@ -264,7 +264,7 @@ Include the full events arrays as returned by gcal_list_events, with every field
const status = partial ? 'partial' : 'success';
// Parse Claude's output and push events
- const parsed = parseCalendarJson(result.output);
+ const parsed = parseCalendarJson(result.output.split(prompt).join(''));
if (!parsed) {
// Carry the stderr tail so the failure names WHY the CLI produced no
// usable JSON instead of a bare, undiagnosable parse error.
@@ -327,20 +327,21 @@ Include the full events arrays as returned by gcal_list_events, with every field
});
}
+const isCalendarPayload = value => Array.isArray(value?.calendars) && value.calendars.every(cal =>
+ typeof cal?.calendarId === 'string' && cal.calendarId.trim() && Array.isArray(cal.events)
+ && cal.events.every(event => event !== null && typeof event === 'object' && !Array.isArray(event)));
+
function parseCalendarJson(output) {
- // Try to extract JSON from Claude's response
- // Look for {"calendars":...} pattern
- const jsonMatch = output.match(/\{[\s\S]*"calendars"\s*:\s*\[[\s\S]*\]\s*\}/);
- if (jsonMatch) {
- const parsed = safeJSONParse(jsonMatch[0], null);
- if (parsed?.calendars) return parsed;
- }
- // Try parsing the entire output as JSON
- const parsed = safeJSONParse(output, null);
- if (parsed?.calendars) return parsed;
- return null;
+ const { value } = extractJson(output, { shapePredicate: isCalendarPayload, skipInnerFence: true });
+ // The shared extractor can return a parseable nonmatching fallback.
+ return isCalendarPayload(value) ? value : null;
}
+const isDiscoveredCalendars = value => Array.isArray(value) && value.every(cal =>
+ typeof cal?.id === 'string' && cal.id.trim()
+ && (cal.name === undefined || typeof cal.name === 'string')
+ && (cal.color === undefined || typeof cal.color === 'string'));
+
export async function mcpDiscoverCalendars(accountId, io) {
const account = await getAccount(accountId);
if (!account) throw new ServerError('Account not found', { status: 404 });
@@ -371,15 +372,14 @@ Output NOTHING else — just the JSON array.`;
throw new ServerError(`Calendar discovery returned a partial response — not merging: ${reason}`, { status: 502 });
}
- // Parse the calendar list from Claude's output
- const match = result.output.match(/\[[\s\S]*\]/);
- if (!match) {
+ const { value: calendars } = extractJson(result.output.split(prompt).join(''), {
+ blockType: 'array', shapePredicate: isDiscoveredCalendars, skipInnerFence: true,
+ });
+ if (calendars === undefined) {
const reason = result.stderrTail ? `: ${result.stderrTail}` : '';
throw new ServerError(`Failed to parse calendar list from Claude response${reason}`, { status: 502 });
}
-
- const calendars = safeJSONParse(match[0], null);
- if (!Array.isArray(calendars)) throw new ServerError('Invalid calendar list format', { status: 502 });
+ if (!isDiscoveredCalendars(calendars)) throw new ServerError('Invalid calendar list format', { status: 502 });
// Merge with existing subcalendars (preserve enabled/dormant state)
const merged = mergeDiscoveredSubcalendars(account.subcalendars, calendars);
diff --git a/server/services/calendarGoogleSync.test.js b/server/services/calendarGoogleSync.test.js
index 2865db02dd..5603ff2921 100644
--- a/server/services/calendarGoogleSync.test.js
+++ b/server/services/calendarGoogleSync.test.js
@@ -184,6 +184,67 @@ describe('mcpDiscoverCalendars CLI exit-status agreement (#5302)', () => {
});
});
+// #9926: exercise extraction at the service boundary before any destructive write.
+describe('MCP transcript extraction', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getAccount.mockResolvedValue(account());
+ loadCache.mockResolvedValue({ events: cachedEvents() });
+ });
+
+ it('skips metadata and every echoed prompt, preserving fenced event string content', async () => {
+ const event = rawEvent('new-event', 'Review [draft] {v2}');
+ event.description = 'Keep ```json {"example":[]} ``` in the notes.';
+ runCliProviderPrompt.mockImplementation(async ({ prompt }) => ({
+ text: `${prompt}\nMetadata: {"request":"complete"}\n${prompt}\nActual: \`\`\`json\n${JSON.stringify({ calendars: [{ calendarId: CAL_ID, events: [event] }] })}\n\`\`\``,
+ exitCode: 0, partial: false,
+ }));
+
+ const result = await mcpSyncAccount(ACCOUNT_ID, null);
+
+ expect(result.status).toBe('success');
+ expect(savedCache().events).toEqual([expect.objectContaining({ title: event.summary, description: event.description })]);
+ });
+
+ it('accepts an empty event snapshot and an empty calendar response', async () => {
+ runCliProviderPrompt.mockResolvedValue({ text: JSON.stringify({ calendars: [{ calendarId: CAL_ID, events: [] }] }), exitCode: 0 });
+ expect((await mcpSyncAccount(ACCOUNT_ID, null)).pruned).toBe(1);
+ expect(savedCache().events).toEqual([]);
+ saveCache.mockClear();
+ runCliProviderPrompt.mockResolvedValue({ text: '{"calendars":[]}', exitCode: 0 });
+ expect((await mcpSyncAccount(ACCOUNT_ID, null)).calendars).toEqual([]);
+ expect(saveCache).not.toHaveBeenCalled();
+ });
+
+ it.each(['{"calendars":{}}', '{"calendars":[{"calendarId":"example","events":[null]}]}', 'not JSON', 'prompt only'])('rejects invalid sync payload %s before touching events', async text => {
+ runCliProviderPrompt.mockImplementation(async ({ prompt }) => ({ text: text === 'prompt only' ? `${prompt}\n${prompt}` : text, exitCode: 0 }));
+ await expect(mcpSyncAccount(ACCOUNT_ID, null)).rejects.toMatchObject({ status: 502 });
+ expect(saveCache).not.toHaveBeenCalled();
+ expect(updateSyncStatus).toHaveBeenCalledWith(ACCOUNT_ID, 'error');
+ });
+
+ it('skips discovery banners and repeated schema echoes before merging the actual list', async () => {
+ const discovered = [{ id: CAL_ID, name: 'Work [draft] {v2}', color: '#123456' }];
+ runCliProviderPrompt.mockImplementation(async ({ prompt }) => ({
+ text: `${prompt}\n[workdir, example]\n${prompt}\n\`\`\`json\n${JSON.stringify(discovered)}\n\`\`\``, exitCode: 0,
+ }));
+ expect((await mcpDiscoverCalendars(ACCOUNT_ID, null)).calendars).toEqual(discovered);
+ expect(updateSubcalendars).toHaveBeenCalledWith(ACCOUNT_ID, discovered);
+ });
+
+ it('preserves a valid empty discovered list', async () => {
+ runCliProviderPrompt.mockResolvedValue({ text: '```json\n[]\n```', exitCode: 0 });
+ expect((await mcpDiscoverCalendars(ACCOUNT_ID, null)).calendars).toEqual([]);
+ expect(updateSubcalendars).toHaveBeenCalledWith(ACCOUNT_ID, []);
+ });
+
+ it.each(['[{"name":"Missing identity"}]', '["not a calendar"]', 'not JSON', 'prompt only'])('refuses invalid discovery %s without replacing subcalendars', async text => {
+ runCliProviderPrompt.mockImplementation(async ({ prompt }) => ({ text: text === 'prompt only' ? `${prompt}\n${prompt}` : text, exitCode: 0 }));
+ await expect(mcpDiscoverCalendars(ACCOUNT_ID, null)).rejects.toMatchObject({ status: 502 });
+ expect(updateSubcalendars).not.toHaveBeenCalled();
+ });
+});
+
// #6289: a Google event's join link is projected into a single cached
// `meetingUrl`. The regressions these pin are (a) caching something that is not
// a usable video link, and (b) an older producer that omits the conference
diff --git a/server/services/codeAnimation/stages.db.test.js b/server/services/codeAnimation/stages.db.test.js
index c224525119..24bd77101d 100644
--- a/server/services/codeAnimation/stages.db.test.js
+++ b/server/services/codeAnimation/stages.db.test.js
@@ -34,6 +34,18 @@ vi.mock('fs/promises', async importOriginal => {
};
});
vi.mock('../socket.js', () => ({ emitCodeAnimationChanged: vi.fn() }));
+// Exercise the default review adapter with only its external provider boundary doubled.
+vi.mock('./preflight.js', async importOriginal => ({
+ ...await importOriginal(),
+ preflightProductionProject: vi.fn(async () => ({
+ resolved: { providerId: 'example-provider', model: 'example-model' }, problems: [],
+ capabilities: { imageInputAccepted: true }, allowFallback: false,
+ })),
+}));
+vi.mock('../providers.js', () => ({ getProviderById: vi.fn(async () => ({ id: 'example-provider' })) }));
+vi.mock('../promptRunner.js', () => ({ runPromptThroughProvider: vi.fn() }));
+vi.mock('../runner.js', () => ({ stopRun: vi.fn() }));
+import { runPromptThroughProvider } from '../promptRunner.js';
import { checkHealth, ensureSchema, query, close } from '../../lib/db.js';
import { requireDbOrSkip } from '../../lib/dbTestGate.js';
import { createCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';
@@ -180,6 +192,39 @@ describe.skipIf(!ready)('Production stage runs', () => {
expect(saved.data.verdict.unverified.map(item => item.dimension)).not.toContain('semantic-visual');
});
+ it.each([false, true])('extracts default-adapter review evidence after metadata and repeated prompt echoes (empty=%s)', async empty => {
+ const { id } = await project();
+ const detail = ` Brighter [background] {please}: ${'x'.repeat(510)} `;
+ const findings = empty ? [] : [{ detail, atSeconds: 1 }, { detail: 'Keep ```json {"shape":[]} ``` in frame.', atSeconds: 'unknown' }];
+ runPromptThroughProvider.mockImplementation(async ({ prompt }) => ({
+ text: `${prompt}\nExample: {"schema":"findings"}\n${prompt}\nActual: \`\`\`json\n${JSON.stringify({ findings })}\n\`\`\``,
+ provider: { id: 'example-provider' }, model: 'example-model',
+ }));
+ const { run, done } = await startProductionStageRun(id, { visualReview: true }, { sample, repair: unfreeze, render });
+ expect(await done).toBe('completed');
+ const saved = (await getProductionHistory(id, { limit: 1, offset: 0 })).items.find(item => item.id === run.id);
+ const review = saved.data.stages.find(stage => stage.key === 'review');
+ expect(review.status).toBe('completed');
+ expect(review.reviewFindings).toEqual(empty ? [] : [
+ { detail: detail.trim().slice(0, 500), atSeconds: 1 },
+ { detail: findings[1].detail, atSeconds: null },
+ ]);
+ expect(saved.data.verdict.unverified.map(item => item.dimension)).not.toContain('semantic-visual');
+ expect(runPromptThroughProvider.mock.calls.at(-1)[0]).toMatchObject({ toolFree: true, source: 'code-animation-review', screenshots: expect.any(Array) });
+ });
+
+ it.each(['{"schema":"findings"}', '{"findings":[{"detail":42}]}', 'not JSON', 'prompt only'])('fails default-adapter review without successful evidence for %s', async text => {
+ const { id } = await project();
+ runPromptThroughProvider.mockImplementation(async ({ prompt }) => ({ text: text === 'prompt only' ? `${prompt}\n${prompt}` : text }));
+ render.mockClear();
+ const { done } = await startProductionStageRun(id, { visualReview: true }, { sample, repair: unfreeze, render });
+ expect(await done).toBe('failed');
+ const [saved] = (await getProductionHistory(id, { limit: 1, offset: 0 })).items;
+ expect(saved.data.stages.find(stage => stage.key === 'review')).toMatchObject({ status: 'failed', error: 'CODE_ANIMATION_REVIEW_INVALID' });
+ expect(saved.data.stages.some(stage => stage.key === 'inspect')).toBe(false);
+ expect(render).not.toHaveBeenCalled();
+ });
+
it('cancels a pending visual review through its signal and resumes with the opt-in inherited', async () => {
const { id } = await project();
let reviewStarted;
diff --git a/server/services/codeAnimation/stages.js b/server/services/codeAnimation/stages.js
index 71e0a7781c..091262b693 100644
--- a/server/services/codeAnimation/stages.js
+++ b/server/services/codeAnimation/stages.js
@@ -16,6 +16,7 @@ import { join } from 'path';
import { createCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';
import { codeAnimationStageRunSchema } from '../../lib/codeAnimationProjects.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { extractJson } from '../../lib/jsonExtract.js';
import { PATHS } from '../../lib/paths.js';
import { htmlCompositionContractSchema, validateRequest } from '../../lib/validation.js';
import { emitCodeAnimationChanged } from '../socket.js';
@@ -226,18 +227,17 @@ async function reviewViaAuthoringRoute({ project, manifest, artifacts, signal, t
source: 'code-animation-review', cwd: PATHS.data, allowFallback: preflight.allowFallback, toolFree: true,
}).finally(() => signal?.removeEventListener('abort', stopProvider));
const route = _recordEffectiveRoute(preflight.resolved, project.localSettings, result);
- const parsed = parseReviewFindings(result.text);
+ const parsed = parseReviewFindings(result.text?.split(prompt).join(''));
if (!parsed) throw new ServerError('The reviewer response was not valid JSON findings', { status: 422, code: 'CODE_ANIMATION_REVIEW_INVALID' });
return { findings: parsed, tokens: Math.ceil((prompt.length + result.text.length) / 4), reviewer: { providerId: route.effective.providerId, model: route.effective.model }, effective: route };
}
/** Pull `{findings:[…]}` out of a reply that may be fenced or wrapped in prose; null when it carries none. */
function parseReviewFindings(text) {
- const match = String(text ?? '').match(/\{[\s\S]*\}/);
- if (!match) return null;
- let value;
- try { value = JSON.parse(match[0]); } catch { return null; }
- if (!Array.isArray(value?.findings)) return null;
+ const isReviewPayload = value => Array.isArray(value?.findings)
+ && value.findings.every(item => typeof item?.detail === 'string');
+ const { value } = extractJson(text, { shapePredicate: isReviewPayload, skipInnerFence: true });
+ if (!isReviewPayload(value)) return null;
return value.findings.filter(item => typeof item?.detail === 'string' && item.detail.trim()).slice(0, 10)
.map(item => ({ detail: item.detail.trim().slice(0, 500), atSeconds: Number.isFinite(item.atSeconds) ? item.atSeconds : null }));
}