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

25.2 KB
Raw Blame
import { composeMaintainerInstructions } from '../lib/persistentMindMaintainer.js';
import mindToolRecipeRoutes from './mindToolRecipeRoutes.js';
import { persistentMindMemoryProtectionSchema } from '../lib/persistentMindMemory.js';
import { getPersistentMindThinkingRequestCatalog, cancelPersistentMindThinkingRequest } from '../services/persistentMindThinkingRequests.js';
/** Persistent Chief-of-Staff mind conversation and lifecycle routes. */

import { Router } from 'express';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { getDomainMode } from '../lib/domainAutonomy.js';
import { PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';
import { MAX_SCREENSHOT_BYTES } from '../lib/uploadLimits.js';
import {
  normalizePersistentMindCapabilities,
  PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,
  PERSISTENT_MIND_CLEANUP_SCOPES,
  PERSISTENT_MIND_TOOL_BOUNDARIES,
  PERSISTENT_MIND_TOOL_CATALOG,
} from '../lib/persistentMindCapabilities.js';
import {
  PERSISTENT_MIND_ID,
  PERSISTENT_MIND_TRAJECTORY_LIMITS,
  parsePersistentMindCursor,
} from '../lib/persistentMindTrajectory.js';
import {
  PERSISTENT_MIND_JOURNAL_KINDS,
  PERSISTENT_MIND_JOURNAL_LIMITS,
  PERSISTENT_MIND_JOURNAL_STATUSES,
  publicPersistentMindJournalEvent,
} from '../lib/persistentMindJournal.js';
import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';
import {
  normalizePersistentMindThinkingPresets,
  persistentMindThinkingPresetSchema,
  persistentMindThinkingSelectionSchema,
} from '../lib/persistentMindThinkingPresets.js';
import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';
import { composePersistentMindInstructions, normalizePersistentMindPlaybook, PERSISTENT_MIND_PLAYBOOK_CATALOG } from '../lib/persistentMindPlaybook.js';
import { resolvePersistentMindPlaybookPhase } from '../services/persistentMindPlaybookSignals.js';
import { publicPersistentMindState } from '../lib/persistentMindPublic.js';
import { publicPersistentMindTurnExecutions } from '../lib/persistentMindTrajectory.js';
import { mindBundleApplySchema, mindBundleExportSchema, mindBundlePreviewSchema, validateRequest } from '../lib/validation.js';
import { readPersistentMindEvents, readPersistentMindHistory } from '../services/agentRunEventLog.js';
import { loadState } from '../services/cosState.js';
import {
  appendPersistentMindAnnotation,
  createPersistentMindMemory,
  preparePersistentMindContext,
  promotePersistentMindMemory,
  readPersistentMindMemories,
  readPersistentMindName,
  readPersistentMindRollups,
  updatePersistentMindMemory,
} from '../services/persistentMindContext.js';
import {
  correctPersistentMindJournalEvent,
  readPersistentMindJournal,
} from '../services/persistentMindJournal.js';
import { getProviderById } from '../services/providers.js';
import { persistentMindHarnessInfo } from '../services/persistentMindAdapter.js';
import { cleanupPersistentMind } from '../services/persistentMindMaintenance.js';
import {
  applyPersistentMindBundle,
  exportPersistentMindBundle,
  previewPersistentMindBundle,
} from '../services/persistentMindBundle.js';
import { resolvePersistentMindImageCapability } from '../services/persistentMindImageCapability.js';

import { inspectPersistentMindRuntime } from '../services/persistentMindRuntime.js';
import { readPersistentMindVisibility } from '../services/persistentMindVisibility.js';
import {
  createPersistentMindAttachment,
  deletePersistentMindAttachment,
} from '../services/persistentMindAttachments.js';
import {
  enqueuePersistentMindMessage,
  getPersistentMindState,
  pausePersistentMind,
  resumePersistentMind,
  startPersistentMind,
  stopPersistentMind,
  wakePersistentMind,
  persistentMindUsageLimitRetryAt,
} from '../services/persistentMindSupervisor.js';

const router = Router();
router.use('/mind/recipes', mindToolRecipeRoutes);

const idempotencyId = z.string().trim().min(1).max(200);
const eventId = z.string().trim().min(1).max(128);
const text = z.string().trim().min(1).max(PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS);
const messageText = z.string().trim().max(PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS).optional();
const attachmentId = z.string()
  .trim()
  .min(1)
  .max(PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_ID_CHARS)
  .regex(/^[A-Za-z0-9_-]+$/, 'invalid attachment id');
const imageReference = z.union([
  attachmentId,
  z.object({ attachmentId }).strict(),
]);
const mindReadSchema = z.object({
  cursor: z.string().max(260).refine((value) => parsePersistentMindCursor(value) !== null, 'Invalid cursor').optional(),
  limit: z.coerce.number().int().positive().max(PERSISTENT_MIND_TRAJECTORY_LIMITS.maxPageSize).optional(),
}).strict();
const visibilityReadSchema = z.object({
  refresh: z.enum(['true', 'false']).transform((value) => value === 'true').optional(),
}).strict();
const messageSchema = z.object({
  id: idempotencyId,
  text: messageText,
  images: z.array(imageReference).max(PERSISTENT_MIND_LIMITS.MAX_MESSAGE_IMAGES).optional(),
  // "Send with another model": one saved preset, for this message's single turn
  // only. Absent, empty, and null all mean the same thing here — the mind's
  // unchanged default route — so a composer that clears its picker does not
  // have to omit the key to say "no override".
  thinkingPresetId: z.union([
    persistentMindThinkingPresetSchema.shape.id,
    z.literal(''),
    z.null(),
  ]).optional(),
  thinkingPreset: persistentMindThinkingSelectionSchema.optional(),
}).strict().superRefine((value, ctx) => {
  if (value.thinkingPreset && value.thinkingPreset.id !== value.thinkingPresetId) {
    ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['thinkingPreset'], message: 'The displayed selection must match thinkingPresetId' });
  }
  const images = Array.isArray(value.images) ? value.images : [];
  const ids = images.map((image) => typeof image === 'string' ? image : image.attachmentId);
  if (!value.text && ids.length === 0) {
    ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['text'], message: 'text or at least one image is required' });
  }
  if (new Set(ids).size !== ids.length) {
    ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['images'], message: 'image references must be unique' });
  }
});
const attachmentUploadSchema = z.object({
  filename: z.string().trim().min(1).max(PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_FILENAME_CHARS),
  data: z.string().min(1).max(Math.ceil(MAX_SCREENSHOT_BYTES * 4 / 3) + 16),
}).strict();
const attachmentParamsSchema = z.object({ attachmentId }).strict();
const annotationSchema = z.object({
  id: idempotencyId,
  text,
  turnId: z.string().trim().min(1).max(128).nullable().optional(),
  targetEventId: eventId.nullable().optional(),
}).strict();
const pauseSchema = z.object({ reason: z.string().trim().min(1).max(PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS).optional() }).strict();
const acknowledgementSchema = z.object({ id: idempotencyId }).strict();
const eventParamsSchema = z.object({ eventId }).strict();
const promotionSchema = z.object({
  id: idempotencyId,
  approved: z.literal(true),
  content: z.string().trim().min(1).max(10_240),
  summary: z.string().trim().max(500).optional(),
  turnId: z.string().trim().min(1).max(128).nullable().optional(),
  type: z.enum(['fact', 'preference', 'pattern', 'insight', 'context']).optional(),
  category: z.string().trim().min(1).max(100).optional(),
  tags: z.array(z.string().trim().min(1).max(100)).max(20).optional(),
}).strict();
const memoryType = z.enum(['fact', 'learning', 'observation', 'decision', 'preference', 'context']);
const memoryFields = {
  protection: persistentMindMemoryProtectionSchema.optional(),
  content: z.string().trim().min(1).max(10_240),
  summary: z.string().trim().max(500).optional(),
  type: memoryType,
  category: z.string().trim().min(1).max(100),
  tags: z.array(z.string().trim().min(1).max(50)).max(20),
  importance: z.number().min(0).max(1),
};
const memoryInputSchema = z.object({
  ...memoryFields,
  type: memoryFields.type.optional().default('observation'),
  category: memoryFields.category.optional().default('other'),
  tags: memoryFields.tags.optional().default([]),
  importance: memoryFields.importance.optional().default(0.5),
}).strict();
const memoryUpdateSchema = z.object(memoryFields).partial().strict().refine(
  (value) => Object.keys(value).length > 0,
  'At least one memory field is required'
);
const memoryParamsSchema = z.object({ memoryId: z.string().trim().min(1).max(128) }).strict();
const journalReadSchema = z.object({
  kind: z.enum(PERSISTENT_MIND_JOURNAL_KINDS).optional(),
  status: z.enum(PERSISTENT_MIND_JOURNAL_STATUSES).optional(),
  limit: z.coerce.number().int().positive().max(PERSISTENT_MIND_JOURNAL_LIMITS.maxPageSize).optional(),
  offset: z.coerce.number().int().nonnegative().optional(),
}).strict();
// Two verbs, not a free status write: the user may settle an entry or retire
// one the mind got wrong. Neither deletes it, and neither can resurrect a
// retired statement — that is the mind's own supersede operation.
const journalCorrectionSchema = z.object({
  action: z.enum(['resolve', 'retire']),
  resolution: z.string().trim().max(PERSISTENT_MIND_JOURNAL_LIMITS.maxResolutionChars).optional(),
}).strict();
const journalParamsSchema = z.object({ journalEventId: z.string().trim().min(1).max(160) }).strict();
const cleanupSchema = z.object({
  scopes: z.array(z.enum(PERSISTENT_MIND_CLEANUP_SCOPES))
    .min(1)
    .max(PERSISTENT_MIND_CLEANUP_SCOPES.length)
    .refine((scopes) => new Set(scopes).size === scopes.length, 'cleanup scopes must be unique'),
  reason: z.string().trim().min(1).max(300).optional(),
  confirmation: z.literal('CLEAR'),
}).strict();

