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

test([issue-1172]): add route-level coverage for digital-twin and agentTools

[._.]/ Adam Eivy7b56d4cb9cc2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 22c59964f7..9ff68bee2a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -35,6 +35,8 @@
## Changed
+- **[issue-1172] Added route-level tests for the Digital Twin and Agent Tools APIs** — pins request validation and error/status handling so a regression in those endpoints surfaces in CI. No behavior change.
+
- **[issue-1167] Trimmed two dependencies' footprint** — the Moltworld real-time connection now uses the runtime's built-in WebSocket instead of a third-party library, and the Claude Code changelog feed parses with a small built-in extractor. No behavior change.
- **[issue-1154] Library hygiene for the genome + writers-room internals** — the curated SNP marker dataset now loads from a data file instead of a hardcoded array, and the writers-room storage factory moved out of the shared sanitizer library. No behavior change.
diff --git a/server/routes/agentTools.test.js b/server/routes/agentTools.test.js
new file mode 100644
index 0000000000..b43ed51bc7
--- /dev/null
+++ b/server/routes/agentTools.test.js
@@ -0,0 +1,166 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+// Route-contract tests for agentTools: validation (400), account/agent status
+// mapping (404 / ACCOUNT_INACTIVE), and the MOLTBOOK_ACTION_DELAY_MS throttle
+// on the engage loop. The platform + content + moltbook deps are mocked so no
+// network or real 1.5s sleeps happen.
+const fnMap = vi.hoisted(() => (names) => Object.fromEntries(names.map((n) => [n, vi.fn()])));
+
+// Capture sleep calls (the throttle) and resolve instantly so the engage loop
+// doesn't actually wait 1.5s between writes.
+const sleepMock = vi.hoisted(() => vi.fn(() => Promise.resolve()));
+vi.mock('../lib/fileUtils.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, sleep: sleepMock };
+});
+
+vi.mock('../services/platformAccounts.js', () => fnMap([
+ 'getAccountWithCredentials', 'recordActivity',
+]));
+vi.mock('../services/agentPersonalities.js', () => fnMap(['getAgentById']));
+vi.mock('../services/agentActivity.js', () => fnMap(['logActivity']));
+vi.mock('../services/agentDrafts.js', () => fnMap([
+ 'listDrafts', 'createDraft', 'updateDraft', 'deleteDraft',
+]));
+vi.mock('../services/agentContentGenerator.js', () => fnMap([
+ 'generatePost', 'generateComment', 'generateReply',
+]));
+vi.mock('../services/agentFeedFilter.js', () => fnMap([
+ 'findRelevantPosts', 'findReplyOpportunities',
+]));
+vi.mock('../services/agentPublished.js', () => fnMap(['collectPublishedPosts']));
+
+// MoltbookClient is a factory; checkRateLimit gates the engage loop's writes.
+const moltbookClient = vi.hoisted(() => ({
+ upvote: vi.fn(() => Promise.resolve({})),
+ createComment: vi.fn(() => Promise.resolve({ id: 'c1' })),
+ getPost: vi.fn(() => Promise.resolve({ id: 'p1', title: 'T' })),
+ getComments: vi.fn(() => Promise.resolve({ comments: [] })),
+ apiKey: 'key-123',
+}));
+const checkRateLimitMock = vi.hoisted(() => vi.fn(() => ({ allowed: true })));
+vi.mock('../integrations/moltbook/index.js', () => ({
+ // The route calls `new MoltbookClient(apiKey)`; a plain function returning
+ // the shared mock client is constructable (new returns the object).
+ MoltbookClient: function MoltbookClient() { return moltbookClient; },
+ checkRateLimit: checkRateLimitMock,
+}));
+
+import agentToolsRoutes from './agentTools.js';
+import * as platformAccounts from '../services/platformAccounts.js';
+import * as agentPersonalities from '../services/agentPersonalities.js';
+import { generatePost, generateComment } from '../services/agentContentGenerator.js';
+import { findRelevantPosts, findReplyOpportunities } from '../services/agentFeedFilter.js';
+
+const ACTIVE_ACCOUNT = { id: 'acc-1', status: 'active', credentials: { apiKey: 'key-123' } };
+const AGENT = { id: 'agent-1', name: 'Bot', aiConfig: {} };
+
+describe('Agent Tools Routes', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/agents/tools', agentToolsRoutes);
+ vi.clearAllMocks();
+ });
+
+ describe('POST /generate-post', () => {
+ it('400s when agentId/accountId are missing', async () => {
+ const res = await request(app).post('/api/agents/tools/generate-post').send({ submolt: 'general' });
+ expect(res.status).toBe(400);
+ expect(generatePost).not.toHaveBeenCalled();
+ });
+
+ it('returns the generated post on the happy path', async () => {
+ platformAccounts.getAccountWithCredentials.mockResolvedValue(ACTIVE_ACCOUNT);
+ agentPersonalities.getAgentById.mockResolvedValue(AGENT);
+ generatePost.mockResolvedValue({ title: 'Hi', content: 'Body' });
+
+ const res = await request(app)
+ .post('/api/agents/tools/generate-post')
+ .send({ agentId: 'agent-1', accountId: 'acc-1', submolt: 'general' });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ title: 'Hi', content: 'Body' });
+ expect(generatePost).toHaveBeenCalledOnce();
+ });
+
+ it('404s when the account is unknown', async () => {
+ platformAccounts.getAccountWithCredentials.mockResolvedValue(null);
+ const res = await request(app)
+ .post('/api/agents/tools/generate-post')
+ .send({ agentId: 'agent-1', accountId: 'ghost' });
+ expect(res.status).toBe(404);
+ expect(res.body.code).toBe('NOT_FOUND');
+ });
+
+ it('404s when the agent is unknown', async () => {
+ platformAccounts.getAccountWithCredentials.mockResolvedValue(ACTIVE_ACCOUNT);
+ agentPersonalities.getAgentById.mockResolvedValue(null);
+ const res = await request(app)
+ .post('/api/agents/tools/generate-post')
+ .send({ agentId: 'ghost', accountId: 'acc-1' });
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe('POST /engage', () => {
+ it('returns ACCOUNT_INACTIVE (400) for a non-active account', async () => {
+ platformAccounts.getAccountWithCredentials.mockResolvedValue({ ...ACTIVE_ACCOUNT, status: 'suspended' });
+ const res = await request(app)
+ .post('/api/agents/tools/engage')
+ .send({ agentId: 'agent-1', accountId: 'acc-1' });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('ACCOUNT_INACTIVE');
+ expect(findRelevantPosts).not.toHaveBeenCalled();
+ });
+
+ it('400s on out-of-range maxVotes', async () => {
+ const res = await request(app)
+ .post('/api/agents/tools/engage')
+ .send({ agentId: 'agent-1', accountId: 'acc-1', maxVotes: 999 });
+ expect(res.status).toBe(400);
+ });
+
+ it('throttles between each vote with MOLTBOOK_ACTION_DELAY_MS', async () => {
+ platformAccounts.getAccountWithCredentials.mockResolvedValue(ACTIVE_ACCOUNT);
+ agentPersonalities.getAgentById.mockResolvedValue(AGENT);
+ findRelevantPosts.mockResolvedValue([
+ { id: 'p1', title: 'A' },
+ { id: 'p2', title: 'B' },
+ { id: 'p3', title: 'C' },
+ ]);
+ findReplyOpportunities.mockResolvedValue([]);
+
+ const res = await request(app)
+ .post('/api/agents/tools/engage')
+ .send({ agentId: 'agent-1', accountId: 'acc-1', maxVotes: 3, maxComments: 0 });
+
+ expect(res.status).toBe(200);
+ expect(res.body.votes).toHaveLength(3);
+ expect(moltbookClient.upvote).toHaveBeenCalledTimes(3);
+ // One throttle sleep per vote, all with the documented delay.
+ expect(sleepMock).toHaveBeenCalledTimes(3);
+ expect(sleepMock).toHaveBeenCalledWith(1500);
+ });
+
+ it('stops voting early when the rate limiter disallows', async () => {
+ platformAccounts.getAccountWithCredentials.mockResolvedValue(ACTIVE_ACCOUNT);
+ agentPersonalities.getAgentById.mockResolvedValue(AGENT);
+ findRelevantPosts.mockResolvedValue([{ id: 'p1', title: 'A' }, { id: 'p2', title: 'B' }]);
+ findReplyOpportunities.mockResolvedValue([]);
+ checkRateLimitMock.mockReturnValueOnce({ allowed: false });
+
+ const res = await request(app)
+ .post('/api/agents/tools/engage')
+ .send({ agentId: 'agent-1', accountId: 'acc-1', maxVotes: 5, maxComments: 0 });
+
+ expect(res.status).toBe(200);
+ expect(res.body.votes).toHaveLength(0);
+ expect(moltbookClient.upvote).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/server/routes/digital-twin.test.js b/server/routes/digital-twin.test.js
new file mode 100644
index 0000000000..140305d01d
--- /dev/null
+++ b/server/routes/digital-twin.test.js
@@ -0,0 +1,216 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+// The route delegates to several service modules; we don't exercise their
+// internals here — this suite pins the ROUTE contract (Zod validation → 400,
+// status mapping → 404/201/204, and one happy path per operation group). Each
+// service method the route calls is mocked as a vi.fn(); tests override only
+// the few they assert on. (Vitest mock factories must return a plain object,
+// not a Proxy, so the method list is spelled out.)
+// Hoisted so the vi.mock factories below (which are hoisted to the top of the
+// module) can call it.
+const fnMap = vi.hoisted(() => (names) => Object.fromEntries(names.map((n) => [n, vi.fn()])));
+
+vi.mock('../services/digital-twin.js', () => fnMap([
+ 'getDigitalTwinStatus', 'getDocuments', 'getDocumentById', 'createDocument', 'updateDocument', 'deleteDocument',
+ 'parseTestSuite', 'runTests', 'runMultiTests', 'getTestHistory', 'parseValuesAlignmentSuite', 'runValuesAlignmentTests',
+ 'getValuesAlignmentHistory', 'parseAdversarialSuite', 'runAdversarialTests', 'getAdversarialTestHistory',
+ 'parseMultiTurnSuite', 'runMultiTurnTests', 'getMultiTurnTestHistory', 'getEnrichmentCategories', 'getEnrichmentProgress',
+ 'generateEnrichmentQuestion', 'processEnrichmentAnswer', 'analyzeEnrichmentList', 'saveEnrichmentListDocument',
+ 'getEnrichmentListItems', 'getExportFormats', 'exportDigitalTwin', 'loadMeta', 'updateSettings', 'getPersonas',
+ 'createPersona', 'getActivePersona', 'setActivePersona', 'updatePersona', 'deletePersona', 'getPersonaById',
+ 'validateCompleteness', 'detectContradictions', 'generateDynamicTests', 'analyzeWritingSamples', 'compareSpokenWrittenStyle',
+ 'analyzeIdentityImage', 'saveIdentityImageDocument', 'getTraits', 'analyzeTraits', 'updateTraits', 'getConfidence',
+ 'calculateConfidence', 'getGapRecommendations', 'analyzeAssessment', 'getImportSources', 'analyzeImportedData',
+ 'saveImportAsDocument',
+]));
+vi.mock('../services/taste-questionnaire.js', () => fnMap([
+ 'TASTE', 'getNextQuestion', 'submitAnswer', 'getTasteProfile', 'getSectionResponses', 'generateSectionSummary',
+ 'generateOverallSummary', 'resetSection', 'generatePersonalizedTasteQuestion',
+]));
+vi.mock('../services/feedbackLoop.js', () => fnMap([
+ 'submitFeedback', 'getFeedbackStats', 'getRecentFeedback', 'recalculateWeights',
+]));
+vi.mock('../services/timeCapsule.js', () => fnMap([
+ 'createSnapshot', 'listSnapshots', 'getSnapshot', 'deleteSnapshot', 'compareSnapshots',
+]));
+
+import digitalTwinRoutes from './digital-twin.js';
+import * as digitalTwinService from '../services/digital-twin.js';
+
+const VALID_UUID = '11111111-1111-1111-1111-111111111111';
+
+describe('Digital Twin Routes', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/digital-twin', digitalTwinRoutes);
+ vi.clearAllMocks();
+ });
+
+ describe('GET / (status)', () => {
+ it('returns the status summary', async () => {
+ digitalTwinService.getDigitalTwinStatus.mockResolvedValue({ documentCount: 3, enabled: true });
+ const res = await request(app).get('/api/digital-twin');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ documentCount: 3, enabled: true });
+ });
+ });
+
+ describe('documents', () => {
+ it('GET /documents lists documents', async () => {
+ digitalTwinService.getDocuments.mockResolvedValue([{ id: 'a' }, { id: 'b' }]);
+ const res = await request(app).get('/api/digital-twin/documents');
+ expect(res.status).toBe(200);
+ expect(res.body).toHaveLength(2);
+ });
+
+ it('GET /documents/:id returns 404 for an unknown doc', async () => {
+ digitalTwinService.getDocumentById.mockResolvedValue(null);
+ const res = await request(app).get('/api/digital-twin/documents/nope');
+ expect(res.status).toBe(404);
+ expect(res.body.code).toBe('NOT_FOUND');
+ });
+
+ it('POST /documents creates a document (201)', async () => {
+ const created = { id: 'doc-1', filename: 'bio.md', title: 'Bio' };
+ digitalTwinService.createDocument.mockResolvedValue(created);
+ const res = await request(app)
+ .post('/api/digital-twin/documents')
+ .send({ filename: 'bio.md', title: 'Bio', category: 'core', content: 'Hello world' });
+ expect(res.status).toBe(201);
+ expect(res.body).toEqual(created);
+ expect(digitalTwinService.createDocument).toHaveBeenCalledOnce();
+ });
+
+ it('POST /documents 400s on a missing required field (no title)', async () => {
+ const res = await request(app)
+ .post('/api/digital-twin/documents')
+ .send({ filename: 'bio.md', category: 'core', content: 'Hello' });
+ expect(res.status).toBe(400);
+ expect(digitalTwinService.createDocument).not.toHaveBeenCalled();
+ });
+
+ it('POST /documents 400s on an invalid filename (not *.md)', async () => {
+ const res = await request(app)
+ .post('/api/digital-twin/documents')
+ .send({ filename: 'bio.txt', title: 'Bio', category: 'core', content: 'Hello' });
+ expect(res.status).toBe(400);
+ });
+
+ it('PUT /documents/:id returns 404 when the doc is unknown', async () => {
+ digitalTwinService.updateDocument.mockResolvedValue(null);
+ const res = await request(app)
+ .put('/api/digital-twin/documents/ghost')
+ .send({ title: 'New' });
+ expect(res.status).toBe(404);
+ });
+
+ it('DELETE /documents/:id returns 204 on success', async () => {
+ digitalTwinService.deleteDocument.mockResolvedValue(true);
+ const res = await request(app).delete('/api/digital-twin/documents/doc-1');
+ expect(res.status).toBe(204);
+ });
+
+ it('DELETE /documents/:id returns 404 when nothing was deleted', async () => {
+ digitalTwinService.deleteDocument.mockResolvedValue(false);
+ const res = await request(app).delete('/api/digital-twin/documents/ghost');
+ expect(res.status).toBe(404);
+ });
+ });
+
+ describe('tests', () => {
+ it('GET /tests parses + returns the suite', async () => {
+ digitalTwinService.parseTestSuite.mockResolvedValue([{ id: 1, prompt: 'x' }]);
+ const res = await request(app).get('/api/digital-twin/tests');
+ expect(res.status).toBe(200);
+ expect(res.body).toHaveLength(1);
+ });
+
+ it('POST /tests/run runs the suite (happy path)', async () => {
+ digitalTwinService.runTests.mockResolvedValue({ runId: 'r1', results: [] });
+ const res = await request(app)
+ .post('/api/digital-twin/tests/run')
+ .send({ providerId: 'p1', model: 'm1' });
+ expect(res.status).toBe(200);
+ expect(digitalTwinService.runTests).toHaveBeenCalledOnce();
+ });
+
+ it('POST /tests/run 400s without providerId/model', async () => {
+ const res = await request(app).post('/api/digital-twin/tests/run').send({ testIds: [1] });
+ expect(res.status).toBe(400);
+ expect(digitalTwinService.runTests).not.toHaveBeenCalled();
+ });
+
+ it('POST /tests/run 404s for an unknown personaId', async () => {
+ digitalTwinService.getPersonaById.mockResolvedValue(null);
+ const res = await request(app)
+ .post('/api/digital-twin/tests/run')
+ .send({ providerId: 'p1', model: 'm1', personaId: VALID_UUID });
+ expect(res.status).toBe(404);
+ expect(digitalTwinService.runTests).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('export', () => {
+ it('POST /export 400s on an invalid format', async () => {
+ const res = await request(app).post('/api/digital-twin/export').send({ format: 'invalid-format' });
+ expect(res.status).toBe(400);
+ });
+
+ it('POST /export returns the export payload on a valid format', async () => {
+ digitalTwinService.exportDigitalTwin.mockResolvedValue({ format: 'json', content: '# Twin' });
+ const res = await request(app).post('/api/digital-twin/export').send({ format: 'json' });
+ expect(res.status).toBe(200);
+ expect(res.body.format).toBe('json');
+ });
+ });
+
+ describe('settings', () => {
+ it('GET /settings returns settings', async () => {
+ digitalTwinService.loadMeta.mockResolvedValue({ settings: { autoEnrich: false } });
+ const res = await request(app).get('/api/digital-twin/settings');
+ expect(res.status).toBe(200);
+ });
+
+ it('PUT /settings updates settings (happy path)', async () => {
+ digitalTwinService.updateSettings.mockResolvedValue({ autoEnrich: true });
+ const res = await request(app).put('/api/digital-twin/settings').send({ autoEnrich: true });
+ expect(res.status).toBe(200);
+ expect(digitalTwinService.updateSettings).toHaveBeenCalledOnce();
+ });
+ });
+
+ describe('personas', () => {
+ it('GET /personas lists personas', async () => {
+ digitalTwinService.getPersonas.mockResolvedValue([{ id: VALID_UUID, name: 'Formal' }]);
+ const res = await request(app).get('/api/digital-twin/personas');
+ expect(res.status).toBe(200);
+ expect(res.body).toHaveLength(1);
+ });
+
+ it('POST /personas creates a persona (201)', async () => {
+ digitalTwinService.createPersona.mockResolvedValue({ id: VALID_UUID, name: 'Formal' });
+ const res = await request(app)
+ .post('/api/digital-twin/personas')
+ .send({ name: 'Formal', instructions: 'Be formal and concise.' });
+ expect(res.status).toBe(201);
+ expect(digitalTwinService.createPersona).toHaveBeenCalledOnce();
+ });
+
+ it('POST /personas 400s without instructions', async () => {
+ const res = await request(app).post('/api/digital-twin/personas').send({ name: 'Formal' });
+ expect(res.status).toBe(400);
+ expect(digitalTwinService.createPersona).not.toHaveBeenCalled();
+ });
+
+ it('DELETE /personas/:id returns 404 when nothing was deleted', async () => {
+ digitalTwinService.deletePersona.mockResolvedValue({ deleted: false });
+ const res = await request(app).delete(`/api/digital-twin/personas/${VALID_UUID}`);
+ expect(res.status).toBe(404);
+ });
+ });
+});