Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

50.0 KB
Raw Blame
import { existsSync, readFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import type { ServerResponse } from 'node:http';
import { relative, resolve, sep } from 'node:path';
import type { Hocuspocus } from '@hocuspocus/server';
import {
  canonicalTemplateName,
  EmptyRequestSchema,
  FolderConfigGetSuccessSchema,
  FolderConfigPutRequestSchema,
  FolderConfigPutSuccessSchema,
  type FolderConfigWarningCode,
  instantiateDoc,
  type Principal,
  type ProblemType,
  parseTemplateFile,
  stripFrontmatter,
  TEMPLATE_NAME_REGEX,
  TEMPLATE_NAME_RULE,
  TemplateDeleteSuccessSchema,
  TemplateGetSuccessSchema,
  TemplateImportRequestSchema,
  TemplateImportSuccessSchema,
  TemplateMoveRequestSchema,
  TemplateMoveSuccessSchema,
  TemplatePutRequestSchema,
  TemplatePutSuccessSchema,
  templateContentDocName,
  unwrapFrontmatterFences,
} from '@inkeep/open-knowledge-core';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import type { AgentSessionManager } from '../agent-sessions.ts';
import {
  type AgentWriteFlushOutcome,
  answeredWithSuccessOnAppRoutes,
  outcomeOfSavedWrite,
} from '../agent-write-outcome.ts';
import { composeAndWriteRawBody } from '../bridge-intake.ts';
import { isConfigDoc, isSystemDoc } from '../cc1-broadcast.ts';
import type { ConflictAuthority } from '../conflict-authority.ts';
import { DocInConflictError, respondDocInConflict } from '../conflict-errors.ts';
import type { RemovalLifecycleStatus } from '../conflict-kinds.ts';
import { enrichDirectory } from '../content/enrichment.ts';
import {
  applyFolderFrontmatterPatch,
  type FolderFrontmatterErrorCode,
} from '../content/folder-frontmatter-write.ts';
import {
  applyTemplateDelete,
  applyTemplateMove,
  applyTemplateWrite,
  composeTemplateContent,
  type TemplateFrontmatter,
} from '../content/templates-write.ts';
import type { StoreFailure } from '../document-durability-state.ts';
import { extractActorIdentity } from '../extract-actor-identity.ts';
import type { DiskEvent } from '../file-watcher.ts';
import { assertNoSymlinkEscape, checkSymlinkLeaf, isContainmentRejection } from '../fs-safety.ts';
import { tracedUnlinkSync } from '../fs-traced.ts';
import type { PinoLogger } from '../logger.ts';
import { extractPageTitle } from '../page-identity.ts';
import type { RecentlyRemovedDocs } from '../recently-removed-docs.ts';
import { type ApiRouteGroup, createApiRouteGroup } from './api-pipeline.ts';
import { errorResponse } from './error-response.ts';
import { methodRouter } from './method-router.ts';
import { withValidation } from './request-validation.ts';
import { successResponse } from './success-response.ts';

export interface FolderTemplateRouteDeps {
  contentDir: string;
  projectDir: string | undefined;
  ephemeral: boolean;
  log: PinoLogger;
  hocuspocus: Hocuspocus;
  sessionManager: AgentSessionManager;
  getPrincipal: (() => Principal | null) | undefined;
  signalChannel: ((channel: 'files' | 'lint-config' | 'comments') => void) | undefined;
  conflicts: ConflictAuthority;
  recentlyRemovedDocs: RecentlyRemovedDocs | undefined;
  isSafeDocName: (docName: string) => boolean;
  resolveAlias: (docName: string) => string;
  resolveContentEntryPath: (contentDir: string, kind: 'file' | 'folder', path: string) => string;
  validateFolderRel: (
    raw: string,
    res: ServerResponse,
    label: 'path' | 'folder',
    handler: string,
    components: 'ok' | 'ok-and-templates',
  ) => { folderRel: string; resolvedContentDir: string } | null;
  extractAgentIdentity: (body: Record<string, unknown>) => {
    agentId: string;
    agentName: string;
    colorSeed: string;
    clientName: string | undefined;
  };
  extractActorIdentityFromQuery: (
    url: URL,
    principal: (() => Principal | null) | undefined,
  ) => ReturnType<typeof extractActorIdentity>;
  okArtifactKey: (
    kind: 'template' | 'folder-frontmatter' | 'folder' | 'skill',
    folder: string,
    name?: string,
  ) => string;
  attributeOkArtifactWrite: (
    actor: ReturnType<typeof extractActorIdentity>,
    artifactKey: string,
    subject: string,
    previousPaths?: Array<{ from: string; to: string }>,
  ) => void;
  scheduleOkArtifactFlush: (context: string) => void;
  flushDiskAndDetectOutcome: (docName: string) => Promise<AgentWriteFlushOutcome>;
  markAgentWriteStore: (docName: string) => void;
  respondPersistenceFailure: (res: ServerResponse, failure: StoreFailure, handler: string) => void;
  respondStaleExternalWrite: (res: ServerResponse, handler: string, docName: string) => void;
  registerWrittenDocInFileIndex: (docName: string, content: string) => void;
  captureAndCloseDocuments: (
    docNames: string[],
    lifecycleStatus: RemovalLifecycleStatus,
  ) => Promise<Map<string, string>>;
  captureNamespaceMove?: (docName: string) => () => void;
  renameTrackedPathInGit: (
    projectDir: string | undefined,
    sourcePath: string,
    destinationPath: string,
  ) => Promise<boolean>;
  renamePathOnDisk: (sourcePath: string, destinationPath: string) => void;
  splitContentPath: (path: string) => { parent: string; basename: string };
  mutateFileIndex: ((event: DiskEvent) => void) | undefined;
}

const FOLDER_FRONTMATTER_ERROR_META = {
  BAD_CONTENT_DIR: { status: 400, urn: 'urn:ok:error:invalid-request' },
  PATH_ESCAPE: { status: 400, urn: 'urn:ok:error:path-escape' },
  SYMLINK_REFUSED: { status: 400, urn: 'urn:ok:error:symlink-refused' },
  WRITE_ERROR: { status: 500, urn: 'urn:ok:error:internal-server-error' },
} as const satisfies Record<FolderFrontmatterErrorCode, { status: 400 | 500; urn: ProblemType }>;

export function createFolderTemplateRoutes(deps: FolderTemplateRouteDeps): ApiRouteGroup {
  const {
    contentDir,
    projectDir,
    ephemeral,
    log,
    hocuspocus,
    sessionManager,
    getPrincipal,
    signalChannel,
    conflicts,
    recentlyRemovedDocs,
    isSafeDocName,
    resolveAlias,
    resolveContentEntryPath,
    validateFolderRel,
    extractAgentIdentity,
    extractActorIdentityFromQuery,
    okArtifactKey,
    attributeOkArtifactWrite,
    scheduleOkArtifactFlush,
    flushDiskAndDetectOutcome,
    markAgentWriteStore,
    respondPersistenceFailure,
    respondStaleExternalWrite,
    registerWrittenDocInFileIndex,
    captureAndCloseDocuments,
    captureNamespaceMove,
    renameTrackedPathInGit,
    renamePathOnDisk,
    splitContentPath,
    mutateFileIndex,
  } = deps;

  function validateTemplateName(name: string, res: ServerResponse, handler = 'template'): boolean {
    if (!name || !TEMPLATE_NAME_REGEX.test(name)) {
      errorResponse(
        res,
        400,
        'urn:ok:error:invalid-request',
        `Invalid name: must use ${TEMPLATE_NAME_RULE}, without the \`.md\` extension.`,
        { handler },
      );
      return false;
    }
    return true;
  }

  function findTemplateLeafToRoot(
    resolvedContentDir: string,
    folderRel: string,
    name: string,
  ):
    | { kind: 'found'; abs: string; folder: string; scope: 'local' | 'inherited' }
    | { kind: 'refused'; folder: string }
    | { kind: 'unverifiable'; folder: string; code: string | undefined }
    | { kind: 'absent' } {
    const segments = folderRel === '' ? [] : folderRel.split('/');
    for (let depth = segments.length; depth >= 0; depth--) {
      const ancestorFolder = depth === 0 ? '' : segments.slice(0, depth).join('/');
      const ancestorAbs =
        ancestorFolder === '' ? resolvedContentDir : resolve(resolvedContentDir, ancestorFolder);
      if (
        ancestorAbs !== resolvedContentDir &&
        !ancestorAbs.startsWith(`${resolvedContentDir}${sep}`)
      ) {
        continue;
      }
      /* STOP: identity, not containment — an IN-ROOT symlinked ancestor
         `.ok` / `.ok/templates` realpaths inside the content root and defeats
         every root-anchored check, exactly like the leaf case. The invariant
         is one-directional: this walk must never SERVE what the menu
         (`collectFromFolder` in templates-resolver.ts) hides; refusing more
         than the menu is permitted. A symlink aborts loudly (400). ENOTDIR is
         treated as absent and the walk continues — a non-directory `.ok` or
         `templates` provably holds no templates, matching the menu's skip.
         Every OTHER lstat errno (EACCES/ELOOP) aborts loudly (500): an
         unreadable ancestor COULD hold a shadowing name, so resolving past it
         from a higher folder would be a silent wrong answer. */
      const okAbs = resolve(ancestorAbs, '.ok');
      const okCheck = checkSymlinkLeaf(okAbs);
      if (okCheck.kind === 'symlink') {
        return { kind: 'refused', folder: ancestorFolder };
      }
      if (okCheck.kind === 'unverifiable' && okCheck.code !== 'ENOTDIR') {
        return { kind: 'unverifiable', folder: ancestorFolder, code: okCheck.code };
      }
      const templatesAbs = resolve(okAbs, 'templates');
      const templatesCheck = checkSymlinkLeaf(templatesAbs);
      if (templatesCheck.kind === 'symlink') {
        return { kind: 'refused', folder: ancestorFolder };
      }
      if (templatesCheck.kind === 'unverifiable' && templatesCheck.code !== 'ENOTDIR') {
        return { kind: 'unverifiable', folder: ancestorFolder, code: templatesCheck.code };
      }
      const candidate = resolve(templatesAbs, `${name}.md`);
      if (existsSync(candidate)) {
        return {
          kind: 'found',
          abs: candidate,
          folder: ancestorFolder,
          scope: depth === segments.length ? 'local' : 'inherited',
        };
      }
    }
    return { kind: 'absent' };
  }

  function pickFrontmatterFields(raw: unknown): Record<string, unknown> {
    const out: Record<string, unknown> = {};
    if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out;
    for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
      if (value === undefined) continue;
      out[key] = value;
    }
    return out;
  }

  function templateDocNameFor(folderRel: string, name: string): string {
    return templateContentDocName(folderRel, name);
  }

  const reservedImportTargets = new Set<string>();

  function isTemplateNameTaken(templatesDir: string, name: string): boolean {
    const filePath = resolve(templatesDir, `${name}.md`);
    return reservedImportTargets.has(filePath) || existsSync(filePath);
  }

  const handleFolderConfigGet = withValidation(
    EmptyRequestSchema,
    async (req, res) => {
      try {
        const url = new URL(req.url ?? '', 'http://localhost');
        const validated = validateFolderRel(
          url.searchParams.get('path') ?? '',
          res,
          'path',
          'folder-config-get',
          'ok',
        );
        if (!validated) return;
        const folderOkDir = resolve(validated.resolvedContentDir, validated.folderRel, '.ok');
        const localFmPath = resolve(folderOkDir, 'frontmatter.yml');
        const warnings: string[] = [];
        const warningCodes: FolderConfigWarningCode[] = [];
        const addWarning = (code: FolderConfigWarningCode, text: string): void => {
          warnings.push(text);
          warningCodes.push(code);
        };
        const meta = await enrichDirectory(
          validated.folderRel,
          { projectDir: validated.resolvedContentDir },
          {
            onTemplateRefused: (refusal) => {
              const where = `${refusal.folder || '.'}/${refusal.component}`;
              const path = resolve(validated.resolvedContentDir, refusal.folder, refusal.component);
              switch (refusal.kind) {
                case 'symlink':
                  addWarning(
                    'templates-symlink-refused',
                    `${where} is a symlink — its templates are not enumerated. Replace the symlink with a real file or directory and retry.`,
                  );
                  log.warn(
                    { path, folder: validated.folderRel || '.' },
                    `[folder-config:get] ${where} is a symlink — templates_available skips it.`,
                  );
                  break;
                case 'unverifiable':
                  addWarning(
                    'templates-unverifiable',
                    `${where} could not be inspected (${refusal.code ?? 'unknown errno'}) — its templates are not enumerated. The errno may come from ${refusal.folder || '.'}/.ok itself; check its permissions.`,
                  );
                  log.warn(
                    { path, folder: validated.folderRel || '.', code: refusal.code },
                    `[folder-config:get] cannot lstat ${where} (${refusal.code ?? 'unknown errno'}) — templates_available skips it.`,
                  );
                  break;
                default: {
                  const _exhaustive: never = refusal;
                  throw new Error(
                    `Unhandled template refusal kind in handleFolderConfigGet: ${String((_exhaustive as { kind?: unknown }).kind)}`,
                  );
                }
              }
            },
          },
        );
        let frontmatterLocal: Record<string, unknown> | null = null;
        const leafCheck = checkSymlinkLeaf(localFmPath);
        if (leafCheck.kind === 'symlink') {
          addWarning(
            'symlink-refused',
            `${validated.folderRel || '.'}/.ok/frontmatter.yml is a symlink — refusing to read through it. Replace the symlink with a real file or directory and retry.`,
          );
          log.warn(
            { path: localFmPath, folder: validated.folderRel || '.' },
            `[folder-config:get] ${validated.folderRel || '.'}/.ok/frontmatter.yml is a symlink — refusing to read through it.`,
          );
        } else if (leafCheck.kind === 'unverifiable') {
          addWarning(
            'unverifiable',
            `${validated.folderRel || '.'}/.ok/frontmatter.yml could not be inspected (${leafCheck.code ?? 'unknown errno'}) — folder properties skipped.`,
          );
          log.warn(
            { path: localFmPath, code: leafCheck.code },
            `[folder-config:get] cannot lstat ${localFmPath} (${leafCheck.code ?? 'unknown errno'}) — frontmatter_local skipped.`,
          );
        } else if (existsSync(localFmPath)) {
          try {
            const raw = await readFile(localFmPath, 'utf-8');
            const parsed = parseYaml(raw);
            if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
              frontmatterLocal = parsed as Record<string, unknown>;
            } else {
              frontmatterLocal = {};
            }
          } catch (err) {
            const reason = err instanceof Error ? err.message : String(err);
            addWarning(
              'malformed-yaml',
              `${validated.folderRel || '.'}/.ok/frontmatter.yml has malformed YAML.`,
            );
            log.warn(
              { path: localFmPath, reason },
              `[folder-config:get] malformed YAML in ${localFmPath}: ${reason}`,
            );
            frontmatterLocal = null;
          }
        }

        successResponse(
          res,
          200,
          FolderConfigGetSuccessSchema,
          {
            folder: meta,
            frontmatter_local: frontmatterLocal,
            ...(warningCodes.length > 0 ? { warnings, warningCodes } : {}),
          },
          { handler: 'folder-config-get' },
        );
      } catch (e) {
        errorResponse(
          res,
          500,
          'urn:ok:error:internal-server-error',
          'Failed to read folder config.',
          { handler: 'folder-config-get', cause: e },
        );
      }
    },
    { handler: 'folder-config-get', method: 'GET', skipBodyParse: true },
  );

  const handleFolderConfigPut = withValidation(
    FolderConfigPutRequestSchema,
    async (_req, res, body) => {
      try {
        if (ephemeral) {
          errorResponse(
            res,
            403,
            'urn:ok:error:single-file-mode',
            'Folder configuration is not available in single-file mode.',
            { handler: 'folder-config-put' },
          );
          return;
        }
        const actor = extractActorIdentity(
          body as unknown as Record<string, unknown>,
          getPrincipal,
        );
        if (actor.kind === 'invalid-summary') {
          errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
            handler: 'folder-config-put',
          });
          return;
        }
        const validated = validateFolderRel(body.path, res, 'path', 'folder-config-put', 'ok');
        if (!validated) return;

        const allApplied: Array<{ path: string; action: 'written' | 'deleted' | 'noop' }> = [];
        if (body.frontmatter !== undefined) {
          const result = applyFolderFrontmatterPatch({
            anchorDir: validated.resolvedContentDir,
            folderRel: validated.folderRel,
            patch: body.frontmatter,
          });
          if (!result.ok) {
            const { status, urn } = FOLDER_FRONTMATTER_ERROR_META[result.error.code];
            const title = status === 500 ? 'Failed to write folder config.' : result.error.message;
            errorResponse(res, status, urn, title, {
              handler: 'folder-config-put',
              detail: result.error.code,
              cause: new Error(result.error.message),
            });
            return;
          }
          allApplied.push({ path: result.path, action: result.action });
          if (result.action !== 'noop') {
            attributeOkArtifactWrite(
              actor,
              okArtifactKey('folder-frontmatter', validated.folderRel),
              `folder-frontmatter-${result.action === 'deleted' ? 'delete' : 'edit'}: ${result.path}`,
            );
            scheduleOkArtifactFlush('folder-config-put');
          }
        }

        successResponse(
          res,
          200,
          FolderConfigPutSuccessSchema,
          { applied: allApplied },
          { handler: 'folder-config-put' },
        );
      } catch (e) {
        errorResponse(
          res,
          500,
          'urn:ok:error:internal-server-error',
          'Failed to write folder config.',
          { handler: 'folder-config-put', cause: e },
        );
      }
    },
    { handler: 'folder-config-put', method: 'PUT' },
  );

  const handleFolderConfig = methodRouter(
    { GET: handleFolderConfigGet, PUT: handleFolderConfigPut },
    { handler: 'folder-config' },
  );

  function checkTemplateConflictGate(
    templateDocName: string,
    handler: 'template-put' | 'template-delete' | 'template-move' | 'template-import',
    res: ServerResponse,
  ): boolean {
    const entry = conflicts.findByDocName(templateDocName);
    if (entry !== undefined) {
      respondDocInConflict(res, new DocInConflictError({ file: entry.file }), handler, entry);
      return true;
    }
    return false;
  }

  const handleTemplateGet = withValidation(
    EmptyRequestSchema,
    async (req, res) => {
      try {
        const url = new URL(req.url ?? '', 'http://localhost');
        const name = url.searchParams.get('name') ?? '';
        if (!validateTemplateName(name, res, 'template-get')) return;

        const validated = validateFolderRel(
          url.searchParams.get('folder') ?? '',
          res,
          'folder',
          'template-get',
          'ok-and-templates',
        );
        if (!validated) return;
        const { folderRel, resolvedContentDir } = validated;

        const found = findTemplateLeafToRoot(resolvedContentDir, folderRel, name);
        if (found.kind === 'refused') {
          errorResponse(
            res,
            400,
            'urn:ok:error:symlink-refused',
            `"${found.folder || '.'}/.ok" or its templates directory is a symlink — refusing to resolve templates through it. Replace the symlink with a real file or directory and retry.`,
            { handler: 'template-get', detail: found.folder || '.' },
          );
          return;
        }
        if (found.kind === 'unverifiable') {
          errorResponse(
            res,
            500,
            'urn:ok:error:internal-server-error',
            `Cannot inspect "${found.folder || '.'}/.ok" (${found.code ?? 'unknown errno'}) — refusing to resolve templates through it.`,
            { handler: 'template-get', detail: found.code ?? 'unknown-errno' },
          );
          return;
        }
        if (found.kind === 'absent') {
          errorResponse(res, 404, 'urn:ok:error:template-not-found', 'Template not found.', {
            handler: 'template-get',
            detail: `Template "${name}" not found for folder "${folderRel || '.'}". Walked leaf → root.`,
          });
          return;
        }
        const { abs: foundAbs, folder: foundFolder, scope: foundScope } = found;

        /* STOP: the walk above refuses symlinked ancestor `.ok` /
           `.ok/templates` dirs BY IDENTITY (in-root included); the two checks
           below cover the remaining shapes — a symlinked `<name>.md` leaf,
           and (defence in depth) a resolved path escaping the content root.
           The fetch-by-name arm bypasses the resolver's guarded enumeration
           (`collectFromFolder`), so all three must live here. */
        if (checkSymlinkLeaf(foundAbs).kind === 'symlink') {
          errorResponse(
            res,
            400,
            'urn:ok:error:symlink-refused',
            `Template "${name}" at "${foundFolder || '.'}/.ok/templates/${name}.md" is a symlink — refusing to read through it. Replace the symlink with a real file or directory and retry.`,
            { handler: 'template-get', detail: foundFolder || '.' },
          );
          return;
        }
        try {
          assertNoSymlinkEscape(foundAbs, resolvedContentDir);
        } catch (err) {
          if (isContainmentRejection(err)) {
            errorResponse(
              res,
              400,
              'urn:ok:error:symlink-refused',
              `Template "${name}" resolves through a symlink outside the content directory — refusing to read through it. Replace the symlink with a real file or directory and retry.`,
              { handler: 'template-get', detail: foundFolder || '.' },
            );
            return;
          }
          throw err;
        }

        const raw = await readFile(foundAbs, 'utf-8');
        const model = parseTemplateFile(raw);
        const frontmatter = model.identity as Record<string, unknown>;
        const body = model.starterContent;

        const relPath = relative(resolvedContentDir, foundAbs)
          .split(/[\\/]/)
          .filter(Boolean)
          .join('/');

        successResponse(
          res,
          200,
          TemplateGetSuccessSchema,
          {
            template: {
              name,
              folder: foundFolder,
              scope: foundScope,
              path: relPath,
              frontmatter,
              body,
            },
          },
          { handler: 'template-get' },
        );
      } catch (e) {
        errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to read template.', {
          handler: 'template-get',
          cause: e,
        });
      }
    },
    { handler: 'template-get', method: 'GET', skipBodyParse: true },
  );

  const handleTemplatePut = withValidation(
    TemplatePutRequestSchema,
    async (_req, res, body) => {
      try {
        if (ephemeral) {
          errorResponse(
            res,
            403,
            'urn:ok:error:single-file-mode',
            'Templates are not available in single-file mode.',
            { handler: 'template-put' },
          );
          return;
        }
        const actor = extractActorIdentity(
          body as unknown as Record<string, unknown>,
          getPrincipal,
        );
        if (actor.kind === 'invalid-summary') {
          errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
            handler: 'template-put',
          });
          return;
        }
        const name = body.name;
        if (!validateTemplateName(name, res, 'template-put')) return;
        const validated = validateFolderRel(
          body.folder,
          res,
          'folder',
          'template-put',
          'ok-and-templates',
        );
        if (!validated) return;

        const templateFilePath = resolve(
          validated.resolvedContentDir,
          validated.folderRel,
          '.ok',
          'templates',
          `${name}.md`,
        );
        /* STOP: the persistence plane realpaths this leaf and renames onto
           the TARGET, so a committed in-root symlink here lets a template
           save overwrite any in-root `.md` — including paths the content
           plane refuses to serve (`.claude/`, `.agents/`). The leaf is
           refused on GET; the write arms must refuse it too. */
        if (checkSymlinkLeaf(templateFilePath).kind === 'symlink') {
          errorResponse(
            res,
            400,
            'urn:ok:error:symlink-refused',
            `${validated.folderRel || '.'}/.ok/templates/${name}.md is a symlink — refusing to write through it. Replace the symlink with a real file or directory and retry.`,
            { handler: 'template-put', detail: validated.folderRel || '.' },
          );
          return;
        }

        if (
          checkTemplateConflictGate(
            templateDocNameFor(validated.folderRel, name),
            'template-put',
            res,
          )
        )
          return;

        const composed = composeTemplateContent({
          name,
          body: typeof body.body === 'string' ? body.body : '',
          frontmatter: pickFrontmatterFields(body.frontmatter) satisfies TemplateFrontmatter,
        });
        if (!composed.ok) {
          errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid template request.', {
            handler: 'template-put',
            detail: composed.error.code,
            cause: new Error(composed.error.message),
          });
          return;
        }

        const templateCreated = !existsSync(templateFilePath);
        const templateRelPath = relative(validated.resolvedContentDir, templateFilePath)
          .split(/[\\/]/)
          .filter(Boolean)
          .join('/');
        const templateDocName = templateDocNameFor(validated.folderRel, name);

        const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(
          body as unknown as Record<string, unknown>,
        );
        const templateSession = await sessionManager.getSession(templateDocName, agentId, {
          displayName: agentName,
          colorSeed,
          clientName,
        });
        templateSession.dc.document.transact(() => {
          composeAndWriteRawBody(templateSession.dc.document, composed.content, 'agent');
        }, templateSession.origin);
        markAgentWriteStore(templateDocName);

        const templateFlush = await flushDiskAndDetectOutcome(templateDocName);
        if (
          templateFlush?.kind === 'failure' &&
          !answeredWithSuccessOnAppRoutes(templateFlush.failure)
        ) {
          respondPersistenceFailure(res, templateFlush.failure, 'template-put');
          return;
        }
        if (templateFlush?.kind === 'stale-external-write') {
          respondStaleExternalWrite(res, 'template-put', templateDocName);
          return;
        }

        registerWrittenDocInFileIndex(templateDocName, composed.content);

        attributeOkArtifactWrite(
          actor,
          okArtifactKey('template', validated.folderRel, name),
          `${templateCreated ? 'template-create' : 'template-edit'}: ${templateRelPath}`,
        );
        scheduleOkArtifactFlush('template-put');
        successResponse(
          res,
          200,
          TemplatePutSuccessSchema,
          {
            ...outcomeOfSavedWrite(undefined, templateFlush),
            path: templateRelPath,
            created: templateCreated,
            warnings: composed.warnings,
          },
          { handler: 'template-put' },
        );
      } catch (e) {
        errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to write template.', {
          handler: 'template-put',
          cause: e,
        });
      }
    },
    { handler: 'template-put', method: 'PUT' },
  );

  const handleTemplateDelete = withValidation(
    EmptyRequestSchema,
    async (req, res) => {
      try {
        const url = new URL(req.url ?? '', 'http://localhost');
        const name = url.searchParams.get('name') ?? '';
        if (!validateTemplateName(name, res, 'template-delete')) return;
        const validated = validateFolderRel(
          url.searchParams.get('folder') ?? '',
          res,
          'folder',
          'template-delete',
          'ok-and-templates',
        );
        if (!validated) return;

        const actor = extractActorIdentityFromQuery(url, getPrincipal);
        if (actor.kind === 'invalid-summary') {
          errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
            handler: 'template-delete',
          });
          return;
        }

        if (
          checkTemplateConflictGate(
            templateDocNameFor(validated.folderRel, name),
            'template-delete',
            res,
          )
        )
          return;

        await captureAndCloseDocuments(
          [templateDocNameFor(validated.folderRel, name)],
          'deleted-upstream',
        );

        const deleteInput: Parameters<typeof applyTemplateDelete>[0] = {
          projectDir: validated.resolvedContentDir,
          folder: validated.folderRel,
          name,
        };
        const result = applyTemplateDelete(deleteInput);
        if (!result.ok) {
          const status =
            result.error.code === 'WRITE_ERROR' ||
            result.error.code === 'UNLINK_FAILED' ||
            result.error.code === 'BAD_PROJECT_DIR'
              ? 500
              : 400;
          const urn =
            status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request';
          const title = status === 500 ? 'Failed to delete template.' : 'Invalid template request.';
          errorResponse(res, status, urn, title, {
            handler: 'template-delete',
            detail: result.error.code,
            cause: new Error(result.error.message),
          });
          return;
        }
        if (result.existed) {
          attributeOkArtifactWrite(
            actor,
            okArtifactKey('template', validated.folderRel, name),
            `template-delete: ${result.path}`,
          );
          scheduleOkArtifactFlush('template-delete');
          recentlyRemovedDocs?.setDeleted(templateDocNameFor(validated.folderRel, name));
        }
        successResponse(
          res,
          200,
          TemplateDeleteSuccessSchema,
          { existed: result.existed, path: result.path },
          { handler: 'template-delete' },
        );
      } catch (e) {
        errorResponse(
          res,
          500,
          'urn:ok:error:internal-server-error',
          'Failed to delete template.',
          { handler: 'template-delete', cause: e },
        );
      }
    },
    { handler: 'template-delete', method: 'DELETE', skipBodyParse: true },
  );

  const handleTemplateMove = withValidation(
    TemplateMoveRequestSchema,
    async (_req, res, body) => {
      try {
        const actor = extractActorIdentity(
          body as unknown as Record<string, unknown>,
          getPrincipal,
        );
        if (actor.kind === 'invalid-summary') {
          errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
            handler: 'template-move',
          });
          return;
        }
        if (!validateTemplateName(body.fromName, res, 'template-move')) return;
        if (!validateTemplateName(body.toName, res, 'template-move')) return;
        const fromValidated = validateFolderRel(
          body.fromFolder,
          res,
          'folder',
          'template-move',
          'ok-and-templates',
        );
        if (!fromValidated) return;
        const toValidated = validateFolderRel(
          body.toFolder,
          res,
          'folder',
          'template-move',
          'ok-and-templates',
        );
        if (!toValidated) return;

        if (
          checkTemplateConflictGate(
            templateDocNameFor(fromValidated.folderRel, body.fromName),
            'template-move',
            res,
          )
        ) {
          return;
        }

        await captureAndCloseDocuments(
          [templateDocNameFor(fromValidated.folderRel, body.fromName)],
          'renamed',
        );

        const acceptMove = captureNamespaceMove?.(
          templateDocNameFor(toValidated.folderRel, body.toName),
        );
        const result = await applyTemplateMove({
          projectDir: fromValidated.resolvedContentDir,
          fromFolder: fromValidated.folderRel,
          fromName: body.fromName,
          toFolder: toValidated.folderRel,
          toName: body.toName,
          relocate: async (fromAbs, toAbs) => {
            const movedWithGit = await renameTrackedPathInGit(projectDir, fromAbs, toAbs);
            if (!movedWithGit) renamePathOnDisk(fromAbs, toAbs);
            return movedWithGit;
          },
        });

        if (!result.ok) {
          if (result.error.code === 'TEMPLATE_NOT_FOUND') {
            const found = findTemplateLeafToRoot(
              fromValidated.resolvedContentDir,
              fromValidated.folderRel,
              body.fromName,
            );
            if (found.kind === 'refused') {
              errorResponse(
                res,
                400,
                'urn:ok:error:symlink-refused',
                `"${found.folder || '.'}/.ok" or its templates directory is a symlink — refusing to resolve templates through it. Replace the symlink with a real file or directory and retry.`,
                { handler: 'template-move', detail: found.folder || '.' },
              );
              return;
            }
            if (found.kind === 'unverifiable') {
              errorResponse(
                res,
                500,
                'urn:ok:error:internal-server-error',
                `Cannot inspect "${found.folder || '.'}/.ok" (${found.code ?? 'unknown errno'}) — refusing to resolve templates through it.`,
                { handler: 'template-move', detail: found.code ?? 'unknown-errno' },
              );
              return;
            }
            if (found.kind === 'found' && found.scope === 'inherited') {
              errorResponse(
                res,
                400,
                'urn:ok:error:invalid-request',
                `Template "${body.fromName}" is inherited from "${found.folder || '(root)'}", not local to "${fromValidated.folderRel || '(root)'}". Move it from the folder that owns it, or create a local copy here first (then move that).`,
                { handler: 'template-move', detail: 'TEMPLATE_INHERITED' },
              );
              return;
            }
            errorResponse(res, 404, 'urn:ok:error:template-not-found', 'Template not found.', {
              handler: 'template-move',
              detail: result.error.message,
            });
            return;
          }
          if (result.error.code === 'TEMPLATE_EXISTS') {
            errorResponse(res, 409, 'urn:ok:error:doc-already-exists', result.error.message, {
              handler: 'template-move',
              detail: result.error.code,
            });
            return;
          }
          const status =
            result.error.code === 'WRITE_ERROR' || result.error.code === 'MOVE_FAILED' ? 500 : 400;
          errorResponse(
            res,
            status,
            status === 500 ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
            status === 500 ? 'Failed to move template.' : 'Invalid template move request.',
            {
              handler: 'template-move',
              detail: result.error.code,
              cause: new Error(result.error.message),
            },
          );
          return;
        }

        acceptMove?.();
        recentlyRemovedDocs?.setDeleted(templateDocNameFor(fromValidated.folderRel, body.fromName));

        const movedAbs = resolve(toValidated.resolvedContentDir, result.toPath);
        const movedIsSymlink = checkSymlinkLeaf(movedAbs).kind === 'symlink';

        attributeOkArtifactWrite(
          actor,
          okArtifactKey('template', toValidated.folderRel, body.toName),
          `template-rename: ${result.fromPath} -> ${result.toPath}`,
          [{ from: result.fromPath, to: result.toPath }],
        );
        scheduleOkArtifactFlush('template-move');
        signalChannel?.('files');

        if (movedIsSymlink) {
          log.warn(
            { path: movedAbs, folder: toValidated.folderRel || '.' },
            `[template-move] moved template "${result.toPath}" is a symlink — skipping content read-back and index registration.`,
          );
          if (body.body !== undefined || body.frontmatter !== undefined) {
            errorResponse(
              res,
              400,
              'urn:ok:error:symlink-refused',
              `Template moved to "${result.toPath}", but it is a symlink — refusing to read or rewrite through it. Replace it with a regular file and retry the edit.`,
              { handler: 'template-move', detail: toValidated.folderRel || '.' },
            );
            return;
          }
          successResponse(
            res,
            200,
            TemplateMoveSuccessSchema,
            { from: result.fromPath, to: result.toPath, committed: result.committed },
            { handler: 'template-move' },
          );
          return;
        }

        let contentEditError: { code: string; message: string } | null = null;
        if (body.body !== undefined || body.frontmatter !== undefined) {
          let writeBody: string | null;
          if (typeof body.body === 'string') {
            writeBody = body.body;
          } else {
            try {
              writeBody = instantiateDoc(readFileSync(movedAbs, 'utf-8'));
            } catch {
              writeBody = null;
            }
          }
          if (writeBody === null) {
            contentEditError = {
              code: 'READ_FAILED',
              message:
                'could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit',
            };
          } else {
            const writeResult = applyTemplateWrite({
              projectDir: toValidated.resolvedContentDir,
              folder: toValidated.folderRel,
              name: body.toName,
              body: writeBody,
              frontmatter: pickFrontmatterFields(body.frontmatter) satisfies TemplateFrontmatter,
            });
            if (!writeResult.ok) contentEditError = writeResult.error;
          }
        }

        try {
          registerWrittenDocInFileIndex(
            templateDocNameFor(toValidated.folderRel, body.toName),
            readFileSync(movedAbs, 'utf-8'),
          );
        } catch {}

        if (contentEditError) {
          const isServerError =
            contentEditError.code === 'WRITE_ERROR' || contentEditError.code === 'READ_FAILED';
          errorResponse(
            res,
            isServerError ? 500 : 400,
            isServerError ? 'urn:ok:error:internal-server-error' : 'urn:ok:error:invalid-request',
            `Template moved to "${result.toPath}", but updating its content failed.`,
            {
              handler: 'template-move',
              detail: contentEditError.code,
              cause: new Error(contentEditError.message),
            },
          );
          return;
        }
        successResponse(
          res,
          200,
          TemplateMoveSuccessSchema,
          { from: result.fromPath, to: result.toPath, committed: result.committed },
          { handler: 'template-move' },
        );
      } catch (e) {
        errorResponse(res, 500, 'urn:ok:error:internal-server-error', 'Failed to move template.', {
          handler: 'template-move',
          cause: e,
        });
      }
    },
    { handler: 'template-move', method: 'POST' },
  );

  const handleTemplate = methodRouter(
    {
      GET: handleTemplateGet,
      PUT: handleTemplatePut,
      POST: handleTemplateMove,
      DELETE: handleTemplateDelete,
    },
    { handler: 'template' },
  );

  const handleTemplateImport = withValidation(
    TemplateImportRequestSchema,
    async (_req, res, body) => {
      let reservedTarget: string | undefined;
      try {
        if (ephemeral) {
          errorResponse(
            res,
            403,
            'urn:ok:error:single-file-mode',
            'Templates are not available in single-file mode.',
            { handler: 'template-import' },
          );
          return;
        }

        const actor = extractActorIdentity(
          body as unknown as Record<string, unknown>,
          getPrincipal,
        );
        if (actor.kind === 'invalid-summary') {
          errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Summary must be a string.', {
            handler: 'template-import',
          });
          return;
        }

        const sourcePath = body.sourcePath;
        if (!isSafeDocName(sourcePath)) {
          errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid sourcePath.', {
            handler: 'template-import',
          });
          return;
        }

        const sourceDocName = resolveAlias(sourcePath);
        if (isSystemDoc(sourceDocName) || isConfigDoc(sourceDocName)) {
          errorResponse(
            res,
            400,
            'urn:ok:error:reserved-doc-name',
            `'${sourceDocName}' is a reserved document name.`,
            { handler: 'template-import' },
          );
          return;
        }

        const sourceFilePath = resolveContentEntryPath(contentDir, 'file', sourceDocName);
        if (!existsSync(sourceFilePath)) {
          errorResponse(
            res,
            404,
            'urn:ok:error:doc-not-found',
            `Source document not found: ${sourceDocName}.`,
            {
              handler: 'template-import',
            },
          );
          return;
        }

        const existing = hocuspocus.documents.get(sourceDocName);
        if (body.deleteSource) {
          const sourceConflict = conflicts.findByDocName(sourceDocName);
          if (sourceConflict !== undefined) {
            respondDocInConflict(
              res,
              new DocInConflictError({ file: sourceConflict.file }),
              'template-import',
              sourceConflict,
            );
            return;
          }
        }

        let sourceContent = '';
        if (existing) {
          sourceContent = existing.getText('source').toString();
        } else {
          const dc = await hocuspocus.openDirectConnection(sourceDocName);
          try {
            const document = dc.document;
            if (!document) {
              errorResponse(
                res,
                500,
                'urn:ok:error:doc-not-available',
                'Source document is not available.',
                {
                  handler: 'template-import',
                },
              );
              return;
            }
            sourceContent = document.getText('source').toString();
          } finally {
            await dc.disconnect();
          }
        }

        let name = body.name;
        if (!name) {
          const { basename } = splitContentPath(sourcePath);
          const nameWithoutExt = basename.replace(/\.(md|mdx)$/i, '');
          name = canonicalTemplateName(nameWithoutExt)
            .replace(/[^\p{L}\p{M}\p{N}_-]|\p{DI}/gu, '-')
            .toLowerCase();
          name = name.replace(/^[-_]+|[-_]+$/g, '');
          name ||= 'imported-template';
        }

        if (!validateTemplateName(name, res, 'template-import')) return;

        const validated = validateFolderRel(
          body.targetFolder,
          res,
          'folder',
          'template-import',
          'ok-and-templates',
        );
        if (!validated) return;

        const templatesDir = resolve(
          validated.resolvedContentDir,
          validated.folderRel,
          '.ok',
          'templates',
        );
        if (!body.name) {
          const baseName = name;
          for (let suffix = 2; isTemplateNameTaken(templatesDir, name); suffix++) {
            name = `${baseName}-${suffix}`;
          }
        }

        const templateFilePath = resolve(templatesDir, `${name}.md`);
        if (checkSymlinkLeaf(templateFilePath).kind === 'symlink') {
          errorResponse(
            res,
            400,
            'urn:ok:error:symlink-refused',
            `${validated.folderRel || '.'}/.ok/templates/${name}.md is a symlink — refusing to write through it. Replace the symlink with a real file or directory and retry.`,
            { handler: 'template-import', detail: validated.folderRel || '.' },
          );
          return;
        }

        if (
          checkTemplateConflictGate(
            templateDocNameFor(validated.folderRel, name),
            'template-import',
            res,
          )
        )
          return;

        if (isTemplateNameTaken(templatesDir, name)) {
          errorResponse(
            res,
            409,
            'urn:ok:error:doc-already-exists',
            `Template "${name}" already exists in "${validated.folderRel || '(root)'}". Choose another name, or edit the existing template instead.`,
            { handler: 'template-import', detail: 'TEMPLATE_EXISTS' },
          );
          return;
        }
        reservedImportTargets.add(templateFilePath);
        reservedTarget = templateFilePath;

        const { frontmatter: sourceFmText, body: sourceBody } = stripFrontmatter(sourceContent);
        const cleanFmText = unwrapFrontmatterFences(sourceFmText);
        let sourceFmObj: Record<string, unknown> = {};
        try {
          if (cleanFmText.trim()) {
            sourceFmObj = parseYaml(cleanFmText) as Record<string, unknown>;
          }
        } catch {}

        const templateTitle =
          body.title || (sourceFmObj?.title as string) || extractPageTitle(sourceContent, name);
        const templateDescription = (sourceFmObj?.description as string) || '';
        const templateTags = Array.isArray(sourceFmObj?.tags) ? (sourceFmObj.tags as string[]) : [];

        const starterFmObj = { ...sourceFmObj };
        delete starterFmObj.template;
        delete starterFmObj.title;

        let starterContent = '';
        if (Object.keys(starterFmObj).length > 0) {
          const fmYaml = stringifyYaml(starterFmObj);
          starterContent = `${fmYaml.trim()}\n`;
        }
        starterContent = starterContent ? `---\n${starterContent}---\n${sourceBody}` : sourceBody;

        const composed = composeTemplateContent({
          name,
          body: starterContent,
          frontmatter: {
            title: templateTitle,
            description: templateDescription,
            tags: templateTags,
          },
        });

        if (!composed.ok) {
          errorResponse(res, 400, 'urn:ok:error:invalid-request', 'Invalid template request.', {
            handler: 'template-import',
            detail: composed.error.code,
            cause: new Error(composed.error.message),
          });
          return;
        }

        const templateCreated = !existsSync(templateFilePath);
        const templateRelPath = relative(validated.resolvedContentDir, templateFilePath)
          .split(/[\\/]/)
          .filter(Boolean)
          .join('/');
        const templateDocName = templateDocNameFor(validated.folderRel, name);

        const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(
          body as unknown as Record<string, unknown>,
        );
        const templateSession = await sessionManager.getSession(templateDocName, agentId, {
          displayName: agentName,
          colorSeed,
          clientName,
        });
        templateSession.dc.document.transact(() => {
          composeAndWriteRawBody(templateSession.dc.document, composed.content, 'agent');
        }, templateSession.origin);
        markAgentWriteStore(templateDocName);

        const templateFlush = await flushDiskAndDetectOutcome(templateDocName);
        if (
          templateFlush?.kind === 'failure' &&
          !answeredWithSuccessOnAppRoutes(templateFlush.failure)
        ) {
          respondPersistenceFailure(res, templateFlush.failure, 'template-import');
          return;
        }
        if (templateFlush?.kind === 'stale-external-write') {
          respondStaleExternalWrite(res, 'template-import', templateDocName);
          return;
        }

        registerWrittenDocInFileIndex(templateDocName, composed.content);

        attributeOkArtifactWrite(
          actor,
          okArtifactKey('template', validated.folderRel, name),
          `template-import: ${templateRelPath}`,
        );

        if (body.deleteSource) {
          const deletedDocNames = [sourceDocName];
          await captureAndCloseDocuments(deletedDocNames, 'deleted-upstream');
          if (recentlyRemovedDocs) {
            recentlyRemovedDocs.setDeleted(sourceDocName);
          }
          tracedUnlinkSync(sourceFilePath);
          mutateFileIndex?.({
            kind: 'delete',
            path: sourceFilePath,
            docName: sourceDocName,
          });
        }

        scheduleOkArtifactFlush('template-import');
        signalChannel?.('files');

        successResponse(
          res,
          200,
          TemplateImportSuccessSchema,
          {
            ...outcomeOfSavedWrite(undefined, templateFlush),
            path: templateRelPath,
            created: templateCreated,
            warnings: composed.warnings,
          },
          { handler: 'template-import' },
        );
      } catch (e) {
        errorResponse(
          res,
          500,
          'urn:ok:error:internal-server-error',
          'Failed to import template.',
          {
            handler: 'template-import',
            cause: e,
          },
        );
      } finally {
        if (reservedTarget !== undefined) reservedImportTargets.delete(reservedTarget);
      }
    },
    { handler: 'template-import', method: 'POST' },
  );

  return createApiRouteGroup(
    {
      '/api/folder-config': handleFolderConfig,
      '/api/template': handleTemplate,
      '/api/template/import': handleTemplateImport,
    },
    {
      mutating: ['/api/folder-config', '/api/template', '/api/template/import'],
    },
  );
}