const requireSuccess = (result) => {
  if (result?.success === false) {
    throw new ServerError(result.error || 'Persistent mind request was refused', {
      status: Number.isInteger(result.status) ? result.status : 409,
      code: result.code || 'INVALID_STATE',
    });
  }
  return result;
};

const requireMindEvent = async (targetEventId) => {
  const events = await readPersistentMindHistory(PERSISTENT_MIND_ID);
  if (!events.some((event) => event.eventId === targetEventId)) {
    throw new ServerError('Persistent mind event not found', { status: 404, code: 'NOT_FOUND' });
  }
};

router.get('/mind', asyncHandler(async (req, res) => {
  const query = validateRequest(mindReadSchema, req.query);
  const [history, state, root] = await Promise.all([
    readPersistentMindEvents({ mindId: PERSISTENT_MIND_ID, ...query }),
    getPersistentMindState(),
    loadState(),
  ]);
  const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
  const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);
  const provider = profile.providerId ? await getProviderById(profile.providerId) : null;
  const imageCapability = await resolvePersistentMindImageCapability({ provider, model: profile.model });
  // The full replay projection carries message bodies; only the per-turn
  // execution receipts (route, run ids, elapsed time, outcome, usage) are safe
  // to serve, and they are what answers 'what did this turn actually spend'.
  const { snapshot, ...publicHistory } = history;
  res.json({
    ...publicHistory,
    identity: { mindId: PERSISTENT_MIND_ID, name: await readPersistentMindName(PERSISTENT_MIND_ID) },
    turnExecutions: publicPersistentMindTurnExecutions(snapshot),
    state: publicPersistentMindState(state),
    profile: {
      enabled: profile.enabled,
      providerId: profile.providerId || null,
      model: profile.model || null,
      effort: profile.effort || null,
      thinkingInterface: profile.thinkingInterface,
      wakeIntervalMinutes: profile.wakeIntervalMinutes,
    },
    thinkingRequests: await getPersistentMindThinkingRequestCatalog({ human: true }),
    thinkingPresets: normalizePersistentMindThinkingPresets(root.config?.persistentMindThinkingPresets),
    capabilities,
    harness: persistentMindHarnessInfo(provider),
    imageCapability,
    autonomyMode: getDomainMode(root.config, 'cos'),
  });
}));

