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

refactor: remove three orphan service modules (~860 LOC)

Adam Eivy4e59f6701661
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e4cc9d6414..419f420858 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -49,3 +49,5 @@
- **Writers Room loaded empty in dev (Vite on `:5554`) while production worked.** All five `mountedRef` guards in the Writers Room and Ask pages used `useRef(true)` plus a cleanup-only `useEffect(() => () => { mountedRef.current = false; }, [])` to skip post-`await` `setState` after unmount. In React 18 `<StrictMode>` (dev only), the mount → cleanup → mount cycle flipped the ref to `false` permanently and never reset it, so every async fetch resolved with the guard tripped and folders/works/exercises/analyses/draft saves never reached state. Fixed by setting `mountedRef.current = true` at the top of the same effect — production builds (port `:5553`/`:5555`) were unaffected because StrictMode does not double-mount in production. Touched: `client/src/pages/WritersRoom.jsx`, `client/src/components/writers-room/{ExercisePanel,AiPanel,WorkEditor}.jsx`, `client/src/pages/Ask.jsx`.
## Removed
+
+- **Dead code cleanup — three orphan service modules deleted (~860 LOC).** `server/services/cosEvolution.js` (402 LOC, base-model self-modification proposals), `server/services/selfImprovement.js` (233 LOC, alternate self-improvement task generator superseded by the inline `evaluateAppImprovementTasks` flow in `cos.js`), and `server/services/portosChangelog.js` (90 LOC, recent-feat/fix commit extractor for daily briefing) had zero call sites in the codebase — `cosEvolution` and `selfImprovement` were never imported by any production module, and `portosChangelog` was only imported by its own test file. Also dropped the unused `PATHS.cosEvolution` entry in `server/lib/fileUtils.js` and the corresponding row in `docs/features/cos-enhancement.md`. Test count went 3089 → 3079 (the 10 tests in the deleted `portosChangelog.test.js`); no other tests affected.
diff --git a/docs/features/cos-enhancement.md b/docs/features/cos-enhancement.md
index 64e15d23cb..9018dd55cb 100644
--- a/docs/features/cos-enhancement.md
+++ b/docs/features/cos-enhancement.md
@@ -22,7 +22,6 @@ Comprehensive upgrade from reactive task executor to proactive autonomous agent
| `server/services/localThinking.js` | Local model completions |
| `server/services/thinkingLevels.js` | Dynamic model selection |
| `server/services/contextUpgrader.js` | Complexity analysis for model upgrade |
-| `server/services/cosEvolution.js` | Self-evolution and model changes |
## Features
diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.js
index 9d487490d6..09b5e55896 100644
--- a/server/lib/fileUtils.js
+++ b/server/lib/fileUtils.js
@@ -54,7 +54,6 @@ export const PATHS = {
digests: join(__lib_dirname, '../../data/cos/digests'),
promptSkills: join(__lib_dirname, '../../data/prompts/skills'),
promptSkillsJobs: join(__lib_dirname, '../../data/prompts/skills/jobs'),
- cosEvolution: join(__lib_dirname, '../../data/cos/evolution'),
decisions: join(__lib_dirname, '../../data/cos/decisions'),
telegram: join(__lib_dirname, '../../data/telegram'),
templates: join(__lib_dirname, '../../data/prompts/templates'),
diff --git a/server/services/cosEvolution.js b/server/services/cosEvolution.js
deleted file mode 100644
index b1d7d1f87e..0000000000
--- a/server/services/cosEvolution.js
+++ /dev/null
@@ -1,402 +0,0 @@
-/**
- * COS Evolution Service
- *
- * Enables COS to propose and execute self-modifications:
- * - Base model changes
- * - Threshold adjustments
- * - Model downloads
- *
- * Full autonomy - COS can evolve without user approval.
- * Changes are logged for transparency.
- */
-
-import { promises as fs } from 'fs'
-import path from 'path'
-import { v4 as uuidv4 } from '../lib/uuid.js'
-import { cosEvents } from './cosEvents.js'
-import * as lmStudioManager from './lmStudioManager.js'
-import { safeJSONParse, ensureDir, PATHS } from '../lib/fileUtils.js'
-
-const EVOLUTION_FILE = path.join(PATHS.cos, 'evolution.json')
-
-// Default evolution state
-const DEFAULT_STATE = {
- currentBaseModel: 'gpt-oss-20b',
- currentThinkingThresholds: {
- contextLength: { low: 1000, medium: 3000, high: 6000 },
- complexity: { low: 0.4, medium: 0.6, high: 0.8 }
- },
- proposals: [],
- evolutionHistory: [],
- performanceBaseline: {
- successRate: 0.7,
- avgDurationMs: 60000,
- recordedAt: null
- },
- settings: {
- autoApproveModelChanges: true, // Full autonomy
- autoApproveThresholdChanges: true,
- rollbackThreshold: 0.2, // Rollback if success rate drops >20%
- minTasksBeforeEvaluation: 50 // Evaluate after 50 tasks
- }
-}
-
-// In-memory state
-let evolutionState = null
-
-/**
- * Load evolution state
- * @returns {Promise<Object>} - Evolution state
- */
-async function loadState() {
- if (evolutionState) return evolutionState
-
- await ensureDir(PATHS.cos)
-
- const exists = await fs.access(EVOLUTION_FILE).then(() => true).catch(() => false)
- if (exists) {
- const content = await fs.readFile(EVOLUTION_FILE, 'utf-8')
- evolutionState = safeJSONParse(content, { ...DEFAULT_STATE }, { context: 'cosEvolution' })
- } else {
- evolutionState = { ...DEFAULT_STATE }
- }
-
- return evolutionState
-}
-
-/**
- * Save evolution state
- */
-async function saveState() {
- await ensureDir(PATHS.cos)
- await fs.writeFile(EVOLUTION_FILE, JSON.stringify(evolutionState, null, 2))
-}
-
-/**
- * Get current evolution state
- * @returns {Promise<Object>} - Current state
- */
-async function getState() {
- return loadState()
-}
-
-/**
- * Propose a base model change
- * With full autonomy, this executes immediately.
- *
- * @param {string} newModel - New model identifier
- * @param {string} reasoning - Reasoning for change
- * @returns {Promise<Object>} - Proposal result
- */
-async function proposeBaseModelChange(newModel, reasoning) {
- const state = await loadState()
- const proposal = {
- id: uuidv4(),
- type: 'base-model-change',
- currentModel: state.currentBaseModel,
- proposedModel: newModel,
- reasoning,
- createdAt: new Date().toISOString(),
- status: 'approved', // Auto-approved with full autonomy
- executedAt: null,
- result: null
- }
-
- state.proposals.push(proposal)
-
- // Execute immediately (full autonomy)
- const result = await executeBaseModelChange(proposal.id)
-
- await saveState()
-
- console.log(`🧬 Evolution: Base model changed ${proposal.currentModel} → ${newModel}`)
- cosEvents.emit('evolution:modelChanged', {
- from: proposal.currentModel,
- to: newModel,
- reasoning
- })
-
- return result
-}
-
-/**
- * Execute a base model change
- * @param {string} proposalId - Proposal to execute
- * @returns {Promise<Object>} - Execution result
- */
-async function executeBaseModelChange(proposalId) {
- const state = await loadState()
- const proposal = state.proposals.find(p => p.id === proposalId)
-
- if (!proposal) {
- return { success: false, error: 'Proposal not found' }
- }
-
- // Record the change
- const previousModel = state.currentBaseModel
- state.currentBaseModel = proposal.proposedModel
- proposal.executedAt = new Date().toISOString()
- proposal.status = 'executed'
-
- // Record in history
- state.evolutionHistory.push({
- type: 'base-model-change',
- from: previousModel,
- to: proposal.proposedModel,
- reasoning: proposal.reasoning,
- executedAt: proposal.executedAt
- })
-
- await saveState()
-
- return {
- success: true,
- previousModel,
- newModel: proposal.proposedModel
- }
-}
-
-/**
- * Request a model download
- * @param {string} modelId - Model to download
- * @param {string} purpose - Why this model is needed
- * @returns {Promise<Object>} - Download result
- */
-async function requestModelDownload(modelId, purpose) {
- const state = await loadState()
-
- // Record the request
- state.evolutionHistory.push({
- type: 'model-download-request',
- modelId,
- purpose,
- requestedAt: new Date().toISOString()
- })
-
- await saveState()
-
- // Attempt download via LM Studio
- const result = await lmStudioManager.downloadModel(modelId)
-
- console.log(`📥 Evolution: Model download requested - ${modelId}`)
- cosEvents.emit('evolution:downloadRequested', { modelId, purpose, result })
-
- return result
-}
-
-/**
- * Adjust thinking thresholds
- * @param {string} thresholdType - 'contextLength' or 'complexity'
- * @param {Object} newValues - New threshold values
- * @param {string} reasoning - Reasoning for change
- * @returns {Promise<Object>} - Adjustment result
- */
-async function adjustThinkingThreshold(thresholdType, newValues, reasoning) {
- const state = await loadState()
-
- if (!state.currentThinkingThresholds[thresholdType]) {
- return { success: false, error: 'Unknown threshold type' }
- }
-
- const previousValues = { ...state.currentThinkingThresholds[thresholdType] }
-
- // Apply new values
- Object.assign(state.currentThinkingThresholds[thresholdType], newValues)
-
- // Record in history
- state.evolutionHistory.push({
- type: 'threshold-adjustment',
- thresholdType,
- from: previousValues,
- to: state.currentThinkingThresholds[thresholdType],
- reasoning,
- executedAt: new Date().toISOString()
- })
-
- await saveState()
-
- console.log(`🎚️ Evolution: Threshold ${thresholdType} adjusted`)
- cosEvents.emit('evolution:thresholdAdjusted', {
- thresholdType,
- from: previousValues,
- to: state.currentThinkingThresholds[thresholdType],
- reasoning
- })
-
- return {
- success: true,
- thresholdType,
- previousValues,
- newValues: state.currentThinkingThresholds[thresholdType]
- }
-}
-
-/**
- * Record performance metrics for baseline comparison
- * @param {Object} metrics - Current performance metrics
- */
-async function recordPerformanceMetrics(metrics) {
- const state = await loadState()
-
- const previous = { ...state.performanceBaseline }
-
- state.performanceBaseline = {
- successRate: metrics.successRate,
- avgDurationMs: metrics.avgDurationMs,
- taskCount: metrics.taskCount || 0,
- recordedAt: new Date().toISOString()
- }
-
- // Check for significant drop requiring rollback
- if (previous.successRate && metrics.successRate) {
- const drop = previous.successRate - metrics.successRate
- if (drop > state.settings.rollbackThreshold) {
- console.log(`⚠️ Evolution: Performance drop detected (${(drop * 100).toFixed(1)}%)`)
- cosEvents.emit('evolution:performanceDrop', {
- previousRate: previous.successRate,
- currentRate: metrics.successRate,
- dropPercent: drop * 100
- })
- // Could trigger automatic rollback here
- }
- }
-
- await saveState()
-}
-
-/**
- * Rollback to previous base model
- * @param {string} reason - Reason for rollback
- * @returns {Promise<Object>} - Rollback result
- */
-async function rollbackBaseModel(reason) {
- const state = await loadState()
-
- // Find the previous model change in history
- const modelChanges = state.evolutionHistory
- .filter(e => e.type === 'base-model-change')
- .reverse()
-
- if (modelChanges.length < 2) {
- return { success: false, error: 'No previous model to rollback to' }
- }
-
- const previousChange = modelChanges[1]
- const currentModel = state.currentBaseModel
- const rollbackTo = previousChange.from
-
- state.currentBaseModel = rollbackTo
-
- state.evolutionHistory.push({
- type: 'rollback',
- from: currentModel,
- to: rollbackTo,
- reason,
- executedAt: new Date().toISOString()
- })
-
- await saveState()
-
- console.log(`⏪ Evolution: Rolled back to ${rollbackTo}`)
- cosEvents.emit('evolution:rollback', {
- from: currentModel,
- to: rollbackTo,
- reason
- })
-
- return {
- success: true,
- previousModel: currentModel,
- restoredModel: rollbackTo
- }
-}
-
-/**
- * Get evolution history
- * @param {Object} options - Filter options
- * @returns {Promise<Array>} - Evolution history
- */
-async function getHistory(options = {}) {
- const state = await loadState()
- let history = [...state.evolutionHistory]
-
- if (options.type) {
- history = history.filter(e => e.type === options.type)
- }
-
- // Sort by date descending
- history.sort((a, b) =>
- new Date(b.executedAt || b.requestedAt).getTime() -
- new Date(a.executedAt || a.requestedAt).getTime()
- )
-
- const limit = options.limit || 50
- return history.slice(0, limit)
-}
-
-/**
- * Get pending proposals (for display, though auto-approved)
- * @returns {Promise<Array>} - Pending proposals
- */
-async function getPendingProposals() {
- const state = await loadState()
- return state.proposals.filter(p => p.status === 'pending')
-}
-
-/**
- * Get evolution statistics
- * @returns {Promise<Object>} - Evolution stats
- */
-async function getStats() {
- const state = await loadState()
-
- const byType = {}
- for (const entry of state.evolutionHistory) {
- byType[entry.type] = (byType[entry.type] || 0) + 1
- }
-
- return {
- currentBaseModel: state.currentBaseModel,
- currentThresholds: state.currentThinkingThresholds,
- performanceBaseline: state.performanceBaseline,
- totalEvolutions: state.evolutionHistory.length,
- byType,
- pendingProposals: state.proposals.filter(p => p.status === 'pending').length,
- settings: state.settings
- }
-}
-
-/**
- * Update evolution settings
- * @param {Object} newSettings - Settings to update
- * @returns {Promise<Object>} - Updated settings
- */
-async function updateSettings(newSettings) {
- const state = await loadState()
-
- Object.assign(state.settings, newSettings)
- await saveState()
-
- return state.settings
-}
-
-/**
- * Invalidate cache
- */
-function invalidateCache() {
- evolutionState = null
-}
-
-export {
- getState,
- proposeBaseModelChange,
- requestModelDownload,
- adjustThinkingThreshold,
- recordPerformanceMetrics,
- rollbackBaseModel,
- getHistory,
- getPendingProposals,
- getStats,
- updateSettings,
- invalidateCache
-}
diff --git a/server/services/portosChangelog.js b/server/services/portosChangelog.js
deleted file mode 100644
index 4be21c9159..0000000000
--- a/server/services/portosChangelog.js
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- * PortOS Changelog Service
- *
- * Extracts recent PortOS feature commits from git history.
- * Used by the daily briefing to highlight new features for the user.
- */
-
-import { execFileSync } from 'child_process';
-import { writeFile } from 'fs/promises';
-import { join, dirname } from 'path';
-import { readJSONFile, ensureDir, PATHS, DAY } from '../lib/fileUtils.js';
-
-const STATE_FILE = join(PATHS.data, 'portos-changelog.json');
-const NUL = '\x00';
-
-const DEFAULT_STATE = { lastBriefedAt: null, lastBriefedCommit: null };
-
-function parseConventionalCommit(message) {
- const match = message.match(/^(feat|fix|refactor|perf|docs|chore|style|test)(?:\(([^)]+)\))?:\s*(.+)/);
- if (!match) return null;
- return { type: match[1], scope: match[2] || null, description: match[3] };
-}
-
-/**
- * @param {string} [since] - ISO date string. Defaults to last briefed time or 24h ago.
- * @returns {{ features: Array, fixes: Array, other: Array, since: string }}
- */
-export async function getRecentChanges(since) {
- let sinceDate = since;
- if (!sinceDate) {
- const state = await readJSONFile(STATE_FILE, DEFAULT_STATE);
- sinceDate = state.lastBriefedAt || new Date(Date.now() - DAY).toISOString();
- }
-
- let raw;
- try {
- // NUL delimiter avoids breakage from | in commit messages
- raw = execFileSync('git', [
- 'log', `--since=${sinceDate}`, '--no-merges', `--format=%H${NUL}%s${NUL}%ai`
- ], { cwd: process.cwd(), encoding: 'utf-8', windowsHide: true }).trim();
- } catch {
- console.log('📋 PortOS changelog: git not available, skipping');
- return { features: [], fixes: [], other: [], since: sinceDate };
- }
-
- if (!raw) {
- return { features: [], fixes: [], other: [], since: sinceDate };
- }
-
- const features = [];
- const fixes = [];
- const other = [];
-
- for (const line of raw.split('\n')) {
- const [hash, message, date] = line.split(NUL);
- const parsed = parseConventionalCommit(message);
- const commit = { hash: hash?.slice(0, 8), message, date, parsed };
- if (parsed?.type === 'feat') features.push(commit);
- else if (parsed?.type === 'fix') fixes.push(commit);
- else if (parsed) other.push(commit);
- }
-
- return { features, fixes, other, since: sinceDate };
-}
-
-export async function markBriefed() {
- let headCommit;
- try {
- headCommit = execFileSync('git', ['rev-parse', '--short', 'HEAD'], {
- cwd: process.cwd(), encoding: 'utf-8', windowsHide: true
- }).trim();
- } catch {
- console.log('📋 PortOS changelog: git not available, skipping markBriefed');
- return DEFAULT_STATE;
- }
-
- const state = {
- lastBriefedAt: new Date().toISOString(),
- lastBriefedCommit: headCommit
- };
-
- await ensureDir(dirname(STATE_FILE));
- await writeFile(STATE_FILE, JSON.stringify(state, null, 2));
- console.log(`📋 PortOS changelog briefed at ${headCommit}`);
- return state;
-}
-
-export async function getState() {
- return readJSONFile(STATE_FILE, DEFAULT_STATE);
-}
diff --git a/server/services/portosChangelog.test.js b/server/services/portosChangelog.test.js
deleted file mode 100644
index 6c34d16aa6..0000000000
--- a/server/services/portosChangelog.test.js
+++ /dev/null
@@ -1,133 +0,0 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-const NUL = '\x00';
-
-vi.mock('child_process', () => ({
- execFileSync: vi.fn()
-}));
-
-vi.mock('fs/promises', () => ({
- writeFile: vi.fn().mockResolvedValue(undefined)
-}));
-
-vi.mock('../lib/fileUtils.js', () => ({
- readJSONFile: vi.fn(),
- ensureDir: vi.fn().mockResolvedValue(undefined),
- PATHS: { data: '/mock/data' },
- DAY: 86400000
-}));
-
-import { execFileSync } from 'child_process';
-import { writeFile } from 'fs/promises';
-import { readJSONFile } from '../lib/fileUtils.js';
-import { getRecentChanges, markBriefed, getState } from './portosChangelog.js';
-
-beforeEach(() => {
- vi.clearAllMocks();
- readJSONFile.mockResolvedValue({ lastBriefedAt: null, lastBriefedCommit: null });
-});
-
-describe('getRecentChanges', () => {
- it('returns empty arrays when no commits found', async () => {
- execFileSync.mockReturnValue('');
- const result = await getRecentChanges();
- expect(result.features).toEqual([]);
- expect(result.fixes).toEqual([]);
- expect(result.other).toEqual([]);
- });
-
- it('parses feature commits correctly', async () => {
- execFileSync.mockReturnValue(
- `abc12345${NUL}feat(cos): add new briefing section${NUL}2026-03-23 10:00:00 -0700\n` +
- `def67890${NUL}feat(ui): add dark mode toggle${NUL}2026-03-23 09:00:00 -0700`
- );
- const result = await getRecentChanges();
- expect(result.features).toHaveLength(2);
- expect(result.features[0].parsed.type).toBe('feat');
- expect(result.features[0].parsed.scope).toBe('cos');
- expect(result.features[0].parsed.description).toBe('add new briefing section');
- expect(result.features[0].hash).toBe('abc12345');
- });
-
- it('separates features from fixes', async () => {
- execFileSync.mockReturnValue(
- `abc12345${NUL}feat(cos): add feature${NUL}2026-03-23 10:00:00 -0700\n` +
- `def67890${NUL}fix(ui): broken button${NUL}2026-03-23 09:00:00 -0700`
- );
- const result = await getRecentChanges();
- expect(result.features).toHaveLength(1);
- expect(result.fixes).toHaveLength(1);
- expect(result.fixes[0].parsed.type).toBe('fix');
- });
-
- it('categorizes refactor/chore/docs as other', async () => {
- execFileSync.mockReturnValue(
- `abc12345${NUL}refactor(api): clean up routes${NUL}2026-03-23 10:00:00 -0700\n` +
- `def67890${NUL}chore: update deps${NUL}2026-03-23 09:00:00 -0700`
- );
- const result = await getRecentChanges();
- expect(result.features).toHaveLength(0);
- expect(result.fixes).toHaveLength(0);
- expect(result.other).toHaveLength(2);
- });
-
- it('uses lastBriefedAt from state when no since param provided', async () => {
- readJSONFile.mockResolvedValue({ lastBriefedAt: '2026-03-22T00:00:00Z', lastBriefedCommit: 'aaa' });
- execFileSync.mockReturnValue('');
- const result = await getRecentChanges();
- expect(result.since).toBe('2026-03-22T00:00:00Z');
- expect(execFileSync).toHaveBeenCalledWith(
- 'git',
- expect.arrayContaining(['--since=2026-03-22T00:00:00Z']),
- expect.any(Object)
- );
- });
-
- it('skips state file read when since param is provided', async () => {
- execFileSync.mockReturnValue('');
- const result = await getRecentChanges('2026-03-20T00:00:00Z');
- expect(result.since).toBe('2026-03-20T00:00:00Z');
- expect(readJSONFile).not.toHaveBeenCalled();
- });
-
- it('handles commits without conventional format', async () => {
- execFileSync.mockReturnValue(
- `abc12345${NUL}feat(cos): add feature${NUL}2026-03-23 10:00:00 -0700\n` +
- `bbb22222${NUL}Merge branch main${NUL}2026-03-23 08:00:00 -0700`
- );
- const result = await getRecentChanges();
- expect(result.features).toHaveLength(1);
- expect(result.fixes).toHaveLength(0);
- expect(result.other).toHaveLength(0);
- });
-
- it('handles feat commits without scope', async () => {
- execFileSync.mockReturnValue(`abc12345${NUL}feat: global feature${NUL}2026-03-23 10:00:00 -0700`);
- const result = await getRecentChanges();
- expect(result.features).toHaveLength(1);
- expect(result.features[0].parsed.scope).toBeNull();
- expect(result.features[0].parsed.description).toBe('global feature');
- });
-});
-
-describe('markBriefed', () => {
- it('writes state file with current commit hash', async () => {
- execFileSync.mockReturnValue('abc1234\n');
- const result = await markBriefed();
- expect(result.lastBriefedCommit).toBe('abc1234');
- expect(result.lastBriefedAt).toBeDefined();
- expect(writeFile).toHaveBeenCalledWith(
- expect.stringContaining('portos-changelog.json'),
- expect.any(String)
- );
- });
-});
-
-describe('getState', () => {
- it('returns default state when no file exists', async () => {
- readJSONFile.mockResolvedValue({ lastBriefedAt: null, lastBriefedCommit: null });
- const state = await getState();
- expect(state.lastBriefedAt).toBeNull();
- expect(state.lastBriefedCommit).toBeNull();
- });
-});
diff --git a/server/services/selfImprovement.js b/server/services/selfImprovement.js
deleted file mode 100644
index 49903b7ede..0000000000
--- a/server/services/selfImprovement.js
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * Self-Improvement Service
- *
- * Automated system for analyzing PortOS UI and codebase,
- * generating improvement tasks for the CoS to execute.
- *
- * Uses Playwright MCP or direct Playwright to:
- * - Navigate to all known routes
- * - Capture accessibility snapshots
- * - Check mobile responsiveness
- * - Capture console/network errors
- * - Generate improvement tasks
- */
-
-import { cosEvents, getConfig } from './cos.js';
-import { PORTOS_UI_URL } from '../lib/ports.js';
-
-// Known routes to analyze
-const ROUTES = [
- { path: '/', name: 'Dashboard', critical: true },
- { path: '/apps', name: 'Apps', critical: true },
- { path: '/cos', name: 'Chief of Staff', critical: true },
- { path: '/cos/tasks', name: 'CoS Tasks', critical: true },
- { path: '/cos/agents', name: 'CoS Agents', critical: true },
- { path: '/cos/health', name: 'CoS Health', critical: false },
- { path: '/cos/config', name: 'CoS Config', critical: false },
- { path: '/cos/memory', name: 'CoS Memory', critical: false },
- { path: '/devtools', name: 'DevTools', critical: true },
- { path: '/devtools/history', name: 'DevTools History', critical: true },
- { path: '/devtools/runner', name: 'DevTools Runner', critical: true },
- { path: '/providers', name: 'AI Providers', critical: true },
- { path: '/usage', name: 'Usage Metrics', critical: false },
- { path: '/prompts', name: 'Prompts', critical: false },
- { path: '/logs', name: 'Logs', critical: false }
-];
-
-// Viewport sizes for responsive testing
-const VIEWPORTS = [
- { name: 'mobile', width: 375, height: 812 },
- { name: 'tablet', width: 768, height: 1024 },
- { name: 'desktop', width: 1440, height: 900 }
-];
-
-// Analysis task types
-const ANALYSIS_TYPES = {
- UI_BUGS: 'ui-bugs',
- MOBILE_RESPONSIVE: 'mobile-responsive',
- ACCESSIBILITY: 'accessibility',
- CONSOLE_ERRORS: 'console-errors',
- SECURITY: 'security',
- PERFORMANCE: 'performance',
- CODE_QUALITY: 'code-quality',
- TEST_COVERAGE: 'test-coverage',
- DOCUMENTATION: 'documentation',
- FEATURE_IDEAS: 'feature-ideas',
- DEPENDENCY_UPDATES: 'dependency-updates',
- ERROR_HANDLING: 'error-handling',
- TYPING: 'typing',
- RELEASE_CHECK: 'release-check'
-};
-
-/**
- * Emit log event for CoS UI
- */
-function emitLog(level, message, data = {}) {
- const logEntry = {
- timestamp: new Date().toISOString(),
- level,
- message,
- ...data
- };
- console.log(`${level === 'error' ? '❌' : level === 'warn' ? '⚠️' : level === 'success' ? '✅' : level === 'debug' ? '🔍' : 'ℹ️'} 🔧 SelfImprovement: ${message}`);
- cosEvents.emit('log', logEntry);
-}
-
-/**
- * Run a full self-improvement cycle
- * This is called when CoS is idle and wants to improve itself
- */
-export async function runSelfImprovementCycle() {
- const config = await getConfig();
-
- if (!config.selfImprovementEnabled) {
- emitLog('debug', 'Self-improvement is disabled');
- return null;
- }
-
- emitLog('info', 'Starting self-improvement cycle');
-
- // Rotate through analysis types
- const analysisTypes = Object.values(ANALYSIS_TYPES);
- const lastAnalysis = config.lastSelfImprovementType || '';
- const currentIndex = analysisTypes.indexOf(lastAnalysis);
- const nextType = analysisTypes[(currentIndex + 1) % analysisTypes.length];
-
- emitLog('info', `Running ${nextType} analysis`);
-
- // Generate the task based on type
- const task = await generateSelfImprovementTask(nextType);
-
- return task;
-}
-
-/**
- * Generate a self-improvement task based on analysis type
- */
-async function generateSelfImprovementTask(analysisType) {
- const taskDescriptions = {
- [ANALYSIS_TYPES.UI_BUGS]: `Analyze PortOS UI at ${PORTOS_UI_URL} for bugs and issues
-
-Use Playwright MCP to:
-1. Navigate to each main route (/, /apps, /cos, /devtools, /providers, /usage)
-2. Capture browser snapshots and console messages
-3. Look for JavaScript errors, failed requests, broken UI elements
-4. Fix any bugs found and commit the changes
-
-Model: claude-opus-4-5-20251101`,
-
- [ANALYSIS_TYPES.MOBILE_RESPONSIVE]: `Analyze PortOS UI for mobile responsiveness issues
-
-Use Playwright MCP to:
-1. Navigate to ${PORTOS_UI_URL} and its sub-routes
-2. Test at mobile (375px), tablet (768px), and desktop (1440px) viewports
-3. Capture snapshots at each viewport size
-4. Identify layout issues, overflow, touch targets, font sizes
-5. Fix responsiveness issues in the Tailwind CSS classes
-6. Commit fixes with clear descriptions
-
-Model: claude-opus-4-5-20251101`,
-
- [ANALYSIS_TYPES.SECURITY]: `Security audit of PortOS codebase
-
-Analyze the following for security vulnerabilities:
-1. server/routes/*.js - Check all API endpoints for injection vulnerabilities
-2. server/services/*.js - Check for command injection, path traversal
-3. server/lib/commandAllowlist.js - Verify allowlist is comprehensive
-4. client/src/services/api.js - Check for XSS, CSRF protection
-5. Check for hardcoded secrets, unsafe eval, missing validation
-
-Fix any issues found with secure alternatives and commit changes.
-
-Model: claude-opus-4-5-20251101`,
-
- [ANALYSIS_TYPES.CODE_QUALITY]: `Code quality review of PortOS
-
-Analyze the codebase for:
-1. DRY violations - Find and consolidate duplicated code
-2. Large functions (>50 lines) that should be split
-3. Missing error handling
-4. Dead code and unused imports
-5. Inconsistent patterns between files
-6. TODO/FIXME comments that need addressing
-
-Focus on server/ and client/src/ directories.
-Make improvements and commit with clear messages.
-
-Model: claude-opus-4-5-20251101`,
-
- [ANALYSIS_TYPES.ACCESSIBILITY]: `Accessibility audit of PortOS UI
-
-Use Playwright MCP to:
-1. Navigate to ${PORTOS_UI_URL} and sub-routes
-2. Capture accessibility snapshots
-3. Check for missing ARIA labels, alt text, keyboard navigation
-4. Verify color contrast ratios
-5. Test screen reader compatibility
-
-Fix accessibility issues and commit changes.
-
-Model: claude-opus-4-5-20251101`,
-
- [ANALYSIS_TYPES.CONSOLE_ERRORS]: `Check PortOS for console errors and warnings
-
-Use Playwright MCP to:
-1. Navigate to ${PORTOS_UI_URL}
-2. Open each main route and interact with key features
-3. Capture all console messages (errors, warnings)
-4. Identify the source of each error
-5. Fix the underlying issues in the code
-6. Commit fixes with clear descriptions
-
-Model: claude-opus-4-5-20251101`,
-
- [ANALYSIS_TYPES.PERFORMANCE]: `Performance analysis of PortOS
-
-Analyze for performance issues:
-1. Check component re-renders in React DevTools patterns
-2. Look for N+1 query patterns in API calls
-3. Identify large bundle sizes or missing code splitting
-4. Check for memory leaks in useEffect hooks
-5. Analyze Socket.IO event handling efficiency
-
-Optimize and commit improvements.
-
-Model: claude-opus-4-5-20251101`
- };
-
- const description = taskDescriptions[analysisType] || taskDescriptions[ANALYSIS_TYPES.CODE_QUALITY];
-
- const task = {
- id: `self-improve-${analysisType}-${Date.now().toString(36)}`,
- status: 'pending',
- priority: 'MEDIUM',
- priorityValue: 2,
- description: `[Self-Improvement] ${description}`,
- metadata: {
- analysisType,
- autoGenerated: true,
- selfImprovement: true,
- model: 'claude-opus-4-5-20251101'
- },
- taskType: 'internal',
- autoApproved: true,
- model: 'claude-opus-4-5-20251101'
- };
-
- emitLog('info', `Generated self-improvement task: ${analysisType}`, { taskId: task.id });
- return task;
-}
-
-/**
- * Get the next self-improvement task type based on rotation
- */
-export function getNextImprovementType(lastType) {
- const types = Object.values(ANALYSIS_TYPES);
- const currentIndex = types.indexOf(lastType);
- return types[(currentIndex + 1) % types.length];
-}
-
-/**
- * Export analysis types for configuration
- */
-export { ANALYSIS_TYPES, ROUTES, VIEWPORTS };