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: decompose brain.js router into per-domain sub-routers + thin barrel (#1832)
[._.]/ Adam Eivy6c568474761c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex acb83ad4f3..9976a8d72c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -24,6 +24,7 @@## Internal+- **Decomposed `server/routes/brain.js` (1,149-line router covering 13 sub-domains)** — the monolithic Brain router that mixed capture/inbox, four entity CRUD collections + memories, digest/review, settings/summary, links + buckets, graph, federation sync, and the daily log is now split one concern per file (`brainCapture.js`, `brainCrud.js`, `brainDigest.js`, `brainSettings.js`, `brainLinks.js`, `brainGraph.js`, `brainSync.js`, `brainDailyLog.js`), assembled by a thin `brain.js` barrel that mounts each sub-router under `/api/brain` — the same pattern `routes/cos.js` already uses. The split is wiring-only: route paths, ordering (literal-before-`:id` routes stay within their owning sub-router), validation, and the barrel's default export are unchanged, so `server/index.js` and the existing `brain.test.js` (105 tests) pass without edits. (#1832)- **Split `server/lib/validation.js` (1,897-line multi-domain Zod barrel)** — the catch-all schema file that mixed 15+ unrelated domains is decomposed (continuing the #1151 `peerSyncValidation.js`/`creativeDirectorValidation.js` precedent) into four per-domain files: `agentValidation.js` (social-bot agent personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads, CoS Feature Agents), `cosValidation.js` (CoS tasks/jobs/loops/learning, the Review-Loop reviewer vocabulary + `normalizeReviewers`/`buildReviewWithArgs`, the Code-Review settings slice, and the task-metadata sanitizer), `mediaValidation.js` (LoRA training, local-LLM/Ollama/LM Studio management, CyberCity snapshots, media-collection bulk ops), and `pipelineValidation.js` (Writers Room, story-bible character/place/object, editorial checks, storyboard shots/scenes, prompt-stage config, issue-list query). `validation.js` (~550 lines) keeps the app/process/provider, social-account, GitHub, backup/sharing, and document/legacy-export core plus the `validateRequest`/`validate`/`parsePagination` helpers, and re-exports the four new files (flat) so every existing deep `import { x } from '../lib/validation.js'` callsite keeps working unchanged; the barrel surfaces each as a namespace export. The new domain files import only `zodCompat.js` + leaf constant modules (never back through `validation.js`), keeping the transitional re-export cycle-safe under ESM. (#1831)- **Decomposed `server/services/sharing/peerSync.js` (4,004-line god file mixing 3 sync protocols)** — the single module that inlined per-record subscription CRUD + the outbound push path (951-line region) + the receiver path (909-line region) + standalone media-library sync + CoS-history/tasks sync is now split into one concern per file: `peerSyncShared.js` (state machine, constants, peer-capability helpers, the cross-cutting event bus), `peerSyncAssets.js` (asset manifest build/diff/hash + the receiver-side asset-pull worker, reused by every receive path), `peerSyncPush.js` (the `pushRecordToPeer` pipeline + payload builder + schema-gate bookkeeping), `peerSyncReceive.js` (`applyIncomingPush` + reverse-subscribe + merge dispatch), `peerMediaLibrarySync.js` (#1566 media-library sweep), and `peerCosSync.js` (#1650 CoS history + tasks). `peerSync.js` (~985 lines) stays the orchestrator — subscription CRUD, the debounced push scheduler, the `recordEvents`/`peer:online` listeners, and the boot-time `registerSubscriptionAdapter` wiring — and re-exports the extracted modules' public surface so every existing importer (routes, `sharing/index.js`, `dataSync`, the test suite) keeps working unchanged. The leaf-`peerSyncShared` design keeps the only module cycle (`peerSync` ↔ `peerSyncReceive`, both call-time-only) safe under ESM. Verified behavior-preserving: the full server suite produces byte-identical pass/fail results before and after (zero regressions, 15,092 tests), the DB suite is 156/156 green, and the server smoke-boots cleanly. (#1830)- **Decomposed `server/lib/editorial/checkRegistry.js` (7,474-line god file)** — the single module that held ~2,400 lines of shared infra plus a 68-entry `EDITORIAL_CHECKS` array (each embedding a full `run(ctx)` closure) is now split: shared infra lives in `checkInfra.js`, the 68 checks are grouped by category into `checks/*.js` (`naming`, `cast`, `pov`, `characterArc`, `continuity`, `comic`, `visual`, `scene`, `dialogue`, `proseStyle`, `research`), and `checkRegistry.js` (~480 lines) stays the public entry point — assembling `EDITORIAL_CHECKS` from the per-category arrays and keeping the registry's lookup/state helpers. The check files import shared infra from `checkInfra.js` (not back through the registry) so the `EDITORIAL_CHECKS` spread can't hit a TDZ on the checks' eagerly-evaluated `configSchema`s. The editorial barrel's public API is byte-for-byte identical (173 exports, verified) and all editorial + runner tests pass unchanged. (#1829)diff --git a/server/routes/brain.js b/server/routes/brain.jsindex 1e5a36d885..92e0d28f39 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -1,1149 +1,30 @@/**- * Brain API Routes+ * Brain API Routes (barrel)*- * Handles all HTTP endpoints for the Brain feature:- * - Capture and classify thoughts- * - CRUD for People, Projects, Ideas, Admin- * - Daily digest and weekly review- * - Settings management+ * Thin assembler over the per-domain sub-routers. Each sub-router owns one+ * brain concern; this file just mounts them under /api/brain. See routes/cos.js+ * for the same pattern.*/import { Router } from 'express';-import { existsSync } from 'fs';-import * as brainService from '../services/brain.js';-import { openFolderInSystemExplorer } from '../lib/openFolder.js';-import { getProviderById } from '../services/providers.js';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { validateRequest } from '../lib/validation.js';-import { partialWithoutDefaults } from '../lib/zodCompat.js';-import {- captureInputSchema,- resolveReviewInputSchema,- fixInputSchema,- updateInboxInputSchema,- markInboxSentToCatalogSchema,- inboxQuerySchema,- peopleInputSchema,- projectInputSchema,- ideaInputSchema,- adminInputSchema,- memoryInputSchema,- settingsUpdateInputSchema,- linkInputSchema,- linkUpdateInputSchema,- linkReorderSchema,- linksQuerySchema,- bucketInputSchema,- bucketUpdateInputSchema,- bucketReorderSchema,- brainSyncQuerySchema,- brainSyncPushSchema,- brainBridgeSyncSchema,- brainGraphQuerySchema,- dailyLogSettingsSchema-} from '../lib/brainValidation.js';-import * as githubCloner from '../services/githubCloner.js';-import {- getBrainGraphSearchIndex,- getBrainGraphOverview,- getBrainGraphNeighborhood-} from '../services/brainGraph.js';-import { syncAllBrainData, getEmbeddingCoverage } from '../services/brainMemoryBridge.js';-import * as brainSyncLog from '../services/brainSyncLog.js';-import * as brainSync from '../services/brainSync.js';-import * as brainReconcile from '../services/brainReconcile.js';-import * as journal from '../services/brainJournal.js';-import { loadSlashdoCommand } from '../services/subAgentSpawner.js';-import * as cos from '../services/cos.js';+import captureRoutes from './brainCapture.js';+import crudRoutes from './brainCrud.js';+import digestRoutes from './brainDigest.js';+import settingsRoutes from './brainSettings.js';+import linkRoutes from './brainLinks.js';+import graphRoutes from './brainGraph.js';+import syncRoutes from './brainSync.js';+import dailyLogRoutes from './brainDailyLog.js';const router = Router();-// =============================================================================-// CAPTURE & INBOX-// =============================================================================--/**- * POST /api/brain/capture- * Capture a thought, classify it, and store it- */-router.post('/capture', asyncHandler(async (req, res) => {- const { text, providerOverride, modelOverride, creative } = validateRequest(captureInputSchema, req.body);- const result = await brainService.captureThought(text, providerOverride, modelOverride, { creative });- res.json(result);-}));--/**- * GET /api/brain/inbox- * Get inbox log entries with optional filters- */-router.get('/inbox', asyncHandler(async (req, res) => {- const data = validateRequest(inboxQuerySchema, req.query);- const [entries, counts] = await Promise.all([- brainService.getInboxLog(data),- brainService.getInboxLogCounts(),- ]);- res.json({ entries, counts });-}));--/**- * GET /api/brain/inbox/:id- * Get a single inbox log entry- */-router.get('/inbox/:id', asyncHandler(async (req, res) => {- const entry = await brainService.getInboxLogById(req.params.id);- if (!entry) {- throw new ServerError('Inbox entry not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(entry);-}));--/**- * POST /api/brain/review/resolve- * Resolve a needs_review inbox item- */-router.post('/review/resolve', asyncHandler(async (req, res) => {- const { inboxLogId, destination, editedExtracted } = validateRequest(resolveReviewInputSchema, req.body);- const result = await brainService.resolveReview(inboxLogId, destination, editedExtracted);- res.json(result);-}));--/**- * POST /api/brain/fix- * Fix/correct a filed inbox item- */-router.post('/fix', asyncHandler(async (req, res) => {- const { inboxLogId, newDestination, updatedFields, note } = validateRequest(fixInputSchema, req.body);- const result = await brainService.fixClassification(inboxLogId, newDestination, updatedFields, note);- res.json(result);-}));--/**- * POST /api/brain/inbox/:id/retry- * Retry AI classification for a needs_review item- */-router.post('/inbox/:id/retry', asyncHandler(async (req, res) => {- const { providerOverride, modelOverride } = req.body || {};- const result = await brainService.retryClassification(req.params.id, providerOverride, modelOverride);- res.json(result);-}));--/**- * POST /api/brain/inbox/:id/done- * Mark an inbox entry as done- */-router.post('/inbox/:id/done', asyncHandler(async (req, res) => {- const result = await brainService.markInboxDone(req.params.id);- if (!result) {- throw new ServerError('Inbox entry not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(result);-}));--/**- * POST /api/brain/inbox/sent-to-catalog- * Mark a batch of creative inbox notes as consumed by a committed catalog ingest.- * Literal path — declared before the `/inbox/:id` routes so it isn't shadowed.- */-router.post('/inbox/sent-to-catalog', asyncHandler(async (req, res) => {- const { ids } = validateRequest(markInboxSentToCatalogSchema, req.body);- const updated = await brainService.markInboxSentToCatalog(ids);- res.json({ updated, count: updated.length });-}));--/**- * PUT /api/brain/inbox/:id- * Update an inbox entry (edit captured text)- */-router.put('/inbox/:id', asyncHandler(async (req, res) => {- const data = validateRequest(updateInboxInputSchema, req.body);- const result = await brainService.updateInboxEntry(req.params.id, data);- if (!result) {- throw new ServerError('Inbox entry not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(result);-}));--/**- * DELETE /api/brain/inbox/:id- * Delete an inbox entry- */-router.delete('/inbox/:id', asyncHandler(async (req, res) => {- const deleted = await brainService.deleteInboxEntry(req.params.id);- if (!deleted) {- throw new ServerError('Inbox entry not found', { status: 404, code: 'NOT_FOUND' });- }- res.status(204).send();-}));--// =============================================================================-// PEOPLE CRUD-// =============================================================================--router.get('/people', asyncHandler(async (req, res) => {- const people = await brainService.getPeople();- res.json(people);-}));--router.get('/people/:id', asyncHandler(async (req, res) => {- const person = await brainService.getPersonById(req.params.id);- if (!person) {- throw new ServerError('Person not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(person);-}));--router.post('/people', asyncHandler(async (req, res) => {- const data = validateRequest(peopleInputSchema, req.body);- const person = await brainService.createPerson(data);- res.status(201).json(person);-}));--router.put('/people/:id', asyncHandler(async (req, res) => {- const data = validateRequest(peopleInputSchema.partial(), req.body);- const person = await brainService.updatePerson(req.params.id, data);- if (!person) {- throw new ServerError('Person not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(person);-}));--router.delete('/people/:id', asyncHandler(async (req, res) => {- const deleted = await brainService.deletePerson(req.params.id);- if (!deleted) {- throw new ServerError('Person not found', { status: 404, code: 'NOT_FOUND' });- }- res.status(204).send();-}));--// =============================================================================-// PROJECTS CRUD-// =============================================================================--router.get('/projects', asyncHandler(async (req, res) => {- const { status } = req.query;- const filters = status ? { status } : undefined;- const projects = await brainService.getProjects(filters);- res.json(projects);-}));--router.get('/projects/:id', asyncHandler(async (req, res) => {- const project = await brainService.getProjectById(req.params.id);- if (!project) {- throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(project);-}));--router.post('/projects', asyncHandler(async (req, res) => {- const data = validateRequest(projectInputSchema, req.body);- const project = await brainService.createProject(data);- res.status(201).json(project);-}));--router.put('/projects/:id', asyncHandler(async (req, res) => {- const data = validateRequest(partialWithoutDefaults(projectInputSchema), req.body);- const project = await brainService.updateProject(req.params.id, data);- if (!project) {- throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(project);-}));--router.delete('/projects/:id', asyncHandler(async (req, res) => {- const deleted = await brainService.deleteProject(req.params.id);- if (!deleted) {- throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });- }- res.status(204).send();-}));--// =============================================================================-// IDEAS CRUD-// =============================================================================--router.get('/ideas', asyncHandler(async (req, res) => {- const { status } = req.query;- const filters = status ? { status } : undefined;- const ideas = await brainService.getIdeas(filters);- res.json(ideas);-}));--router.get('/ideas/:id', asyncHandler(async (req, res) => {- const idea = await brainService.getIdeaById(req.params.id);- if (!idea) {- throw new ServerError('Idea not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(idea);-}));--router.post('/ideas', asyncHandler(async (req, res) => {- const data = validateRequest(ideaInputSchema, req.body);- const idea = await brainService.createIdea(data);- res.status(201).json(idea);-}));--router.put('/ideas/:id', asyncHandler(async (req, res) => {- const data = validateRequest(partialWithoutDefaults(ideaInputSchema), req.body);- const idea = await brainService.updateIdea(req.params.id, data);- if (!idea) {- throw new ServerError('Idea not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(idea);-}));--router.delete('/ideas/:id', asyncHandler(async (req, res) => {- const deleted = await brainService.deleteIdea(req.params.id);- if (!deleted) {- throw new ServerError('Idea not found', { status: 404, code: 'NOT_FOUND' });- }- res.status(204).send();-}));--// =============================================================================-// ADMIN CRUD-// =============================================================================--router.get('/admin', asyncHandler(async (req, res) => {- const { status } = req.query;- const filters = status ? { status } : undefined;- const adminItems = await brainService.getAdminItems(filters);- res.json(adminItems);-}));--router.get('/admin/:id', asyncHandler(async (req, res) => {- const item = await brainService.getAdminById(req.params.id);- if (!item) {- throw new ServerError('Admin item not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(item);-}));--router.post('/admin', asyncHandler(async (req, res) => {- const data = validateRequest(adminInputSchema, req.body);- const item = await brainService.createAdminItem(data);- res.status(201).json(item);-}));--router.put('/admin/:id', asyncHandler(async (req, res) => {- const data = validateRequest(partialWithoutDefaults(adminInputSchema), req.body);- const item = await brainService.updateAdminItem(req.params.id, data);- if (!item) {- throw new ServerError('Admin item not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(item);-}));--router.delete('/admin/:id', asyncHandler(async (req, res) => {- const deleted = await brainService.deleteAdminItem(req.params.id);- if (!deleted) {- throw new ServerError('Admin item not found', { status: 404, code: 'NOT_FOUND' });- }- res.status(204).send();-}));--// =============================================================================-// MEMORIES CRUD-// =============================================================================--router.get('/memories', asyncHandler(async (req, res) => {- const memories = await brainService.getMemoryEntries();- res.json(memories);-}));--router.get('/memories/:id', asyncHandler(async (req, res) => {- const memory = await brainService.getMemoryEntryById(req.params.id);- if (!memory) {- throw new ServerError('Memory not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(memory);-}));--router.post('/memories', asyncHandler(async (req, res) => {- const data = validateRequest(memoryInputSchema, req.body);- const memory = await brainService.createMemoryEntry(data);- res.status(201).json(memory);-}));--router.put('/memories/:id', asyncHandler(async (req, res) => {- const data = validateRequest(memoryInputSchema.partial(), req.body);- const memory = await brainService.updateMemoryEntry(req.params.id, data);- if (!memory) {- throw new ServerError('Memory not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(memory);-}));--router.delete('/memories/:id', asyncHandler(async (req, res) => {- const deleted = await brainService.deleteMemoryEntry(req.params.id);- if (!deleted) {- throw new ServerError('Memory not found', { status: 404, code: 'NOT_FOUND' });- }- res.status(204).send();-}));--// =============================================================================-// DIGEST & REVIEW-// =============================================================================--/**- * GET /api/brain/digest/latest- * Get the most recent daily digest- */-router.get('/digest/latest', asyncHandler(async (req, res) => {- const digest = await brainService.getLatestDigest();- res.json(digest);-}));--/**- * GET /api/brain/digests- * Get digest history- */-router.get('/digests', asyncHandler(async (req, res) => {- const limit = parseInt(req.query.limit, 10) || 10;- const digests = await brainService.getDigests(limit);- res.json(digests);-}));--/**- * POST /api/brain/digest/run- * Manually trigger daily digest generation- */-router.post('/digest/run', asyncHandler(async (req, res) => {- const { providerOverride, modelOverride } = req.body || {};- const digest = await brainService.runDailyDigest(providerOverride, modelOverride);- res.json(digest);-}));--/**- * GET /api/brain/review/latest- * Get the most recent weekly review- */-router.get('/review/latest', asyncHandler(async (req, res) => {- const review = await brainService.getLatestReview();- res.json(review);-}));--/**- * GET /api/brain/reviews- * Get review history- */-router.get('/reviews', asyncHandler(async (req, res) => {- const limit = parseInt(req.query.limit, 10) || 10;- const reviews = await brainService.getReviews(limit);- res.json(reviews);-}));--/**- * POST /api/brain/review/run- * Manually trigger weekly review generation- */-router.post('/review/run', asyncHandler(async (req, res) => {- const { providerOverride, modelOverride } = req.body || {};- const review = await brainService.runWeeklyReview(providerOverride, modelOverride);- res.json(review);-}));--// =============================================================================-// SETTINGS & SUMMARY-// =============================================================================--/**- * GET /api/brain/settings- * Get brain settings- */-router.get('/settings', asyncHandler(async (req, res) => {- const settings = await brainService.loadMeta();- res.json(settings);-}));--/**- * PUT /api/brain/settings- * Update brain settings- */-router.put('/settings', asyncHandler(async (req, res) => {- const data = validateRequest(settingsUpdateInputSchema, req.body);-- // Validate provider and model if provided- if (data.defaultProvider || data.defaultModel) {- const providerId = data.defaultProvider;- const modelId = data.defaultModel;-- // Get current settings to use existing provider if only model is being updated- const currentSettings = await brainService.loadMeta();- const effectiveProviderId = providerId || currentSettings.defaultProvider;-- // Validate provider exists- const provider = await getProviderById(effectiveProviderId);- if (!provider) {- throw new ServerError(`Provider "${effectiveProviderId}" not found`, {- status: 400,- code: 'INVALID_PROVIDER'- });- }-- // Validate model exists in provider's models- if (modelId) {- if (!provider.models || provider.models.length === 0) {- throw new ServerError(`Provider "${effectiveProviderId}" has no models configured`, {- status: 400,- code: 'NO_MODELS'- });- }- if (!provider.models.includes(modelId)) {- throw new ServerError(`Model "${modelId}" not found in provider "${effectiveProviderId}"`, {- status: 400,- code: 'INVALID_MODEL',- context: { availableModels: provider.models }- });- }- }- }-- const settings = await brainService.updateMeta(data);- res.json(settings);-}));--/**- * GET /api/brain/summary- * Get brain data summary for dashboard- */-router.get('/summary', asyncHandler(async (req, res) => {- const summary = await brainService.getSummary();- res.json(summary);-}));--/**- * Extract a clean hostname from a URL (strip a leading www.), or null if unparseable.- */-function hostnameFromUrl(url) {- try {- return new URL(url).hostname.replace(/^www\./, '');- } catch {- return null;- }-}--// =============================================================================-// LINKS CRUD-// =============================================================================--/**- * GET /api/brain/links- * Get all links with optional filters- */-router.get('/links', asyncHandler(async (req, res) => {- const { linkType, isGitHubRepo, limit, offset } = validateRequest(linksQuerySchema, req.query);- let links = await brainService.getLinks();-- // Apply filters- if (linkType) {- links = links.filter(l => l.linkType === linkType);- }- if (isGitHubRepo !== undefined) {- links = links.filter(l => l.isGitHubRepo === isGitHubRepo);- }-- // Sort by createdAt descending- links.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));-- // Apply pagination- const total = links.length;- links = links.slice(offset, offset + limit);-- res.json({ links, total, limit, offset });-}));--/**- * POST /api/brain/links/reorder- * Apply a batch of { id, bucketId, bucketOrder } updates for one drag gesture- * in a single atomic write — N concurrent single-link PUTs against the shared- * links store can lose-update each other. Mirrors POST /buckets/reorder.- * (Registered before /links/:id so "reorder" isn't captured as an :id.)- */-router.post('/links/reorder', asyncHandler(async (req, res) => {- const { updates } = validateRequest(linkReorderSchema, req.body);- // All-or-nothing: reject before any write if a batch references a link that- // no longer exists, so the response can't report success after a partial- // apply (mirrors the single-link PUT's 404 on an unknown id).- const known = new Set((await brainService.getLinks()).map(l => l.id));- const missing = updates.filter(u => !known.has(u.id)).map(u => u.id);- if (missing.length) {- throw new ServerError('Unknown link id in reorder batch', {- status: 404,- code: 'NOT_FOUND',- context: { missing }- });- }- const links = await brainService.reorderLinks(updates);- res.json({ links });-}));--/**- * GET /api/brain/links/:id- * Get a single link by ID- */-router.get('/links/:id', asyncHandler(async (req, res) => {- const link = await brainService.getLinkById(req.params.id);- if (!link) {- throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(link);-}));--/**- * POST /api/brain/links- * Create a new link (quick-add with URL)- */-router.post('/links', asyncHandler(async (req, res) => {- const { url, title, description, linkType, tags, bucketId, bucketOrder, autoClone } = validateRequest(linkInputSchema, req.body);-- // Check if URL already exists- const existing = await brainService.getLinkByUrl(url);- if (existing) {- throw new ServerError('Link with this URL already exists', {- status: 409,- code: 'DUPLICATE_URL',- context: { existingId: existing.id }- });- }-- // Parse GitHub URL if applicable- const parsed = githubCloner.parseGitHubUrl(url);- const isGitHubRepo = !!parsed;-- // Derive a readable default title: repo slug for GitHub, hostname for plain- // URLs (so quick-added bucket chips read "example.com" instead of the full URL).- const defaultTitle = parsed- ? `${parsed.owner}/${parsed.repo}`- : (hostnameFromUrl(url) || url);-- // Create initial link record- const linkData = {- url,- title: title || defaultTitle,- description: description || '',- linkType: linkType || (isGitHubRepo ? 'github' : 'other'),- tags: tags || [],- isGitHubRepo,- gitHubOwner: parsed?.owner,- gitHubRepo: parsed?.repo,- localPath: null,- cloneStatus: isGitHubRepo && autoClone !== false ? 'pending' : 'none',- cloneError: null,- ...(bucketId !== undefined ? { bucketId } : {}),- ...(bucketOrder !== undefined ? { bucketOrder } : {})- };-- const link = await brainService.createLink(linkData);- console.log(`🔗 Created link: ${link.id} (${isGitHubRepo ? 'GitHub repo' : 'regular URL'})`);-- // If GitHub repo and auto-clone enabled, start clone in background- if (isGitHubRepo && autoClone !== false) {- cloneRepoInBackground(link.id, url).catch(err => {- console.error(`❌ Background clone setup failed for ${link.id}: ${err.message}`);- });- }-- res.status(201).json(link);-}));--/**- * Clone repo in background and update link record- */-async function cloneRepoInBackground(linkId, url) {- // Update status to cloning- await brainService.updateLink(linkId, { cloneStatus: 'cloning' });-- githubCloner.cloneRepo(url)- .then(async (result) => {- await brainService.updateLink(linkId, {- localPath: result.localPath,- cloneStatus: 'cloned',- cloneError: null- });- console.log(`✅ Background clone complete: ${linkId}`);- })- .catch(async (err) => {- await brainService.updateLink(linkId, {- cloneStatus: 'failed',- cloneError: err.message- });- console.error(`❌ Background clone failed: ${linkId} - ${err.message}`);- });-}--/**- * PUT /api/brain/links/:id- * Update a link- */-router.put('/links/:id', asyncHandler(async (req, res) => {- const data = validateRequest(linkUpdateInputSchema, req.body);-- const existing = await brainService.getLinkById(req.params.id);- if (!existing) {- throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });- }-- // When the URL changes, re-derive the GitHub-specific fields so the link- // type / repo metadata stay consistent with the new target.- if (data.url && data.url !== existing.url) {- const duplicate = await brainService.getLinkByUrl(data.url);- if (duplicate && duplicate.id !== existing.id) {- throw new ServerError('Link with this URL already exists', {- status: 409,- code: 'DUPLICATE_URL',- context: { existingId: duplicate.id }- });- }-- const parsed = githubCloner.parseGitHubUrl(data.url);- data.isGitHubRepo = !!parsed;- data.gitHubOwner = parsed?.owner || null;- data.gitHubRepo = parsed?.repo || null;-- // The previous clone (if any) belongs to the old URL — reset clone state so- // it doesn't point at the wrong repo. The user can re-clone the new target.- data.localPath = null;- data.cloneStatus = 'none';- data.cloneError = null;- }-- const link = await brainService.updateLink(req.params.id, data);- res.json(link);-}));--/**- * DELETE /api/brain/links/:id- * Delete a link- */-router.delete('/links/:id', asyncHandler(async (req, res) => {- const deleted = await brainService.deleteLink(req.params.id);- if (!deleted) {- throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });- }- res.status(204).send();-}));--/**- * POST /api/brain/links/:id/clone- * Manually trigger clone for a GitHub repo link- */-router.post('/links/:id/clone', asyncHandler(async (req, res) => {- const link = await brainService.getLinkById(req.params.id);- if (!link) {- throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });- }-- if (!link.isGitHubRepo) {- throw new ServerError('Link is not a GitHub repository', {- status: 400,- code: 'NOT_GITHUB_REPO'- });- }-- if (link.cloneStatus === 'cloning') {- throw new ServerError('Clone already in progress', {- status: 409,- code: 'CLONE_IN_PROGRESS'- });- }-- // Start clone in background- cloneRepoInBackground(link.id, link.url);-- res.json({ message: 'Clone started', linkId: link.id });-}));--/**- * POST /api/brain/links/:id/pull- * Pull latest changes for a cloned repo- */-router.post('/links/:id/pull', asyncHandler(async (req, res) => {- const link = await brainService.getLinkById(req.params.id);- if (!link) {- throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });- }-- if (!link.isGitHubRepo || !link.localPath) {- throw new ServerError('Link is not a cloned GitHub repository', {- status: 400,- code: 'NOT_CLONED'- });- }-- const result = await githubCloner.pullRepo(link.localPath);- res.json({ message: 'Pull complete', ...result });-}));--/**- * POST /api/brain/links/:id/open-folder- * Open the cloned repo folder in the system file manager- */-router.post('/links/:id/open-folder', asyncHandler(async (req, res) => {- const link = await brainService.getLinkById(req.params.id);- if (!link) {- throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });- }-- if (!link.localPath) {- throw new ServerError('Link has no local folder', {- status: 400,- code: 'NO_LOCAL_PATH'- });- }-- if (!existsSync(link.localPath)) {- throw new ServerError('Local folder does not exist', {- status: 400,- code: 'PATH_NOT_FOUND'- });- }-- openFolderInSystemExplorer(link.localPath);- res.json({ message: 'Folder opened', path: link.localPath });-}));--/**- * POST /api/brain/links/:id/scan- * Queue a read-only malware/risk scan (do:scan) against the cloned repo.- * Creates a CoS user task whose context inlines the do:scan command body- * with the repo's localPath baked in as SCAN_DIR. The agent writes its- * markdown report to ~/.claude/scans/.- */-router.post('/links/:id/scan', asyncHandler(async (req, res) => {- const link = await brainService.getLinkById(req.params.id);- if (!link) {- throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });- }- if (!link.isGitHubRepo || link.cloneStatus !== 'cloned' || !link.localPath) {- throw new ServerError('Link is not a cloned GitHub repository', {- status: 400,- code: 'NOT_CLONED'- });- }- if (!existsSync(link.localPath)) {- throw new ServerError('Local clone folder does not exist', {- status: 400,- code: 'PATH_NOT_FOUND'- });- }-- const scanCommand = await loadSlashdoCommand('scan');- if (!scanCommand) {- throw new ServerError('Failed to load do:scan command', {- status: 500,- code: 'COMMAND_LOAD_FAILED'- });- }-- const repoLabel = link.title || link.url;- const description = `Malware scan: ${repoLabel} (do:scan)`;- const context = `Run the /do:scan workflow against the cloned repository at: \`${link.localPath}\`--Use that path as SCAN_DIR. Adhere to every Operational Invariant in the command body — this is a hostile-until-proven-safe audit. The full markdown report will be written to ~/.claude/scans/. When complete, summarize the verdict (CLEAN / CAUTION / DANGEROUS) and the top findings in your final response so the report can be surfaced in the UI.-------${scanCommand}`;-- const result = await cos.addTask(- { description, context, useWorktree: false, openPR: false, simplify: false, reviewLoop: false },- 'user'- );- if (result?.duplicate) {- throw new ServerError('A scan for this repo is already pending or in progress', {- status: 409,- code: 'DUPLICATE_TASK'- });- }-- console.log(`🛡️ Queued malware scan: link=${link.id} path=${link.localPath} task=${result.id}`);- res.json({ message: 'Scan queued', taskId: result.id, linkId: link.id, scanPath: link.localPath });-}));--// =============================================================================-// BUCKETS (bookmark groups for links)-// =============================================================================--/**- * GET /api/brain/buckets- * List buckets sorted by their display order.- */-router.get('/buckets', asyncHandler(async (req, res) => {- const buckets = await brainService.getBuckets();- buckets.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));- res.json({ buckets });-}));--/**- * POST /api/brain/buckets- * Create a bucket. New buckets are appended after the existing ones.- */-router.post('/buckets', asyncHandler(async (req, res) => {- const { name, color, icon } = validateRequest(bucketInputSchema, req.body);- const bucket = await brainService.createBucketAppended({ name, color, icon });- console.log(`🗂️ Created bucket: ${bucket.id} (${bucket.name})`);- res.status(201).json(bucket);-}));--/**- * POST /api/brain/buckets/reorder- * Persist a new display order for buckets in a single call.- * (Registered before /buckets/:id so "reorder" isn't captured as an :id.)- */-router.post('/buckets/reorder', asyncHandler(async (req, res) => {- const { ids } = validateRequest(bucketReorderSchema, req.body);- for (let i = 0; i < ids.length; i++) {- await brainService.updateBucket(ids[i], { order: i });- }- const buckets = await brainService.getBuckets();- buckets.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));- res.json({ buckets });-}));--/**- * PUT /api/brain/buckets/:id- * Update a bucket's name / color / icon / order.- */-router.put('/buckets/:id', asyncHandler(async (req, res) => {- const data = validateRequest(bucketUpdateInputSchema, req.body);- const existing = await brainService.getBucketById(req.params.id);- if (!existing) {- throw new ServerError('Bucket not found', { status: 404, code: 'NOT_FOUND' });- }- const bucket = await brainService.updateBucket(req.params.id, data);- res.json(bucket);-}));--/**- * DELETE /api/brain/buckets/:id- * Delete a bucket. Its links survive — they're unassigned (bucketId -> null)- * so they fall back to the ungrouped list rather than being orphaned.- */-router.delete('/buckets/:id', asyncHandler(async (req, res) => {- const existing = await brainService.getBucketById(req.params.id);- if (!existing) {- throw new ServerError('Bucket not found', { status: 404, code: 'NOT_FOUND' });- }-- const result = await brainService.deleteBucketAndUnlinkChildren(req.params.id);- console.log(`🗂️ Deleted bucket: ${req.params.id} (unassigned ${result.unassigned} links)`);- res.json(result);-}));--// =============================================================================-// GRAPH-// =============================================================================--/**- * GET /api/brain/graph/search-index- * Lightweight {id,label,brainType} list of every node, for the client search- * box. No edges — cheap even at thousands of nodes.- */-router.get('/graph/search-index', asyncHandler(async (_req, res) => {- const data = await getBrainGraphSearchIndex();- res.json(data);-}));--/**- * GET /api/brain/graph?focus=<id>&limit=<n>- * Bounded graph data for visualization. No `focus` → an overview of the most-- * connected nodes; a `focus` → that node's neighborhood. Never the full graph- * (which crashes the browser at scale).- */-router.get('/graph', asyncHandler(async (req, res) => {- const { focus, limit } = validateRequest(brainGraphQuerySchema, req.query);- const data = focus- ? await getBrainGraphNeighborhood({ focusId: focus, limit })- : await getBrainGraphOverview({ limit });- res.json(data);-}));--// =============================================================================-// SYNC (Federation)-// =============================================================================--/**- * POST /api/brain/bridge-sync- * Sync all brain data to CoS memory system (generates embeddings).- * Body: { refresh?: boolean } — refresh:true re-embeds already-mapped records- * to heal memory entries that diverged before the per-record sync:applied- * signal existed (issue #1080).- * (Renamed from /sync to avoid conflict with federation sync)- */-router.post('/bridge-sync', asyncHandler(async (req, res) => {- const { refresh, onlyMissing } = validateRequest(brainBridgeSyncSchema, req.body ?? {});- const stats = await syncAllBrainData({ refresh, onlyMissing });- const mode = onlyMissing ? ' (missing-only)' : refresh ? ' (refresh)' : '';- console.log(`🧠🔗 Brain bridge sync complete${mode}: ${stats.synced} synced, ${stats.skipped} skipped, ${stats.archived} archived, ${stats.errors} errors`);- res.json(stats);-}));--/**- * GET /api/brain/embeddings/status- * How many active brain records lack an embedding — powers the- * "N missing · Embed missing" affordance on the graph.- */-router.get('/embeddings/status', asyncHandler(async (_req, res) => {- const coverage = await getEmbeddingCoverage();- res.json(coverage);-}));--/**- * GET /api/brain/sync?since={seq}&limit=100- * Get brain changes since a given sequence number (for peers to pull)- */-router.get('/sync', asyncHandler(async (req, res) => {- const { since, limit } = validateRequest(brainSyncQuerySchema, req.query);- const result = await brainSyncLog.getChangesSince(since, limit);- res.json(result);-}));--/**- * POST /api/brain/sync- * Receive remote brain changes from a peer- */-router.post('/sync', asyncHandler(async (req, res) => {- const { changes } = validateRequest(brainSyncPushSchema, req.body);- const result = await brainSync.applyRemoteChanges(changes);- res.json(result);-}));--/**- * GET /api/brain/reconcile/checksum- * Anti-entropy checksum over ALL brain records (incl. tombstones) — #1077.- * A peer fetches this after draining the delta log; on a mismatch it pulls the- * full snapshot below. Lightweight (one hash) so it's cheap to poll each cycle.- */-router.get('/reconcile/checksum', asyncHandler(async (req, res) => {- const checksum = await brainReconcile.getBrainChecksum();- res.json({ checksum });-}));--/**- * GET /api/brain/reconcile/snapshot- * Full brain snapshot (raw record map incl. tombstones + checksum) for a peer- * to LWW-merge. Brain has no per-record push pipeline, so this is unscoped —- * the receiver applies it idempotently via applyRemoteRecord.- */-router.get('/reconcile/snapshot', asyncHandler(async (req, res) => {- const snapshot = await brainReconcile.getBrainSnapshot();- res.json(snapshot);-}));--// =============================================================================-// DAILY LOG-// =============================================================================--// Resolve the :date route param: either 'today' → current local date, or a-// real ISO YYYY-MM-DD calendar day. Delegates to journal.isIsoDate so the-// date rules stay in one place (service layer) and can't drift between-// routes and internal callers.-const resolveJournalDate = async (date) => {- if (!date || date === 'today') return journal.getToday();- if (!journal.isIsoDate(date)) {- throw new ServerError('Invalid date. Expected "today" or YYYY-MM-DD.', {- status: 400,- code: 'BAD_REQUEST',- });- }- return date;-};--/**- * GET /api/brain/daily-log- * List daily log entries (most recent first)- */-router.get('/daily-log', asyncHandler(async (req, res) => {- // Clamp pagination: negative or zero limit / negative offset would slice- // unpredictably (or from the end of the array). Match the convention used- // by other paginated brain routes.- const parsedLimit = parseInt(req.query.limit, 10);- const parsedOffset = parseInt(req.query.offset, 10);- const limit = Math.min(Math.max(Number.isNaN(parsedLimit) ? 50 : parsedLimit, 1), 200);- const offset = Math.max(Number.isNaN(parsedOffset) ? 0 : parsedOffset, 0);- // Opt-in to full entries; default is slim summaries (date + segmentCount +- // obsidianPath) so the sidebar doesn't pull every day's content on load.- const includeContent = req.query.includeContent === '1' || req.query.includeContent === 'true';- const result = await journal.listJournals({ limit, offset, includeContent });- res.json(result);-}));--/**- * GET /api/brain/daily-log/settings- * Get daily log configuration (obsidian vault/folder, auto-sync)- */-router.get('/daily-log/settings', asyncHandler(async (req, res) => {- const settings = await journal.getSettings();- res.json(settings);-}));--/**- * PUT /api/brain/daily-log/settings- */-router.put('/daily-log/settings', asyncHandler(async (req, res) => {- const data = validateRequest(dailyLogSettingsSchema, req.body || {});- const next = await journal.updateSettings(data);- res.json(next);-}));--/**- * POST /api/brain/daily-log/sync-obsidian- * Re-mirror every existing entry into the currently-configured Obsidian vault.- */-router.post('/daily-log/sync-obsidian', asyncHandler(async (req, res) => {- const stats = await journal.resyncAllToObsidian();- res.json(stats);-}));--/**- * GET /api/brain/daily-log/:date (accepts 'today')- */-router.get('/daily-log/:date', asyncHandler(async (req, res) => {- const date = await resolveJournalDate(req.params.date);- const entry = await journal.getJournal(date);- res.json({ date, entry });-}));--/**- * POST /api/brain/daily-log/:date/append — append a text segment- */-router.post('/daily-log/:date/append', asyncHandler(async (req, res) => {- const date = await resolveJournalDate(req.params.date);- const { text, source } = req.body || {};- // Trim-check here too so a whitespace-only payload doesn't no-op all the- // way through appendJournal() and still return a 200 — clients would read- // that as a successful append.- if (typeof text !== 'string' || text.trim().length === 0) {- throw new ServerError('text is required', { status: 400, code: 'BAD_REQUEST' });- }- const entry = await journal.appendJournal(date, text, { source });- res.json({ date, entry });-}));--/**- * PUT /api/brain/daily-log/:date — full content replace- */-router.put('/daily-log/:date', asyncHandler(async (req, res) => {- const date = await resolveJournalDate(req.params.date);- const { content } = req.body || {};- if (typeof content !== 'string') {- throw new ServerError('content is required', { status: 400, code: 'BAD_REQUEST' });- }- const entry = await journal.setJournalContent(date, content);- res.json({ date, entry });-}));--/**- * DELETE /api/brain/daily-log/:date- */-router.delete('/daily-log/:date', asyncHandler(async (req, res) => {- const date = await resolveJournalDate(req.params.date);- const deleted = await journal.deleteJournal(date);- if (!deleted) {- throw new ServerError('Journal not found', { status: 404, code: 'NOT_FOUND' });- }- res.status(204).send();-}));+router.use(captureRoutes);+router.use(crudRoutes);+router.use(digestRoutes);+router.use(settingsRoutes);+router.use(linkRoutes);+router.use(graphRoutes);+router.use(syncRoutes);+router.use(dailyLogRoutes);export default router;diff --git a/server/routes/brainCapture.js b/server/routes/brainCapture.jsnew file mode 100644index 0000000000..9910dc6966--- /dev/null+++ b/server/routes/brainCapture.js@@ -0,0 +1,135 @@+/**+ * Brain Capture & Inbox Routes+ *+ * Capture/classify thoughts and manage the inbox log (review, fix, retry, done).+ */++import { Router } from 'express';+import * as brainService from '../services/brain.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import {+ captureInputSchema,+ resolveReviewInputSchema,+ fixInputSchema,+ updateInboxInputSchema,+ markInboxSentToCatalogSchema,+ inboxQuerySchema+} from '../lib/brainValidation.js';++const router = Router();++/**+ * POST /api/brain/capture+ * Capture a thought, classify it, and store it+ */+router.post('/capture', asyncHandler(async (req, res) => {+ const { text, providerOverride, modelOverride, creative } = validateRequest(captureInputSchema, req.body);+ const result = await brainService.captureThought(text, providerOverride, modelOverride, { creative });+ res.json(result);+}));++/**+ * GET /api/brain/inbox+ * Get inbox log entries with optional filters+ */+router.get('/inbox', asyncHandler(async (req, res) => {+ const data = validateRequest(inboxQuerySchema, req.query);+ const [entries, counts] = await Promise.all([+ brainService.getInboxLog(data),+ brainService.getInboxLogCounts(),+ ]);+ res.json({ entries, counts });+}));++/**+ * GET /api/brain/inbox/:id+ * Get a single inbox log entry+ */+router.get('/inbox/:id', asyncHandler(async (req, res) => {+ const entry = await brainService.getInboxLogById(req.params.id);+ if (!entry) {+ throw new ServerError('Inbox entry not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(entry);+}));++/**+ * POST /api/brain/review/resolve+ * Resolve a needs_review inbox item+ */+router.post('/review/resolve', asyncHandler(async (req, res) => {+ const { inboxLogId, destination, editedExtracted } = validateRequest(resolveReviewInputSchema, req.body);+ const result = await brainService.resolveReview(inboxLogId, destination, editedExtracted);+ res.json(result);+}));++/**+ * POST /api/brain/fix+ * Fix/correct a filed inbox item+ */+router.post('/fix', asyncHandler(async (req, res) => {+ const { inboxLogId, newDestination, updatedFields, note } = validateRequest(fixInputSchema, req.body);+ const result = await brainService.fixClassification(inboxLogId, newDestination, updatedFields, note);+ res.json(result);+}));++/**+ * POST /api/brain/inbox/:id/retry+ * Retry AI classification for a needs_review item+ */+router.post('/inbox/:id/retry', asyncHandler(async (req, res) => {+ const { providerOverride, modelOverride } = req.body || {};+ const result = await brainService.retryClassification(req.params.id, providerOverride, modelOverride);+ res.json(result);+}));++/**+ * POST /api/brain/inbox/:id/done+ * Mark an inbox entry as done+ */+router.post('/inbox/:id/done', asyncHandler(async (req, res) => {+ const result = await brainService.markInboxDone(req.params.id);+ if (!result) {+ throw new ServerError('Inbox entry not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(result);+}));++/**+ * POST /api/brain/inbox/sent-to-catalog+ * Mark a batch of creative inbox notes as consumed by a committed catalog ingest.+ * Literal path — declared before the `/inbox/:id` routes so it isn't shadowed.+ */+router.post('/inbox/sent-to-catalog', asyncHandler(async (req, res) => {+ const { ids } = validateRequest(markInboxSentToCatalogSchema, req.body);+ const updated = await brainService.markInboxSentToCatalog(ids);+ res.json({ updated, count: updated.length });+}));++/**+ * PUT /api/brain/inbox/:id+ * Update an inbox entry (edit captured text)+ */+router.put('/inbox/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(updateInboxInputSchema, req.body);+ const result = await brainService.updateInboxEntry(req.params.id, data);+ if (!result) {+ throw new ServerError('Inbox entry not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(result);+}));++/**+ * DELETE /api/brain/inbox/:id+ * Delete an inbox entry+ */+router.delete('/inbox/:id', asyncHandler(async (req, res) => {+ const deleted = await brainService.deleteInboxEntry(req.params.id);+ if (!deleted) {+ throw new ServerError('Inbox entry not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));++export default router;diff --git a/server/routes/brainCrud.js b/server/routes/brainCrud.jsnew file mode 100644index 0000000000..266b77116b--- /dev/null+++ b/server/routes/brainCrud.js@@ -0,0 +1,229 @@+/**+ * Brain CRUD Routes+ *+ * Create/read/update/delete for the four brain entity collections+ * (People, Projects, Ideas, Admin) plus standalone Memories.+ */++import { Router } from 'express';+import * as brainService from '../services/brain.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { partialWithoutDefaults } from '../lib/zodCompat.js';+import {+ peopleInputSchema,+ projectInputSchema,+ ideaInputSchema,+ adminInputSchema,+ memoryInputSchema+} from '../lib/brainValidation.js';++const router = Router();++// =============================================================================+// PEOPLE CRUD+// =============================================================================++router.get('/people', asyncHandler(async (req, res) => {+ const people = await brainService.getPeople();+ res.json(people);+}));++router.get('/people/:id', asyncHandler(async (req, res) => {+ const person = await brainService.getPersonById(req.params.id);+ if (!person) {+ throw new ServerError('Person not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(person);+}));++router.post('/people', asyncHandler(async (req, res) => {+ const data = validateRequest(peopleInputSchema, req.body);+ const person = await brainService.createPerson(data);+ res.status(201).json(person);+}));++router.put('/people/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(peopleInputSchema.partial(), req.body);+ const person = await brainService.updatePerson(req.params.id, data);+ if (!person) {+ throw new ServerError('Person not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(person);+}));++router.delete('/people/:id', asyncHandler(async (req, res) => {+ const deleted = await brainService.deletePerson(req.params.id);+ if (!deleted) {+ throw new ServerError('Person not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));++// =============================================================================+// PROJECTS CRUD+// =============================================================================++router.get('/projects', asyncHandler(async (req, res) => {+ const { status } = req.query;+ const filters = status ? { status } : undefined;+ const projects = await brainService.getProjects(filters);+ res.json(projects);+}));++router.get('/projects/:id', asyncHandler(async (req, res) => {+ const project = await brainService.getProjectById(req.params.id);+ if (!project) {+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(project);+}));++router.post('/projects', asyncHandler(async (req, res) => {+ const data = validateRequest(projectInputSchema, req.body);+ const project = await brainService.createProject(data);+ res.status(201).json(project);+}));++router.put('/projects/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(partialWithoutDefaults(projectInputSchema), req.body);+ const project = await brainService.updateProject(req.params.id, data);+ if (!project) {+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(project);+}));++router.delete('/projects/:id', asyncHandler(async (req, res) => {+ const deleted = await brainService.deleteProject(req.params.id);+ if (!deleted) {+ throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));++// =============================================================================+// IDEAS CRUD+// =============================================================================++router.get('/ideas', asyncHandler(async (req, res) => {+ const { status } = req.query;+ const filters = status ? { status } : undefined;+ const ideas = await brainService.getIdeas(filters);+ res.json(ideas);+}));++router.get('/ideas/:id', asyncHandler(async (req, res) => {+ const idea = await brainService.getIdeaById(req.params.id);+ if (!idea) {+ throw new ServerError('Idea not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(idea);+}));++router.post('/ideas', asyncHandler(async (req, res) => {+ const data = validateRequest(ideaInputSchema, req.body);+ const idea = await brainService.createIdea(data);+ res.status(201).json(idea);+}));++router.put('/ideas/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(partialWithoutDefaults(ideaInputSchema), req.body);+ const idea = await brainService.updateIdea(req.params.id, data);+ if (!idea) {+ throw new ServerError('Idea not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(idea);+}));++router.delete('/ideas/:id', asyncHandler(async (req, res) => {+ const deleted = await brainService.deleteIdea(req.params.id);+ if (!deleted) {+ throw new ServerError('Idea not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));++// =============================================================================+// ADMIN CRUD+// =============================================================================++router.get('/admin', asyncHandler(async (req, res) => {+ const { status } = req.query;+ const filters = status ? { status } : undefined;+ const adminItems = await brainService.getAdminItems(filters);+ res.json(adminItems);+}));++router.get('/admin/:id', asyncHandler(async (req, res) => {+ const item = await brainService.getAdminById(req.params.id);+ if (!item) {+ throw new ServerError('Admin item not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(item);+}));++router.post('/admin', asyncHandler(async (req, res) => {+ const data = validateRequest(adminInputSchema, req.body);+ const item = await brainService.createAdminItem(data);+ res.status(201).json(item);+}));++router.put('/admin/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(partialWithoutDefaults(adminInputSchema), req.body);+ const item = await brainService.updateAdminItem(req.params.id, data);+ if (!item) {+ throw new ServerError('Admin item not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(item);+}));++router.delete('/admin/:id', asyncHandler(async (req, res) => {+ const deleted = await brainService.deleteAdminItem(req.params.id);+ if (!deleted) {+ throw new ServerError('Admin item not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));++// =============================================================================+// MEMORIES CRUD+// =============================================================================++router.get('/memories', asyncHandler(async (req, res) => {+ const memories = await brainService.getMemoryEntries();+ res.json(memories);+}));++router.get('/memories/:id', asyncHandler(async (req, res) => {+ const memory = await brainService.getMemoryEntryById(req.params.id);+ if (!memory) {+ throw new ServerError('Memory not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(memory);+}));++router.post('/memories', asyncHandler(async (req, res) => {+ const data = validateRequest(memoryInputSchema, req.body);+ const memory = await brainService.createMemoryEntry(data);+ res.status(201).json(memory);+}));++router.put('/memories/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(memoryInputSchema.partial(), req.body);+ const memory = await brainService.updateMemoryEntry(req.params.id, data);+ if (!memory) {+ throw new ServerError('Memory not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(memory);+}));++router.delete('/memories/:id', asyncHandler(async (req, res) => {+ const deleted = await brainService.deleteMemoryEntry(req.params.id);+ if (!deleted) {+ throw new ServerError('Memory not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));++export default router;diff --git a/server/routes/brainDailyLog.js b/server/routes/brainDailyLog.jsnew file mode 100644index 0000000000..a046af7fe6--- /dev/null+++ b/server/routes/brainDailyLog.js@@ -0,0 +1,126 @@+/**+ * Brain Daily Log Routes+ *+ * Per-day journal entries with optional Obsidian vault mirroring.+ */++import { Router } from 'express';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { dailyLogSettingsSchema } from '../lib/brainValidation.js';+import * as journal from '../services/brainJournal.js';++const router = Router();++// Resolve the :date route param: either 'today' → current local date, or a+// real ISO YYYY-MM-DD calendar day. Delegates to journal.isIsoDate so the+// date rules stay in one place (service layer) and can't drift between+// routes and internal callers.+const resolveJournalDate = async (date) => {+ if (!date || date === 'today') return journal.getToday();+ if (!journal.isIsoDate(date)) {+ throw new ServerError('Invalid date. Expected "today" or YYYY-MM-DD.', {+ status: 400,+ code: 'BAD_REQUEST',+ });+ }+ return date;+};++/**+ * GET /api/brain/daily-log+ * List daily log entries (most recent first)+ */+router.get('/daily-log', asyncHandler(async (req, res) => {+ // Clamp pagination: negative or zero limit / negative offset would slice+ // unpredictably (or from the end of the array). Match the convention used+ // by other paginated brain routes.+ const parsedLimit = parseInt(req.query.limit, 10);+ const parsedOffset = parseInt(req.query.offset, 10);+ const limit = Math.min(Math.max(Number.isNaN(parsedLimit) ? 50 : parsedLimit, 1), 200);+ const offset = Math.max(Number.isNaN(parsedOffset) ? 0 : parsedOffset, 0);+ // Opt-in to full entries; default is slim summaries (date + segmentCount ++ // obsidianPath) so the sidebar doesn't pull every day's content on load.+ const includeContent = req.query.includeContent === '1' || req.query.includeContent === 'true';+ const result = await journal.listJournals({ limit, offset, includeContent });+ res.json(result);+}));++/**+ * GET /api/brain/daily-log/settings+ * Get daily log configuration (obsidian vault/folder, auto-sync)+ */+router.get('/daily-log/settings', asyncHandler(async (req, res) => {+ const settings = await journal.getSettings();+ res.json(settings);+}));++/**+ * PUT /api/brain/daily-log/settings+ */+router.put('/daily-log/settings', asyncHandler(async (req, res) => {+ const data = validateRequest(dailyLogSettingsSchema, req.body || {});+ const next = await journal.updateSettings(data);+ res.json(next);+}));++/**+ * POST /api/brain/daily-log/sync-obsidian+ * Re-mirror every existing entry into the currently-configured Obsidian vault.+ */+router.post('/daily-log/sync-obsidian', asyncHandler(async (req, res) => {+ const stats = await journal.resyncAllToObsidian();+ res.json(stats);+}));++/**+ * GET /api/brain/daily-log/:date (accepts 'today')+ */+router.get('/daily-log/:date', asyncHandler(async (req, res) => {+ const date = await resolveJournalDate(req.params.date);+ const entry = await journal.getJournal(date);+ res.json({ date, entry });+}));++/**+ * POST /api/brain/daily-log/:date/append — append a text segment+ */+router.post('/daily-log/:date/append', asyncHandler(async (req, res) => {+ const date = await resolveJournalDate(req.params.date);+ const { text, source } = req.body || {};+ // Trim-check here too so a whitespace-only payload doesn't no-op all the+ // way through appendJournal() and still return a 200 — clients would read+ // that as a successful append.+ if (typeof text !== 'string' || text.trim().length === 0) {+ throw new ServerError('text is required', { status: 400, code: 'BAD_REQUEST' });+ }+ const entry = await journal.appendJournal(date, text, { source });+ res.json({ date, entry });+}));++/**+ * PUT /api/brain/daily-log/:date — full content replace+ */+router.put('/daily-log/:date', asyncHandler(async (req, res) => {+ const date = await resolveJournalDate(req.params.date);+ const { content } = req.body || {};+ if (typeof content !== 'string') {+ throw new ServerError('content is required', { status: 400, code: 'BAD_REQUEST' });+ }+ const entry = await journal.setJournalContent(date, content);+ res.json({ date, entry });+}));++/**+ * DELETE /api/brain/daily-log/:date+ */+router.delete('/daily-log/:date', asyncHandler(async (req, res) => {+ const date = await resolveJournalDate(req.params.date);+ const deleted = await journal.deleteJournal(date);+ if (!deleted) {+ throw new ServerError('Journal not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));++export default router;diff --git a/server/routes/brainDigest.js b/server/routes/brainDigest.jsnew file mode 100644index 0000000000..4ece4f273d--- /dev/null+++ b/server/routes/brainDigest.js@@ -0,0 +1,71 @@+/**+ * Brain Digest & Review Routes+ *+ * Daily digest and weekly review generation + history.+ */++import { Router } from 'express';+import * as brainService from '../services/brain.js';+import { asyncHandler } from '../lib/errorHandler.js';++const router = Router();++/**+ * GET /api/brain/digest/latest+ * Get the most recent daily digest+ */+router.get('/digest/latest', asyncHandler(async (req, res) => {+ const digest = await brainService.getLatestDigest();+ res.json(digest);+}));++/**+ * GET /api/brain/digests+ * Get digest history+ */+router.get('/digests', asyncHandler(async (req, res) => {+ const limit = parseInt(req.query.limit, 10) || 10;+ const digests = await brainService.getDigests(limit);+ res.json(digests);+}));++/**+ * POST /api/brain/digest/run+ * Manually trigger daily digest generation+ */+router.post('/digest/run', asyncHandler(async (req, res) => {+ const { providerOverride, modelOverride } = req.body || {};+ const digest = await brainService.runDailyDigest(providerOverride, modelOverride);+ res.json(digest);+}));++/**+ * GET /api/brain/review/latest+ * Get the most recent weekly review+ */+router.get('/review/latest', asyncHandler(async (req, res) => {+ const review = await brainService.getLatestReview();+ res.json(review);+}));++/**+ * GET /api/brain/reviews+ * Get review history+ */+router.get('/reviews', asyncHandler(async (req, res) => {+ const limit = parseInt(req.query.limit, 10) || 10;+ const reviews = await brainService.getReviews(limit);+ res.json(reviews);+}));++/**+ * POST /api/brain/review/run+ * Manually trigger weekly review generation+ */+router.post('/review/run', asyncHandler(async (req, res) => {+ const { providerOverride, modelOverride } = req.body || {};+ const review = await brainService.runWeeklyReview(providerOverride, modelOverride);+ res.json(review);+}));++export default router;diff --git a/server/routes/brainGraph.js b/server/routes/brainGraph.jsnew file mode 100644index 0000000000..6fc07caa05--- /dev/null+++ b/server/routes/brainGraph.js@@ -0,0 +1,44 @@+/**+ * Brain Graph Routes+ *+ * Bounded knowledge-graph data for the visualization (search index + overview /+ * focused neighborhood).+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { brainGraphQuerySchema } from '../lib/brainValidation.js';+import {+ getBrainGraphSearchIndex,+ getBrainGraphOverview,+ getBrainGraphNeighborhood+} from '../services/brainGraph.js';++const router = Router();++/**+ * GET /api/brain/graph/search-index+ * Lightweight {id,label,brainType} list of every node, for the client search+ * box. No edges — cheap even at thousands of nodes.+ */+router.get('/graph/search-index', asyncHandler(async (_req, res) => {+ const data = await getBrainGraphSearchIndex();+ res.json(data);+}));++/**+ * GET /api/brain/graph?focus=<id>&limit=<n>+ * Bounded graph data for visualization. No `focus` → an overview of the most-+ * connected nodes; a `focus` → that node's neighborhood. Never the full graph+ * (which crashes the browser at scale).+ */+router.get('/graph', asyncHandler(async (req, res) => {+ const { focus, limit } = validateRequest(brainGraphQuerySchema, req.query);+ const data = focus+ ? await getBrainGraphNeighborhood({ focusId: focus, limit })+ : await getBrainGraphOverview({ limit });+ res.json(data);+}));++export default router;diff --git a/server/routes/brainLinks.js b/server/routes/brainLinks.jsnew file mode 100644index 0000000000..0c4567ca57--- /dev/null+++ b/server/routes/brainLinks.js@@ -0,0 +1,448 @@+/**+ * Brain Links & Buckets Routes+ *+ * Bookmark links (with GitHub clone/pull/scan affordances) and the buckets+ * that group them.+ */++import { Router } from 'express';+import { existsSync } from 'fs';+import * as brainService from '../services/brain.js';+import { openFolderInSystemExplorer } from '../lib/openFolder.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import {+ linkInputSchema,+ linkUpdateInputSchema,+ linkReorderSchema,+ linksQuerySchema,+ bucketInputSchema,+ bucketUpdateInputSchema,+ bucketReorderSchema+} from '../lib/brainValidation.js';+import * as githubCloner from '../services/githubCloner.js';+import { loadSlashdoCommand } from '../services/subAgentSpawner.js';+import * as cos from '../services/cos.js';++const router = Router();++/**+ * Extract a clean hostname from a URL (strip a leading www.), or null if unparseable.+ */+function hostnameFromUrl(url) {+ try {+ return new URL(url).hostname.replace(/^www\./, '');+ } catch {+ return null;+ }+}++/**+ * Clone repo in background and update link record+ */+async function cloneRepoInBackground(linkId, url) {+ // Update status to cloning+ await brainService.updateLink(linkId, { cloneStatus: 'cloning' });++ githubCloner.cloneRepo(url)+ .then(async (result) => {+ await brainService.updateLink(linkId, {+ localPath: result.localPath,+ cloneStatus: 'cloned',+ cloneError: null+ });+ console.log(`✅ Background clone complete: ${linkId}`);+ })+ .catch(async (err) => {+ await brainService.updateLink(linkId, {+ cloneStatus: 'failed',+ cloneError: err.message+ });+ console.error(`❌ Background clone failed: ${linkId} - ${err.message}`);+ });+}++// =============================================================================+// LINKS CRUD+// =============================================================================++/**+ * GET /api/brain/links+ * Get all links with optional filters+ */+router.get('/links', asyncHandler(async (req, res) => {+ const { linkType, isGitHubRepo, limit, offset } = validateRequest(linksQuerySchema, req.query);+ let links = await brainService.getLinks();++ // Apply filters+ if (linkType) {+ links = links.filter(l => l.linkType === linkType);+ }+ if (isGitHubRepo !== undefined) {+ links = links.filter(l => l.isGitHubRepo === isGitHubRepo);+ }++ // Sort by createdAt descending+ links.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));++ // Apply pagination+ const total = links.length;+ links = links.slice(offset, offset + limit);++ res.json({ links, total, limit, offset });+}));++/**+ * POST /api/brain/links/reorder+ * Apply a batch of { id, bucketId, bucketOrder } updates for one drag gesture+ * in a single atomic write — N concurrent single-link PUTs against the shared+ * links store can lose-update each other. Mirrors POST /buckets/reorder.+ * (Registered before /links/:id so "reorder" isn't captured as an :id.)+ */+router.post('/links/reorder', asyncHandler(async (req, res) => {+ const { updates } = validateRequest(linkReorderSchema, req.body);+ // All-or-nothing: reject before any write if a batch references a link that+ // no longer exists, so the response can't report success after a partial+ // apply (mirrors the single-link PUT's 404 on an unknown id).+ const known = new Set((await brainService.getLinks()).map(l => l.id));+ const missing = updates.filter(u => !known.has(u.id)).map(u => u.id);+ if (missing.length) {+ throw new ServerError('Unknown link id in reorder batch', {+ status: 404,+ code: 'NOT_FOUND',+ context: { missing }+ });+ }+ const links = await brainService.reorderLinks(updates);+ res.json({ links });+}));++/**+ * GET /api/brain/links/:id+ * Get a single link by ID+ */+router.get('/links/:id', asyncHandler(async (req, res) => {+ const link = await brainService.getLinkById(req.params.id);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.json(link);+}));++/**+ * POST /api/brain/links+ * Create a new link (quick-add with URL)+ */+router.post('/links', asyncHandler(async (req, res) => {+ const { url, title, description, linkType, tags, bucketId, bucketOrder, autoClone } = validateRequest(linkInputSchema, req.body);++ // Check if URL already exists+ const existing = await brainService.getLinkByUrl(url);+ if (existing) {+ throw new ServerError('Link with this URL already exists', {+ status: 409,+ code: 'DUPLICATE_URL',+ context: { existingId: existing.id }+ });+ }++ // Parse GitHub URL if applicable+ const parsed = githubCloner.parseGitHubUrl(url);+ const isGitHubRepo = !!parsed;++ // Derive a readable default title: repo slug for GitHub, hostname for plain+ // URLs (so quick-added bucket chips read "example.com" instead of the full URL).+ const defaultTitle = parsed+ ? `${parsed.owner}/${parsed.repo}`+ : (hostnameFromUrl(url) || url);++ // Create initial link record+ const linkData = {+ url,+ title: title || defaultTitle,+ description: description || '',+ linkType: linkType || (isGitHubRepo ? 'github' : 'other'),+ tags: tags || [],+ isGitHubRepo,+ gitHubOwner: parsed?.owner,+ gitHubRepo: parsed?.repo,+ localPath: null,+ cloneStatus: isGitHubRepo && autoClone !== false ? 'pending' : 'none',+ cloneError: null,+ ...(bucketId !== undefined ? { bucketId } : {}),+ ...(bucketOrder !== undefined ? { bucketOrder } : {})+ };++ const link = await brainService.createLink(linkData);+ console.log(`🔗 Created link: ${link.id} (${isGitHubRepo ? 'GitHub repo' : 'regular URL'})`);++ // If GitHub repo and auto-clone enabled, start clone in background+ if (isGitHubRepo && autoClone !== false) {+ cloneRepoInBackground(link.id, url).catch(err => {+ console.error(`❌ Background clone setup failed for ${link.id}: ${err.message}`);+ });+ }++ res.status(201).json(link);+}));++/**+ * PUT /api/brain/links/:id+ * Update a link+ */+router.put('/links/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(linkUpdateInputSchema, req.body);++ const existing = await brainService.getLinkById(req.params.id);+ if (!existing) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }++ // When the URL changes, re-derive the GitHub-specific fields so the link+ // type / repo metadata stay consistent with the new target.+ if (data.url && data.url !== existing.url) {+ const duplicate = await brainService.getLinkByUrl(data.url);+ if (duplicate && duplicate.id !== existing.id) {+ throw new ServerError('Link with this URL already exists', {+ status: 409,+ code: 'DUPLICATE_URL',+ context: { existingId: duplicate.id }+ });+ }++ const parsed = githubCloner.parseGitHubUrl(data.url);+ data.isGitHubRepo = !!parsed;+ data.gitHubOwner = parsed?.owner || null;+ data.gitHubRepo = parsed?.repo || null;++ // The previous clone (if any) belongs to the old URL — reset clone state so+ // it doesn't point at the wrong repo. The user can re-clone the new target.+ data.localPath = null;+ data.cloneStatus = 'none';+ data.cloneError = null;+ }++ const link = await brainService.updateLink(req.params.id, data);+ res.json(link);+}));++/**+ * DELETE /api/brain/links/:id+ * Delete a link+ */+router.delete('/links/:id', asyncHandler(async (req, res) => {+ const deleted = await brainService.deleteLink(req.params.id);+ if (!deleted) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));++/**+ * POST /api/brain/links/:id/clone+ * Manually trigger clone for a GitHub repo link+ */+router.post('/links/:id/clone', asyncHandler(async (req, res) => {+ const link = await brainService.getLinkById(req.params.id);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }++ if (!link.isGitHubRepo) {+ throw new ServerError('Link is not a GitHub repository', {+ status: 400,+ code: 'NOT_GITHUB_REPO'+ });+ }++ if (link.cloneStatus === 'cloning') {+ throw new ServerError('Clone already in progress', {+ status: 409,+ code: 'CLONE_IN_PROGRESS'+ });+ }++ // Start clone in background+ cloneRepoInBackground(link.id, link.url);++ res.json({ message: 'Clone started', linkId: link.id });+}));++/**+ * POST /api/brain/links/:id/pull+ * Pull latest changes for a cloned repo+ */+router.post('/links/:id/pull', asyncHandler(async (req, res) => {+ const link = await brainService.getLinkById(req.params.id);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }++ if (!link.isGitHubRepo || !link.localPath) {+ throw new ServerError('Link is not a cloned GitHub repository', {+ status: 400,+ code: 'NOT_CLONED'+ });+ }++ const result = await githubCloner.pullRepo(link.localPath);+ res.json({ message: 'Pull complete', ...result });+}));++/**+ * POST /api/brain/links/:id/open-folder+ * Open the cloned repo folder in the system file manager+ */+router.post('/links/:id/open-folder', asyncHandler(async (req, res) => {+ const link = await brainService.getLinkById(req.params.id);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }++ if (!link.localPath) {+ throw new ServerError('Link has no local folder', {+ status: 400,+ code: 'NO_LOCAL_PATH'+ });+ }++ if (!existsSync(link.localPath)) {+ throw new ServerError('Local folder does not exist', {+ status: 400,+ code: 'PATH_NOT_FOUND'+ });+ }++ openFolderInSystemExplorer(link.localPath);+ res.json({ message: 'Folder opened', path: link.localPath });+}));++/**+ * POST /api/brain/links/:id/scan+ * Queue a read-only malware/risk scan (do:scan) against the cloned repo.+ * Creates a CoS user task whose context inlines the do:scan command body+ * with the repo's localPath baked in as SCAN_DIR. The agent writes its+ * markdown report to ~/.claude/scans/.+ */+router.post('/links/:id/scan', asyncHandler(async (req, res) => {+ const link = await brainService.getLinkById(req.params.id);+ if (!link) {+ throw new ServerError('Link not found', { status: 404, code: 'NOT_FOUND' });+ }+ if (!link.isGitHubRepo || link.cloneStatus !== 'cloned' || !link.localPath) {+ throw new ServerError('Link is not a cloned GitHub repository', {+ status: 400,+ code: 'NOT_CLONED'+ });+ }+ if (!existsSync(link.localPath)) {+ throw new ServerError('Local clone folder does not exist', {+ status: 400,+ code: 'PATH_NOT_FOUND'+ });+ }++ const scanCommand = await loadSlashdoCommand('scan');+ if (!scanCommand) {+ throw new ServerError('Failed to load do:scan command', {+ status: 500,+ code: 'COMMAND_LOAD_FAILED'+ });+ }++ const repoLabel = link.title || link.url;+ const description = `Malware scan: ${repoLabel} (do:scan)`;+ const context = `Run the /do:scan workflow against the cloned repository at: \`${link.localPath}\`++Use that path as SCAN_DIR. Adhere to every Operational Invariant in the command body — this is a hostile-until-proven-safe audit. The full markdown report will be written to ~/.claude/scans/. When complete, summarize the verdict (CLEAN / CAUTION / DANGEROUS) and the top findings in your final response so the report can be surfaced in the UI.++---++${scanCommand}`;++ const result = await cos.addTask(+ { description, context, useWorktree: false, openPR: false, simplify: false, reviewLoop: false },+ 'user'+ );+ if (result?.duplicate) {+ throw new ServerError('A scan for this repo is already pending or in progress', {+ status: 409,+ code: 'DUPLICATE_TASK'+ });+ }++ console.log(`🛡️ Queued malware scan: link=${link.id} path=${link.localPath} task=${result.id}`);+ res.json({ message: 'Scan queued', taskId: result.id, linkId: link.id, scanPath: link.localPath });+}));++// =============================================================================+// BUCKETS (bookmark groups for links)+// =============================================================================++/**+ * GET /api/brain/buckets+ * List buckets sorted by their display order.+ */+router.get('/buckets', asyncHandler(async (req, res) => {+ const buckets = await brainService.getBuckets();+ buckets.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ res.json({ buckets });+}));++/**+ * POST /api/brain/buckets+ * Create a bucket. New buckets are appended after the existing ones.+ */+router.post('/buckets', asyncHandler(async (req, res) => {+ const { name, color, icon } = validateRequest(bucketInputSchema, req.body);+ const bucket = await brainService.createBucketAppended({ name, color, icon });+ console.log(`🗂️ Created bucket: ${bucket.id} (${bucket.name})`);+ res.status(201).json(bucket);+}));++/**+ * POST /api/brain/buckets/reorder+ * Persist a new display order for buckets in a single call.+ * (Registered before /buckets/:id so "reorder" isn't captured as an :id.)+ */+router.post('/buckets/reorder', asyncHandler(async (req, res) => {+ const { ids } = validateRequest(bucketReorderSchema, req.body);+ for (let i = 0; i < ids.length; i++) {+ await brainService.updateBucket(ids[i], { order: i });+ }+ const buckets = await brainService.getBuckets();+ buckets.sort((a, b) => (a.order ?? 0) - (b.order ?? 0));+ res.json({ buckets });+}));++/**+ * PUT /api/brain/buckets/:id+ * Update a bucket's name / color / icon / order.+ */+router.put('/buckets/:id', asyncHandler(async (req, res) => {+ const data = validateRequest(bucketUpdateInputSchema, req.body);+ const existing = await brainService.getBucketById(req.params.id);+ if (!existing) {+ throw new ServerError('Bucket not found', { status: 404, code: 'NOT_FOUND' });+ }+ const bucket = await brainService.updateBucket(req.params.id, data);+ res.json(bucket);+}));++/**+ * DELETE /api/brain/buckets/:id+ * Delete a bucket. Its links survive — they're unassigned (bucketId -> null)+ * so they fall back to the ungrouped list rather than being orphaned.+ */+router.delete('/buckets/:id', asyncHandler(async (req, res) => {+ const existing = await brainService.getBucketById(req.params.id);+ if (!existing) {+ throw new ServerError('Bucket not found', { status: 404, code: 'NOT_FOUND' });+ }++ const result = await brainService.deleteBucketAndUnlinkChildren(req.params.id);+ console.log(`🗂️ Deleted bucket: ${req.params.id} (unassigned ${result.unassigned} links)`);+ res.json(result);+}));++export default router;diff --git a/server/routes/brainSettings.js b/server/routes/brainSettings.jsnew file mode 100644index 0000000000..5708d5adf9--- /dev/null+++ b/server/routes/brainSettings.js@@ -0,0 +1,81 @@+/**+ * Brain Settings & Summary Routes+ *+ * Brain configuration (default provider/model) and the dashboard data summary.+ */++import { Router } from 'express';+import * as brainService from '../services/brain.js';+import { getProviderById } from '../services/providers.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { settingsUpdateInputSchema } from '../lib/brainValidation.js';++const router = Router();++/**+ * GET /api/brain/settings+ * Get brain settings+ */+router.get('/settings', asyncHandler(async (req, res) => {+ const settings = await brainService.loadMeta();+ res.json(settings);+}));++/**+ * PUT /api/brain/settings+ * Update brain settings+ */+router.put('/settings', asyncHandler(async (req, res) => {+ const data = validateRequest(settingsUpdateInputSchema, req.body);++ // Validate provider and model if provided+ if (data.defaultProvider || data.defaultModel) {+ const providerId = data.defaultProvider;+ const modelId = data.defaultModel;++ // Get current settings to use existing provider if only model is being updated+ const currentSettings = await brainService.loadMeta();+ const effectiveProviderId = providerId || currentSettings.defaultProvider;++ // Validate provider exists+ const provider = await getProviderById(effectiveProviderId);+ if (!provider) {+ throw new ServerError(`Provider "${effectiveProviderId}" not found`, {+ status: 400,+ code: 'INVALID_PROVIDER'+ });+ }++ // Validate model exists in provider's models+ if (modelId) {+ if (!provider.models || provider.models.length === 0) {+ throw new ServerError(`Provider "${effectiveProviderId}" has no models configured`, {+ status: 400,+ code: 'NO_MODELS'+ });+ }+ if (!provider.models.includes(modelId)) {+ throw new ServerError(`Model "${modelId}" not found in provider "${effectiveProviderId}"`, {+ status: 400,+ code: 'INVALID_MODEL',+ context: { availableModels: provider.models }+ });+ }+ }+ }++ const settings = await brainService.updateMeta(data);+ res.json(settings);+}));++/**+ * GET /api/brain/summary+ * Get brain data summary for dashboard+ */+router.get('/summary', asyncHandler(async (req, res) => {+ const summary = await brainService.getSummary();+ res.json(summary);+}));++export default router;diff --git a/server/routes/brainSync.js b/server/routes/brainSync.jsnew file mode 100644index 0000000000..5a4d17d329--- /dev/null+++ b/server/routes/brainSync.js@@ -0,0 +1,91 @@+/**+ * Brain Sync (Federation) Routes+ *+ * The CoS memory bridge (embeddings) plus the cross-machine federation delta+ * log and anti-entropy reconcile (checksum + snapshot).+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import {+ brainSyncQuerySchema,+ brainSyncPushSchema,+ brainBridgeSyncSchema+} from '../lib/brainValidation.js';+import { syncAllBrainData, getEmbeddingCoverage } from '../services/brainMemoryBridge.js';+import * as brainSyncLog from '../services/brainSyncLog.js';+import * as brainSync from '../services/brainSync.js';+import * as brainReconcile from '../services/brainReconcile.js';++const router = Router();++/**+ * POST /api/brain/bridge-sync+ * Sync all brain data to CoS memory system (generates embeddings).+ * Body: { refresh?: boolean } — refresh:true re-embeds already-mapped records+ * to heal memory entries that diverged before the per-record sync:applied+ * signal existed (issue #1080).+ * (Renamed from /sync to avoid conflict with federation sync)+ */+router.post('/bridge-sync', asyncHandler(async (req, res) => {+ const { refresh, onlyMissing } = validateRequest(brainBridgeSyncSchema, req.body ?? {});+ const stats = await syncAllBrainData({ refresh, onlyMissing });+ const mode = onlyMissing ? ' (missing-only)' : refresh ? ' (refresh)' : '';+ console.log(`🧠🔗 Brain bridge sync complete${mode}: ${stats.synced} synced, ${stats.skipped} skipped, ${stats.archived} archived, ${stats.errors} errors`);+ res.json(stats);+}));++/**+ * GET /api/brain/embeddings/status+ * How many active brain records lack an embedding — powers the+ * "N missing · Embed missing" affordance on the graph.+ */+router.get('/embeddings/status', asyncHandler(async (_req, res) => {+ const coverage = await getEmbeddingCoverage();+ res.json(coverage);+}));++/**+ * GET /api/brain/sync?since={seq}&limit=100+ * Get brain changes since a given sequence number (for peers to pull)+ */+router.get('/sync', asyncHandler(async (req, res) => {+ const { since, limit } = validateRequest(brainSyncQuerySchema, req.query);+ const result = await brainSyncLog.getChangesSince(since, limit);+ res.json(result);+}));++/**+ * POST /api/brain/sync+ * Receive remote brain changes from a peer+ */+router.post('/sync', asyncHandler(async (req, res) => {+ const { changes } = validateRequest(brainSyncPushSchema, req.body);+ const result = await brainSync.applyRemoteChanges(changes);+ res.json(result);+}));++/**+ * GET /api/brain/reconcile/checksum+ * Anti-entropy checksum over ALL brain records (incl. tombstones) — #1077.+ * A peer fetches this after draining the delta log; on a mismatch it pulls the+ * full snapshot below. Lightweight (one hash) so it's cheap to poll each cycle.+ */+router.get('/reconcile/checksum', asyncHandler(async (req, res) => {+ const checksum = await brainReconcile.getBrainChecksum();+ res.json({ checksum });+}));++/**+ * GET /api/brain/reconcile/snapshot+ * Full brain snapshot (raw record map incl. tombstones + checksum) for a peer+ * to LWW-merge. Brain has no per-record push pipeline, so this is unscoped —+ * the receiver applies it idempotently via applyRemoteRecord.+ */+router.get('/reconcile/snapshot', asyncHandler(async (req, res) => {+ const snapshot = await brainReconcile.getBrainSnapshot();+ res.json(snapshot);+}));++export default router;