router.delete('/mind/thinking-request', asyncHandler(async (_req, res) => {
  res.json(await cancelPersistentMindThinkingRequest());
}));

router.get('/mind/maintainer/watchdog', asyncHandler(async (_req, res) => {
  const { readDevelopmentWatchdogSnapshot } = await import('../services/developmentWatchdog.js');
  res.json(await readDevelopmentWatchdogSnapshot());
}));
router.post('/mind/maintainer/watchdog', asyncHandler(async (req, res) => {
  const request = validateRequest(z.object({ dryRun: z.boolean().optional() }).strict(), req.body || {});
  const { runDevelopmentWatchdog } = await import('../services/developmentWatchdog.js');
  res.json(await runDevelopmentWatchdog({ dryRun: request.dryRun === true, force: true, source: 'manual' }));
}));

router.get('/mind/maintainer', asyncHandler(async (_req, res) => {
  const { describePersistentMindMaintainerSetup } = await import('../services/persistentMindMaintainer.js');
  res.json(await describePersistentMindMaintainerSetup());
}));

router.get('/mind/context', asyncHandler(async (_req, res) => {
  const root = await loadState();
  const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
  const playbook = normalizePersistentMindPlaybook(root.config?.persistentMindPlaybook);
  const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
  const [memories, rollups, provider, playbookPhase] = await Promise.all([
    readPersistentMindMemories(PERSISTENT_MIND_ID),
    readPersistentMindRollups(PERSISTENT_MIND_ID),
    profile.providerId ? getProviderById(profile.providerId) : null,
    // Preview only: the next real wake resolves this itself. Computed here
    // too so the Mind Context panel can show the phase a continuous-play
    // wake would currently pick (#7458).
    playbook.mode === 'continuous-play' ? resolvePersistentMindPlaybookPhase() : null,
  ]);
  const preview = await preparePersistentMindContext({
    mindId: PERSISTENT_MIND_ID,
    identity: prompt.identity,
    instructions: composeMaintainerInstructions(composePersistentMindInstructions(prompt.instructions, playbook, playbookPhase?.phase), root.config?.persistentMindMaintainer),
    memories,
  });
  res.json({
    prompt,
    playbook,
    playbookPhase,
    playbookCatalog: PERSISTENT_MIND_PLAYBOOK_CATALOG,
    preview,
    memories,
    rollups,
    harness: persistentMindHarnessInfo(provider),
  });
}));

