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
refactor: add shared ensureDir utility and reduce DRY violations
Adam Eivybb4acba000f1
diff --git a/.changelog/v0.10.x.md b/.changelog/v0.10.x.mdindex d1960abc9a..e543aa4e9d 100644--- a/.changelog/v0.10.x.md+++ b/.changelog/v0.10.x.md@@ -179,6 +179,16 @@ This release introduces a structured changelog documentation system for creating- `runner.old.js` - superseded by AI Toolkit's runner service- These files were unreferenced throughout the codebase and represented ~1,220 lines of dead code+### DRY Refactoring: Shared File Utilities+- **New `server/lib/fileUtils.js`**: Created shared utility module for directory and path operations+ - `ensureDir(path)` - Ensures directory exists, creating recursively if needed+ - `ensureDirs(paths)` - Ensures multiple directories exist+ - `dataPath(...segments)` - Get path relative to data directory+ - `rootPath(...segments)` - Get path relative to project root+ - `PATHS` - Centralized path constants (data, cos, brain, digitalTwin, runs, memory, agents, scripts, reports)+- **Reduced Code Duplication**: Refactored 4 services (`apps.js`, `history.js`, `usage.js`, `notifications.js`) to use shared utility, eliminating identical `ensureDir` implementations and reducing boilerplate+- **Pattern for Future Refactoring**: Establishes pattern for remaining 7+ services with similar duplicated directory logic+## 📦 Installation```bashdiff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsnew file mode 100644index 0000000000..afa1eb94c7--- /dev/null+++ b/server/lib/fileUtils.js@@ -0,0 +1,89 @@+/**+ * File System Utilities+ *+ * Shared utilities for file operations used across services.+ */++import { mkdir } from 'fs/promises';+import { existsSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';++// Cache __dirname calculation for services importing this module+const __lib_filename = fileURLToPath(import.meta.url);+const __lib_dirname = dirname(__lib_filename);++/**+ * Base directories relative to project root+ */+export const PATHS = {+ root: join(__lib_dirname, '../..'),+ data: join(__lib_dirname, '../../data'),+ cos: join(__lib_dirname, '../../data/cos'),+ brain: join(__lib_dirname, '../../data/brain'),+ digitalTwin: join(__lib_dirname, '../../data/digital-twin'),+ runs: join(__lib_dirname, '../../data/runs'),+ memory: join(__lib_dirname, '../../data/cos/memory'),+ agents: join(__lib_dirname, '../../data/cos/agents'),+ scripts: join(__lib_dirname, '../../data/cos/scripts'),+ reports: join(__lib_dirname, '../../data/cos/reports')+};++/**+ * Ensure a directory exists, creating it recursively if needed.+ *+ * @param {string} dir - Directory path to ensure exists+ * @returns {Promise<void>}+ *+ * @example+ * await ensureDir(PATHS.data);+ * await ensureDir('/custom/path/to/dir');+ */+export async function ensureDir(dir) {+ if (!existsSync(dir)) {+ await mkdir(dir, { recursive: true });+ }+}++/**+ * Ensure multiple directories exist.+ *+ * @param {string[]} dirs - Array of directory paths to ensure exist+ * @returns {Promise<void>}+ *+ * @example+ * await ensureDirs([PATHS.data, PATHS.cos, PATHS.memory]);+ */+export async function ensureDirs(dirs) {+ for (const dir of dirs) {+ await ensureDir(dir);+ }+}++/**+ * Get a path relative to the data directory.+ *+ * @param {...string} segments - Path segments to join+ * @returns {string} Full path under data directory+ *+ * @example+ * const filePath = dataPath('cos', 'state.json');+ * // Returns: /path/to/project/data/cos/state.json+ */+export function dataPath(...segments) {+ return join(PATHS.data, ...segments);+}++/**+ * Get a path relative to the project root.+ *+ * @param {...string} segments - Path segments to join+ * @returns {string} Full path under project root+ *+ * @example+ * const filePath = rootPath('data', 'TASKS.md');+ * // Returns: /path/to/project/data/TASKS.md+ */+export function rootPath(...segments) {+ return join(PATHS.root, ...segments);+}diff --git a/server/services/apps.js b/server/services/apps.jsindex b40dcd9b32..d8fa60439c 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -1,13 +1,11 @@-import { readFile, writeFile, mkdir } from 'fs/promises';+import { readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';-import { join, dirname } from 'path';-import { fileURLToPath } from 'url';+import { join } from 'path';import { v4 as uuidv4 } from 'uuid';import EventEmitter from 'events';+import { ensureDir, PATHS } from '../lib/fileUtils.js';-const __filename = fileURLToPath(import.meta.url);-const __dirname = dirname(__filename);-const DATA_DIR = join(__dirname, '../../data');+const DATA_DIR = PATHS.data;const APPS_FILE = join(DATA_DIR, 'apps.json');// Event emitter for apps changes@@ -22,9 +20,7 @@ const CACHE_TTL_MS = 2000; // Cache for 2 seconds to reduce file reads during ra* Ensure data directory exists*/async function ensureDataDir() {- if (!existsSync(DATA_DIR)) {- await mkdir(DATA_DIR, { recursive: true });- }+ await ensureDir(DATA_DIR);}/**diff --git a/server/services/history.js b/server/services/history.jsindex b3547a1e64..4ccf108fcc 100644--- a/server/services/history.js+++ b/server/services/history.js@@ -1,12 +1,10 @@-import { readFile, writeFile, mkdir } from 'fs/promises';+import { readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';-import { join, dirname } from 'path';-import { fileURLToPath } from 'url';+import { join } from 'path';import { v4 as uuidv4 } from 'uuid';+import { ensureDir, PATHS } from '../lib/fileUtils.js';-const __filename = fileURLToPath(import.meta.url);-const __dirname = dirname(__filename);-const DATA_DIR = join(__dirname, '../../data');+const DATA_DIR = PATHS.data;const HISTORY_FILE = join(DATA_DIR, 'history.json');const MAX_ENTRIES = 500;@@ -16,9 +14,7 @@ let cacheTimestamp = 0;const CACHE_TTL_MS = 2000; // 2 second cache TTLasync function ensureDataDir() {- if (!existsSync(DATA_DIR)) {- await mkdir(DATA_DIR, { recursive: true });- }+ await ensureDir(DATA_DIR);}async function loadHistory() {diff --git a/server/services/notifications.js b/server/services/notifications.jsindex dc4290dea9..7d4aafddc5 100644--- a/server/services/notifications.js+++ b/server/services/notifications.js@@ -8,16 +8,14 @@* - Health issues*/-import { readFile, writeFile, mkdir } from 'fs/promises';+import { readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';-import { join, dirname } from 'path';-import { fileURLToPath } from 'url';+import { join } from 'path';import { v4 as uuidv4 } from 'uuid';import { EventEmitter } from 'events';+import { ensureDir, PATHS } from '../lib/fileUtils.js';-const __filename = fileURLToPath(import.meta.url);-const __dirname = dirname(__filename);-const DATA_DIR = join(__dirname, '../../data');+const DATA_DIR = PATHS.data;const NOTIFICATIONS_FILE = join(DATA_DIR, 'notifications.json');// Event emitter for notification changes@@ -46,9 +44,7 @@ export const PRIORITY_LEVELS = {* Ensure data directory exists*/async function ensureDirectory() {- if (!existsSync(DATA_DIR)) {- await mkdir(DATA_DIR, { recursive: true });- }+ await ensureDir(DATA_DIR);}/**diff --git a/server/services/usage.js b/server/services/usage.jsindex 68ce84f614..a834b4997a 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -1,11 +1,9 @@-import { readFile, writeFile, mkdir } from 'fs/promises';+import { readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';-import { join, dirname } from 'path';-import { fileURLToPath } from 'url';+import { join } from 'path';+import { ensureDir, PATHS } from '../lib/fileUtils.js';-const __filename = fileURLToPath(import.meta.url);-const __dirname = dirname(__filename);-const DATA_DIR = join(__dirname, '../../data');+const DATA_DIR = PATHS.data;const USAGE_FILE = join(DATA_DIR, 'usage.json');let usageData = null;@@ -34,9 +32,7 @@ function getEmptyUsage() {* Load usage data from disk*/export async function loadUsage() {- if (!existsSync(DATA_DIR)) {- await mkdir(DATA_DIR, { recursive: true });- }+ await ensureDir(DATA_DIR);if (existsSync(USAGE_FILE)) {usageData = JSON.parse(await readFile(USAGE_FILE, 'utf-8'));