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: inline isValidJSON into safeJSONParse to stop it being forked (#6181)
Adam Eivyc9c9864c7918
diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.jsindex 6883f24fc8..c69b727d53 100644--- a/server/lib/agentSentinel.js+++ b/server/lib/agentSentinel.js@@ -91,11 +91,12 @@ export function parseSentinelPayload(contents) {if (!trimmed) return { summary: '', payload: null };// Only a JSON OBJECT counts as structured. `safeJSONParse` with allowArray:false- // returns the object, or null for a plain markdown summary / bare JSON- // scalar/array / malformed content — so a legacy sentinel round-trips as text- // (repo convention: reuse safeJSONParse, no bare try/catch).+ // rejects a root array and returns null for malformed content, but still parses+ // a bare scalar (`"42"`, `"true"`) — so guard for a genuine object here too, or+ // a legacy sentinel that happens to be a lone number/string/bool would crash on+ // the `'payload' in parsed` check below instead of round-tripping as text.const parsed = safeJSONParse(trimmed, null, { allowArray: false });- if (parsed) {+ if (parsed && typeof parsed === 'object') {const summary = typeof parsed.summary === 'string' ? parsed.summary : '';const payload = 'payload' in parsed ? parsed.payload : null;return { summary, payload };diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex 1be6573b1d..848c253455 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -33,7 +33,6 @@ import {ensureDir,pathExists,expandHome,- isValidJSON,listDirectoryByExtension,safeJSONParse,safeJSONLParse,@@ -127,56 +126,6 @@ async function withUnreadableFile(err, fn) {}describe('fileUtils', () => {- describe('isValidJSON', () => {- it('should return true for valid JSON object', () => {- expect(isValidJSON('{"key": "value"}')).toBe(true);- });-- it('should return true for valid JSON array when allowed', () => {- expect(isValidJSON('[1, 2, 3]')).toBe(true);- });-- it('should return false for JSON array when not allowed', () => {- expect(isValidJSON('[1, 2, 3]', { allowArray: false })).toBe(false);- });-- it('should return false for empty string', () => {- expect(isValidJSON('')).toBe(false);- });-- it('should return false for whitespace-only string', () => {- expect(isValidJSON(' ')).toBe(false);- });-- it('should return false for null', () => {- expect(isValidJSON(null)).toBe(false);- });-- it('should return false for undefined', () => {- expect(isValidJSON(undefined)).toBe(false);- });-- it('should return false for string not starting with { or [', () => {- expect(isValidJSON('hello')).toBe(false);- });-- it('should return false for incomplete object (missing end)', () => {- expect(isValidJSON('{"key":')).toBe(false);- });-- it('should return false for incomplete array (missing end)', () => {- expect(isValidJSON('[1, 2')).toBe(false);- });-- it('should handle whitespace around valid JSON', () => {- expect(isValidJSON(' {"key": "value"} ')).toBe(true);- });-- it('should handle nested objects', () => {- expect(isValidJSON('{"outer": {"inner": "value"}}')).toBe(true);- });- });-describe('safeJSONParse', () => {it('should parse valid JSON object', () => {const result = safeJSONParse('{"key": "value"}', {});@@ -223,6 +172,23 @@ describe('fileUtils', () => {expect(result).toEqual({});});+ it('should still reject a root array under allowArray: false when defaultValue is not an array', () => {+ const result = safeJSONParse('["a", "b"]', { fallback: true }, { allowArray: false });+ expect(result).toEqual({ fallback: true });+ });++ it('should parse a top-level scalar string', () => {+ expect(safeJSONParse('"hello"', null)).toBe('hello');+ });++ it('should parse a top-level scalar number', () => {+ expect(safeJSONParse('123', null)).toBe(123);+ });++ it('should parse a top-level scalar boolean', () => {+ expect(safeJSONParse('true', null)).toBe(true);+ });+it('should log warning when logError is true', () => {const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});safeJSONParse('invalid', {}, { logError: true });@@ -245,7 +211,6 @@ describe('fileUtils', () => {});it('should handle syntax error in structurally valid JSON', () => {- // Passes structural check but fails JSON.parseconst consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});const result = safeJSONParse('{"key": undefined}', { fallback: true }, { logError: true });expect(result).toEqual({ fallback: true });diff --git a/server/lib/jsonIo.js b/server/lib/jsonIo.jsindex f6869d1498..641cd45c4a 100644--- a/server/lib/jsonIo.js+++ b/server/lib/jsonIo.js@@ -10,34 +10,6 @@ const WIN_RETRY_ATTEMPTS = 5;const WIN_RETRY_DELAY_MS = 10;const WIN_READ_LOCK_CODES = ['EPERM', 'EACCES', 'EBUSY'];-/**- * Check if a string is potentially valid JSON.- * Performs quick structural validation before parsing.- *- * @param {string} str - String to validate- * @param {Object} options - Validation options- * @param {boolean} [options.allowArray=true] - Allow array JSON (default: true)- * @returns {boolean} True if the string appears to be valid JSON- *- * @example- * isValidJSON('{"key": "value"}') // true- * isValidJSON('[1, 2, 3]') // true- * isValidJSON('') // false- * isValidJSON('{"incomplete":') // false- */-export function isValidJSON(str, { allowArray = true } = {}) {- if (!str || !str.trim()) return false;- const trimmed = str.trim();-- // Check for basic JSON structure (object or array)- const isObject = trimmed.startsWith('{') && trimmed.endsWith('}');- const isArray = trimmed.startsWith('[') && trimmed.endsWith(']');-- if (!isObject && !(allowArray && isArray)) return false;-- return true;-}-/*** Index of the first JSON array token in `str`, or -1 when it holds none.*@@ -97,17 +69,22 @@ export function safeJSONParse(str, defaultValue = null, { allowArray = true, logstr = extractJSONArray(str);}- if (!isValidJSON(str, { allowArray })) {+ if (!str || !str.trim()) {if (logError && str) {console.warn(`Invalid JSON${context ? ` in ${context}` : ''}: empty or malformed content`);}return defaultValue;}- // Attempt actual parse - the validation above catches structural issues- // but syntax errors like trailing commas still need handlingtry {- return JSON.parse(str);+ const parsed = JSON.parse(str);+ if (!allowArray && Array.isArray(parsed)) {+ if (logError) {+ console.warn(`Invalid JSON${context ? ` in ${context}` : ''}: array not allowed`);+ }+ return defaultValue;+ }+ return parsed;} catch (err) {if (logError) {console.warn(`Failed to parse JSON${context ? ` in ${context}` : ''}: ${err.message}`);