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

perf: restore server import budget headroom (#7810)

[._.]/ Adam Eivy3ccae93136a3
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index cc51aedf00..09fdcb65a5 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -121,6 +121,8 @@ const NARROWED = [
'needs isStr / trimTo, which textUtils.js declares'],
['lib/renderSlot.js', 'lib/storyBible.js',
'needs isStr / trimTo, which textUtils.js declares'],
+ ['services/review.js', 'services/reviewActionAdapters.js',
+ 'owns source-owned completion policy without the queue action adapters'],
];
describe('narrowed imports stay narrow (#6009)', () => {
@@ -252,6 +254,27 @@ const DEFERRED = [
['services/runner.js', 'services/ollamaAgentContext.js',
'needs the daemon manager only for an ollama-backed CLI run; the call was already predicate-gated',
'./ollamaAgentContext.js'],
+ ['services/reviewQueue.js', 'services/cosAgentFeedback.js',
+ 'loads feedback persistence only when gathering or rating CoS feedback',
+ './cosAgentFeedback.js'],
+ ['services/reviewQueue.js', 'services/askPromote.js',
+ 'loads Ask promotion orchestration only for an explicit promotion action',
+ './askPromote.js'],
+ ['services/reviewQueue.js', 'services/backup.js',
+ 'reads backup status only while gathering the failed-backup producer',
+ './backup.js'],
+ ['services/reviewQueue.js', 'services/reviewActionAdapters.js',
+ 'adapts stored review and notification rows only while building the queue',
+ './reviewActionAdapters.js'],
+ ['services/notifications.js', 'services/reviewActionAdapters.js',
+ 'classifies action history only on notification mutations',
+ './reviewActionAdapters.js'],
+ ['services/telegramForward.js', 'services/reviewActionAdapters.js',
+ 'adapts a notification only when a forward is actually sent',
+ './reviewActionAdapters.js'],
+ ['services/videoGen/generateVideo.js', 'services/videoGen/ensureWeights.js',
+ 'provisions MiniMax H3 weights only for an actual H3 render',
+ './ensureWeights.js'],
];
describe('deferred imports stay deferred (#6156)', () => {
@@ -773,6 +796,11 @@ describe('deferred imports stay deferred (#6156)', () => {
// test files' own closures. Measured before 116,066, after 116,111 (+45);
// restores the ~400 of headroom the recent entries carry — main had eroded
// to 34.
+// The current tree also carries three avoidable operational edges: the review
+// queue's feedback store, its action adapters, and H3 weight provisioning were
+// imported at module scope even though each runs only from an explicit queue,
+// mutation, forwarding, or H3-render path. Keep those boundaries deferred so
+// unrelated server suites do not pay their subtrees.
const MAX_STATIC_INSTANTIATIONS = 116500;
diff --git a/server/services/notifications.js b/server/services/notifications.js
index 5b3a456692..a3678e7cce 100644
--- a/server/services/notifications.js
+++ b/server/services/notifications.js
@@ -13,7 +13,6 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
import { EventEmitter } from 'events';
import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';
import { createMutex } from '../lib/asyncMutex.js';
-import { adaptNotification } from './reviewActionAdapters.js';
const withLock = createMutex();
@@ -36,6 +35,8 @@ export const PRIORITY_LEVELS = {
CRITICAL: 'critical'
};
+const loadActionAdapter = () => import('./reviewActionAdapters.js');
+
/**
* Ensure data directory exists
*/
@@ -132,6 +133,7 @@ export async function getCountsByType() {
*/
export async function addNotification(notification) {
return withLock(async () => {
+ const { adaptNotification } = await loadActionAdapter();
const data = await loadNotifications();
const newNotification = {
@@ -178,6 +180,7 @@ export async function addNotification(notification) {
*/
export async function removeNotification(id) {
return withLock(async () => {
+ const { adaptNotification } = await loadActionAdapter();
const data = await loadNotifications();
const index = data.notifications.findIndex(n => n.id === id);
@@ -277,6 +280,7 @@ export async function markAllAsRead() {
*/
export async function clearAll() {
return withLock(async () => {
+ const { adaptNotification } = await loadActionAdapter();
const data = await loadNotifications();
const count = data.notifications.filter(n => !n.historyHidden).length;
diff --git a/server/services/review.js b/server/services/review.js
index 5decc4d9a3..02a3dce334 100644
--- a/server/services/review.js
+++ b/server/services/review.js
@@ -11,9 +11,43 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
import { EventEmitter } from 'events';
import { ensureDir, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';
import { cosEvents } from './cosEvents.js';
-import { isSourceOwnedReviewItem } from './reviewActionAdapters.js';
import { GOAL_FIDELITY_HOLD_EVENT, formatGoalFidelitySummary } from '../lib/goalFidelity.js';
+const SOURCE_OWNED_REVIEW_CATEGORIES = new Set([
+ 'content-review',
+ 'goal-fidelity',
+ 'memory-approval',
+ 'plan-question',
+ 'task-approval',
+ 'autopilot-paused',
+]);
+
+const toText = (value) => (typeof value === 'string' ? value.trim() : '');
+
+const toReference = (value) => {
+ if (typeof value === 'number' && Number.isFinite(value)) return String(value);
+ return toText(value);
+};
+
+/**
+ * Source-owned obligations must be completed by their owning action, not by
+ * the generic Review service. Keep this classifier beside the policy it
+ * protects so review.js does not eagerly load the queue's notification
+ * adapters and their vocabulary for every caller that only needs review
+ * storage.
+ */
+export const isSourceOwnedReviewItem = (item) => {
+ const metadata = item?.metadata && typeof item.metadata === 'object' ? item.metadata : {};
+ const category = toText(metadata.category);
+
+ if (metadata.sourceOwned === true || metadata.triageOnly === true) return true;
+ if (SOURCE_OWNED_REVIEW_CATEGORIES.has(category)) return true;
+ if (item?.type === 'cos' && (toReference(metadata.taskId) || toReference(metadata.referenceId))) {
+ return true;
+ }
+ return item?.type === 'alert';
+};
+
const DATA_DIR = join(PATHS.data, 'review');
const ITEMS_FILE = join(DATA_DIR, 'items.json');
// Cold storage for completed/dismissed items retention moves out of items.json
diff --git a/server/services/reviewActionAdapters.js b/server/services/reviewActionAdapters.js
index ce2f37e4b8..920d452f2e 100644
--- a/server/services/reviewActionAdapters.js
+++ b/server/services/reviewActionAdapters.js
@@ -1,14 +1,5 @@
import { NOTIFICATION_ACTION_POLICY } from '../lib/notificationTypes.js';
-const SOURCE_OWNED_REVIEW_CATEGORIES = new Set([
- 'content-review',
- 'goal-fidelity',
- 'memory-approval',
- 'plan-question',
- 'task-approval',
- 'autopilot-paused',
-]);
-
const CONTEXT_ONLY_REVIEW_CATEGORIES = new Set([
'client-error',
'health-issue',
@@ -38,18 +29,6 @@ const operation = (id, label, available = true) => ({
export const canonicalActionId = (source, sourceRef) => `${source}:${sourceRef}`;
-export const isSourceOwnedReviewItem = (item) => {
- const metadata = item?.metadata && typeof item.metadata === 'object' ? item.metadata : {};
- const category = toText(metadata.category);
-
- if (metadata.sourceOwned === true || metadata.triageOnly === true) return true;
- if (SOURCE_OWNED_REVIEW_CATEGORIES.has(category)) return true;
- if (item?.type === 'cos' && (toReference(metadata.taskId) || toReference(metadata.referenceId))) {
- return true;
- }
- return item?.type === 'alert';
-};
-
const reviewItemBase = (item, values) => ({
...values,
title: toText(item?.title) || 'Review obligation',
diff --git a/server/services/reviewActionAdapters.test.js b/server/services/reviewActionAdapters.test.js
index c1e4adb321..625bb82ee6 100644
--- a/server/services/reviewActionAdapters.test.js
+++ b/server/services/reviewActionAdapters.test.js
@@ -3,7 +3,6 @@ import { NOTIFICATION_TYPES } from '../lib/notificationTypes.js';
import {
adaptNotification,
adaptStoredReviewItem,
- isSourceOwnedReviewItem,
} from './reviewActionAdapters.js';
describe('review action adapters', () => {
@@ -115,15 +114,4 @@ describe('review action adapters', () => {
metadata: {},
})).toBeNull();
});
-
- it('marks source-owned alerts as unavailable to generic completion', () => {
- expect(isSourceOwnedReviewItem({
- type: 'alert',
- metadata: { category: 'goal-fidelity' },
- })).toBe(true);
- expect(isSourceOwnedReviewItem({
- type: 'todo',
- metadata: {},
- })).toBe(false);
- });
});
diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.js
index 727480a71c..8b15dd79d8 100644
--- a/server/services/reviewQueue.js
+++ b/server/services/reviewQueue.js
@@ -32,17 +32,13 @@ import * as brain from './brain.js';
import * as brainStorage from './brainStorage.js';
import * as askConversations from './askConversations.js';
import * as cosTaskStore from './cosTaskStore.js';
-import * as cosAgentFeedback from './cosAgentFeedback.js';
import * as messageDrafts from './messageDrafts.js';
import { generateNonProductAlerts } from './proactiveAlertSources.js';
-import * as backup from './backup.js';
import * as identity from './identity.js';
import * as reviewService from './review.js';
import * as notifications from './notifications.js';
import * as stackerNews from './stackerNews.js';
import * as x from './x.js';
-import { promoteLatestAssistantTurn } from './askPromote.js';
-import { adaptNotification, adaptStoredReviewItem } from './reviewActionAdapters.js';
import { ServerError } from '../lib/errorHandler.js';
import { safeJSONParse } from '../lib/fileUtils.js';
import { getUserTimezone } from './userTimezone.js';
@@ -346,7 +342,8 @@ const PRODUCERS = [
drillTo: '/cos/agents?feedback=needs-feedback',
views: ['today', 'all', 'history'],
async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT, ctx = {}) {
- const pending = await cosAgentFeedback.getPendingAgentFeedback({ includeUnavailable: ctx.view === 'history' });
+ const { getPendingAgentFeedback } = await import('./cosAgentFeedback.js');
+ const pending = await getPendingAgentFeedback({ includeUnavailable: ctx.view === 'history' });
const items = [
...(Array.isArray(pending?.agents) ? pending.agents : []),
...(ctx.view === 'history' && Array.isArray(pending?.unavailable) ? pending.unavailable : []),
@@ -445,6 +442,7 @@ const PRODUCERS = [
label: 'Stored review obligations',
drillTo: '/review',
async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {
+ const { adaptStoredReviewItem } = await import('./reviewActionAdapters.js');
const pendingItems = await reviewService.getItems({ status: 'pending' });
const items = (Array.isArray(pendingItems) ? pendingItems : [])
.map(adaptStoredReviewItem)
@@ -525,6 +523,7 @@ const PRODUCERS = [
label: 'Actionable notifications',
drillTo: '/review',
async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {
+ const { adaptNotification } = await import('./reviewActionAdapters.js');
// Filter before applying the queue cap. A busy history stream must not
// hide a source-owned approval that happens to be older than it.
const records = await notifications.getNotifications({ includeHidden: true });
@@ -674,11 +673,12 @@ const PRODUCERS = [
label: 'Failed backups',
drillTo: '/settings/backup',
async gather(limit = REVIEW_QUEUE_SOURCE_READ_LIMIT) {
+ const { getState } = await import('./backup.js');
// A backup needing acknowledgement is either a full failure (status
// 'error') or a degraded run (status 'degraded' — file rsync succeeded but
// the DB dump failed; it also carries an `error` string). Both warrant a
// queue item, but they map to different severities below.
- const state = await backup.getState();
+ const state = await getState();
const needsAttention = state && (state.status === 'error' || state.status === 'degraded' || state.error);
return needsAttention ? [state].slice(0, limit) : [];
},
@@ -1037,7 +1037,10 @@ const SOURCE_ACTIONS = Object.freeze({
reopen: (id) => reviewService.reopenItem(id),
}),
feedback: Object.freeze({
- rate: (id, input) => cosAgentFeedback.submitAgentFeedback(id, input),
+ rate: async (id, input) => {
+ const { submitAgentFeedback } = await import('./cosAgentFeedback.js');
+ return submitAgentFeedback(id, input);
+ },
}),
});
@@ -1237,6 +1240,7 @@ export async function promoteAskQueueItem(queueItemId, target, goalId) {
throw new ServerError('goalId is required to promote into a goal', { status: 400, code: 'VALIDATION_ERROR' });
}
+ const { promoteLatestAssistantTurn } = await import('./askPromote.js');
const result = await promoteLatestAssistantTurn({ conversationId, target, goalId });
await clearQueueTriageMarkersForItem(queueItemId);
return { source, id: queueItemId, promoted: true, target: result.target, ref: result.ref };
diff --git a/server/services/telegramForward.js b/server/services/telegramForward.js
index 8b69fc206e..0b7e8d1150 100644
--- a/server/services/telegramForward.js
+++ b/server/services/telegramForward.js
@@ -18,7 +18,6 @@ import { getDomainAutonomyMode } from './cosState.js';
import { getDomainBudgetStatus, recordDomainUsage } from './domainUsage.js';
import { peekMemory } from './memoryBackend.js';
import { buildNotificationMessage, isMemoryApprovalNotification } from '../lib/telegramMessage.js';
-import { adaptNotification } from './reviewActionAdapters.js';
const DOMAIN = 'messages';
@@ -75,6 +74,7 @@ export async function forwardNotification(notification, { cachedForwardTypes, se
if (!await shouldForward(notification, cachedForwardTypes)) return;
// Only proven references participate. Legacy uncorrelated forwards retain
// their existing type/autonomy/budget behavior.
+ const { adaptNotification } = await import('./reviewActionAdapters.js');
const action = adaptNotification(notification);
const actionId = action?.id || (notification.type === 'daily_post_reminder'
&& notification.metadata?.actionId === 'product:daily-post' ? 'product:daily-post' : null);
diff --git a/server/services/videoGen/generateVideo.js b/server/services/videoGen/generateVideo.js
index cd57e71991..e06fd734e3 100644
--- a/server/services/videoGen/generateVideo.js
+++ b/server/services/videoGen/generateVideo.js
@@ -29,7 +29,6 @@ import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../.
import { hardwareUnavailableReason, isHardwareCompatible } from '../../lib/systemCapabilities.js';
import { resolveVideoModelSelection } from './modelSelection.js';
import { findCachedRepoFile, findCachedRepoFiles } from '../../lib/hfCache.js';
-import { ensureMiniMaxH3Weights } from './ensureWeights.js';
import { describeRenderConditioning, RENDER_INPUTS_VERSION } from './generateVideoHelpers.js';
import { readTriggerWordsByFilename, readLoraLicensesByFilename } from '../loras.js';
import { provenanceForRender } from '../../lib/assetProvenance.js';
@@ -681,7 +680,10 @@ export async function generateVideo({ pythonPath, prompt, negativePrompt = '', m
ffprobePath: ffprobe,
}));
if (batch) args.push('--batch-seeds', JSON.stringify(batch.map((item) => item.seed)));
- await ensureMiniMaxH3Weights(model);
+ if (model.runtime === 'minimax_h3') {
+ const { ensureMiniMaxH3Weights } = await import('./ensureWeights.js');
+ await ensureMiniMaxH3Weights(model);
+ }
} catch (err) {
job.status = 'error';
const reason = err.message || 'Failed to prepare video generation';