router.get('/mind/journal', asyncHandler(async (req, res) => {
  const { limit = PERSISTENT_MIND_JOURNAL_LIMITS.defaultPageSize, offset = 0, ...filters } = validateRequest(journalReadSchema, req.query);
  const events = await readPersistentMindJournal(PERSISTENT_MIND_ID, filters);
  res.json({
    kinds: PERSISTENT_MIND_JOURNAL_KINDS,
    statuses: PERSISTENT_MIND_JOURNAL_STATUSES,
    total: events.length,
    counts: Object.fromEntries(PERSISTENT_MIND_JOURNAL_STATUSES.map((status) => [
      status, events.filter((event) => event.status === status).length,
    ])),
    events: events.slice(offset, offset + limit).map(publicPersistentMindJournalEvent),
  });
}));

router.post('/mind/journal/:journalEventId/correct', asyncHandler(async (req, res) => {
  const { journalEventId } = validateRequest(journalParamsSchema, req.params);
  const input = validateRequest(journalCorrectionSchema, req.body);
  const result = requireSuccess(await correctPersistentMindJournalEvent({
    mindId: PERSISTENT_MIND_ID, eventId: journalEventId, ...input,
  }));
  res.json({ success: true, changed: result.changed, event: publicPersistentMindJournalEvent(result.event) });
}));

