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: remove dead code and deduplicate stripCodeFences
Adam Eivy896aa96db9d3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 7e69471089..8e5bb3f8db 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,9 @@- Interactive storage backend chooser during setup: Docker PostgreSQL, Native PostgreSQL, or file-based JSON (deprecated) when Docker is unavailable## Changed+- Consolidated 5 duplicate `timeAgo`/`formatTimeAgo` implementations into a single `timeAgo()` in `utils/formatters.js`+- Deduplicated `stripCodeFences` from insightsService — now imports from shared `lib/aiProvider.js`+- Added `MINUTE` time constant to `lib/fileUtils.js` alongside existing `HOUR`/`DAY`- Quick-add buttons for alcohol and nicotine now combine duplicate entries on the same date by incrementing count instead of stacking separate rows- Extracted shared `dayOfWeek` utility and `DAY_LABELS` constant to meatspace constants (deduplicated from AlcoholTab)- Health correlation endpoint now includes heart rate, resting heart rate, and nicotine data alongside existing HRV/alcohol/steps@@ -36,3 +39,5 @@- README screenshot labels corrected to match actual screenshot content (all 6 were mislabeled)## Removed+- Dead code: `euclideanDistance`, `averageVectors`, `similarityMatrix` from `vectorMath.js` (unused outside tests)+- Dead code: `rootPath` from `fileUtils.js`, `getClient` from `db.js` (never imported)diff --git a/server/lib/db.js b/server/lib/db.jsindex df7790bad3..c582388e9e 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -39,15 +39,6 @@ export async function query(text, params) {return pool.query(text, params);}-/**- * Get a client from the pool for transactions.- * Caller must call client.release() when done.- * @returns {Promise<pg.PoolClient>}- */-export async function getClient() {- return pool.connect();-}-/*** Run a function inside a database transaction.* Auto-commits on success, rolls back on error.diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex e555e08e74..5d0c8c02a8 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -95,20 +95,6 @@ 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);-}-/*** Check if a string is potentially valid JSON.* Performs quick structural validation before parsing.@@ -346,7 +332,8 @@ export function createCachedStore(filePath, defaultValue, { ttl = 2000, contextreturn { load, save, invalidateCache };}-export const HOUR = 60 * 60 * 1000;+export const MINUTE = 60 * 1000;+export const HOUR = 60 * MINUTE;export const DAY = 24 * HOUR;/**diff --git a/server/lib/vectorMath.js b/server/lib/vectorMath.jsindex b3e430d2f5..3c00662dc6 100644--- a/server/lib/vectorMath.js+++ b/server/lib/vectorMath.js@@ -27,24 +27,6 @@ export function cosineSimilarity(a, b) {return denominator === 0 ? 0 : dotProduct / denominator;}-/**- * Calculate Euclidean distance between two vectors- * Lower values mean more similar- */-export function euclideanDistance(a, b) {- if (!a || !b || a.length !== b.length || a.length === 0) {- return Infinity;- }-- let sum = 0;- for (let i = 0; i < a.length; i++) {- const diff = a[i] - b[i];- sum += diff * diff;- }-- return Math.sqrt(sum);-}-/*** Normalize a vector to unit length*/@@ -101,26 +83,6 @@ export function findAboveThreshold(queryVector, vectors, threshold = 0.7) {return results;}-/**- * Calculate average vector from multiple vectors- * Useful for combining related memories- */-export function averageVectors(vectors) {- if (!vectors || vectors.length === 0) return [];-- const dimension = vectors[0].length;- const result = new Array(dimension).fill(0);-- for (const v of vectors) {- for (let i = 0; i < dimension; i++) {- result[i] += v[i];- }- }-- const count = vectors.length;- return result.map(x => x / count);-}-/*** Cluster vectors by similarity using simple single-linkage clustering* Returns array of clusters, each cluster is array of { id, vector }@@ -152,24 +114,3 @@ export function clusterBySimilarity(items, threshold = 0.9) {return clusters;}--/**- * Compute pairwise similarity matrix for a set of vectors- * Returns object with { ids, matrix } where matrix[i][j] is similarity between ids[i] and ids[j]- */-export function similarityMatrix(vectors) {- const ids = Object.keys(vectors);- const n = ids.length;- const matrix = Array(n).fill(null).map(() => Array(n).fill(0));-- for (let i = 0; i < n; i++) {- matrix[i][i] = 1;- for (let j = i + 1; j < n; j++) {- const sim = cosineSimilarity(vectors[ids[i]], vectors[ids[j]]);- matrix[i][j] = sim;- matrix[j][i] = sim;- }- }-- return { ids, matrix };-}diff --git a/server/lib/vectorMath.test.js b/server/lib/vectorMath.test.jsindex cef307b87a..84ecb25c3a 100644--- a/server/lib/vectorMath.test.js+++ b/server/lib/vectorMath.test.js@@ -1,13 +1,10 @@import { describe, it, expect } from 'vitest';import {cosineSimilarity,- euclideanDistance,normalize,findTopK,findAboveThreshold,- averageVectors,- clusterBySimilarity,- similarityMatrix+ clusterBySimilarity} from './vectorMath.js';describe('vectorMath.js', () => {@@ -60,39 +57,6 @@ describe('vectorMath.js', () => {});});- describe('euclideanDistance', () => {- it('should return 0 for identical vectors', () => {- const a = [1, 2, 3];- const b = [1, 2, 3];- expect(euclideanDistance(a, b)).toBe(0);- });-- it('should calculate distance correctly', () => {- const a = [0, 0];- const b = [3, 4];- expect(euclideanDistance(a, b)).toBe(5); // 3-4-5 triangle- });-- it('should return Infinity for null inputs', () => {- expect(euclideanDistance(null, [1, 2])).toBe(Infinity);- expect(euclideanDistance([1, 2], null)).toBe(Infinity);- });-- it('should return Infinity for different length vectors', () => {- expect(euclideanDistance([1, 2], [1, 2, 3])).toBe(Infinity);- });-- it('should return Infinity for empty vectors', () => {- expect(euclideanDistance([], [])).toBe(Infinity);- });-- it('should be commutative', () => {- const a = [1, 2, 3];- const b = [4, 5, 6];- expect(euclideanDistance(a, b)).toBe(euclideanDistance(b, a));- });- });-describe('normalize', () => {it('should normalize a vector to unit length', () => {const v = [3, 4];@@ -226,42 +190,6 @@ describe('vectorMath.js', () => {});});- describe('averageVectors', () => {- it('should calculate average of vectors', () => {- const vectors = [- [1, 2, 3],- [3, 2, 1],- [2, 2, 2]- ];- const avg = averageVectors(vectors);- expect(avg).toEqual([2, 2, 2]);- });-- it('should return empty for null input', () => {- expect(averageVectors(null)).toEqual([]);- });-- it('should return empty for empty array', () => {- expect(averageVectors([])).toEqual([]);- });-- it('should handle single vector', () => {- const vectors = [[1, 2, 3]];- const avg = averageVectors(vectors);- expect(avg).toEqual([1, 2, 3]);- });-- it('should handle decimal results', () => {- const vectors = [- [1, 0],- [0, 1]- ];- const avg = averageVectors(vectors);- expect(avg[0]).toBeCloseTo(0.5);- expect(avg[1]).toBeCloseTo(0.5);- });- });-describe('clusterBySimilarity', () => {it('should cluster similar items together', () => {const items = [@@ -308,55 +236,4 @@ describe('vectorMath.js', () => {expect(clusters.length).toBe(1);});});-- describe('similarityMatrix', () => {- it('should compute pairwise similarity matrix', () => {- const vectors = {- 'a': [1, 0],- 'b': [0, 1],- 'c': [1, 0]- };-- const { ids, matrix } = similarityMatrix(vectors);-- expect(ids).toHaveLength(3);- expect(matrix).toHaveLength(3);- expect(matrix[0]).toHaveLength(3);-- // Diagonal should be 1- for (let i = 0; i < ids.length; i++) {- expect(matrix[i][i]).toBe(1);- }- });-- it('should be symmetric', () => {- const vectors = {- 'a': [1, 0],- 'b': [0.5, 0.5],- 'c': [0, 1]- };-- const { matrix } = similarityMatrix(vectors);-- for (let i = 0; i < matrix.length; i++) {- for (let j = 0; j < matrix.length; j++) {- expect(matrix[i][j]).toBeCloseTo(matrix[j][i]);- }- }- });-- it('should handle single vector', () => {- const vectors = { 'a': [1, 0] };- const { ids, matrix } = similarityMatrix(vectors);-- expect(ids).toEqual(['a']);- expect(matrix).toEqual([[1]]);- });-- it('should handle empty vectors object', () => {- const { ids, matrix } = similarityMatrix({});- expect(ids).toEqual([]);- expect(matrix).toEqual([]);- });- });});diff --git a/server/services/insightsService.js b/server/services/insightsService.jsindex db7f38b5fc..d8d021c1d1 100644--- a/server/services/insightsService.js+++ b/server/services/insightsService.js@@ -20,6 +20,7 @@ import { MARKER_CATEGORIES } from '../lib/curatedGenomeMarkers.js';import { getTasteProfile } from './taste-questionnaire.js';import { getActiveProvider, getProviderById } from './providers.js';import { getCorrelationData } from './appleHealthQuery.js';+import { stripCodeFences, parseLLMJSON } from '../lib/aiProvider.js';const INSIGHTS_DIR = join(PATHS.data, 'insights');const THEMES_FILE = join(INSIGHTS_DIR, 'themes.json');@@ -170,13 +171,6 @@ async function callProviderAISimple(provider, model, prompt, { temperature = 0.3return { error: 'Insights analysis requires an API-based provider' };}-/**- * Strip markdown code fences from LLM output before JSON.parse.- */-function stripCodeFences(raw) {- return raw.replace(/^```(?:json)?\n?/, '').replace(/\n?```$/, '').trim();-}-// =============================================================================// EXPORTED FUNCTIONS// =============================================================================@@ -359,7 +353,7 @@ Example format:return { available: false, reason: result.error };}- const themes = JSON.parse(stripCodeFences(result.text));+ const themes = parseLLMJSON(result.text);await ensureDir(INSIGHTS_DIR);const output = {