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 unused server exports and guard new ones (#8215)
[._.]/ Adam Eivy22cc670b012f
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex d4e3f026fe..c18893f1ed 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -232,6 +232,8 @@ export const ALWAYS_RUN_TESTS = ['scripts/server-imports-no-client.test.js','scripts/tailnet-identity-leak.test.js','server/dependency-overrides.test.js',+ // Whole-tree scanner: a caller can disappear from any file without touching its export.+ 'server/deadExports.test.js',// Whole-tree scanner: any server file can add a `process.env` read, and// `.env.example` itself is not a scope the selector routes to a runner.'server/envExampleDrift.test.js',diff --git a/server/deadExports.test.js b/server/deadExports.test.jsnew file mode 100644index 0000000000..7f9ef090f0--- /dev/null+++ b/server/deadExports.test.js@@ -0,0 +1,79 @@+import { execFileSync } from 'node:child_process';+import { existsSync, readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { fileURLToPath } from 'node:url';+import { describe, expect, it } from 'vitest';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const EXPORT = /^export (?:async )?function ([A-Za-z_$][\w$]*)\b/gm;+const WORD = /\b[A-Za-z_$][\w$]*\b/g;++function excluded(file, name) {+ if (name.startsWith('_')) return true; // Test and integration hooks are intentionally public.+ if (file === 'server/services/beeperClient.js') return true; // Standalone external API client.+ if (file.startsWith('server/integrations/')) return true; // Standalone integration API clients.+ if (file.startsWith('server/lib/aiToolkit/')) return true; // Vendored toolkit public barrel surface.+ return false;+}++function deadExports(files, candidateNames = null) {+ const declarations = [];+ const names = new Set();+ for (const [file, source] of files) {+ if (!/^server\/(services|lib)\/.*\.js$/.test(file) || file.endsWith('.test.js')) continue;+ for (const match of source.matchAll(EXPORT)) {+ if (excluded(file, match[1])) continue;+ if (candidateNames && !candidateNames.has(match[1])) continue;+ declarations.push({ file, name: match[1] });+ names.add(match[1]);+ }+ }++ const mentionedBy = new Map();+ for (const [file, source] of files) {+ if (/\.test\.[cm]?[jt]sx?$/.test(file) || /(^|\/)README\.md$/i.test(file)) continue;+ for (const match of source.matchAll(WORD)) {+ if (!names.has(match[0])) continue;+ if (!mentionedBy.has(match[0])) mentionedBy.set(match[0], new Set());+ mentionedBy.get(match[0]).add(file);+ }+ }+ return declarations.filter(({ file, name }) =>+ ![...(mentionedBy.get(name) || [])].some(other => other !== file));+}++function addedExportNames() {+ const base = process.env.CI_BASE_SHA || execFileSync('git', ['merge-base', 'HEAD', 'origin/main'], { cwd: ROOT, encoding: 'utf8' }).trim();+ const diff = execFileSync('git', ['diff', '--unified=0', base, '--', 'server/services', 'server/lib'], { cwd: ROOT, encoding: 'utf8' });+ const names = new Set();+ for (const line of diff.split('\n')) {+ if (!line.startsWith('+') || line.startsWith('+++')) continue;+ const match = /^\+export (?:async )?function ([A-Za-z_$][\w$]*)\b/.exec(line);+ if (match) names.add(match[1]);+ }+ return names;+}++function trackedFiles() {+ return execFileSync('git', ['ls-files', '-z'], { cwd: ROOT })+ .toString('utf8').split('\0').filter(Boolean)+ .filter(file => /\.(?:[cm]?[jt]sx?|json|md)$/.test(file))+ .filter(file => existsSync(join(ROOT, file)))+ .map(file => [file, readFileSync(join(ROOT, file), 'utf8')]);+}++describe('server dead exports', () => {+ it('detects a caller-less exported function and ignores a live export', () => {+ const files = new Map([+ ['server/services/example.js', 'export function orphan() {}\nexport async function used() {}\n'],+ ['server/routes/example.js', 'used();\n'],+ ]);+ expect(deadExports(files)).toEqual([{ file: 'server/services/example.js', name: 'orphan' }]);+ });++ it('keeps newly added server function exports reachable', () => {+ // Existing test-only and undocumented public exports predate this guard.+ // Gate additions while that legacy inventory is reduced separately.+ expect(deadExports(trackedFiles(), addedExportNames())).toEqual([]);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 9bdae45034..6ea2084aca 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -262,7 +262,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. Under a `no-tool` public-review profile it also applies `hardenOpencodeConfigForNoTool` — root `permission: deny`, an emptied tool map on every agent, `tool_call: false` on every declared model, and no MCP/plugins/share/autoupdate — which IS OpenCode's enforced tool-free recipe, since it ships no read-only argv flag (`providerVendors.js` pairs it with `run --agent` + `OPENCODE_PUBLIC_REVIEW_AGENT`). The harden step also copies `agent.build`'s generation settings onto that agent, so the stage's configured thinking effort reaches the model that actually runs. || `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localEndpointPort` + `isLocalInstanceHost`, and re-exports of `localBackendForProvider` / `localRuntimeKind` / `modelPinIsOffered` — all three now live in the browser-safe leaf `modelPinMembership.js` (a picker needs the pin rule and must not pull the endpoint graph below to get it), so existing importers here are untouched — `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project); `standbyWhenStopped` marks an installed runtime such as llama.cpp whose stopped state is intentional standby rather than incomplete setup. |-| `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`, `services/slotstreamServerManager.js` → `portos-slotstream`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_APP`, `SLOTSTREAM_APP`, and the `isModelServerProcess(name)` predicate over them — so a caller like the CoS health monitor can recognize a model server without importing a manager; the managers re-export those names. `createDaemonWatcher({...})` supplies the common PM2 launch-line re-adoption, endpoint probe, status skeleton, bounded log view, and port-release wait while managers retain daemon-specific parsing and lifecycle policy. `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Also the shared **idle reaper**, for a daemon that cannot release its weights any other way: `registerIdleDaemon({name, getIdleMs, isPinned?, isRunning?, stop})` (seeds `lastUsedAt` to NOW, so a hand-started daemon gets a full window; `isPinned` exempts user-pinned servers), `markDaemonUsed(name)` — call on real traffic, NEVER on a status poll — `daemonLastUsedAt(name)`, `daemonReleaseReason(name)`, `idleWindowMs(minutes)` (minutes → ms; `0` = never, `null` = not configured, kept distinct), `evaluateMemoryPressurePolicy({...})` (pure policy function evaluating current state, pressure reading, and recent history), `reapIdleDaemons(now?, options?)` → the names stopped (stops idle daemons whose window elapsed, and runs a pressure-aware pass releasing the least recently used unpinned daemon under sustained host memory pressure; at most one daemon stopped per tick), and `startIdleReaper({intervalMs?})` / `stopIdleReaper()` (ONE interval for all registrants, `unref`'d, idempotent). `mtplxServerManager` and `slotstreamServerManager` register: llama.cpp releases its checkpoint in place via `--sleep-idle-seconds` and must NOT be stopped for it. `createOnDemandDaemon({appName, label, emoji, readSection, endpointFor, probe, start, stop, getStatusStrict, clearStatusCache?, exitTail?, resolveLaunch, getConfig?, sleep, getRelaunchReadyTimeoutMs, getRelaunchPollMs})` is the shared ON-DEMAND WAKE mechanism (#8105) — `ensureRunning()` (mark used → already online? → resolve the launch line via the manager's `resolveLaunch(current, saved)` → probe → start → wait), `registerIdle()` (wraps `registerIdleDaemon` with the idle-minutes/keep-loaded reads, including the legacy `pinned` fallback and their own `set*OverrideForTests` seams), `waitForReady(endpoint)` (the death-detecting readiness poll, with `exitTail` folded in), `servesPort(provider, managedPort)` (the numeric port-match arm — `Number(localEndpointPort(...))`, fixing a `===` string/number mismatch that made the MTPLX arm permanently dead), and `idleMinutes` / `keepLoaded` / `savedLaunch` for a status card's reads. `createPm2ExitTail({appName, execPm2, appendLog, lines?, tailLines?})` is the shared "what did the dead process print" diagnosis both `waitForReady` and a manager's own startup-window failure can share. Both mechanisms only — what a launch line means and when a daemon may start is exactly what differs between the two. |+| `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`, `services/slotstreamServerManager.js` → `portos-slotstream`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_APP`, and `SLOTSTREAM_APP`; the managers re-export those names. `createDaemonWatcher({...})` supplies the common PM2 launch-line re-adoption, endpoint probe, status skeleton, bounded log view, and port-release wait while managers retain daemon-specific parsing and lifecycle policy. `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Also the shared **idle reaper**, for a daemon that cannot release its weights any other way: `registerIdleDaemon({name, getIdleMs, isPinned?, isRunning?, stop})` (seeds `lastUsedAt` to NOW, so a hand-started daemon gets a full window; `isPinned` exempts user-pinned servers), `markDaemonUsed(name)` — call on real traffic, NEVER on a status poll — `daemonLastUsedAt(name)`, `daemonReleaseReason(name)`, `idleWindowMs(minutes)` (minutes → ms; `0` = never, `null` = not configured, kept distinct), `evaluateMemoryPressurePolicy({...})` (pure policy function evaluating current state, pressure reading, and recent history), `reapIdleDaemons(now?, options?)` → the names stopped (stops idle daemons whose window elapsed, and runs a pressure-aware pass releasing the least recently used unpinned daemon under sustained host memory pressure; at most one daemon stopped per tick), and `startIdleReaper({intervalMs?})` / `stopIdleReaper()` (ONE interval for all registrants, `unref`'d, idempotent). `mtplxServerManager` and `slotstreamServerManager` register: llama.cpp releases its checkpoint in place via `--sleep-idle-seconds` and must NOT be stopped for it. `createOnDemandDaemon({appName, label, emoji, readSection, endpointFor, probe, start, stop, getStatusStrict, clearStatusCache?, exitTail?, resolveLaunch, getConfig?, sleep, getRelaunchReadyTimeoutMs, getRelaunchPollMs})` is the shared ON-DEMAND WAKE mechanism (#8105) — `ensureRunning()` (mark used → already online? → resolve the launch line via the manager's `resolveLaunch(current, saved)` → probe → start → wait), `registerIdle()` (wraps `registerIdleDaemon` with the idle-minutes/keep-loaded reads, including the legacy `pinned` fallback and their own `set*OverrideForTests` seams), `waitForReady(endpoint)` (the death-detecting readiness poll, with `exitTail` folded in), `servesPort(provider, managedPort)` (the numeric port-match arm — `Number(localEndpointPort(...))`, fixing a `===` string/number mismatch that made the MTPLX arm permanently dead), and `idleMinutes` / `keepLoaded` / `savedLaunch` for a status card's reads. `createPm2ExitTail({appName, execPm2, appendLog, lines?, tailLines?})` is the shared "what did the dead process print" diagnosis both `waitForReady` and a manager's own startup-window failure can share. Both mechanisms only — what a launch line means and when a daemon may start is exactly what differs between the two. || `mtplxModels.js` | `services/localCachedModels.js` owns provider-refresh discovery and gates it on runtime readiness without loading the process manager. `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (walks local directories — pulls no weights, loads no model, but see `mtplxRuntime.js`: on an un-warmed Homebrew wrapper the spawn ITSELF is a several-hundred-megabyte runtime download, so poll callers must gate on `describeMtplxRuntime().ready` first) `servableMtplxCachedModels(models)` → the rows MTPLX itself calls complete, and `pickMtplxCachedModel(models)` → the one repo id to hand `mtplx serve --model`. `models: null` means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from `[]` (read, and empty), because `services/localRuntimeSetup.js` starts MTPLX on its own default in the first case and refuses with the `mtplx pull` command in the second. Exists because `mtplx serve` defaults `--model` to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (`validation.ok !== false`, so a half-finished pull is not served), preferring one with a recorded `mtplx_runtime.json` exactness contract. `describeMtplxCache(cache)` → `{state: 'unknown'\|'empty'\|'partial'\|'ready', model, count, error}` folds both into the one value `services/providerReadiness.js` puts on the checklist and `describeRuntimeSetup` picks a button from — so an empty cache is named up front instead of only inside the failure of a Start that could never work. || `mtplxRuntime.js` | `describeMtplxRuntime(binaryPath, {env?})` → `{ready, wrapper, venvPath}` — is MTPLX's own Python runtime on disk, decided by READING the binary rather than running it. Homebrew's `mtplx` is a shell wrapper that lazily bootstraps a version-keyed Python venv (a multi-hundred-megabyte pip install) on its first invocation, and `brew upgrade` re-arms it, so a status poll or an 8s-judged PM2 start is really a package download. This parses the wrapper's own `VENV=` assignment, honours `$MTPLX_BREW_VENV` the way `${MTPLX_BREW_VENV:-…}` does, and tests `<venv>/bin/mtplx` for executability — the wrapper's own `[ ! -x … ]` guard, so the two cannot disagree. Anything unrecognisable (a pip install, a compiled binary, an unparseable script) reports `ready: true, wrapper: false`, i.e. the status quo — never a block over a parse failure. || `slotstreamCatalog.js` | `SLOTSTREAM_CATALOG` — the curated mixture-of-experts checkpoints worth streaming from SSD (the technique only pays off on MoE: a dense model of the same size would stream every layer for every token). `resolveSlotstreamRepo(idOrRepo)` maps a catalog id or an `owner/name` repo id to a repo (null for anything else), `slotstreamModelDirName(repo)` flattens it to the single-segment cache directory whose NAME is the id a start hands `--model`, and `selectSlotstreamRepoFiles(siblings)` picks the `.safetensors`/config/tokenizer files a checkpoint is made of while dropping mirrored `original/`, GGUF, ONNX, and PyTorch copies of the same weights (which can double a 100 GB+ pull) and any name that is not a plain relative path. |diff --git a/server/lib/cudaCapability.js b/server/lib/cudaCapability.jsindex e76c919aac..104ff07e4e 100644--- a/server/lib/cudaCapability.js+++ b/server/lib/cudaCapability.js@@ -343,8 +343,3 @@ export async function getCudaUtilization({ refresh = false, now = Date.now, ...putilizationExpiresAt = now() + CUDA_UTILIZATION_TTL_MS;return pending;}--export function resetCudaUtilizationCache() {- cachedUtilization = null;- utilizationExpiresAt = 0;-}diff --git a/server/lib/managedDaemon.js b/server/lib/managedDaemon.jsindex 271d318281..6333fe53d1 100644--- a/server/lib/managedDaemon.js+++ b/server/lib/managedDaemon.js@@ -26,33 +26,14 @@ import { localEndpointPort } from './localEndpoint.js';/*** The PM2 process names of the local model servers PortOS manages.*- * Declared here rather than in each manager so the health monitor can recognize- * them without importing a manager (and its whole PM2/model-probe dependency- * chain); `llamaServerManager.js`, `mtplxServerManager.js`, and+ * Declared here rather than in each manager so process names remain consistent;+ * `llamaServerManager.js`, `mtplxServerManager.js`, and* `slotstreamServerManager.js` re-export these as `LLAMA_APP` / `MTPLX_APP` /* `SLOTSTREAM_APP`.*/export const LLAMA_APP = 'portos-llama-server';export const MTPLX_APP = 'portos-mtplx';export const SLOTSTREAM_APP = 'portos-slotstream';-const MODEL_SERVER_APPS = [LLAMA_APP, MTPLX_APP, SLOTSTREAM_APP];--/**- * Whether a PM2 process is one of those model servers.- *- * A model server's resident size IS the checkpoint it loaded — llama.cpp,- * MTPLX, and Slotstream hold multi-GB weights for as long as they are up, by- * design. Measuring- * them against a generic per-process memory cap produces a warning the user can- * never clear (a 24GB llama-server against a 2GB cap is a correctly-running- * server, not a leak), so callers policing per-process memory skip them. Genuine- * host-wide pressure is still reported — `services/proactiveAlerts.js` alerts on- * total used-vs-installed memory, which is where a too-large model actually- * shows up.- *- * @param {string} [name] PM2 process name- */-export const isModelServerProcess = (name) => MODEL_SERVER_APPS.includes(name);/** Same cap both managers used, and what the launcher cards render. */const DEFAULT_MAX_LINES = 100;@@ -844,4 +825,3 @@ export function _resetIdleDaemonsForTests() {pressureHistory = [];lastPressureReleaseAt = null;}-diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 2d71b89bf9..1d45608ade 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -1301,7 +1301,6 @@ export const isZImage = (model) => model?.runner === RUNNER_FAMILIES.Z_IMAGE;export const isErnie = (model) => model?.runner === RUNNER_FAMILIES.ERNIE;export const isHiDream = (model) => model?.runner === RUNNER_FAMILIES.HIDREAM;export const isQwen = (model) => model?.runner === RUNNER_FAMILIES.QWEN;-export const isCfgDisabled = (model) => model?.cfgDisabled === true;export const isEditOnly = (model) => model?.editOnly === true;// Append models that are genuinely new in this release (not indiff --git a/server/lib/postPowersLadder.js b/server/lib/postPowersLadder.jsindex 72679f91d8..e5a29371c0 100644--- a/server/lib/postPowersLadder.js+++ b/server/lib/postPowersLadder.js@@ -102,7 +102,3 @@ export function resolvePowersLevel(levelStats = {}, opts = {}, floorLevel = 0) {levels: result.levels.map(({ descriptor, ...rung }) => ({ ...rung, technique: descriptor })),};}--export function powersLevelMastered(stat, level, opts = POWERS_MASTERY_DEFAULTS) {- return progression.isLevelMastered(stat, level, opts);-}diff --git a/server/lib/pythonSetup.js b/server/lib/pythonSetup.jsindex ff36f8fb84..711fb0fcb2 100644--- a/server/lib/pythonSetup.js+++ b/server/lib/pythonSetup.js@@ -448,8 +448,6 @@ const MFLUX_VENV_CANDIDATES = IS_WINjoin(PATHS.data, 'python', 'venv-mflux', 'bin', 'python3'),];-export const MFLUX_VENV_DEFAULT = MFLUX_VENV_CANDIDATES[0];-// Resolve the Python whose `mflux-train` PortOS should spawn for MLX LoRA// training. Preference order: (1) an explicitly-configured image-gen Python// that actually ships mflux-train — the historical `pip --user` layout, so@@ -497,10 +495,6 @@ export function resolveMusicgenPython() {return null;}-export function invalidateMusicgenPython() {- cachedMusicgenPython = null;-}-// AudioLDM2 (Pipeline Audio Phase 4c.2 — second music backend) runs in its own// venv at ~/.portos/venv-audioldm2 — torch + diffusers + transformers, kept// apart from MusicGen's MLX pile. AudioLDM2 ships in HuggingFace `diffusers` (a@@ -535,10 +529,6 @@ export function resolveAudioldm2Python() {return null;}-export function invalidateAudioldm2Python() {- cachedAudioldm2Python = null;-}-// ACE-Step (third music backend — full-song generation with vocals) runs in its// own venv at ~/.portos/venv-acestep — the `acestep` pip package + torch, kept// apart from the MusicGen MLX pile and the AudioLDM2 diffusers pile. ACE-Step@@ -574,10 +564,6 @@ export function resolveAcestepPython() {return null;}-export function invalidateAcestepPython() {- cachedAcestepPython = null;-}-// ACE-Step 1.5 has a different runtime from v1: its installed package supplies// the multi-component Transformers pipeline that loads the fixed HF snapshot// with trust_remote_code. Keep it in a sibling venv so v1 renders remain@@ -604,10 +590,6 @@ export function resolveAcestep15Python() {return null;}-export function invalidateAcestep15Python() {- cachedAcestep15Python = null;-}-const MINIMAX_MUSIC3_VENV_CANDIDATES = IS_WIN? [join(HOME, '.portos', 'venv-minimax-music3', 'Scripts', 'python.exe'),@@ -630,10 +612,6 @@ export function resolveMinimaxMusic3Python() {return null;}-export function invalidateMinimaxMusic3Python() {- cachedMinimaxMusic3Python = null;-}-// MiniMax Music 3's native MLX port runs in a separate venv from the CUDA// Diffusers runtime above. Keeping the stacks isolated prevents a torch/// diffusers upgrade from changing the MLX install (and vice versa).@@ -654,10 +632,6 @@ export function resolveMinimaxMusic3MlxPython() {return null;}-export function invalidateMinimaxMusic3MlxPython() {- cachedMinimaxMusic3MlxPython = null;-}-// Every venv PortOS provisions with `huggingface_hub` installed, in preference// order. hfDownload.js falls back through these to find an interpreter that can// run scripts/hf_download_repo.py when no image-gen runtime is configured — adiff --git a/server/lib/taskParser.js b/server/lib/taskParser.jsindex e5c120b093..062ce087e7 100644--- a/server/lib/taskParser.js+++ b/server/lib/taskParser.js@@ -561,76 +561,3 @@ export function addTask(tasks, { id, priority = 'MEDIUM', description, metadatareturn [...tasks, newTask];}--/**- * Remove a task by ID- */-export function removeTask(tasks, taskId) {- return tasks.filter(t => t.id !== taskId);-}--/**- * Check if a task is a critical auto-fix task that should be prioritized- */-function isCriticalAutoFix(task) {- const desc = (task.description || '').toLowerCase();- const isSysTask = isInternalTaskId(task.id);- const isCritical = task.priority === 'CRITICAL';- const isHighPriorityFix = task.priority === 'HIGH' && (- desc.includes('fix critical error') ||- desc.includes('[auto-fix]') ||- desc.includes('fix error:') ||- task.metadata?.autoFix === true- );-- return isSysTask && (isCritical || isHighPriorityFix);-}--/**- * Get next pending task- * Priority: Critical auto-fix tasks first, then queue order- */-export function getNextTask(tasks) {- const pending = tasks.filter(t => t.status === 'pending');- if (pending.length === 0) return null;-- // First, check for critical auto-fix tasks that need immediate attention- const criticalAutoFix = pending.find(isCriticalAutoFix);- if (criticalAutoFix) return criticalAutoFix;-- // Otherwise, return tasks in queue order (first pending task)- return pending[0];-}--/**- * Validate task format- */-export function validateTask(task) {- const errors = [];-- if (!task.id || typeof task.id !== 'string') {- errors.push('Task must have a valid id');- }-- if (!task.description || typeof task.description !== 'string') {- errors.push('Task must have a description');- }-- // Both read the vocabularies above rather than a hand-written list — this was- // the fourth copy of the same five statuses in the tree (#7239).- if (!TASK_STATUS_VALUES.includes(task.status)) {- errors.push('Invalid task status');- }-- if (!TASK_PRIORITY_VALUES.includes(task.priority)) {- // Derived, but phrased exactly as before — this message is the one a user reads.- const options = [...TASK_PRIORITY_VALUES];- const last = options.pop();- errors.push(`Invalid priority (must be ${[...options, `or ${last}`].join(', ')})`);- }-- return {- valid: errors.length === 0,- errors- };-}diff --git a/server/lib/taskParser.test.js b/server/lib/taskParser.test.jsindex 7e4fcd4712..ae714ce2ec 100644--- a/server/lib/taskParser.test.js+++ b/server/lib/taskParser.test.js@@ -8,9 +8,6 @@ import {getAwaitingApprovalTasks,updateTaskStatus,addTask,- removeTask,- getNextTask,- validateTask,TASK_STATUS_VALUES,TASK_PRIORITY_VALUES,UNKNOWN_STATUS_BLOCKED_CATEGORY@@ -607,177 +604,6 @@ describe('Task Parser', () => {});});- describe('removeTask', () => {- it('should remove task by ID', () => {- const tasks = [- { id: 'task-001' },- { id: 'task-002' },- { id: 'task-003' }- ];-- const remaining = removeTask(tasks, 'task-002');-- expect(remaining).toHaveLength(2);- expect(remaining.find(t => t.id === 'task-002')).toBeUndefined();- });-- it('should return same array if task not found', () => {- const tasks = [{ id: 'task-001' }];- const remaining = removeTask(tasks, 'task-999');-- expect(remaining).toHaveLength(1);- });- });-- describe('getNextTask', () => {- it('should return first pending task in queue order', () => {- const tasks = [- { id: 'task-001', status: 'pending', priority: 'LOW', priorityValue: 1 },- { id: 'task-002', status: 'pending', priority: 'HIGH', priorityValue: 4 },- { id: 'task-003', status: 'pending', priority: 'MEDIUM', priorityValue: 2 }- ];-- const next = getNextTask(tasks);-- // Should return first in queue, not highest priority- expect(next.id).toBe('task-001');- });-- it('should prioritize critical auto-fix tasks over queue order', () => {- const tasks = [- { id: 'task-001', status: 'pending', priority: 'LOW', priorityValue: 1 },- { id: 'sys-002', status: 'pending', priority: 'HIGH', priorityValue: 3, description: 'Fix critical error: something broke' },- { id: 'task-003', status: 'pending', priority: 'MEDIUM', priorityValue: 2 }- ];-- const next = getNextTask(tasks);-- // Should return the critical auto-fix task even though it's not first- expect(next.id).toBe('sys-002');- });-- it('should prioritize CRITICAL priority system tasks', () => {- const tasks = [- { id: 'task-001', status: 'pending', priority: 'HIGH', priorityValue: 3 },- { id: 'sys-002', status: 'pending', priority: 'CRITICAL', priorityValue: 4, description: 'System issue' },- { id: 'task-003', status: 'pending', priority: 'MEDIUM', priorityValue: 2 }- ];-- const next = getNextTask(tasks);-- expect(next.id).toBe('sys-002');- });-- it('should not prioritize regular system tasks without critical indicators', () => {- const tasks = [- { id: 'task-001', status: 'pending', priority: 'LOW', priorityValue: 1 },- { id: 'sys-002', status: 'pending', priority: 'MEDIUM', priorityValue: 2, description: 'Regular system task' },- { id: 'task-003', status: 'pending', priority: 'HIGH', priorityValue: 3 }- ];-- const next = getNextTask(tasks);-- // Should return first in queue since sys-002 is not a critical auto-fix- expect(next.id).toBe('task-001');- });-- it('should return null if no pending tasks', () => {- const tasks = [- { id: 'task-001', status: 'completed', priorityValue: 4 }- ];-- const next = getNextTask(tasks);-- expect(next).toBeNull();- });-- it('should return null for empty array', () => {- const next = getNextTask([]);- expect(next).toBeNull();- });- });-- describe('validateTask', () => {- it('should validate a correct task', () => {- const task = {- id: 'task-001',- description: 'Test task',- status: 'pending',- priority: 'HIGH'- };-- const result = validateTask(task);-- expect(result.valid).toBe(true);- expect(result.errors).toHaveLength(0);- });-- it('should reject task without id', () => {- const task = {- description: 'Test',- status: 'pending',- priority: 'HIGH'- };-- const result = validateTask(task);-- expect(result.valid).toBe(false);- expect(result.errors).toContain('Task must have a valid id');- });-- it('should reject task without description', () => {- const task = {- id: 'task-001',- status: 'pending',- priority: 'HIGH'- };-- const result = validateTask(task);-- expect(result.valid).toBe(false);- expect(result.errors).toContain('Task must have a description');- });-- it('should reject task with invalid status', () => {- const task = {- id: 'task-001',- description: 'Test',- status: 'invalid',- priority: 'HIGH'- };-- const result = validateTask(task);-- expect(result.valid).toBe(false);- expect(result.errors).toContain('Invalid task status');- });-- it('should reject task with invalid priority', () => {- const task = {- id: 'task-001',- description: 'Test',- status: 'pending',- priority: 'INVALID'- };-- const result = validateTask(task);-- expect(result.valid).toBe(false);- expect(result.errors).toContain('Invalid priority (must be CRITICAL, HIGH, MEDIUM, or LOW)');- });-- it('should collect multiple errors', () => {- const task = {- status: 'invalid',- priority: 'INVALID'- };-- const result = validateTask(task);-- expect(result.valid).toBe(false);- expect(result.errors.length).toBeGreaterThan(2);- });- });});describe('Task Parser — challenged status (#2441)', () => {@@ -821,10 +647,6 @@ describe('Task Parser — challenged status (#2441)', () => {expect(grouped.challenged.map((t) => t.id)).toEqual(['a']);});- it('validates challenged as a legal status', () => {- const result = validateTask({ id: 'task-902', description: 'x', status: 'challenged', priority: 'HIGH' });- expect(result.valid).toBe(true);- });});describe('unrepresentable status/priority never drops a task (#7239)', () => {diff --git a/server/services/activityDigestScheduler.js b/server/services/activityDigestScheduler.jsindex a227377f8a..486ae533bd 100644--- a/server/services/activityDigestScheduler.js+++ b/server/services/activityDigestScheduler.js@@ -100,11 +100,3 @@ export function startActivityDigestScheduler() {checkSchedule().catch((err) => console.error(`🗓️ Activity digest scheduler check failed: ${err.message}`));}, CHECK_INTERVAL_MS);}--export function stopActivityDigestScheduler() {- if (schedulerInterval) {- clearInterval(schedulerInterval);- schedulerInterval = null;- console.log('🗓️ Activity digest scheduler: stopped');- }-}diff --git a/server/services/agentActivity.js b/server/services/agentActivity.jsindex a54d168c20..fae370f9e5 100644--- a/server/services/agentActivity.js+++ b/server/services/agentActivity.js@@ -106,28 +106,6 @@ export async function logActivity(activity) {return entry;}-/**- * Update activity status (e.g., from 'started' to 'completed')- */-export async function updateActivityStatus(agentId, activityId, status, result = null, error = null) {- const date = new Date();- const dateStr = getDateString(date);- const data = await loadActivity(agentId, date);-- const activity = data.activities.find(a => a.id === activityId);- if (activity) {- activity.status = status;- if (result) activity.result = result;- if (error) activity.error = error;- activity.completedAt = new Date().toISOString();-- await saveActivity(agentId, dateStr, data);- activityEvents.emit('activity:updated', { agentId, activityId, status });- }-- return activity;-}-/*** Get activities for an agent*/diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 7fc64c27dd..d7a6596aa7 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -730,7 +730,7 @@ export async function terminateAgent(agentId) {// terminateAgent stays result-shaped (not a throw): its route path is// fire-and-forget (cosAgentLifecycle emits `agent:terminate` and returns// `{ success: true }` before termination runs), and its other callers are- // internal orchestration (the event handler, killAllAgents' bulk sweep) that+ // internal orchestration (including the event handler) that// inspect the result rather than a thrown ServerError. Only pauseAgent and// killAgent — whose routes surface an HTTP status — throw (issue #2534).if (!agent) {@@ -967,17 +967,6 @@ export async function getAgentProcessStats(agentId) {return null;}-/**- * Kill all active agents.- */-export async function killAllAgents() {- const directIds = Array.from(activeAgents.keys());- const runnerIds = Array.from(runnerAgents.keys());-- await Promise.all([...directIds, ...runnerIds].map(agentId => terminateAgent(agentId)));- return { killed: directIds.length + runnerIds.length };-}-/*** Check if a process is running by PID.*/diff --git a/server/services/agentPersonalities.js b/server/services/agentPersonalities.jsindex f93f59433e..b9f6f96577 100644--- a/server/services/agentPersonalities.js+++ b/server/services/agentPersonalities.js@@ -140,14 +140,3 @@ export async function deleteAgent(id) {export async function toggleAgent(id, enabled) {return updateAgent(id, { enabled });}--/**- * Get agent count by user- */-export async function getAgentCount(userId = null) {- const agents = await getAllAgents();- if (userId) {- return agents.filter(a => a.userId === userId).length;- }- return agents.length;-}diff --git a/server/services/artificialAnalysis.js b/server/services/artificialAnalysis.jsindex 203671380e..3d0c534632 100644--- a/server/services/artificialAnalysis.js+++ b/server/services/artificialAnalysis.js@@ -226,10 +226,6 @@ export async function fetchAllArtificialAnalysisModels(apiKey) {// Presence only — never the value. The comparison page reads this to decide// whether the Sync button prompts for a key or just syncs with the stored one.-export async function hasArtificialAnalysisKey() {- return Boolean(await resolveArtificialAnalysisKey());-}-async function resolveArtificialAnalysisKey(apiKey) {const settings = await getSettings();return apiKey?.trim() || settings.secrets?.artificialAnalysis?.apiKey || process.env.ARTIFICIAL_ANALYSIS_API_KEY || '';diff --git a/server/services/brainScheduler.js b/server/services/brainScheduler.jsindex 98b1fa095d..cc95317833 100644--- a/server/services/brainScheduler.js+++ b/server/services/brainScheduler.js@@ -179,51 +179,3 @@ export function startBrainScheduler() {console.log('🧠 Scheduler: Brain scheduler started');}--/**- * Stop the Brain scheduler- */-export function stopBrainScheduler() {- if (schedulerInterval) {- clearInterval(schedulerInterval);- schedulerInterval = null;- console.log('🧠 Scheduler: Brain scheduler stopped');- }-}--/**- * Get scheduler status- */-export async function getSchedulerStatus() {- const settings = await storage.loadMeta();-- return {- running: schedulerInterval !== null,- checkIntervalMs: CHECK_INTERVAL_MS,- dailyDigest: {- scheduledTime: settings.dailyDigestTime,- lastRun: settings.lastDailyDigest- },- weeklyReview: {- scheduledDay: settings.weeklyReviewDay,- scheduledTime: settings.weeklyReviewTime,- lastRun: settings.lastWeeklyReview- }- };-}--/**- * Manually trigger the next scheduled digest (for testing)- */-export async function triggerNextDigest() {- console.log('🧠 Scheduler: Manually triggering daily digest...');- return runDailyDigest();-}--/**- * Manually trigger the next scheduled review (for testing)- */-export async function triggerNextReview() {- console.log('🧠 Scheduler: Manually triggering weekly review...');- return runWeeklyReview();-}diff --git a/server/services/catalogDB/tags.js b/server/services/catalogDB/tags.jsindex c1cde8d4e8..cc4cf6f1bc 100644--- a/server/services/catalogDB/tags.js+++ b/server/services/catalogDB/tags.js@@ -92,30 +92,3 @@ export async function listTags({ q, limit = 20 } = {}) {);return { items: result.rows.map(rowToTag) };}--/**- * Patch a tag's mutable fields (description / color / parent_id). `label` is- * intentionally NOT patchable here — relabeling would orphan the freeform- * array values that reference the old casing. Self-parent is rejected.- */-export async function updateTag(id, patch = {}) {- const fields = [];- const params = [];- let idx = 1;- const fieldMap = { description: 'description', color: 'color', parentId: 'parent_id' };- for (const [jsField, dbField] of Object.entries(fieldMap)) {- if (patch[jsField] === undefined) continue;- if (jsField === 'parentId' && patch.parentId === id) {- throw new Error('a tag cannot be its own parent');- }- fields.push(`${dbField} = $${idx++}`);- params.push(patch[jsField] === '' ? null : patch[jsField]);- }- if (fields.length === 0) return getTag(id);- params.push(id);- const result = await query(- `UPDATE catalog_tags SET ${fields.join(', ')} WHERE id = $${idx} RETURNING *`,- params,- );- return rowToTag(result.rows[0]);-}diff --git a/server/services/contactsSync.js b/server/services/contactsSync.jsindex c5a4c74c25..e822d79b07 100644--- a/server/services/contactsSync.js+++ b/server/services/contactsSync.js@@ -524,11 +524,6 @@ export async function searchContacts({ q, limit } = {}) {return out;}-export async function getContactById(id) {- const { contacts } = await readContactCache();- return contacts.find((c) => c.id === id || c.uniqueId === id) || null;-}-/*** Load contacts + build index. Cached in-process for the duration of a request* batch via the returned object (caller holds it).diff --git a/server/services/cosRunnerClient.js b/server/services/cosRunnerClient.jsindex 6af742b869..6690395e64 100644--- a/server/services/cosRunnerClient.js+++ b/server/services/cosRunnerClient.js@@ -515,28 +515,3 @@ export async function getAgentStatsFromRunner(agentId) {}return readRunnerJson(response);}--/**- * Terminate all agents via the runner- */-export async function terminateAllAgentsViaRunner() {- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/terminate-all`, {- method: 'POST'- }, 30000);- if (!response.ok) {- throw new Error('Failed to terminate agents');- }- return readRunnerJson(response);-}--/**- * Get agent output from runner- */-export async function getAgentOutputFromRunner(agentId) {- const response = await fetchWithTimeout(`${COS_RUNNER_URL}/agents/${agentId}/output`, {}, 10000);- if (!response.ok) {- const error = await readRunnerJson(response);- throw new Error(error.error || 'Failed to get agent output');- }- return readRunnerJson(response);-}diff --git a/server/services/cosRunnerClient.test.js b/server/services/cosRunnerClient.test.jsindex 61e3bd4a48..3f0ec6b40d 100644--- a/server/services/cosRunnerClient.test.js+++ b/server/services/cosRunnerClient.test.js@@ -35,8 +35,6 @@ import {terminateAgentViaRunner,killAgentViaRunner,getAgentStatsFromRunner,- terminateAllAgentsViaRunner,- getAgentOutputFromRunner,spawnTuiSessionViaRunner,connectTuiSessionViaRunner,classifyRunnerSpawnFailure,@@ -574,46 +572,4 @@ describe('cosRunnerClient', () => {});});- // ===========================================================================- // terminateAllAgentsViaRunner- // ===========================================================================- describe('terminateAllAgentsViaRunner', () => {- it('should POST terminate-all and return result', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(true, { terminated: 3 }));- const result = await terminateAllAgentsViaRunner();- expect(result).toEqual({ terminated: 3 });- expect(fetchWithTimeout).toHaveBeenCalledWith(- expect.stringContaining('/terminate-all'),- { method: 'POST' },- 30000- );- });-- it('should throw on failure', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(false, {}));- await expect(terminateAllAgentsViaRunner()).rejects.toThrow('Failed to terminate agents');- });- });-- // ===========================================================================- // getAgentOutputFromRunner- // ===========================================================================- describe('getAgentOutputFromRunner', () => {- it('should return agent output', async () => {- const output = { output: 'Hello world', lines: 10 };- fetchWithTimeout.mockResolvedValue(mockResponse(true, output));- const result = await getAgentOutputFromRunner('agent-1');- expect(result).toEqual(output);- expect(fetchWithTimeout).toHaveBeenCalledWith(- expect.stringContaining('/agents/agent-1/output'),- {},- 10000- );- });-- it('should throw on failure', async () => {- fetchWithTimeout.mockResolvedValue(mockResponse(false, { error: 'Not found' }));- await expect(getAgentOutputFromRunner('bad-id')).rejects.toThrow('Not found');- });- });});diff --git a/server/services/identityResolve.js b/server/services/identityResolve.jsindex 36c60f910d..737a521eb5 100644--- a/server/services/identityResolve.js+++ b/server/services/identityResolve.js@@ -130,19 +130,6 @@ export function createHandleResolver(ctx) {};}-/**- * Resolve many handles with one shared context (avoids N Tribe loads).- */-export function resolveHandles(handles = [], ctx) {- const out = new Map();- for (const h of handles) {- if (h == null || h === '') continue;- if (out.has(h)) continue;- out.set(h, resolveHandle(h, ctx));- }- return out;-}-/*** Enrich a conversation-like row that has `handle` / `title` / `participants`.*/diff --git a/server/services/meatspaceAlcohol.js b/server/services/meatspaceAlcohol.jsindex 2b36060099..37cebaf986 100644--- a/server/services/meatspaceAlcohol.js+++ b/server/services/meatspaceAlcohol.js@@ -40,7 +40,6 @@ let averageCache = null;let averageCacheAt = 0;const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes-// === Pure Functions ===// 1 standard drink = 0.6 oz pure alcohol = ~14g pure alcohol@@ -390,14 +389,3 @@ export async function removeCustomDrink(index) {console.log(`🗑️ Removed custom drink button: ${removed.name}`);return removed;}--export async function reorderCustomDrinks(fromIndex, toIndex) {- if (!Number.isInteger(fromIndex) || !Number.isInteger(toIndex)) return null;- const data = await loadCustomDrinks();- if (fromIndex < 0 || fromIndex >= data.drinks.length) return null;- if (toIndex < 0 || toIndex >= data.drinks.length) return null;- const [moved] = data.drinks.splice(fromIndex, 1);- data.drinks.splice(toIndex, 0, moved);- await saveCustomDrinks(data);- return data.drinks;-}diff --git a/server/services/meatspaceCalendar.js b/server/services/meatspaceCalendar.jsindex f5a1564226..3cac2fd9c4 100644--- a/server/services/meatspaceCalendar.js+++ b/server/services/meatspaceCalendar.js@@ -269,64 +269,6 @@ export async function removeLifeEvent(id) {return data.events;}-/**- * Compute which weeks in the life grid correspond to events.- * Returns a Map<"age-week", { type, name }> for grid coloring.- */-export function computeAllEventWeeks(birthDate, deathDate, events) {- const result = new Map();- const birth = new Date(birthDate);- const death = new Date(deathDate);- const now = new Date();- const totalYears = Math.ceil((death - birth) / (365.25 * 86400000));-- for (const event of events) {- if (!event.enabled) continue;-- if (event.recurrence === 'yearly' && event.month != null && event.day != null) {- // Yearly recurring: mark each future year- for (let y = 0; y < totalYears; y++) {- const yearStart = new Date(birth);- yearStart.setFullYear(birth.getFullYear() + y);- const eventDate = new Date(yearStart.getFullYear(), event.month, event.day);- if (eventDate <= now || eventDate > death) continue;- const weekOfYear = Math.floor((eventDate - yearStart) / (7 * 86400000));- if (weekOfYear >= 0 && weekOfYear < 52) {- const key = `${y}-${weekOfYear}`;- // Don't overwrite existing events (first-registered wins)- if (!result.has(key)) {- result.set(key, { type: event.type, name: event.name });- }- }- }- } else if (event.recurrence === 'once' && event.date) {- // One-time event: mark single date (or range if endDate)- const start = new Date(event.date);- const end = event.endDate ? new Date(event.endDate) : start;- const cursor = new Date(start);- while (cursor <= end && cursor <= death) {- if (cursor > now) {- // Find age and week- const ageMs = cursor - birth;- const age = Math.floor(ageMs / (365.25 * 86400000));- const yearStart = new Date(birth);- yearStart.setFullYear(birth.getFullYear() + age);- const weekOfYear = Math.floor((cursor - yearStart) / (7 * 86400000));- if (weekOfYear >= 0 && weekOfYear < 52) {- const key = `${age}-${weekOfYear}`;- if (!result.has(key)) {- result.set(key, { type: event.type, name: event.name });- }- }- }- cursor.setDate(cursor.getDate() + 7); // Jump by week for ranges- }- }- }-- return result;-}-// === Exported Service Functions ===export async function getCalendarData() {diff --git a/server/services/meatspaceHealth.js b/server/services/meatspaceHealth.jsindex 5b6a3664a3..daff19d013 100644--- a/server/services/meatspaceHealth.js+++ b/server/services/meatspaceHealth.js@@ -61,10 +61,6 @@ export async function addBloodTest(test) {return test;}-export async function saveBloodTests(data) {- await writeLocal(BLOOD_TESTS_FILE, data);-}-// === Body Composition ===/**diff --git a/server/services/meatspaceNicotine.js b/server/services/meatspaceNicotine.jsindex 49b6cd4df9..0ad08378c9 100644--- a/server/services/meatspaceNicotine.js+++ b/server/services/meatspaceNicotine.js@@ -333,14 +333,3 @@ export async function removeCustomProduct(index) {console.log(`🗑️ Removed custom nicotine product: ${removed.name}`);return removed;}--export async function reorderCustomProducts(fromIndex, toIndex) {- if (!Number.isInteger(fromIndex) || !Number.isInteger(toIndex)) return null;- const data = await loadCustomProducts();- if (fromIndex < 0 || fromIndex >= data.products.length) return null;- if (toIndex < 0 || toIndex >= data.products.length) return null;- const [moved] = data.products.splice(fromIndex, 1);- data.products.splice(toIndex, 0, moved);- await saveCustomProducts(data);- return data.products;-}diff --git a/server/services/meatspacePostMemory.js b/server/services/meatspacePostMemory.jsindex 8d2da1a329..fb6ff5ccb9 100644--- a/server/services/meatspacePostMemory.js+++ b/server/services/meatspacePostMemory.js@@ -941,12 +941,6 @@ export async function getMastery(id) {return item.mastery;}-export async function getTrainingLog(memoryItemId, limit = 50) {- let entries = await listStoredTrainingEntries();- if (memoryItemId) entries = entries.filter(e => e.memoryItemId === memoryItemId);- return entries.slice(-limit);-}-// =============================================================================// DRILL GENERATION (for POST sessions)// =============================================================================diff --git a/server/services/memoryEmbeddings.js b/server/services/memoryEmbeddings.jsindex 0e0ef4dd13..3bec9b86e9 100644--- a/server/services/memoryEmbeddings.js+++ b/server/services/memoryEmbeddings.js@@ -164,13 +164,6 @@ function getConfig() {return embeddingConfig || DEFAULT_MEMORY_CONFIG;}-/**- * Set embedding configuration (called by CoS service on startup)- */-export function setEmbeddingConfig(config) {- embeddingConfig = { ...DEFAULT_MEMORY_CONFIG, ...config };-}-/*** Check if the embedding backend is reachable and an embedding model is usable.* Works for any OpenAI-compatible backend (LM Studio, Ollama, …) — all servediff --git a/server/services/memoryExtractor.js b/server/services/memoryExtractor.jsindex b07fc3f5fc..f8d7b5c9c2 100644--- a/server/services/memoryExtractor.js+++ b/server/services/memoryExtractor.js@@ -400,10 +400,3 @@ export async function extractAndStoreMemories(agentId, taskId, output, task = nupendingMemories};}--/**- * Manual extraction endpoint (for API)- */-export async function extractFromOutput(agentId, taskId, output) {- return extractAndStoreMemories(agentId, taskId, output);-}diff --git a/server/services/memoryRetriever.js b/server/services/memoryRetriever.jsindex e286d17d4d..68071f4883 100644--- a/server/services/memoryRetriever.js+++ b/server/services/memoryRetriever.js@@ -229,28 +229,3 @@ export async function getMemorySection(task, options = {}) {return formatForPrompt(memories);}--/**- * Get memory stats for a task (useful for debugging)- */-export async function getRetrievalStats(task) {- const memories = await getRelevantMemories(task, { maxTokens: 10000 });-- return {- total: memories.length,- byType: memories.reduce((acc, m) => {- acc[m.type] = (acc[m.type] || 0) + 1;- return acc;- }, {}),- bySource: memories.reduce((acc, m) => {- acc[m.source] = (acc[m.source] || 0) + 1;- return acc;- }, {}),- totalTokens: memories.reduce((acc, m) => acc + estimateTokens(m.content), 0),- topMemories: memories.slice(0, 5).map(m => ({- type: m.type,- summary: m.summary,- relevance: m.relevance.toFixed(2)- }))- };-}diff --git a/server/services/messageApiSync.js b/server/services/messageApiSync.jsindex cf87cc629b..34320fa3d9 100644--- a/server/services/messageApiSync.js+++ b/server/services/messageApiSync.js@@ -131,15 +131,3 @@ export async function syncOutlookApi(account, cache, io, options = {}) {console.log(`📧 API sync complete: ${messages.length} messages fetched in ${page} page(s)`);return { messages, status: 'success', syncMethod: 'api' };}--/**- * Teams API sync is not yet available.- * Teams v2 is a fully offline-first PWA using service workers and WebSocket (SignalR)- * for data. The Graph API token from the browser lacks Chat.Read scope, and the- * chatsvcagg token doesn't map to documented REST endpoints.- * Teams continues to use Playwright scraping for now.- * @returns null (signals fallback to Playwright)- */-export async function syncTeamsApi() {- return null;-}diff --git a/server/services/messageTokenExtractor.js b/server/services/messageTokenExtractor.jsindex 875c6beeb0..bfdd1fd126 100644--- a/server/services/messageTokenExtractor.js+++ b/server/services/messageTokenExtractor.js@@ -209,9 +209,6 @@ export async function getToken(provider) {}// Convenience aliases-export const getOutlookToken = () => getToken('outlook');-export const getTeamsToken = () => getToken('teams');-/*** Get token info without the raw token value (for status/debug display).*/diff --git a/server/services/messageTriageRules.js b/server/services/messageTriageRules.jsindex db18b2a484..8a140e213f 100644--- a/server/services/messageTriageRules.js+++ b/server/services/messageTriageRules.js@@ -54,19 +54,6 @@ export async function recordCorrection({ from, subject, triaged, corrected }) {console.log(`📧 Triage rule recorded: "${senderPattern}" ${triaged} -> ${corrected}`);}-/**- * Build a prompt section describing user triage preferences.- */-export async function buildRulesPromptSection() {- const rules = await getTriageRules();- if (!rules.length) return '';-- const lines = rules.map(r =>- `- Emails from "${r.senderPattern}" should be "${r.correctedAction}" (not "${r.originalAction}"). Example subject: "${r.exampleSubject}"`- );- return `\n\nUser triage preferences (ALWAYS follow these rules — they override your default judgment):\n${lines.join('\n')}\n`;-}-/*** Delete a specific rule by index.*/diff --git a/server/services/moltworldQueue.js b/server/services/moltworldQueue.jsindex ebfd7a2b21..daa7fad426 100644--- a/server/services/moltworldQueue.js+++ b/server/services/moltworldQueue.js@@ -45,13 +45,6 @@ export function getQueue(agentId) {return queue.filter(item => item.status === 'pending' || item.status === 'executing');}-/**- * Get all items for an agent (including completed/failed, for display)- */-export function getFullQueue(agentId) {- return queues.get(agentId) || [];-}-/*** Add an action to the queue*/@@ -79,25 +72,6 @@ export function addAction(agentId, actionType, params = {}, scheduledFor = null)return item;}-/**- * Pop the next pending item (FIFO), mark it as executing- */-export function popNext(agentId) {- const queue = queues.get(agentId) || [];- const now = new Date().toISOString();- const idx = queue.findIndex(item =>- item.status === 'pending' &&- (!item.scheduledFor || item.scheduledFor <= now)- );- if (idx === -1) return null;-- queue[idx].status = 'executing';- const item = queue[idx];- console.log(`📋 Queue: executing ${item.actionType} id=${item.id}`);- queueEvents.emit('updated', item);- return item;-}-/*** Mark an item as completed*/diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.jsindex 3a8678fbc2..e1da831525 100644--- a/server/services/mortalLoomStore.js+++ b/server/services/mortalLoomStore.js@@ -82,8 +82,6 @@ const ARRAY_KEYS = ['nicotineEntries', 'nicotinePresets', 'saunaPresets', 'saunaSessions'];-export function defaultStorePath() { return DEFAULT_ICLOUD_PATH; }-// === Eviction pinning ===// macOS Optimize-Mac-Storage can evict iCloud files. When that happens thediff --git a/server/services/openrouterBenchmarks.js b/server/services/openrouterBenchmarks.jsindex 9636c8b066..7d4cdb99e8 100644--- a/server/services/openrouterBenchmarks.js+++ b/server/services/openrouterBenchmarks.js@@ -383,12 +383,3 @@ export function transformOpenRouterEndpointsToObservations(modelEndpoints, { ret}return observations;}--export async function syncOpenRouterEndpointCatalog() {- const models = await fetchOpenRouterModels();- const endpoints = await mapWithConcurrency(models, OPENROUTER_ENDPOINT_CONCURRENCY, fetchOpenRouterModelEndpoints);- const observations = transformOpenRouterEndpointsToObservations(endpoints);- const validated = modelComparisonImportSchema.parse({ schemaVersion: 1, observations });- const updated = await importModelComparison(validated);- return { success: true, fetched: models.length, observations: observations.length, total: updated.observations.length, catalog: updated };-}diff --git a/server/services/peerSocketRelay.js b/server/services/peerSocketRelay.jsindex 64ca945da0..ea04eb9e1c 100644--- a/server/services/peerSocketRelay.js+++ b/server/services/peerSocketRelay.js@@ -135,21 +135,3 @@ export function disconnectFromPeer(peerId) {instanceEvents.emit('peer:agents:updated', { peerId, agents: [] });console.log(`🔗 Peer relay cleaned up: ${conn.peer.name}`);}--/**- * Get current agent snapshot for a peer- */-export function getPeerAgents(peerId) {- const conn = peerConnections.get(peerId);- if (!conn) return [];- return Array.from(conn.agents.values());-}--/**- * Disconnect all peer relays (for shutdown)- */-export function disconnectAll() {- for (const [peerId] of peerConnections) {- disconnectFromPeer(peerId);- }-}diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.jsindex ef38034b32..c9455b3827 100644--- a/server/services/pipeline/arcPlanner/context.js+++ b/server/services/pipeline/arcPlanner/context.js@@ -265,15 +265,6 @@ export const stageVersionsOf = (stage) =>// The dominant manuscript type across the series' sections — the editor's// display "mode". Per-section stageId stays authoritative for writes.-export function primaryStageIdOf(sections) {- const counts = new Map();- for (const s of sections) counts.set(s.stageId, (counts.get(s.stageId) || 0) + 1);- let best = null;- let bestN = 0;- for (const [sid, n] of counts) if (n > bestN) { best = sid; bestN = n; }- return best;-}-/*** Collect the FULL series manuscript in every format at once, for the* format-switching manuscript editor. Unlike `collectManuscriptSections`diff --git a/server/services/pipeline/covers.js b/server/services/pipeline/covers.jsindex b1356629d3..e0016e8d98 100644--- a/server/services/pipeline/covers.js+++ b/server/services/pipeline/covers.js@@ -378,15 +378,6 @@ export async function enqueueVolumeCover(seriesId, seasonId, options = {}) {return { ...rest, coverScript: script };}-/**- * Enqueue a volume (season) BACK cover render. Returns- * { jobId, mode, prompt, backCoverScript, variant, fromProof }.- */-export async function enqueueVolumeBackCover(seriesId, seasonId, options = {}) {- const { script, ...rest } = await enqueueVolumeCoverLike(seriesId, seasonId, 'backCover', options);- return { ...rest, backCoverScript: script };-}-/*** Enqueue + persist a volume (season) cover render (front or back) in ONE* service call — the shared entry point behind both the route handler and thediff --git a/server/services/pipeline/editorialScore.js b/server/services/pipeline/editorialScore.jsindex 97291d31b1..76c0c6bda2 100644--- a/server/services/pipeline/editorialScore.js+++ b/server/services/pipeline/editorialScore.js@@ -328,15 +328,6 @@ async function readLedger(seriesId) {return raw == null ? emptyLedger(seriesId) : sanitizeLedger(raw, seriesId);}-/**- * Read the persisted revision-trend ledger for a series (never null — an empty- * ledger when none has been recorded yet).- */-export async function getTrendLedger(seriesId) {- assertValidSeriesId(seriesId);- return readLedger(seriesId);-}-/*** Record a revision-trend snapshot for a series from its CURRENT review state.* Called after each editorial-checks / completeness run (the run is thediff --git a/server/services/platformAccounts.js b/server/services/platformAccounts.jsindex f2eb14600d..e4778b7e68 100644--- a/server/services/platformAccounts.js+++ b/server/services/platformAccounts.js@@ -148,28 +148,6 @@ export async function recordActivity(id) {return getAccountById(id);}-/**- * Update account credentials- */-export async function updateCredentials(id, credentials) {- let found = false;- await store.mutate((data) => {- if (!data.accounts[id]) return data;- found = true;- data.accounts[id].credentials = {- ...data.accounts[id].credentials,- ...credentials- };- return data;- });-- if (!found) return null;- notifyChanged('update', id);-- console.log(`🔑 Updated credentials for account ${id}`);- return getAccountById(id);-}-/*** Delete a platform account*/@@ -196,11 +174,3 @@ export async function getAccountsByPlatform(platform) {const accounts = await getAllAccounts();return accounts.filter(account => account.platform === platform);}--/**- * Get active accounts for an agent- */-export async function getActiveAccountsForAgent(agentId) {- const accounts = await getAccountsByAgent(agentId);- return accounts.filter(account => account.status === 'active');-}diff --git a/server/services/repoCloner.js b/server/services/repoCloner.jsindex 358ef2fd7d..b929588871 100644--- a/server/services/repoCloner.js+++ b/server/services/repoCloner.js@@ -265,41 +265,3 @@ export async function pullRepo(localPath) {}, 120000);});}--/**- * Get repo info (last commit, etc.)- */-export async function getRepoInfo(localPath) {- if (!existsSync(join(localPath, '.git'))) {- return null;- }-- return new Promise((resolve) => {- const child = spawn('git', ['log', '-1', '--format=%H|%s|%ci'], {- cwd: localPath,- env: process.env,- shell: false- });-- let stdout = '';-- child.stdout.on('data', (data) => {- stdout += data.toString();- });-- child.on('close', (code) => {- if (code === 0 && stdout.trim()) {- const [hash, message, date] = stdout.trim().split('|');- resolve({- lastCommitHash: hash,- lastCommitMessage: message,- lastCommitDate: date- });- } else {- resolve(null);- }- });-- child.on('error', () => resolve(null));- });-}diff --git a/server/services/threejsModels/db.js b/server/services/threejsModels/db.jsindex 6d1d93d978..22d5b33ed9 100644--- a/server/services/threejsModels/db.js+++ b/server/services/threejsModels/db.js@@ -139,10 +139,6 @@ export async function mutateModel(id, mutate, { includeDeleted = false } = {}) {});}-export function updateModel(id, patch) {- return mutateModel(id, (current) => ({ ...current, ...patch }));-}-export async function deleteModel(id) {const now = new Date().toISOString();await mutateModel(id, (current) => ({diff --git a/server/services/twinEnrichmentScheduler.js b/server/services/twinEnrichmentScheduler.jsindex 6ff9bbb105..f59595c878 100644--- a/server/services/twinEnrichmentScheduler.js+++ b/server/services/twinEnrichmentScheduler.js@@ -55,11 +55,3 @@ export function startTwinEnrichmentScheduler() {checkSchedule().catch((err) => console.error(`🧭 Twin enrichment rollup check failed: ${err.message}`));}, CHECK_INTERVAL_MS);}--export function stopTwinEnrichmentScheduler() {- if (schedulerInterval) {- clearInterval(schedulerInterval);- schedulerInterval = null;- console.log('🧭 Twin enrichment scheduler: stopped');- }-}diff --git a/server/services/updateChecker.js b/server/services/updateChecker.jsindex b2cb42e87b..7b9382caeb 100644--- a/server/services/updateChecker.js+++ b/server/services/updateChecker.js@@ -562,17 +562,3 @@ export function startUpdateScheduler() {console.log(`🔄 Update scheduler started (every ${CHECK_INTERVAL_MS / 60000}min)`);}--/**- * Stop the periodic update checker.- */-export function stopUpdateScheduler() {- if (startupTimeout) {- clearTimeout(startupTimeout);- startupTimeout = null;- }- if (schedulerInterval) {- clearInterval(schedulerInterval);- schedulerInterval = null;- }-}diff --git a/server/services/usage.js b/server/services/usage.jsindex 0614587550..9d72e34ce8 100644--- a/server/services/usage.js+++ b/server/services/usage.js@@ -709,15 +709,6 @@ export async function recordRunUsage(record) {await saveUsage();}-/**- * Record tool calls- */-export async function recordToolCalls(count) {- if (!usageData) await loadUsage();- usageData.totalToolCalls += count;- await saveUsage();-}-/*** Record token usage*/