// Keep the persistent mind's authority inventory separate from the broader
// onboard-tools registry. Those tools belong to other agent surfaces and are
// not direct capabilities of the persistent mind.
router.get('/mind/tools', asyncHandler(async (_req, res) => {
  const root = await loadState();
  const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);
  const { getCosToolCatalog, readCosToolRecipeCatalog } = await import('../services/cosToolRegistry.js');
  // The allowlist is shared by the task and issue grants, so the page gets ONE
  // roster carrying what each grant needs — `planOnly` for tasks, `forge` for
  // issues, `granted` for both. Loading it per grant would let either editor
  // narrow the list from a partial view and silently revoke the other's apps.
  const managedApps = capabilities.createTasks || capabilities.fileIssues
    ? import('../services/persistentMindManagedApps.js')
      .then(({ readPersistentMindManagedApps }) => readPersistentMindManagedApps())
    : null;
  const [recipes, roster, reportAccess] = await Promise.all([
    readCosToolRecipeCatalog({ scope: 'mind' }),
    managedApps,
    import('../services/persistentMindProcessAudit.js').then(({ readProcessAuditAccess }) => readProcessAuditAccess({ root })),
  ]);
  res.json({
    semanticTools: getCosToolCatalog({ scope: 'mind', capabilities, recipes, reportAccess }).tools,
    schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,
    capabilities,
    boundaries: PERSISTENT_MIND_TOOL_BOUNDARIES,
    // The coding-provider catalog stays on the wake-time task prompt. This
    // settings view configures grants and the allowlist; it does not list
    // every provider, model, and effort. Apps come from the one shared roster.
    taskCatalog: null,
    managedApps: roster && roster.map(({ id, name, planOnly, forge, fullName, granted }) => ({
      id, name, planOnly, forge, fullName, granted,
    })),
    tools: PERSISTENT_MIND_TOOL_CATALOG.map((tool) => ({
      ...tool,
      granted: tool.id === 'reports.audit' ? reportAccess.granted : capabilities[tool.capability] === true,
      ...(tool.id === 'reports.audit' ? { access: reportAccess } : {}),
    })),
  });
}));

router.get('/mind/runtime', asyncHandler(async (_req, res) => {
  const [root, state] = await Promise.all([loadState(), getPersistentMindState()]);
  const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
  const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
  const providerId = state.activeTurn?.providerId || profile.providerId;
  const provider = providerId ? await getProviderById(providerId) : null;
  res.json(await inspectPersistentMindRuntime({
    state, profile, prompt, provider, usageLimitRetryAt: persistentMindUsageLimitRetryAt(),
  }));
}));

router.get('/mind/visibility', asyncHandler(async (req, res) => {
  const { refresh = false } = validateRequest(visibilityReadSchema, req.query);
  const [root, state] = await Promise.all([loadState(), getPersistentMindState()]);
  const prompt = normalizePersistentMindPrompt(root.config?.persistentMindPrompt);
  const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);
  const providerId = state.activeTurn?.providerId || profile.providerId;
  const provider = providerId ? await getProviderById(providerId) : null;
  res.json(await readPersistentMindVisibility({ root, state, profile, prompt, provider, force: refresh }));
}));

router.post('/mind/memories', asyncHandler(async (req, res) => {
  const input = validateRequest(memoryInputSchema, req.body);
  const memory = await createPersistentMindMemory(input);
  res.status(201).json({ success: true, memory });
}));

router.put('/mind/memories/:memoryId', asyncHandler(async (req, res) => {
  const { memoryId } = validateRequest(memoryParamsSchema, req.params);
  const updates = validateRequest(memoryUpdateSchema, req.body);
  const memory = await updatePersistentMindMemory(memoryId, updates);
  if (!memory) throw new ServerError('Persistent mind memory not found', { status: 404, code: 'NOT_FOUND' });
  res.json({ success: true, memory });
}));

router.post('/mind/cleanup', asyncHandler(async (req, res) => {
  const { confirmation: _confirmation, ...input } = validateRequest(cleanupSchema, req.body);
  // A user-initiated cleanup creates a stable boundary: stop inference first so
  // an in-flight turn cannot immediately repopulate state from the old context.
  await stopPersistentMind({ waitForTurn: true });
  const result = await cleanupPersistentMind({ ...input, requestedBy: 'user' });
  const state = await getPersistentMindState();
  res.json({ ...result, state: publicPersistentMindState(state) });
}));

/**
 * Seal the Mind into a downloadable, passphrase-encrypted bundle (#7621).
 *
 * Machine-local and user-initiated: the bytes are streamed straight back to the
 * caller and never written to disk, never logged, and never offered to a peer.
 * The passphrase is used once, inside the sealer, and appears in no log line
 * and no error body (`validateRequest` reports paths, not values).
 */
router.post('/mind/bundle/export', asyncHandler(async (req, res) => {
  const { scopes, passphrase } = validateRequest(mindBundleExportSchema, req.body);
  const { bundle, filename } = await exportPersistentMindBundle({ scopes, passphrase });
  res.setHeader('Content-Type', 'application/octet-stream');
  res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
  // A sealed identity must not sit in a shared/proxy cache on its way to the
  // browser, even though the bytes are encrypted.
  res.setHeader('Cache-Control', 'no-store');
  res.send(bundle);
}));

