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: promote local memory orchestration to services (#4901)

[._.]/ Adam Eivye2a1ccd2d090
diff --git a/docs/features/sglang-qwen38.md b/docs/features/sglang-qwen38.md
index 5e3dca8ffc..4405d25e69 100644
--- a/docs/features/sglang-qwen38.md
+++ b/docs/features/sglang-qwen38.md
@@ -267,7 +267,7 @@ command, instead of spending minutes loading a model into VRAM they cannot have
and dying with an OOM that names nothing. PortOS **detects and refuses; it never
auto-stops** — nothing would restart the container, an attached CoS session dies
with it, and a cold start is minutes. See `detectGpuBlockers` in
-`server/lib/localMemory.js`.
+`server/services/localMemory.js`.
The probe is skipped entirely when no enabled `sglangBacked` provider exists, and
again when the host reports no NVIDIA GPU at all.
diff --git a/server/lib/README.md b/server/lib/README.md
index 7fc3152412..947fc07f35 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -204,7 +204,6 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `imageRgba.js` | Sharp-backed RGBA boundary: `decodeRgbaFrame` decodes an image to `{ data, width, height }`, and `encodePng` turns a raw frame into PNG bytes for the caller's destination/hash policy. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
-| `localMemory.js` | Shared preflight for GPU-heavy local work: `prepareLocalMemory` unloads resident local models (only loopback Ollama / LM Studio backends are evicted) and reports available memory, plus a `blockers` array from `detectGpuBlockers` — a serving vLLM Qwen container holds ~23 GB of a 24 GB card, is invisible to the unload path, and would otherwise fail the job with an OOM inside model load naming neither vLLM nor a remedy. Detect and refuse, never auto-stop (#4766): `gpuBlockersMessage` renders the refusal that names `docker compose --profile single stop` and its project directory. Skips the probe entirely with no enabled `vllmBacked` provider or on a non-CUDA host, and a failed/timed-out probe never blocks. |
| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that into default refinement feedback. The same pass emits a `reflective-material-without-environment` note when a spec authors reflective channels (metalness above 0.6, or any transmission/clearcoat/iridescence) while `environment.preset` is `none` — those channels read off an environment, so in that scene their values cannot be judged at all. Attachments are declared in two forms — the original anchor-less `attachmentPartIds` and the anchored `attachments: [{ partId, anchorPartId | anchorSocket, maxOffset }]` — and `resolveThreejsAttachments(articulation)` merges them into one canonical list (an anchored entry wins over a bare id) so every gate reads the same set; `isThreejsAttachmentAnchored(attachment)` is the shared anchored/unanchored predicate and `DEFAULT_ATTACHMENT_MAX_OFFSET` the default tolerance. The spec-level refinement rejects an anchor that does not resolve, one that is the attachment itself, an anchor chain that cycles, and the model root (the sole top-level part) — which carries no relationship to any body part. The spec carries an optional `environment` block (see `threejsModelEnvironment.js`), and `buildThreejsFactorySource()` stamps its render profile onto `root.userData.sculptRuntime.render` and exports it as `renderProfile`, so a consumer wiring their own `WebGLRenderer` reproduces the model instead of a differently tone-mapped approximation. |
| `threejsModelAnimation.js` | `summarizeThreejsAnimation(spec)` — clip inventory *and* playback gate over an already-validated Three.js spec: `{ animated, clipCount, cueCount, sequenceCount, movingPartCount, longestClipSeconds, findings, warningCount, clips }`. The schema proves a declared `animation` block is well *formed* (sequences on real parts, inside their clip, never two on one channel at once, never a cue without motion); this reports what the model *declared* — one entry per clip with its role, duration, sequence and distinct-cue counts — plus the ways a well-formed clip still plays badly: a clip authored against a pose the assembly does not build (`clip-start-pose-mismatch`), a handover between sequences that do not meet (`clip-sequence-jump`), a `loop: true` clip that does not return to where it began, a one-shot `idle`, an unfired cue, a long dead tail, and an articulation graph with no clip at all. Advisory warnings only — a static assembly is a complete answer. `buildThreejsAnimationFeedback(animation)` turns those findings into default refinement feedback. A spec with no `animation` key summarizes as not animated — never as evaluated-and-empty. |
| `threejsModelCoverage.js` | `evaluateThreejsPartCoverage(spec, { family })` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). With a subject family it also warns on a required component the spec never mentions at all — the one check that can fault a spec for what it failed to *promise*. `buildThreejsCoverageFeedback(coverage)` turns the error findings (plus any family gap) into default refinement feedback. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 61beb2c971..80fccc7bdb 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -204,7 +204,6 @@ export * from './imageFrameStats.js';
export * from './imageRgba.js';
export * from './imageWatermark.js';
export * from './localImageFilename.js';
-export * from './localMemory.js';
export * from './pgFileFacade.js';
export * from './multipart.js';
export * from './safetensors.js';
diff --git a/server/services/imageGen/local.js b/server/services/imageGen/local.js
index e9be74bf64..5b0cc8d809 100644
--- a/server/services/imageGen/local.js
+++ b/server/services/imageGen/local.js
@@ -31,7 +31,7 @@ import { extractGatedRepo, isGatedRepoError } from '../../lib/hfErrors.js';
import { killWithEscalation } from '../../lib/killWithEscalation.js';
import { createLineReader } from '../../lib/streamLines.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
-import { prepareLocalMemory, gpuBlockersMessage } from '../../lib/localMemory.js';
+import { prepareLocalMemory, gpuBlockersMessage } from '../localMemory.js';
import { safeChildProcessOptions } from '../../lib/processEnv.js';
import { IMAGE_GEN_MODE, LOCAL_IMAGEGEN_DEFAULT_MODEL } from './modes.js';
import { computePixelDelta } from './regen.js';
diff --git a/server/services/imageTo3d/models.js b/server/services/imageTo3d/models.js
index 4bacb5ac1e..3a87705e03 100644
--- a/server/services/imageTo3d/models.js
+++ b/server/services/imageTo3d/models.js
@@ -21,7 +21,7 @@ import { rm, access } from 'node:fs/promises';
import { ServerError } from '../../lib/errorHandler.js';
import { PATHS, resolveGalleryImage, ensureDir } from '../../lib/fileUtils.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
-import { prepareLocalMemory, gpuBlockersMessage } from '../../lib/localMemory.js';
+import { prepareLocalMemory, gpuBlockersMessage } from '../localMemory.js';
import { slugifyForFilename } from '../../lib/civitai.js';
import {
detectHostCapabilities, resolveTarget, renderOptionSupportFor, DEFAULT_IMAGE_TO_3D_TARGET,
diff --git a/server/services/imageTo3d/models.test.js b/server/services/imageTo3d/models.test.js
index d7323964cd..bd8a53c54f 100644
--- a/server/services/imageTo3d/models.test.js
+++ b/server/services/imageTo3d/models.test.js
@@ -51,7 +51,7 @@ const { claimRelease } = vi.hoisted(() => ({ claimRelease: vi.fn(async () => {})
vi.mock('../../lib/heavyJobClaim.js', () => ({
claimHeavyLocalJob: vi.fn(async () => ({ ok: true, holder: {}, release: claimRelease })),
}));
-vi.mock('../../lib/localMemory.js', async (importOriginal) => ({
+vi.mock('../localMemory.js', async (importOriginal) => ({
...(await importOriginal()),
prepareLocalMemory: vi.fn(async () => ({ unloaded: [], availableGb: 64, totalGb: 64, budgetGb: 64, blockers: [] })),
}));
diff --git a/server/lib/localMemory.js b/server/services/localMemory.js
similarity index 94%
rename from server/lib/localMemory.js
rename to server/services/localMemory.js
index 2a48cb7aae..147c92e944 100644
--- a/server/lib/localMemory.js
+++ b/server/services/localMemory.js
@@ -1,16 +1,16 @@
/** Shared best-effort local-model memory reclamation and headroom reporting. */
-import { execFile } from './childProcess.js';
+import { execFile } from '../lib/childProcess.js';
import { platform, freemem, totalmem } from 'os';
import { promisify } from 'util';
-import { getLoadedModels as ollamaLoadedModels, unloadModel as ollamaUnload, getBaseUrl as ollamaBaseUrl } from '../services/ollamaManager.js';
-import { getLoadedModels as lmStudioLoadedModels, unloadModel as lmStudioUnload, getBaseUrl as lmStudioBaseUrl } from '../services/lmStudioManager.js';
-import { getAllProviders } from '../services/providers.js';
-import { probeOpenAiModels } from './openAiModelsProbe.js';
-import { getCudaCapability } from './cudaCapability.js';
-import { localRuntimeForProvider, LOCAL_RUNTIMES } from './localProviderRuntime.js';
-import { resolveVllmProjectDir } from './vllmQwenProject.js';
-import { resolveSglangProjectDir } from './sglangQwenProject.js';
+import { getLoadedModels as ollamaLoadedModels, unloadModel as ollamaUnload, getBaseUrl as ollamaBaseUrl } from './ollamaManager.js';
+import { getLoadedModels as lmStudioLoadedModels, unloadModel as lmStudioUnload, getBaseUrl as lmStudioBaseUrl } from './lmStudioManager.js';
+import { getAllProviders } from './providers.js';
+import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
+import { getCudaCapability } from '../lib/cudaCapability.js';
+import { localRuntimeForProvider, LOCAL_RUNTIMES } from '../lib/localProviderRuntime.js';
+import { resolveVllmProjectDir } from '../lib/vllmQwenProject.js';
+import { resolveSglangProjectDir } from '../lib/sglangQwenProject.js';
const execFileAsync = promisify(execFile);
const GB = 2 ** 30;
diff --git a/server/lib/localMemory.test.js b/server/services/localMemory.test.js
similarity index 96%
rename from server/lib/localMemory.test.js
rename to server/services/localMemory.test.js
index 2d3aefc364..57cc7395e5 100644
--- a/server/lib/localMemory.test.js
+++ b/server/services/localMemory.test.js
@@ -10,17 +10,17 @@ const h = vi.hoisted(() => ({
lmUnload: vi.fn(),
}));
-vi.mock('../services/ollamaManager.js', () => ({
+vi.mock('./ollamaManager.js', () => ({
getLoadedModels: vi.fn(async () => [{ name: 'llama3' }]),
unloadModel: (...a) => h.ollamaUnload(...a),
getBaseUrl: () => 'http://localhost:11434',
}));
-vi.mock('../services/lmStudioManager.js', () => ({
+vi.mock('./lmStudioManager.js', () => ({
getLoadedModels: vi.fn(async () => []),
unloadModel: (...a) => h.lmUnload(...a),
getBaseUrl: () => 'http://localhost:1234',
}));
-vi.mock('../services/providers.js', () => ({
+vi.mock('./providers.js', () => ({
getAllProviders: vi.fn(async () => {
// The real one rejects when the AI toolkit was never initialized — the
// failure mode this module must survive without blocking a job.
@@ -28,11 +28,11 @@ vi.mock('../services/providers.js', () => ({
return h.providers;
}),
}));
-vi.mock('./cudaCapability.js', () => ({ getCudaCapability: vi.fn(async () => h.cuda) }));
-vi.mock('./openAiModelsProbe.js', () => ({ probeOpenAiModels: (...a) => h.probe(...a) }));
+vi.mock('../lib/cudaCapability.js', () => ({ getCudaCapability: vi.fn(async () => h.cuda) }));
+vi.mock('../lib/openAiModelsProbe.js', () => ({ probeOpenAiModels: (...a) => h.probe(...a) }));
const { detectGpuBlockers, gpuBlockersMessage, prepareLocalMemory } = await import('./localMemory.js');
-const { getCudaCapability } = await import('./cudaCapability.js');
+const { getCudaCapability } = await import('../lib/cudaCapability.js');
const VLLM_ENDPOINT = 'http://127.0.0.1:18020/v1';
const vllmProvider = (over = {}) => ({
diff --git a/server/services/localModelAssessmentStore.js b/server/services/localModelAssessmentStore.js
index 53a082869f..6e70e9b81a 100644
--- a/server/services/localModelAssessmentStore.js
+++ b/server/services/localModelAssessmentStore.js
@@ -32,7 +32,7 @@ import { join } from 'path';
import { rename } from 'fs/promises';
import os from 'os';
import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
-import { getAvailableMemoryGb } from '../lib/localMemory.js';
+import { getAvailableMemoryGb } from './localMemory.js';
import { compareEnvironments, describeStaleness, measuredFitVerdict } from '../lib/localModelAssessment.js';
import { ASSESSABLE_RUNTIMES } from '../lib/localProviderRuntime.js';
import { getVersion as getOllamaVersion } from './ollamaManager.js';
diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.js
index aa9352c32b..5ccd7842c2 100644
--- a/server/services/localModelAssessments.test.js
+++ b/server/services/localModelAssessments.test.js
@@ -105,7 +105,7 @@ vi.mock('./lmStudioManager.js', () => ({
}));
// A fixed, generous memory budget so the memory axis is deterministic.
-vi.mock('../lib/localMemory.js', () => ({ getAvailableMemoryGb: async () => 64 }));
+vi.mock('./localMemory.js', () => ({ getAvailableMemoryGb: async () => 64 }));
const svc = await import('./localModelAssessments.js');
// The durable store is a separate module (no path to a provider); the read-only
diff --git a/server/services/loraTraining/memoryPrep.js b/server/services/loraTraining/memoryPrep.js
index 304db3eb7e..b9e02b5f15 100644
--- a/server/services/loraTraining/memoryPrep.js
+++ b/server/services/loraTraining/memoryPrep.js
@@ -1,8 +1,8 @@
/** Training-specific memory policy built on the shared local-memory preflight. */
-import { prepareLocalMemory } from '../../lib/localMemory.js';
+import { prepareLocalMemory } from '../localMemory.js';
-export { unloadResidentModels, getAvailableMemoryGb, isLocalBackendUrl, gpuBlockersMessage } from '../../lib/localMemory.js';
+export { unloadResidentModels, getAvailableMemoryGb, isLocalBackendUrl, gpuBlockersMessage } from '../localMemory.js';
// Below this floor even a small 4-bit training run risks swap-thrash. Larger
// run sizing remains training-specific and still consumes `budgetGb` below.
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index b2836a7eed..652a558e9a 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -25,7 +25,7 @@ vi.mock('../../lib/heavyJobClaim.js', () => ({
ok: true, holder: {}, release: heavyClaimRelease, handoffTo: heavyClaimHandoff,
})),
}));
-vi.mock('../../lib/localMemory.js', async (importOriginal) => ({
+vi.mock('../localMemory.js', async (importOriginal) => ({
...(await importOriginal()),
prepareLocalMemory: mockPrepareLocalMemory,
}));
diff --git a/server/services/videoGen/spawnWatch.js b/server/services/videoGen/spawnWatch.js
index ff653917c9..5a7136ac81 100644
--- a/server/services/videoGen/spawnWatch.js
+++ b/server/services/videoGen/spawnWatch.js
@@ -8,7 +8,7 @@ import { PATHS } from '../../lib/fileUtils.js';
import { spawnDetached } from '../../lib/detachedSpawn.js';
import { createLineReader } from '../../lib/streamLines.js';
import { claimHeavyLocalJob } from '../../lib/heavyJobClaim.js';
-import { prepareLocalMemory, gpuBlockersMessage } from '../../lib/localMemory.js';
+import { prepareLocalMemory, gpuBlockersMessage } from '../localMemory.js';
import { ServerError } from '../../lib/errorHandler.js';
import { videoGenEvents } from './events.js';
import {