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

simplify: clean up digital-twin modules post-decomposition

Adam Eivy5a43942f6d3e
diff --git a/server/services/digital-twin-analysis.js b/server/services/digital-twin-analysis.js
index 8dd8d39973..0c2fb74b87 100644
--- a/server/services/digital-twin-analysis.js
+++ b/server/services/digital-twin-analysis.js
@@ -275,16 +275,16 @@ function parseWritingAnalysis(response) {
*/
export async function getAllTwinContent() {
const meta = await loadMeta();
- const enabledDocs = meta.documents.filter(d => d.enabled && d.category !== 'behavioral');
-
- const contents = [];
- for (const doc of enabledDocs) {
- const filePath = join(DIGITAL_TWIN_DIR, doc.filename);
- if (existsSync(filePath)) {
- const content = await readFile(filePath, 'utf-8');
- contents.push(`## ${doc.title} (${doc.filename})\n\n${content}`);
- }
- }
+ const enabledDocs = meta.documents
+ .filter(d => d.enabled && d.category !== 'behavioral')
+ .filter(d => existsSync(join(DIGITAL_TWIN_DIR, d.filename)));
+
+ const contents = await Promise.all(
+ enabledDocs.map(async doc => {
+ const content = await readFile(join(DIGITAL_TWIN_DIR, doc.filename), 'utf-8');
+ return `## ${doc.title} (${doc.filename})\n\n${content}`;
+ })
+ );
return contents.join('\n\n---\n\n');
}
diff --git a/server/services/digital-twin-documents.js b/server/services/digital-twin-documents.js
index 97cb5ad0ed..01e9b44510 100644
--- a/server/services/digital-twin-documents.js
+++ b/server/services/digital-twin-documents.js
@@ -7,23 +7,13 @@ import { extractVersion } from './digital-twin-meta.js';
export async function getDocuments() {
const meta = await loadMeta();
- const documents = [];
-
- for (const doc of meta.documents) {
- const filePath = join(DIGITAL_TWIN_DIR, doc.filename);
- const exists = existsSync(filePath);
-
- if (exists) {
- const stats = await stat(filePath);
- documents.push({
- ...doc,
- lastModified: stats.mtime.toISOString(),
- size: stats.size
- });
- }
- }
-
- return documents;
+ const existing = meta.documents.filter(doc => existsSync(join(DIGITAL_TWIN_DIR, doc.filename)));
+ const stats = await Promise.all(existing.map(doc => stat(join(DIGITAL_TWIN_DIR, doc.filename))));
+ return existing.map((doc, i) => ({
+ ...doc,
+ lastModified: stats[i].mtime.toISOString(),
+ size: stats[i].size
+ }));
}
export async function getDocumentById(id) {
diff --git a/server/services/digital-twin-enrichment.js b/server/services/digital-twin-enrichment.js
index 55d05fc628..c58df2785f 100644
--- a/server/services/digital-twin-enrichment.js
+++ b/server/services/digital-twin-enrichment.js
@@ -3,8 +3,9 @@ import { existsSync } from 'fs';
import { join } from 'path';
import { getActiveProvider, getProviderById } from './providers.js';
import { buildPrompt } from './promptService.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
import { ENRICHMENT_CATEGORIES, SCALE_QUESTIONS, SCALE_WEIGHT, CONFIDENCE_BOOST } from './digital-twin-constants.js';
-import { DIGITAL_TWIN_DIR, generateId, now, ensureSoulDir, callProviderAI } from './digital-twin-helpers.js';
+import { DIGITAL_TWIN_DIR, generateId, now, ensureSoulDir, callProviderAI, ensureDocumentInMeta } from './digital-twin-helpers.js';
import { loadMeta, saveMeta, digitalTwinEvents } from './digital-twin-meta.js';
import { getDigitalTwinForPrompt } from './digital-twin-context.js';
import { generateGapRecommendations } from './digital-twin-analysis.js';
@@ -222,18 +223,7 @@ async function processScaleAnswer(data) {
meta.enrichment.completedCategories.push(category);
}
- // Ensure document is in meta
- const existingDoc = meta.documents.find(d => d.filename === config.targetDoc);
- if (!existingDoc) {
- meta.documents.push({
- id: generateId(),
- filename: config.targetDoc,
- title: config.label,
- category: config.targetCategory || 'enrichment',
- enabled: true,
- priority: 30
- });
- }
+ ensureDocumentInMeta(meta, config.targetDoc, config.label, config.targetCategory || 'enrichment');
await saveMeta(meta);
@@ -279,7 +269,7 @@ export async function processEnrichmentAnswer(data) {
}).catch(() => null);
if (prompt) {
- const result = await callProviderAI(provider, providerOverride || provider.defaultModel, prompt, { temperature: 0.3, max_tokens: 500 });
+ const result = await callProviderAI(provider, modelOverride || provider.defaultModel, prompt, { temperature: 0.3, max_tokens: 500 });
if (!result.error && result.text) {
formattedContent = result.text.trim() || formattedContent;
}
@@ -313,18 +303,7 @@ export async function processEnrichmentAnswer(data) {
meta.enrichment.completedCategories.push(category);
}
- // Ensure document is in meta
- const existingDoc = meta.documents.find(d => d.filename === config.targetDoc);
- if (!existingDoc) {
- meta.documents.push({
- id: generateId(),
- filename: config.targetDoc,
- title: config.label,
- category: config.targetCategory || 'enrichment',
- enabled: true,
- priority: 30
- });
- }
+ ensureDocumentInMeta(meta, config.targetDoc, config.label, config.targetCategory || 'enrichment');
// Boost confidence for the dimension this category maps to
const categoryToDimension = {
@@ -480,22 +459,18 @@ Respond in JSON format:
const responseText = result.text || '';
// Parse the JSON response
- const jsonMatch = responseText.match(/```json\s*([\s\S]*?)\s*```/);
- if (jsonMatch) {
- const { safeJSONParse } = await import('../lib/fileUtils.js');
- 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
- };
- }
+ const parsed = safeJSONParse(responseText.match(/```json\s*([\s\S]*?)\s*```/)?.[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
@@ -543,18 +518,7 @@ export async function saveEnrichmentListDocument(category, content, items) {
meta.enrichment.lastSession = now();
- // Ensure document is in meta
- const existingDoc = meta.documents.find(d => d.filename === config.targetDoc);
- if (!existingDoc) {
- meta.documents.push({
- id: generateId(),
- filename: config.targetDoc,
- title: config.label,
- category: config.targetCategory || 'enrichment',
- enabled: true,
- priority: 30
- });
- }
+ ensureDocumentInMeta(meta, config.targetDoc, config.label, config.targetCategory || 'enrichment');
await saveMeta(meta);
diff --git a/server/services/digital-twin-helpers.js b/server/services/digital-twin-helpers.js
index c81462e406..0b8b0d883a 100644
--- a/server/services/digital-twin-helpers.js
+++ b/server/services/digital-twin-helpers.js
@@ -1,6 +1,6 @@
import { v4 as uuidv4 } from '../lib/uuid.js';
import { existsSync } from 'fs';
-import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { ensureDir, PATHS, safeJSONParse } from '../lib/fileUtils.js';
export const DIGITAL_TWIN_DIR = PATHS.digitalTwin;
@@ -12,6 +12,34 @@ export function now() {
return new Date().toISOString();
}
+/**
+ * Extract and parse the first JSON block from an AI response string.
+ * Tries ```json fences first, then bare-object/array fallback.
+ * Returns the parsed value or null.
+ */
+export function extractJSON(response, context = 'response') {
+ const fenceMatch = response.match(/```json\s*([\s\S]*?)\s*```/);
+ if (fenceMatch) {
+ const parsed = safeJSONParse(fenceMatch[1], null, { logError: true, context });
+ if (parsed) return parsed;
+ }
+ const trimmed = response.trim();
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
+ return safeJSONParse(trimmed, null, { logError: true, context: `${context} fallback` });
+ }
+ return null;
+}
+
+/**
+ * Ensure a document entry exists in meta.documents. If absent, push it.
+ * Mutates meta in place; caller must saveMeta() after.
+ */
+export function ensureDocumentInMeta(meta, filename, title, category, { enabled = true, priority = 30 } = {}) {
+ if (!meta.documents.find(d => d.filename === filename)) {
+ meta.documents.push({ id: generateId(), filename, title, category, enabled, priority });
+ }
+}
+
export async function ensureSoulDir() {
if (!existsSync(DIGITAL_TWIN_DIR)) {
await ensureDir(DIGITAL_TWIN_DIR);
diff --git a/server/services/digital-twin-import.js b/server/services/digital-twin-import.js
index 65e4ad4ada..c10c59e2a5 100644
--- a/server/services/digital-twin-import.js
+++ b/server/services/digital-twin-import.js
@@ -538,10 +538,11 @@ export async function analyzeAssessment(content, providerId, model) {
// 5. Create/update documents from suggestions
const docsCreated = [];
const docsUpdated = [];
+ const metaBeforeDocs = await loadMeta();
+ const existingFilenames = new Set(metaBeforeDocs.documents.map(d => d.filename));
for (const doc of (parsed.suggestedDocuments || [])) {
if (!doc.filename || !doc.content) continue;
- const currentMeta = await loadMeta();
- const existsBefore = currentMeta.documents.some(d => d.filename === doc.filename);
+ const existsBefore = existingFilenames.has(doc.filename);
const result = await saveImportAsDocument('interview', {
filename: doc.filename,
title: doc.title || doc.filename.replace('.md', ''),