/**
 * Open a bundle and report what it carries beside what this install holds
 * (#7622). **This route writes nothing** — it is the read that makes the apply
 * below a decision rather than a leap, so it stays free of every side effect.
 * The response is a diff, not a transcript: it is the user's own Mind, shown
 * back to them on their own machine, and it is never logged or offered to a peer.
 */
router.post('/mind/bundle/preview', asyncHandler(async (req, res) => {
  const { bundle, passphrase } = validateRequest(mindBundlePreviewSchema, req.body);
  res.setHeader('Cache-Control', 'no-store');
  res.json(await previewPersistentMindBundle({ text: bundle, passphrase }));
}));

/**
 * Apply a bundle under one whole-group choice per group (#7622). The single
 * write path. The bundle is re-opened here rather than carried over from the
 * preview, so what is applied is what the file says — not a preview payload
 * that made a round trip through the client.
 */
router.post('/mind/bundle/apply', asyncHandler(async (req, res) => {
  const { bundle, passphrase, choices } = validateRequest(mindBundleApplySchema, req.body);
  res.setHeader('Cache-Control', 'no-store');
  res.json(await applyPersistentMindBundle({ text: bundle, passphrase, choices }));
}));

router.post('/mind/attachments', asyncHandler(async (req, res) => {
  const input = validateRequest(attachmentUploadSchema, req.body);
  res.status(201).json(requireSuccess(await createPersistentMindAttachment(input)));
}));

router.delete('/mind/attachments/:attachmentId', asyncHandler(async (req, res) => {
  const { attachmentId: id } = validateRequest(attachmentParamsSchema, req.params);
  res.json(requireSuccess(await deletePersistentMindAttachment(id)));
}));

router.post('/mind/messages', asyncHandler(async (req, res) => {
  const input = validateRequest(messageSchema, req.body);
  res.status(202).json(requireSuccess(await enqueuePersistentMindMessage(input)));
}));

router.post('/mind/annotations', asyncHandler(async (req, res) => {
  const input = validateRequest(annotationSchema, req.body);
  if (input.targetEventId) await requireMindEvent(input.targetEventId);
  const result = await appendPersistentMindAnnotation(input);
  if (result.error) throw new ServerError(result.error, { status: 409, code: 'INVALID_STATE' });
  res.status(202).json({ success: true, duplicate: result.duplicate === true, annotationId: input.id });
}));

router.post('/mind/wake', asyncHandler(async (_req, res) => {
  res.json(requireSuccess(await wakePersistentMind()));
}));

router.post('/mind/start', asyncHandler(async (_req, res) => {
  res.json(requireSuccess(await startPersistentMind()));
}));

router.post('/mind/pause', asyncHandler(async (req, res) => {
  const { reason } = validateRequest(pauseSchema, req.body ?? {});
  const result = requireSuccess(await pausePersistentMind(reason));
  res.json({ success: true, state: publicPersistentMindState(result.state) });
}));

router.post('/mind/resume', asyncHandler(async (_req, res) => {
  res.json(requireSuccess(await resumePersistentMind()));
}));

router.post('/mind/stop', asyncHandler(async (_req, res) => {
  res.json(requireSuccess(await stopPersistentMind()));
}));

router.post('/mind/events/:eventId/acknowledge', asyncHandler(async (req, res) => {
  const { eventId: targetEventId } = validateRequest(eventParamsSchema, req.params);
  const { id } = validateRequest(acknowledgementSchema, req.body);
  await requireMindEvent(targetEventId);
  const result = await appendPersistentMindAnnotation({
    id,
    targetEventId,
    text: 'Acknowledged by user',
  });
  if (result.error) throw new ServerError(result.error, { status: 409, code: 'INVALID_STATE' });
  res.status(202).json({ success: true, duplicate: result.duplicate === true, acknowledgementId: id });
}));

router.post('/mind/events/:eventId/promote', asyncHandler(async (req, res) => {
  const { eventId: sourceEventId } = validateRequest(eventParamsSchema, req.params);
  const input = validateRequest(promotionSchema, req.body);
  await requireMindEvent(sourceEventId);
  const result = requireSuccess(await promotePersistentMindMemory({ ...input, sourceEventId }));
  res.status(201).json({ success: true, memoryId: result.memory?.id || null });
}));

export default router;