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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: protect all external-data JSON.parse calls with safeJSONParse
Adam Eivy2fa842ab49a1
diff --git a/.changelog/v0.16.x.md b/.changelog/v0.16.x.mdindex c0eeded469..e386806751 100644--- a/.changelog/v0.16.x.md+++ b/.changelog/v0.16.x.md@@ -72,6 +72,11 @@ Agent persistence, reliability, and decision transparency improvements.- **Added upfront field validation** -- before entering the loop, each cron field is checked against its valid range (minutes 0-59, hours 0-23, day 1-31, month 1-12, day-of-week 0-7); out-of-range values return `null` immediately- **Added iteration safety cap** -- even for valid-but-unmatchable expressions, the loop now breaks after 525,960 iterations (1 year in minutes) instead of running for the full 2-year window+### Protected all external-data JSON.parse calls from crashing the server+- **Previously**, 15 `JSON.parse` calls on external data (AI responses, file reads, PM2 output, user imports) were unprotected -- a single malformed response or corrupted file would throw and crash the process+- **Now uses `safeJSONParse`** from `fileUtils.js` with appropriate fallbacks: `null` for AI response parsing (graceful degradation to raw-response paths), `[]` for PM2 process lists, `{}` for script metadata, default state for CoS state file+- **Files fixed**: `digital-twin.js` (11 locations across 7 AI-response parser functions and Spotify import), `cos.js` (4 locations: state loading, PM2 parsing, script metadata, report reading)+### Fixed byModelTier data corruption in task type reset- **Model tier metrics drifted from reality** -- `resetTaskTypeLearning()` subtracted counts from `byTaskType`, `errorPatterns`, `routingAccuracy`, and `totals`, but never touched `byModelTier`; after rehabilitation resets, the heavy tier showed 653 completed / 3 succeeded (0.46% success) due to accumulated historical data that was cleared from other structures but not from tier metrics- **Now subtracts routing accuracy data from byModelTier** -- when a task type is reset, its per-tier succeeded/failed counts are decremented from the corresponding `byModelTier` entries, with duration estimated proportionally from the task type's averagediff --git a/server/services/cos.js b/server/services/cos.jsindex f09e17f0c5..bbcd023b25 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -21,7 +21,7 @@ import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getScheduimport { createMutex } from '../lib/asyncMutex.js';import { generateProactiveTasks as generateMissionTasks, getStats as getMissionStats } from './missions.js';import { getDueJobs, generateTaskFromJob, recordJobExecution } from './autonomousJobs.js';-import { formatDuration } from '../lib/fileUtils.js';+import { formatDuration, safeJSONParse } from '../lib/fileUtils.js';import { addNotification, NOTIFICATION_TYPES } from './notifications.js';import { recordDecision, DECISION_TYPES } from './decisionLog.js';// Import and re-export cosEvents from separate module to avoid circular dependencies@@ -260,7 +260,8 @@ async function loadState() {return { ...DEFAULT_STATE };}- const state = JSON.parse(content);+ const state = safeJSONParse(content, null, { logError: true, context: 'CoS state' });+ if (!state) return { ...DEFAULT_STATE };// Merge with defaults to ensure all fields existreturn {@@ -2165,7 +2166,7 @@ export async function runHealthCheck() {jsonStart = emptyMatch ? pm2Output.indexOf(emptyMatch[0]) : -1;}const pm2Json = jsonStart >= 0 ? pm2Output.slice(jsonStart) : '[]';- const pm2Processes = JSON.parse(pm2Json);+ const pm2Processes = safeJSONParse(pm2Json, [], { logError: true, context: 'pm2 process list' });metrics.pm2 = {total: pm2Processes.length,@@ -2305,7 +2306,7 @@ export async function getScript(name) {const content = await readFile(scriptPath, 'utf-8');const metadata = existsSync(metaPath)- ? JSON.parse(await readFile(metaPath, 'utf-8'))+ ? safeJSONParse(await readFile(metaPath, 'utf-8'), {}, { logError: true, context: `script metadata ${name}` }): {};return { name, content, metadata };@@ -2792,7 +2793,7 @@ export async function getReport(date) {}const content = await readFile(reportFile, 'utf-8');- return JSON.parse(content);+ return safeJSONParse(content, null, { logError: true, context: `report ${date}` });}/**diff --git a/server/services/digital-twin.js b/server/services/digital-twin.jsindex b5f61f471d..88b8f16fe3 100644--- a/server/services/digital-twin.js+++ b/server/services/digital-twin.js@@ -1244,17 +1244,19 @@ Respond in JSON format:// Parse the JSON responseconst jsonMatch = responseText.match(/```json\s*([\s\S]*?)\s*```/);if (jsonMatch) {- const parsed = JSON.parse(jsonMatch[1]);- return {- category,- items,- itemAnalysis: parsed.itemAnalysis || [],- patterns: parsed.patterns || [],- personalityInsights: parsed.personalityInsights || {},- suggestedDocument: parsed.suggestedDocument || '',- targetDoc: config.targetDoc,- targetCategory: config.targetCategory- };+ const parsed = safeJSONParse(jsonMatch[1], null, { logError: true, context: 'enrichment analysis' });+ if (parsed) {+ return {+ category,+ items,+ itemAnalysis: parsed.itemAnalysis || [],+ patterns: parsed.patterns || [],+ personalityInsights: parsed.personalityInsights || {},+ suggestedDocument: parsed.suggestedDocument || '',+ targetDoc: config.targetDoc,+ targetCategory: config.targetCategory+ };+ }}// Fallback if JSON parsing fails@@ -1706,14 +1708,14 @@ function parseContradictionResponse(response) {// Try to extract JSON from the responseconst jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);if (jsonMatch) {- const parsed = JSON.parse(jsonMatch[1]);- return { issues: parsed.issues || [], summary: parsed.summary };+ const parsed = safeJSONParse(jsonMatch[1], null, { logError: true, context: 'contradiction analysis' });+ if (parsed) return { issues: parsed.issues || [], summary: parsed.summary };}// Fallback: try direct JSON parseif (response.trim().startsWith('{') || response.trim().startsWith('[')) {- const parsed = JSON.parse(response);- return { issues: parsed.issues || parsed || [], summary: parsed.summary };+ const parsed = safeJSONParse(response, null, { logError: true, context: 'contradiction analysis fallback' });+ if (parsed) return { issues: parsed.issues || parsed || [], summary: parsed.summary };}return { issues: [], rawResponse: response };@@ -1751,14 +1753,14 @@ function parseGeneratedTests(response) {// Try to extract JSON from the responseconst jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);if (jsonMatch) {- const parsed = JSON.parse(jsonMatch[1]);- return { tests: parsed.tests || parsed || [] };+ const parsed = safeJSONParse(jsonMatch[1], null, { logError: true, context: 'generated tests' });+ if (parsed) return { tests: parsed.tests || parsed || [] };}// Fallback: try direct JSON parseif (response.trim().startsWith('{') || response.trim().startsWith('[')) {- const parsed = JSON.parse(response);- return { tests: parsed.tests || parsed || [] };+ const parsed = safeJSONParse(response, null, { logError: true, context: 'generated tests fallback' });+ if (parsed) return { tests: parsed.tests || parsed || [] };}return { tests: [], rawResponse: response };@@ -1796,11 +1798,13 @@ function parseWritingAnalysis(response) {// Try to extract JSONconst jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);if (jsonMatch) {- const parsed = JSON.parse(jsonMatch[1]);- return {- analysis: parsed.analysis || parsed,- suggestedContent: parsed.suggestedContent || parsed.document || ''- };+ const parsed = safeJSONParse(jsonMatch[1], null, { logError: true, context: 'writing analysis' });+ if (parsed) {+ return {+ analysis: parsed.analysis || parsed,+ suggestedContent: parsed.suggestedContent || parsed.document || ''+ };+ }}// Extract markdown content for document if present@@ -2021,11 +2025,13 @@ export async function calculateConfidence(providerId, model) {function parseConfidenceResponse(response) {const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);if (jsonMatch) {- return JSON.parse(jsonMatch[1]);+ const parsed = safeJSONParse(jsonMatch[1], null, { logError: true, context: 'confidence response' });+ if (parsed) return parsed;}if (response.trim().startsWith('{')) {- return JSON.parse(response);+ const parsed = safeJSONParse(response, null, { logError: true, context: 'confidence response fallback' });+ if (parsed) return parsed;}return { error: 'Failed to parse confidence response' };@@ -2292,7 +2298,8 @@ function parseCSVLine(line) {* Spotify exports: endTime, artistName, trackName, msPlayed*/function parseSpotifyJSON(jsonData) {- const data = JSON.parse(jsonData);+ const data = safeJSONParse(jsonData, null, { logError: true, context: 'Spotify JSON import' });+ if (!data) return [];// Handle both array format and object with streams arrayconst streams = Array.isArray(data) ? data : (data.streams || data);@@ -2594,21 +2601,25 @@ async function analyzeWithPrompt(prompt, providerId, model, source, parsedData)function parseImportAnalysisResponse(response, source, parsedData) {const jsonMatch = response.match(/```json\s*([\s\S]*?)\s*```/);if (jsonMatch) {- const parsed = JSON.parse(jsonMatch[1]);- return {- source,- itemCount: Array.isArray(parsedData) ? parsedData.length : (parsedData.artists?.length || 0),- ...parsed- };+ 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+ };+ }}if (response.trim().startsWith('{')) {- const parsed = JSON.parse(response);- return {- source,- itemCount: Array.isArray(parsedData) ? parsedData.length : (parsedData.artists?.length || 0),- ...parsed- };+ 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+ };+ }}return {