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: narrow shared imports that inflated release test closures
[._.]/ Adam Eivydcfd09deab99
diff --git a/server/lib/README.md b/server/lib/README.mdindex 93a9cf4fe0..a7cc828ea9 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -747,6 +747,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `openchamber.js` | OpenChamber control-CLI identity, `session create` headless argv, `provider/model` gate, and `--dir`/`--prompt` spawn-time delivery. || `layaMlx.js` | Pinned Laya-MLX experiment model, request validation and probability normalization; entropy confidence stays distinct from entailment. || `layeredIntelligenceSources.js` | `LAYERED_INTELLIGENCE_SOURCE_KEYS` — the ordered list of built-in Layer-1 telemetry sources the self-improvement loop can gather. Used by server schema and client UI to build source lists from one canonical definition. Pure leaf: no Node built-in, nothing outside `server/lib`. Re-exported by `client/src/lib/layeredIntelligenceSources.js`. |+| `layeredIntelligenceSourceKeys.js` | Dependency-free `LAYERED_INTELLIGENCE_SOURCE_KEYS` leaf shared by the server schema, layered-intelligence reader, and client settings form. || `persistentMindMaintainer.js` | Machine-local maintainer intent, inference allowance schema, normalization and additive wake charter; never grants authority. |diff --git a/server/lib/aiToolkit/internal/providerCatalogService.js b/server/lib/aiToolkit/internal/providerCatalogService.jsindex 8b2d7c801b..914bdad455 100644--- a/server/lib/aiToolkit/internal/providerCatalogService.js+++ b/server/lib/aiToolkit/internal/providerCatalogService.js@@ -13,8 +13,6 @@ import { providerModeGroups } from './providerModes.js';import { ollamaRefreshGroupKey, resolveModelFetcher } from './modelFetchers.js';import { modelCatalogUpdate, parseModelCatalog, toModelCatalog } from './modelCatalog.js';import { CLAUDE_CATALOG_SUBPATH, catalogAge, claudeConfigDir, selectCatalogModels } from './claudeCodeCatalog.js';-import { prepareWindowsSafeSpawn, resolveWindowsExecutable } from './windowsSafeSpawn.js';-import { probeCodexModelsViaAppServer } from './codexModelListProbe.js';function resolveProbeSpawn(provider, defaultBin, args) {const spawned = composeBootstrapSpawn(provider, provider?.command || defaultBin, args);@@ -74,6 +72,7 @@ export function createProviderCatalogService({if (!commandPath) return { success: false, error: `Command '${probeCommand}' not found in PATH` };const searchEnv = { ...process.env, ...provider.envVars };+ const { prepareWindowsSafeSpawn, resolveWindowsExecutable } = await import('./windowsSafeSpawn.js');const invokePath = (isWin32 && resolveWindowsExecutable(provider.command, isWin32, searchEnv)) || commandPath;let everSpawned = false;const tryVersion = async (flag) => {@@ -328,6 +327,7 @@ export function createProviderCatalogService({async _execCliModelList(provider, defaultBin, parse, listArgs = ['models'], isEmptyCatalog = () => false) {const spawned = resolveProbeSpawn(provider, defaultBin, listArgs);const probe = spawned.label;+ const { prepareWindowsSafeSpawn } = await import('./windowsSafeSpawn.js');const { command, args } = prepareWindowsSafeSpawn(spawned.command, spawned.args);const pending = execFileAsync(command, args, {timeout: 15000,@@ -357,6 +357,10 @@ export function createProviderCatalogService({},async _fetchCodexModels(provider) {+ const [{ prepareWindowsSafeSpawn, resolveWindowsExecutable }, { probeCodexModelsViaAppServer }] = await Promise.all([+ import('./windowsSafeSpawn.js'),+ import('./codexModelListProbe.js'),+ ]);const spawned = resolveProbeSpawn(provider, 'codex', ['app-server']);// Only needed here for the Windows shim search — `probeCodexModelsViaAppServer`// rebuilds the same merge itself from `provider.envVars` before spawning.@@ -424,6 +428,7 @@ export function createProviderCatalogService({async _claudeCliVersion(provider) {const spawned = resolveProbeSpawn(provider, 'claude', ['--version']);+ const { prepareWindowsSafeSpawn } = await import('./windowsSafeSpawn.js');const { command, args } = prepareWindowsSafeSpawn(spawned.command, spawned.args);const pending = execFileAsync(command, args, {timeout: 10000,diff --git a/server/lib/index.js b/server/lib/index.jsindex ccf4160573..54c826a875 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -727,6 +727,7 @@ export * from './openchamber.js';export * from './layaMlx.js';export * from './layeredIntelligenceSources.js';+export * from './layeredIntelligenceSourceKeys.js';export * from './persistentMindMaintainer.js';diff --git a/server/lib/layeredIntelligenceSourceKeys.js b/server/lib/layeredIntelligenceSourceKeys.jsnew file mode 100644index 0000000000..73c4e4ddda--- /dev/null+++ b/server/lib/layeredIntelligenceSourceKeys.js@@ -0,0 +1,29 @@+/**+ * Built-in Layer-1 telemetry source keys shared by the server schema and the+ * client settings form. Kept in a dependency-free leaf so importing the+ * broad layered-intelligence reader is not required to build a route schema.+ */+export const LAYERED_INTELLIGENCE_SOURCE_KEYS = [+ 'goals',+ // The app's own success/performance metrics doc (METRICS.md in the app repo).+ // Default on: the primary signal for judging a managed app against its goals.+ 'appMetrics',+ 'cosMetrics',+ 'healthReport',+ 'planMd',+ 'openIssues',+ // The committed backlog (#2698): `plan`-labeled tracker issues / the+ // prioritized Jira backlog / PLAN.md's unchecked items, fed in so the reasoner+ // can suppress a proposal that overlaps work already in scope. Default on.+ 'plannedWork',+ // PortOS-only product-success signals (POST engagement and creative+ // commission feedback). Managed apps use appMetrics/custom sources.+ 'productMetrics',+ // Feedback loop (#2428): feed past LI proposals + their tracker outcomes back+ // into the reasoning prompt. Default on for PortOS, off for managed apps.+ 'outcomes',+ // Self-evaluation (#2700): fold LI's own merge rate, already-filed proposal+ // count, and agent-run health back into the prompt so the loop can judge its+ // proposal quality before filing. Default on for PortOS, off for managed apps.+ 'selfEval',+];diff --git a/server/lib/layeredIntelligenceSources.js b/server/lib/layeredIntelligenceSources.jsindex bf68a887c2..911153ccf2 100644--- a/server/lib/layeredIntelligenceSources.js+++ b/server/lib/layeredIntelligenceSources.js@@ -1,34 +1 @@-/**- * Layered Intelligence source keys — the built-in Layer-1 telemetry toggles the- * self-improvement loop can gather, in the order the app config tab lists them.- * Custom sources are a separate array (`sources.custom`, discriminated on type).- *- * `layeredIntelligenceConfigSchema` in validation.js builds its `sources` object- * from this list, and `client/src/lib/layeredIntelligenceSources.js` re-exports- * it so a client test can require one LI_SOURCE_FIELDS entry per key. Keep it- * pure: no Node built-in, nothing outside `server/lib`.- */-export const LAYERED_INTELLIGENCE_SOURCE_KEYS = [- 'goals',- // The app's own success/performance metrics doc (METRICS.md in the app repo).- // Default on: the primary signal for judging a managed app against its goals.- 'appMetrics',- 'cosMetrics',- 'healthReport',- 'planMd',- 'openIssues',- // The committed backlog (#2698): `plan`-labeled tracker issues / the- // prioritized Jira backlog / PLAN.md's unchecked items, fed in so the reasoner- // can suppress a proposal that overlaps work already in scope. Default on.- 'plannedWork',- // PortOS-only product-success signals (POST engagement and creative- // commission feedback). Managed apps use appMetrics/custom sources.- 'productMetrics',- // Feedback loop (#2428): feed past LI proposals + their tracker outcomes back- // into the reasoning prompt. Default on for PortOS, off for managed apps.- 'outcomes',- // Self-evaluation (#2700): fold LI's own merge rate, already-filed proposal- // count, and agent-run health back into the prompt so the loop can judge its- // proposal quality before filing. Default on for PortOS, off for managed apps.- 'selfEval',-];+export { LAYERED_INTELLIGENCE_SOURCE_KEYS } from './layeredIntelligenceSourceKeys.js';diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 37a8952fd6..9ce621ebb2 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -13,7 +13,7 @@ export const gitDeleteBranchBodySchema = z.object({import { ServerError } from './errorHandler.js';import { partialWithoutDefaults, emptyToUndefined, emptyToNull, optionalBooleanMap, presetProviderIdSchema, providerRefSchema } from './zodCompat.js';import { WORK_TRACKERS } from './workTracker.js';-import { LAYERED_INTELLIGENCE_SOURCE_KEYS } from './layeredIntelligenceSources.js';+import { LAYERED_INTELLIGENCE_SOURCE_KEYS } from './layeredIntelligenceSourceKeys.js';import { PROVIDER_FAMILY_IDS } from './providerFamilies.js';import { APP_FEATURE_IDS, INSTANCE_FEATURE_IDS, INSTANCE_FEATURE_GROUP_IDS } from './instanceFeatureRegistry.js';import { MAX_MONTHLY_COST } from './subscriptionSavings.js';diff --git a/server/routes/apps/icons.js b/server/routes/apps/icons.jsindex d461c28a97..530f4576d6 100644--- a/server/routes/apps/icons.js+++ b/server/routes/apps/icons.js@@ -15,7 +15,6 @@ import { notifyAppsChanged } from '../../services/apps.js';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';import { detectAppIcon, getIconContentType, isUsableSvg } from '../../services/appIconDetect.js';import { loadApp, pathExists } from './shared.js';-import { appIconQuerySchema, validateRequest } from '../../lib/validation.js';const router = Router();const rasterIconCache = new Map();@@ -40,6 +39,7 @@ const getRasterIcon = (appId, iconPath, iconStat, size, iconData) => {// GET /api/apps/:id/icon - Serve the app's detected icon imagerouter.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {const app = req.loadedApp;+ const { appIconQuerySchema, validateRequest } = await import('../../lib/validation.js');const { size } = validateRequest(appIconQuerySchema, req.query);// Use stored appIconPath, or detect on-the-fly. Stored SVGs that embed andiff --git a/server/routes/commands.js b/server/routes/commands.jsindex c7754bb92e..0897a316ad 100644--- a/server/routes/commands.js+++ b/server/routes/commands.js@@ -1,5 +1,4 @@import { Router } from 'express';-import { processActionSchema, processListQuerySchema, validateRequest } from '../lib/validation.js';import { validateCommand } from '../lib/commandSecurity.js';import { existsSync, statSync, realpathSync } from 'fs';import { resolve } from 'path';@@ -92,6 +91,7 @@ router.get('/allowed', asyncHandler(async (req, res) => {// GET /api/commands/processes - Get PM2 process list with detailsrouter.get('/processes', asyncHandler(async (req, res) => {+ const { processListQuerySchema, validateRequest } = await import('../lib/validation.js');const { appId } = validateRequest(processListQuerySchema, req.query);const app = appId ? await (await import('../services/apps.js')).getAppById(appId) : null;if (appId && !app) throw new ServerError('App not found', { status: 404, code: 'NOT_FOUND' });@@ -102,6 +102,7 @@ router.get('/processes', asyncHandler(async (req, res) => {// Apply a scoped process action and return its resulting snapshot.router.post('/processes/:name/action', requireHostControl, asyncHandler(async (req, res) => {+ const { processActionSchema, validateRequest } = await import('../lib/validation.js');const { action, appId } = validateRequest(processActionSchema, req.body);const name = req.params.name;const command = validateCommand(`pm2 ${action} ${name}`);diff --git a/server/services/backup.db.test.js b/server/services/backup.db.test.jsindex c32031594e..7b260db68f 100644--- a/server/services/backup.db.test.js+++ b/server/services/backup.db.test.js@@ -10,10 +10,10 @@ import { resolvePgDumpBinary } from '../lib/pgTools.js';import { runDbMigrations } from '../scripts/run-db-migrations.js';import { listFolders } from './writersRoom/db.js';import { syncFeedTables, syncFeedSequenceName } from '../lib/db/schema/syncFeed.js';-import { rewindPostgresSyncCursors } from './syncOrchestrator.js';// The real rewind rewrites this install's data/instances_sync_cursors.json.-vi.mock('./syncOrchestrator.js', () => ({ rewindPostgresSyncCursors: vi.fn(async () => 0) }));+const rewindPostgresSyncCursors = vi.hoisted(() => vi.fn(async () => 0));+vi.mock('./syncOrchestrator.js', () => ({ rewindPostgresSyncCursors }));const feedSequenceValues = async () => Object.fromEntries((await query('SELECT sequencename, last_value::text AS v FROM pg_sequences WHERE sequencename = ANY($1::text[])',diff --git a/server/services/backup.test.js b/server/services/backup.test.jsindex 36d4d67167..360e50ce6b 100644--- a/server/services/backup.test.js+++ b/server/services/backup.test.js@@ -66,10 +66,10 @@ vi.mock('./backupDatabaseReset.js', () => ({}));import { runDbMigrations } from '../scripts/run-db-migrations.js';// restorePostgres lazily imports the orchestrator to rewind peer cursors (#8710).+const rewindPostgresSyncCursors = vi.hoisted(() => vi.fn().mockResolvedValue(2));vi.mock('./syncOrchestrator.js', () => ({- rewindPostgresSyncCursors: vi.fn().mockResolvedValue(2),+ rewindPostgresSyncCursors,}));-import { rewindPostgresSyncCursors } from './syncOrchestrator.js';// Mock the memory-backend resolver so dumpPostgres can tell whether Postgres is// the ACTIVE backend (explicit or auto-detected) when the DB is unreachable.diff --git a/server/services/pm2.js b/server/services/pm2.jsindex ddeef315e6..8979dae0a9 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -1,4 +1,3 @@-import { noteReadinessChanged } from './readinessNotify.js';import pm2 from 'pm2';import { spawn } from '../lib/childProcess.js';import { existsSync } from 'fs';@@ -21,14 +20,22 @@ const cacheKey = (pm2Home) => pm2Home || '_default';// Track PM2 read failures per home so we log only on state change or reason changeconst jlistFailureState = new Map(); // home -> { lastError: string }+let readinessChangedLoader;++function notifyReadinessChanged(kind) {+ readinessChangedLoader ??= import('./readinessNotify.js').then(({ noteReadinessChanged }) => noteReadinessChanged);+ void readinessChangedLoader+ .then(noteReadinessChanged => noteReadinessChanged(kind))+ .catch(error => console.error(`❌ Readiness invalidation failed: ${error.message}`));+}/*** Invalidate the jlist TTL cache (e.g. after mutations like start/stop/delete).* @param {string|null} [pm2Home=null]*/export function clearJlistCache(pm2Home = null) {- noteReadinessChanged('health');- noteReadinessChanged('capabilities');+ notifyReadinessChanged('health');+ notifyReadinessChanged('capabilities');if (pm2Home !== undefined && pm2Home !== null) {jlistCache.delete(cacheKey(pm2Home));} else {diff --git a/server/sockets/agentProcesses.js b/server/sockets/agentProcesses.jsindex ba633157b1..54463940a1 100644--- a/server/sockets/agentProcesses.js+++ b/server/sockets/agentProcesses.js@@ -1,15 +1,19 @@-import { getRunningAgents } from '../services/agents.js';-// External CLI processes have no push API. All mounted viewers share one// non-overlapping host scan; snapshots avoid a second probe per browser.const subscribers = new Set();let run = null;+let runningAgentsLoader;++const loadRunningAgents = () => {+ runningAgentsLoader ??= import('../services/agents.js').then(({ getRunningAgents }) => getRunningAgents);+ return runningAgentsLoader;+};function start() {if (run) return;const owner = { timer: null, signature: null, agents: null };run = owner;- const tick = () => getRunningAgents().then(agents => {+ const tick = () => loadRunningAgents().then(getRunningAgents => getRunningAgents()).then(agents => {if (run !== owner) return;// Unix start time is derived from elapsed seconds and jitters per scan.// Keep elapsed runtime in the frame so the page clock remains current.