@redaksjon/protokoll 1.0.12 → 1.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{index2.js → configDiscovery.js} +909 -3382
- package/dist/configDiscovery.js.map +1 -0
- package/dist/index.js +3 -31
- package/dist/index.js.map +1 -1
- package/dist/mcp/server-http.js +84 -45
- package/dist/mcp/server-http.js.map +1 -1
- package/dist/mcp/server.js +10 -16
- package/dist/mcp/server.js.map +1 -1
- package/docs/CHANGES_CURSOR_INTEGRATION.md +166 -0
- package/docs/CURSOR_INTEGRATION.md +234 -0
- package/docs/MCP_SERVER_MODES.md +146 -0
- package/docs/QUICK_REFERENCE_AI_ASSISTANTS.md +81 -0
- package/package.json +5 -3
- package/vite.config.ts +6 -5
- package/vitest.config.ts +7 -24
- package/BUG_FIX_CONTEXT_DIRECTORY.md +0 -147
- package/MIGRATION_2025_SUMMARY.md +0 -215
- package/TRANSCRIPT_DATE_CHANGE_IMPLEMENTATION.md +0 -192
- package/VALIDATION_TEST_COVERAGE.md +0 -165
- package/dist/feedback.js +0 -1999
- package/dist/feedback.js.map +0 -1
- package/dist/frontmatter.js +0 -517
- package/dist/frontmatter.js.map +0 -1
- package/dist/index2.js.map +0 -1
- package/dist/scripts/fix-duplicate-delimiters.js +0 -78
- package/dist/scripts/fix-duplicate-delimiters.js.map +0 -1
- package/dist/scripts/migrate-titles-to-frontmatter.js +0 -88
- package/dist/scripts/migrate-titles-to-frontmatter.js.map +0 -1
- package/dist/scripts/migrate-transcripts-2025.js +0 -276
- package/dist/scripts/migrate-transcripts-2025.js.map +0 -1
- package/dist/scripts/verify-migration-2025.js +0 -122
- package/dist/scripts/verify-migration-2025.js.map +0 -1
- package/scripts/fix-duplicate-delimiters.ts +0 -112
- package/scripts/migrate-titles-to-frontmatter.ts +0 -129
- package/scripts/migrate-transcripts-2025.ts +0 -415
- package/scripts/verify-migration-2025.ts +0 -158
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"configDiscovery.js","sources":["../src/mcp/uri.ts","../src/mcp/resources/definitions.ts","../src/constants.ts","../src/context/index.ts","../src/mcp/resources/discovery.ts","../src/mcp/roots.ts","../src/mcp/serverConfig.ts","../src/logging.ts","../src/mcp/tools/shared.ts","../src/mcp/resources/transcriptResources.ts","../src/mcp/resources/entityResources.ts","../src/mcp/resources/audioResources.ts","../src/mcp/resources/configResource.ts","../src/mcp/resources/index.ts","../src/mcp/prompts/index.ts","../src/mcp/tools/discoveryTools.ts","../src/mcp/tools/audioTools.ts","../src/mcp/tools/contextTools.ts","../src/mcp/tools/entityTools.ts","../src/mcp/tools/assistTools.ts","../src/mcp/tools/transcriptTools.ts","../src/mcp/tools/systemTools.ts","../src/mcp/tools/relationshipTools.ts","../src/mcp/tools/contentTools.ts","../src/mcp/tools/statusTools.ts","../src/mcp/tools/index.ts","../src/mcp/configDiscovery.ts"],"sourcesContent":["/**\n * URI Parser for Protokoll MCP Resources\n * \n * Handles parsing and construction of protokoll:// URIs.\n * \n * URI Schemes:\n * - protokoll://transcript/{path}\n * - protokoll://entity/{type}/{id}\n * - protokoll://config/{path}\n * - protokoll://transcripts?directory={dir}&startDate={date}&...\n * - protokoll://entities/{type}\n */\n\nimport type {\n ParsedResourceUri,\n TranscriptUri,\n EntityUri,\n ConfigUri,\n TranscriptsListUri,\n EntitiesListUri,\n AudioInboundUri,\n AudioProcessedUri,\n ResourceType,\n} from './types';\n\nconst SCHEME = 'protokoll';\n\n/**\n * Parse a protokoll:// URI into its components\n */\nexport function parseUri(uri: string): ParsedResourceUri {\n if (!uri.startsWith(`${SCHEME}://`)) {\n throw new Error(`Invalid URI scheme: ${uri}. Expected protokoll://`);\n }\n\n const withoutScheme = uri.substring(`${SCHEME}://`.length);\n const [pathPart, queryPart] = withoutScheme.split('?');\n const segments = pathPart.split('/').filter(s => s.length > 0);\n\n if (segments.length === 0) {\n throw new Error(`Invalid URI: ${uri}. No resource type specified.`);\n }\n\n const firstSegment = segments[0];\n const params = parseQueryParams(queryPart);\n\n switch (firstSegment) {\n case 'transcript':\n return parseTranscriptUri(uri, segments, params);\n case 'entity':\n return parseEntityUri(uri, segments, params);\n case 'config':\n return parseConfigUri(uri, segments, params);\n case 'transcripts':\n case 'transcripts-list':\n return parseTranscriptsListUri(uri, segments, params);\n case 'entities':\n case 'entities-list':\n return parseEntitiesListUri(uri, segments, params);\n case 'audio':\n return parseAudioUri(uri, segments, params);\n default:\n throw new Error(`Unknown resource type: ${firstSegment}`);\n }\n}\n\nfunction parseQueryParams(queryPart?: string): Record<string, string> {\n if (!queryPart) return {};\n \n const params: Record<string, string> = {};\n const pairs = queryPart.split('&');\n \n for (const pair of pairs) {\n const [key, value] = pair.split('=');\n if (key && value !== undefined) {\n params[decodeURIComponent(key)] = decodeURIComponent(value);\n }\n }\n \n return params;\n}\n\nfunction parseTranscriptUri(\n uri: string,\n segments: string[],\n params: Record<string, string>\n): TranscriptUri {\n // protokoll://transcript/path/to/file\n // Note: URIs should NOT include file extensions (.md or .pkl)\n // The server resolves the actual file format automatically\n // \n // Handle both relative and absolute paths\n // If URI has double slash after transcript, it's an absolute path\n const withoutScheme = uri.substring(`${SCHEME}://`.length);\n const [pathPart] = withoutScheme.split('?');\n \n // Check if path starts with transcript/ followed by / (absolute path)\n const transcriptPrefix = 'transcript/';\n let transcriptPath: string;\n \n if (pathPart.startsWith(transcriptPrefix)) {\n // Extract everything after \"transcript/\"\n const afterPrefix = pathPart.substring(transcriptPrefix.length);\n // If it starts with /, it's an absolute path - preserve it\n if (afterPrefix.startsWith('/')) {\n transcriptPath = afterPrefix;\n } else {\n // Relative path - use segments\n transcriptPath = segments.slice(1).join('/');\n }\n } else {\n // Fallback to segments method\n transcriptPath = segments.slice(1).join('/');\n }\n \n if (!transcriptPath) {\n throw new Error(`Invalid transcript URI: ${uri}. No path specified.`);\n }\n\n // Decode the path - the server will resolve the actual file format\n const decodedPath = decodeURIComponent(transcriptPath);\n\n return {\n scheme: SCHEME,\n resourceType: 'transcript',\n path: transcriptPath,\n params,\n transcriptPath: decodedPath,\n };\n}\n\nfunction parseEntityUri(\n uri: string,\n segments: string[],\n params: Record<string, string>\n): EntityUri {\n // protokoll://entity/{type}/{id}\n if (segments.length < 3) {\n throw new Error(`Invalid entity URI: ${uri}. Expected protokoll://entity/{type}/{id}`);\n }\n\n const entityType = segments[1] as EntityUri['entityType'];\n const entityId = segments.slice(2).join('/');\n\n const validTypes = ['person', 'project', 'term', 'company', 'ignored'];\n if (!validTypes.includes(entityType)) {\n throw new Error(`Invalid entity type: ${entityType}. Expected one of: ${validTypes.join(', ')}`);\n }\n\n return {\n scheme: SCHEME,\n resourceType: 'entity',\n path: `${entityType}/${entityId}`,\n params,\n entityType,\n entityId: decodeURIComponent(entityId),\n };\n}\n\nfunction parseConfigUri(\n uri: string,\n segments: string[],\n params: Record<string, string>\n): ConfigUri {\n // protokoll://config/{path}\n const configPath = segments.slice(1).join('/');\n\n return {\n scheme: SCHEME,\n resourceType: 'config',\n path: configPath || '',\n params,\n configPath: configPath ? decodeURIComponent(configPath) : '',\n };\n}\n\nfunction parseTranscriptsListUri(\n uri: string,\n segments: string[],\n params: Record<string, string>\n): TranscriptsListUri {\n // protokoll://transcripts?directory={dir}&startDate={date}&projectId={id}&...\n const directory = params.directory || '';\n\n return {\n scheme: SCHEME,\n resourceType: 'transcripts-list',\n path: segments.slice(1).join('/'),\n params,\n directory,\n startDate: params.startDate,\n endDate: params.endDate,\n limit: params.limit ? parseInt(params.limit, 10) : undefined,\n offset: params.offset ? parseInt(params.offset, 10) : undefined,\n projectId: params.projectId,\n };\n}\n\nfunction parseEntitiesListUri(\n uri: string,\n segments: string[],\n params: Record<string, string>\n): EntitiesListUri {\n // protokoll://entities/{type}\n const entityType = (segments[1] || params.type || 'project') as EntitiesListUri['entityType'];\n\n return {\n scheme: SCHEME,\n resourceType: 'entities-list',\n path: entityType,\n params,\n entityType,\n };\n}\n\nfunction parseAudioUri(\n uri: string,\n segments: string[],\n params: Record<string, string>\n): AudioInboundUri | AudioProcessedUri {\n // protokoll://audio/inbound?directory={dir}\n // protokoll://audio/processed?directory={dir}\n const audioType = segments[1];\n \n if (audioType === 'inbound') {\n return {\n scheme: SCHEME,\n resourceType: 'audio-inbound',\n path: 'audio/inbound',\n params,\n directory: params.directory,\n };\n } else if (audioType === 'processed') {\n return {\n scheme: SCHEME,\n resourceType: 'audio-processed',\n path: 'audio/processed',\n params,\n directory: params.directory,\n };\n }\n \n throw new Error(`Invalid audio URI: ${uri}. Expected protokoll://audio/inbound or protokoll://audio/processed`);\n}\n\n// ============================================================================\n// URI Builders\n// ============================================================================\n\n/**\n * Build a transcript resource URI\n * \n * @param transcriptPath The transcript identifier (should NOT include file extension)\n * e.g., \"2026/1/29-1234-meeting\" not \"2026/1/29-1234-meeting.pkl\"\n * The server resolves the actual file format automatically\n */\nexport function buildTranscriptUri(transcriptPath: string): string {\n const encoded = encodeURIComponent(transcriptPath).replace(/%2F/g, '/');\n return `${SCHEME}://transcript/${encoded}`;\n}\n\n/**\n * Build an entity resource URI\n */\nexport function buildEntityUri(\n entityType: 'person' | 'project' | 'term' | 'company' | 'ignored',\n entityId: string\n): string {\n return `${SCHEME}://entity/${entityType}/${encodeURIComponent(entityId)}`;\n}\n\n/**\n * Build a config resource URI\n */\nexport function buildConfigUri(configPath?: string): string {\n if (configPath) {\n return `${SCHEME}://config/${encodeURIComponent(configPath)}`;\n }\n return `${SCHEME}://config`;\n}\n\n/**\n * Build a transcripts list URI\n */\nexport function buildTranscriptsListUri(options: {\n directory?: string;\n startDate?: string;\n endDate?: string;\n limit?: number;\n offset?: number;\n projectId?: string;\n}): string {\n const params = new URLSearchParams();\n if (options.directory) params.set('directory', options.directory);\n if (options.startDate) params.set('startDate', options.startDate);\n if (options.endDate) params.set('endDate', options.endDate);\n if (options.limit !== undefined) params.set('limit', String(options.limit));\n if (options.offset !== undefined) params.set('offset', String(options.offset));\n if (options.projectId) params.set('projectId', options.projectId);\n \n const queryString = params.toString();\n return queryString ? `${SCHEME}://transcripts?${queryString}` : `${SCHEME}://transcripts`;\n}\n\n/**\n * Build an entities list URI\n */\nexport function buildEntitiesListUri(\n entityType: 'person' | 'project' | 'term' | 'company' | 'ignored'\n): string {\n return `${SCHEME}://entities/${entityType}`;\n}\n\n/**\n * Build an inbound audio list URI\n */\nexport function buildAudioInboundUri(directory?: string): string {\n if (directory) {\n return `${SCHEME}://audio/inbound?directory=${encodeURIComponent(directory)}`;\n }\n return `${SCHEME}://audio/inbound`;\n}\n\n/**\n * Build a processed audio list URI\n */\nexport function buildAudioProcessedUri(directory?: string): string {\n if (directory) {\n return `${SCHEME}://audio/processed?directory=${encodeURIComponent(directory)}`;\n }\n return `${SCHEME}://audio/processed`;\n}\n\n/**\n * Check if a string is a valid Protokoll URI\n */\nexport function isProtokolUri(uri: string): boolean {\n return uri.startsWith(`${SCHEME}://`);\n}\n\n/**\n * Get the resource type from a URI without full parsing\n */\nexport function getResourceType(uri: string): ResourceType | null {\n if (!isProtokolUri(uri)) return null;\n \n const withoutScheme = uri.substring(`${SCHEME}://`.length);\n const segments = withoutScheme.split('/');\n const firstSegment = segments[0].split('?')[0];\n \n if (firstSegment === 'transcripts') return 'transcripts-list';\n if (firstSegment === 'entities') return 'entities-list';\n if (firstSegment === 'audio') {\n const secondSegment = segments[1]?.split('?')[0];\n if (secondSegment === 'inbound') return 'audio-inbound';\n if (secondSegment === 'processed') return 'audio-processed';\n }\n \n return firstSegment as ResourceType;\n}\n","/**\n * Resource Definitions\n * \n * Defines all resource templates and direct resources for the MCP server.\n */\n\nimport type { McpResource, McpResourceTemplate } from '../types';\n\n/**\n * Direct resources that can be listed\n * These are populated dynamically based on context\n */\nexport const directResources: McpResource[] = [\n // Will be populated dynamically based on context\n];\n\n/**\n * Resource templates for parameterized access\n */\nexport const resourceTemplates: McpResourceTemplate[] = [\n {\n uriTemplate: 'protokoll://transcript/{path}',\n name: 'Transcript',\n description: 'A processed transcript file',\n mimeType: 'text/markdown',\n },\n {\n uriTemplate: 'protokoll://entity/{type}/{id}',\n name: 'Context Entity',\n description: 'A context entity (person, project, term, company)',\n mimeType: 'application/yaml',\n },\n {\n uriTemplate: 'protokoll://config',\n name: 'Configuration',\n description: 'Protokoll configuration for a directory',\n mimeType: 'application/json',\n },\n {\n uriTemplate: 'protokoll://transcripts?directory={directory}',\n name: 'Transcripts List',\n description: 'List of transcripts in a directory',\n mimeType: 'application/json',\n },\n {\n uriTemplate: 'protokoll://entities/{type}',\n name: 'Entities List',\n description: 'List of entities of a given type',\n mimeType: 'application/json',\n },\n {\n uriTemplate: 'protokoll://audio/inbound?directory={directory}',\n name: 'Inbound Audio Files',\n description: 'List of audio files waiting to be processed',\n mimeType: 'application/json',\n },\n {\n uriTemplate: 'protokoll://audio/processed?directory={directory}',\n name: 'Processed Audio Files',\n description: 'List of audio files that have been processed',\n mimeType: 'application/json',\n },\n];\n","import os from 'node:os';\nimport { FilenameOption } from '@utilarium/dreadcabinet';\nimport { FilesystemStructure } from '@utilarium/dreadcabinet';\n\nexport const VERSION = '__VERSION__ (__GIT_BRANCH__/__GIT_COMMIT__ __GIT_TAGS__ __GIT_COMMIT_DATE__) __SYSTEM_INFO__';\nexport const PROGRAM_NAME = 'protokoll';\nexport const DEFAULT_CHARACTER_ENCODING = 'utf-8';\nexport const DEFAULT_BINARY_TO_TEXT_ENCODING = 'base64';\nexport const DEFAULT_DIFF = true;\nexport const DEFAULT_LOG = false;\nexport const DEFAULT_TIMEZONE = 'Etc/UTC';\nexport const DATE_FORMAT_MONTH_DAY = 'M-D';\nexport const DATE_FORMAT_YEAR = 'YYYY';\nexport const DATE_FORMAT_YEAR_MONTH = 'YYYY-M';\nexport const DATE_FORMAT_YEAR_MONTH_DAY = 'YYYY-M-D';\nexport const DATE_FORMAT_YEAR_MONTH_DAY_SLASH = 'YYYY/M/D';\nexport const DATE_FORMAT_YEAR_MONTH_DAY_HOURS_MINUTES = 'YYYY-M-D-HHmm';\nexport const DATE_FORMAT_YEAR_MONTH_DAY_HOURS_MINUTES_SECONDS = 'YYYY-M-D-HHmmss';\nexport const DATE_FORMAT_YEAR_MONTH_DAY_HOURS_MINUTES_SECONDS_MILLISECONDS = 'YYYY-M-D-HHmmss.SSS';\nexport const DATE_FORMAT_MONTH = 'M';\nexport const DATE_FORMAT_DAY = 'D';\nexport const DATE_FORMAT_HOURS = 'HHmm';\nexport const DATE_FORMAT_MINUTES = 'mm';\nexport const DATE_FORMAT_SECONDS = 'ss';\nexport const DATE_FORMAT_MILLISECONDS = 'SSS';\nexport const DEFAULT_VERBOSE = false;\nexport const DEFAULT_DRY_RUN = false;\nexport const DEFAULT_DEBUG = false;\nexport const DEFAULT_CONTENT_TYPES = ['diff'];\nexport const DEFAULT_RECURSIVE = false;\nexport const DEFAULT_INPUT_DIRECTORY = './';\nexport const DEFAULT_OUTPUT_DIRECTORY = './';\n\nexport const DEFAULT_AUDIO_EXTENSIONS = ['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm', 'qta'];\n\nexport const ALLOWED_CONTENT_TYPES = ['log', 'diff'];\nexport const ALLOWED_AUDIO_EXTENSIONS = ['mp3', 'mp4', 'mpeg', 'mpga', 'm4a', 'wav', 'webm', 'qta'];\n\nexport const DEFAULT_OUTPUT_STRUCTURE = 'month' as FilesystemStructure;\nexport const DEFAULT_OUTPUT_FILENAME_OPTIONS = ['date', 'time', 'subject'] as FilenameOption[];\n\nexport const ALLOWED_OUTPUT_STRUCTURES = ['none', 'year', 'month', 'day'] as FilesystemStructure[];\nexport const ALLOWED_OUTPUT_FILENAME_OPTIONS = ['date', 'time', 'subject'] as FilenameOption[];\n\nexport const DEFAULT_CONFIG_DIR = `./.${PROGRAM_NAME}`;\nexport const DEFAULT_PROCESSED_DIR = './processed';\n\n// Context System Constants\nexport const DEFAULT_CONTEXT_DIR_NAME = '.protokoll';\nexport const DEFAULT_CONTEXT_NAMESPACE = 'redaksjon';\nexport const DEFAULT_CONTEXT_CONFIG_FILE_NAME = 'config.yaml';\nexport const DEFAULT_MAX_DISCOVERY_LEVELS = 10;\n\nexport const CONTEXT_SUBDIRECTORIES = {\n people: 'people',\n projects: 'projects',\n companies: 'companies',\n terms: 'terms',\n} as const;\n\nexport const DEFAULT_PERSONAS_DIR = `/personas`;\n\nexport const DEFAULT_PERSONA_TRANSCRIBER_FILE = `${DEFAULT_PERSONAS_DIR}/transcriber.md`;\n\nexport const DEFAULT_INSTRUCTIONS_DIR = `/instructions`;\n\nexport const DEFAULT_INSTRUCTIONS_TRANSCRIBE_FILE = `${DEFAULT_INSTRUCTIONS_DIR}/transcribe.md`;\n\n// Note: We no longer maintain a static allowlist of models\n// This allows for dynamic model discovery and future model additions\n// Users can specify any model supported by their OpenAI API\n\nexport const DEFAULT_TRANSCRIPTION_MODEL = 'whisper-1';\nexport const DEFAULT_MODEL = 'gpt-5.2';\nexport const DEFAULT_REASONING_LEVEL = 'medium';\n\n// Smart Assistance Constants\nexport const DEFAULT_PHONETIC_MODEL = 'gpt-5-nano';\nexport const DEFAULT_ANALYSIS_MODEL = 'gpt-5-mini';\nexport const DEFAULT_SMART_ASSISTANCE = true;\n\n// Project-specific smart assistance\nexport const DEFAULT_SOUNDS_LIKE_ON_ADD = true; // Generate phonetic variants\nexport const DEFAULT_TRIGGER_PHRASES_ON_ADD = true; // Generate content-matching phrases\nexport const DEFAULT_PROMPT_FOR_SOURCE = true;\n\n// Term-specific smart assistance\nexport const DEFAULT_TERMS_ENABLED = true;\nexport const DEFAULT_TERM_SOUNDS_LIKE_ON_ADD = true;\nexport const DEFAULT_TERM_DESCRIPTION_ON_ADD = true;\nexport const DEFAULT_TERM_TOPICS_ON_ADD = true;\nexport const DEFAULT_TERM_PROJECT_SUGGESTIONS = true;\n\n// Content limits\nexport const MAX_CONTENT_LENGTH = 15000; // Max characters to send to LLM\nexport const MAX_TERM_CONTEXT_LENGTH = 10000; // Max characters for term context\nexport const ASSIST_TIMEOUT_MS = 30000; // 30 second timeout for LLM calls\nexport const TERM_ASSIST_TIMEOUT_MS = 20000; // 20 second timeout for term LLM calls\n\nexport const DEFAULT_OVERRIDES = false;\nexport const DEFAULT_MAX_AUDIO_SIZE = 26214400; // 25MB in bytes\nexport const DEFAULT_TEMP_DIRECTORY = os.tmpdir(); // Use OS default temp directory\nexport const DEFAULT_INTERACTIVE = true; // Interactive prompts enabled by default\nexport const DEFAULT_SELF_REFLECTION = true;\nexport const DEFAULT_SILENT = false; // Sound notifications enabled by default\n\n// Output Management Constants\nexport const DEFAULT_INTERMEDIATE_DIRECTORY = './output/protokoll';\nexport const DEFAULT_KEEP_INTERMEDIATES = true;\nexport const OUTPUT_FILE_TYPES = [\n 'transcript',\n 'context',\n 'request',\n 'response',\n 'reflection',\n 'session',\n] as const;\n\n// Define Protokoll-specific defaults\nexport const PROTOKOLL_DEFAULTS = {\n dryRun: DEFAULT_DRY_RUN,\n verbose: DEFAULT_VERBOSE,\n debug: DEFAULT_DEBUG,\n diff: DEFAULT_DIFF,\n log: DEFAULT_LOG,\n transcriptionModel: DEFAULT_TRANSCRIPTION_MODEL,\n model: DEFAULT_MODEL,\n reasoningLevel: DEFAULT_REASONING_LEVEL,\n contentTypes: DEFAULT_CONTENT_TYPES,\n overrides: DEFAULT_OVERRIDES,\n maxAudioSize: DEFAULT_MAX_AUDIO_SIZE,\n tempDirectory: DEFAULT_TEMP_DIRECTORY || os.tmpdir(),\n configDirectory: DEFAULT_CONFIG_DIR,\n interactive: DEFAULT_INTERACTIVE,\n selfReflection: DEFAULT_SELF_REFLECTION,\n silent: DEFAULT_SILENT,\n};\n","/**\n * Context System - Protokoll Adapter\n * \n * This module provides protokoll-specific extensions on top of @redaksjon/context runtime.\n * Most functionality is now provided by @redaksjon/context; this module adds:\n * - Smart assistance configuration (LLM model selection, feature flags)\n * - Protokoll-specific defaults\n */\n\nimport { \n create as createContext,\n type ContextInstance as BaseContextInstance,\n type CreateOptions as BaseCreateOptions,\n} from '@redaksjon/context';\nimport {\n DEFAULT_PHONETIC_MODEL,\n DEFAULT_ANALYSIS_MODEL,\n DEFAULT_SMART_ASSISTANCE,\n DEFAULT_SOUNDS_LIKE_ON_ADD,\n DEFAULT_TRIGGER_PHRASES_ON_ADD,\n DEFAULT_PROMPT_FOR_SOURCE,\n DEFAULT_TERMS_ENABLED,\n DEFAULT_TERM_SOUNDS_LIKE_ON_ADD,\n DEFAULT_TERM_DESCRIPTION_ON_ADD,\n DEFAULT_TERM_TOPICS_ON_ADD,\n DEFAULT_TERM_PROJECT_SUGGESTIONS,\n ASSIST_TIMEOUT_MS\n} from '../constants';\nimport type { SmartAssistanceConfig } from './types';\n\n// Re-export base types\nexport type { BaseContextInstance as ContextInstance };\n\n// Use BaseCreateOptions directly (no protokoll-specific extensions needed)\nexport type CreateOptions = BaseCreateOptions;\n\n/**\n * Get smart assistance configuration with defaults\n */\nconst getSmartAssistanceConfig = (config: Record<string, unknown>): SmartAssistanceConfig => {\n const smartConfig = config.smartAssistance as Partial<SmartAssistanceConfig> | undefined;\n \n return {\n enabled: smartConfig?.enabled ?? DEFAULT_SMART_ASSISTANCE,\n phoneticModel: smartConfig?.phoneticModel ?? DEFAULT_PHONETIC_MODEL,\n analysisModel: smartConfig?.analysisModel ?? DEFAULT_ANALYSIS_MODEL,\n \n // Project settings\n soundsLikeOnAdd: smartConfig?.soundsLikeOnAdd ?? DEFAULT_SOUNDS_LIKE_ON_ADD,\n triggerPhrasesOnAdd: smartConfig?.triggerPhrasesOnAdd ?? DEFAULT_TRIGGER_PHRASES_ON_ADD,\n promptForSource: smartConfig?.promptForSource ?? DEFAULT_PROMPT_FOR_SOURCE,\n \n // Term settings\n termsEnabled: smartConfig?.termsEnabled ?? DEFAULT_TERMS_ENABLED,\n termSoundsLikeOnAdd: smartConfig?.termSoundsLikeOnAdd ?? DEFAULT_TERM_SOUNDS_LIKE_ON_ADD,\n termDescriptionOnAdd: smartConfig?.termDescriptionOnAdd ?? DEFAULT_TERM_DESCRIPTION_ON_ADD,\n termTopicsOnAdd: smartConfig?.termTopicsOnAdd ?? DEFAULT_TERM_TOPICS_ON_ADD,\n termProjectSuggestions: smartConfig?.termProjectSuggestions ?? DEFAULT_TERM_PROJECT_SUGGESTIONS,\n \n timeout: smartConfig?.timeout ?? ASSIST_TIMEOUT_MS,\n };\n};\n\n/**\n * Extended ContextInstance with protokoll-specific methods\n */\nexport interface ProtokollContextInstance extends BaseContextInstance {\n getSmartAssistanceConfig(): SmartAssistanceConfig;\n}\n\n/**\n * Create a new context instance with protokoll-specific extensions\n */\nexport const create = async (options: CreateOptions = {}): Promise<ProtokollContextInstance> => {\n const baseInstance = await createContext(options);\n \n return {\n ...baseInstance,\n getSmartAssistanceConfig: () => getSmartAssistanceConfig(baseInstance.getConfig()),\n };\n};\n\n// Re-export types from @redaksjon/context\nexport * from '@redaksjon/context';\n\n// Re-export protokoll-specific types\nexport * from './types';\n\n// Re-export discovery utilities (now from @redaksjon/context)\nexport { discoverConfigDirectories, loadHierarchicalConfig, deepMerge } from '@redaksjon/context';\n","/**\n * Resource Discovery\n * \n * Dynamically discovers available resources based on context.\n */\n\nimport type { McpResource } from '../types';\nimport { \n buildConfigUri, \n buildAudioInboundUri, \n buildAudioProcessedUri,\n buildEntitiesListUri,\n buildTranscriptsListUri,\n} from '../uri';\nimport * as Context from '@/context';\n\n/**\n * Get dynamic resources based on current context\n */\nexport async function getDynamicResources(contextDirectory?: string): Promise<McpResource[]> {\n const resources: McpResource[] = [];\n \n try {\n const context = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n return resources;\n }\n\n const config = context.getConfig();\n const dirs = context.getDiscoveredDirs();\n const configPath = dirs[0]?.path;\n\n // Add config resource\n if (configPath) {\n resources.push({\n uri: buildConfigUri(configPath),\n name: 'Current Configuration',\n description: `Protokoll configuration at ${configPath}`,\n mimeType: 'application/json',\n });\n }\n\n // Add inbound audio resource\n const inputDirectory = (config.inputDirectory as string) || './recordings';\n resources.push({\n uri: buildAudioInboundUri(inputDirectory),\n name: 'Inbound Audio Files',\n description: `Audio files waiting to be processed in ${inputDirectory}`,\n mimeType: 'application/json',\n });\n\n // Add processed audio resource\n const processedDirectory = (config.processedDirectory as string);\n if (processedDirectory) {\n resources.push({\n uri: buildAudioProcessedUri(processedDirectory),\n name: 'Processed Audio Files',\n description: `Audio files that have been processed in ${processedDirectory}`,\n mimeType: 'application/json',\n });\n }\n\n // Add entity list resources\n const entityCounts = {\n projects: context.getAllProjects().length,\n people: context.getAllPeople().length,\n terms: context.getAllTerms().length,\n companies: context.getAllCompanies().length,\n };\n\n if (entityCounts.projects > 0) {\n resources.push({\n uri: buildEntitiesListUri('project'),\n name: 'All Projects',\n description: `${entityCounts.projects} project(s) in context`,\n mimeType: 'application/json',\n });\n }\n\n if (entityCounts.people > 0) {\n resources.push({\n uri: buildEntitiesListUri('person'),\n name: 'All People',\n description: `${entityCounts.people} person/people in context`,\n mimeType: 'application/json',\n });\n }\n\n if (entityCounts.terms > 0) {\n resources.push({\n uri: buildEntitiesListUri('term'),\n name: 'All Terms',\n description: `${entityCounts.terms} term(s) in context`,\n mimeType: 'application/json',\n });\n }\n\n if (entityCounts.companies > 0) {\n resources.push({\n uri: buildEntitiesListUri('company'),\n name: 'All Companies',\n description: `${entityCounts.companies} company/companies in context`,\n mimeType: 'application/json',\n });\n }\n\n // Add output directory transcript list\n const outputDirectory = (config.outputDirectory as string) || '~/notes';\n resources.push({\n uri: buildTranscriptsListUri({ directory: outputDirectory, limit: 10 }),\n name: 'Recent Transcripts',\n description: `10 most recent transcripts in ${outputDirectory}`,\n mimeType: 'application/json',\n });\n\n } catch {\n // Context not available, return empty\n }\n\n return resources;\n}\n","/**\n * MCP Roots Module\n * \n * Enables the server to discover filesystem boundaries exposed by the client.\n * Roots define where the server is allowed to operate.\n * \n * Key behaviors:\n * - Server requests roots via roots/list\n * - Client may notify of changes via notifications/roots/list_changed\n * - All root URIs are file:// URIs\n */\n\nimport type { McpRoot } from './types';\n\n// Cached roots from the client\nlet cachedRoots: McpRoot[] | null = null;\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nlet rootsListChangedSupported = false;\n\n/**\n * Check if the client supports roots\n */\nexport function clientSupportsRoots(clientCapabilities: unknown): {\n supported: boolean;\n listChangedSupported: boolean;\n} {\n const caps = clientCapabilities as Record<string, unknown> | undefined;\n const roots = caps?.roots as Record<string, unknown> | undefined;\n \n if (!roots) {\n return { supported: false, listChangedSupported: false };\n }\n\n return {\n supported: true,\n listChangedSupported: roots.listChanged === true,\n };\n}\n\n/**\n * Store client capabilities for roots\n */\nexport function initializeRoots(clientCapabilities: unknown): void {\n const { listChangedSupported } = clientSupportsRoots(clientCapabilities);\n rootsListChangedSupported = listChangedSupported;\n cachedRoots = null; // Clear cache on init\n}\n\n/**\n * Cache roots received from the client\n */\nexport function setRoots(roots: McpRoot[]): void {\n cachedRoots = roots;\n}\n\n/**\n * Clear cached roots (call when roots/list_changed notification received)\n */\nexport function clearRootsCache(): void {\n cachedRoots = null;\n}\n\n/**\n * Get cached roots (returns null if not yet fetched)\n */\nexport function getCachedRoots(): McpRoot[] | null {\n return cachedRoots;\n}\n\n/**\n * Check if a path is within any of the roots\n */\nexport function isPathWithinRoots(path: string, roots: McpRoot[]): boolean {\n const normalizedPath = normalizePath(path);\n \n for (const root of roots) {\n const rootPath = fileUriToPath(root.uri);\n if (rootPath && normalizedPath.startsWith(normalizePath(rootPath))) {\n return true;\n }\n }\n \n return false;\n}\n\n/**\n * Find which root a path belongs to\n */\nexport function findRootForPath(path: string, roots: McpRoot[]): McpRoot | null {\n const normalizedPath = normalizePath(path);\n \n // Find the most specific (longest) matching root\n let bestMatch: McpRoot | null = null;\n let bestMatchLength = 0;\n \n for (const root of roots) {\n const rootPath = fileUriToPath(root.uri);\n if (rootPath) {\n const normalizedRoot = normalizePath(rootPath);\n if (normalizedPath.startsWith(normalizedRoot) && normalizedRoot.length > bestMatchLength) {\n bestMatch = root;\n bestMatchLength = normalizedRoot.length;\n }\n }\n }\n \n return bestMatch;\n}\n\n/**\n * Convert a file:// URI to a filesystem path\n */\nexport function fileUriToPath(uri: string): string | null {\n if (!uri.startsWith('file://')) {\n return null;\n }\n \n try {\n const url = new URL(uri);\n return decodeURIComponent(url.pathname);\n } catch {\n return null;\n }\n}\n\n/**\n * Convert a filesystem path to a file:// URI\n */\nexport function pathToFileUri(path: string): string {\n // Normalize path separators\n const normalized = path.replace(/\\\\/g, '/');\n \n // Ensure path starts with /\n const withLeadingSlash = normalized.startsWith('/') ? normalized : `/${normalized}`;\n \n return `file://${encodeURIComponent(withLeadingSlash).replace(/%2F/g, '/')}`;\n}\n\n/**\n * Normalize a path for comparison\n */\nfunction normalizePath(path: string): string {\n // Remove trailing slashes, normalize separators\n return path.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n}\n\n/**\n * Get human-readable root names for display\n */\nexport function getRootDisplayNames(roots: McpRoot[]): string[] {\n return roots.map(root => root.name || fileUriToPath(root.uri) || root.uri);\n}\n\n/**\n * Validate that all provided paths are within roots\n * Returns paths that are NOT within roots\n */\nexport function validatePathsAgainstRoots(paths: string[], roots: McpRoot[]): string[] {\n return paths.filter(path => !isPathWithinRoots(path, roots));\n}\n","/**\n * MCP Server Configuration\n * \n * Centralized configuration management for the MCP server.\n * Uses workspace roots to discover and load Protokoll configuration.\n * \n * This eliminates the need for each tool to navigate up the directory tree\n * to find configuration. Instead, configuration is loaded once at the\n * workspace level and shared across all tools.\n */\n\nimport * as Context from '@/context';\nimport type { ContextInstance } from '@/context';\nimport type { McpRoot } from './types';\nimport { fileUriToPath } from './roots';\nimport { resolve } from 'node:path';\nimport * as Cardigantime from '@utilarium/cardigantime';\n\nconst DEFAULT_CONFIG_FILE = 'protokoll-config.yaml';\nconst cardigantime = Cardigantime.create({\n defaults: {\n configDirectory: '.',\n configFile: DEFAULT_CONFIG_FILE,\n isRequired: false,\n // Tell CardiganTime to resolve these path fields relative to the config file's directory\n // Note: contextDirectories must be in BOTH pathFields AND resolvePathArray - \n // pathFields determines which fields are processed, resolvePathArray determines\n // if array elements should be resolved individually\n pathResolution: {\n pathFields: ['inputDirectory', 'outputDirectory', 'processedDirectory', 'contextDirectories'],\n resolvePathArray: ['contextDirectories'],\n },\n },\n configShape: {},\n features: ['config', 'hierarchical'],\n});\n\nasync function readConfigFromDirectory(directory: string): Promise<Record<string, unknown>> {\n const previousCwd = process.cwd();\n try {\n process.chdir(directory);\n return await cardigantime.read({});\n } finally {\n process.chdir(previousCwd);\n }\n}\n\n// ============================================================================\n// Server Configuration State\n// ============================================================================\n\n/**\n * Server mode:\n * - \"remote\": Server is pre-configured with workspace directories (HTTP server).\n * Tools should NOT accept directory parameters - they're already set.\n * - \"local\": Server runs in local mode (stdio). Tools accept directory parameters\n * and perform their own discovery.\n */\nexport type ServerMode = 'remote' | 'local';\n\ninterface ServerConfig {\n mode: ServerMode;\n context: ContextInstance | null;\n workspaceRoot: string | null;\n inputDirectory: string | null;\n outputDirectory: string | null;\n processedDirectory: string | null;\n configFilePath: string | null;\n configFile: Record<string, unknown> | null;\n initialized: boolean;\n}\n\nlet serverConfig: ServerConfig = {\n mode: 'local',\n context: null,\n workspaceRoot: null,\n inputDirectory: null,\n outputDirectory: null,\n processedDirectory: null,\n configFilePath: null,\n configFile: null,\n initialized: false,\n};\n\n// ============================================================================\n// Initialization\n// ============================================================================\n\n/**\n * Initialize server configuration from workspace roots\n * Should be called once when the server starts or when roots change\n * \n * @param roots - Workspace roots (for remote mode)\n * @param mode - Server mode: 'remote' (pre-configured) or 'local' (dynamic discovery)\n */\nexport async function initializeServerConfig(roots: McpRoot[], mode: ServerMode = 'local'): Promise<void> {\n // Find the first workspace root\n const workspaceRoot = roots.length > 0 ? fileUriToPath(roots[0].uri) : null;\n \n if (!workspaceRoot) {\n // No workspace root available - use cwd as fallback\n serverConfig = {\n mode,\n context: null,\n workspaceRoot: process.cwd(),\n inputDirectory: resolve(process.cwd(), './recordings'),\n outputDirectory: resolve(process.cwd(), './notes'),\n processedDirectory: resolve(process.cwd(), './processed'),\n configFilePath: null,\n configFile: null,\n initialized: true,\n };\n return;\n }\n\n try {\n // CardiganTime resolves path fields (inputDirectory, outputDirectory, etc.)\n // relative to the config file's directory automatically via pathResolution config\n const configFile = await readConfigFromDirectory(workspaceRoot);\n const resolvedConfigDirs = (configFile as any).resolvedConfigDirs as unknown;\n const configFilePath = Array.isArray(resolvedConfigDirs) && resolvedConfigDirs.length > 0\n ? resolve(resolvedConfigDirs[0], DEFAULT_CONFIG_FILE)\n : null;\n \n // For defaults (when no config value), use config directory if available\n const configDir = Array.isArray(resolvedConfigDirs) && resolvedConfigDirs.length > 0\n ? resolvedConfigDirs[0]\n : workspaceRoot;\n\n // contextDirectories are resolved by CardiganTime via resolvePathArray config\n const resolvedContextDirs = configFile.contextDirectories as string[] | undefined;\n\n // Load context from workspace root, using explicit contextDirectories if provided\n const context = await Context.create({\n startingDir: workspaceRoot,\n contextDirectories: resolvedContextDirs,\n });\n\n const contextConfig = context.getConfig();\n const mergedConfig = {\n ...contextConfig,\n ...configFile,\n } as Record<string, unknown>;\n \n serverConfig = {\n mode,\n context,\n workspaceRoot,\n // CardiganTime already resolved these paths; just provide defaults if not set\n inputDirectory: (mergedConfig.inputDirectory as string) || resolve(configDir, './recordings'),\n outputDirectory: (mergedConfig.outputDirectory as string) || resolve(configDir, './notes'),\n processedDirectory: (mergedConfig.processedDirectory as string) || resolve(configDir, './processed'),\n configFilePath,\n configFile: configFile ?? null,\n initialized: true,\n };\n } catch {\n // Context not available - use defaults relative to workspace\n const configFile = await readConfigFromDirectory(workspaceRoot);\n const resolvedConfigDirs = (configFile as any).resolvedConfigDirs as unknown;\n const configFilePath = Array.isArray(resolvedConfigDirs) && resolvedConfigDirs.length > 0\n ? resolve(resolvedConfigDirs[0], DEFAULT_CONFIG_FILE)\n : null;\n \n // For defaults (when no config value), use config directory if available\n const configDir = Array.isArray(resolvedConfigDirs) && resolvedConfigDirs.length > 0\n ? resolvedConfigDirs[0]\n : workspaceRoot;\n \n const mergedConfig = (configFile ?? {}) as Record<string, unknown>;\n\n serverConfig = {\n mode,\n context: null,\n workspaceRoot,\n // CardiganTime already resolved these paths; just provide defaults if not set\n inputDirectory: (mergedConfig.inputDirectory as string) || resolve(configDir, './recordings'),\n outputDirectory: (mergedConfig.outputDirectory as string) || resolve(configDir, './notes'),\n processedDirectory: (mergedConfig.processedDirectory as string) || resolve(configDir, './processed'),\n configFilePath,\n configFile: configFile ?? null,\n initialized: true,\n };\n }\n}\n\n/**\n * Reload server configuration (call when roots change)\n */\nexport async function reloadServerConfig(roots: McpRoot[], mode: ServerMode = 'local'): Promise<void> {\n await initializeServerConfig(roots, mode);\n}\n\n/**\n * Clear server configuration\n */\nexport function clearServerConfig(): void {\n serverConfig = {\n mode: 'local',\n context: null,\n workspaceRoot: null,\n inputDirectory: null,\n outputDirectory: null,\n processedDirectory: null,\n configFilePath: null,\n configFile: null,\n initialized: false,\n };\n}\n\n// ============================================================================\n// Accessors\n// ============================================================================\n\n/**\n * Get the server configuration\n * Throws if not initialized\n */\nexport function getServerConfig(): {\n mode: ServerMode;\n context: ContextInstance | null;\n workspaceRoot: string;\n inputDirectory: string;\n outputDirectory: string;\n processedDirectory: string | null;\n configFilePath: string | null;\n configFile: Record<string, unknown> | null;\n initialized: boolean;\n } {\n if (!serverConfig.initialized) {\n throw new Error('Server configuration not initialized. Call initializeServerConfig() first.');\n }\n \n return {\n mode: serverConfig.mode,\n context: serverConfig.context,\n workspaceRoot: serverConfig.workspaceRoot!,\n inputDirectory: serverConfig.inputDirectory!,\n outputDirectory: serverConfig.outputDirectory!,\n processedDirectory: serverConfig.processedDirectory,\n configFilePath: serverConfig.configFilePath,\n configFile: serverConfig.configFile,\n initialized: serverConfig.initialized,\n };\n}\n\n/**\n * Get the context instance\n */\nexport function getContext(): ContextInstance | null {\n return serverConfig.context;\n}\n\n/**\n * Get the workspace root\n */\nexport function getWorkspaceRoot(): string | null {\n return serverConfig.workspaceRoot;\n}\n\n/**\n * Get the input directory (for audio files)\n * Always returns a string, never null\n */\nexport function getInputDirectory(): string {\n if (!serverConfig.initialized || !serverConfig.inputDirectory) {\n return resolve(process.cwd(), './recordings');\n }\n return serverConfig.inputDirectory!;\n}\n\n/**\n * Get the output directory (for transcripts)\n * Always returns a string, never null\n */\nexport function getOutputDirectory(): string {\n if (!serverConfig.initialized || !serverConfig.outputDirectory) {\n return resolve(process.cwd(), './notes');\n }\n return serverConfig.outputDirectory!;\n}\n\n/**\n * Get the processed directory (for processed audio)\n * Returns null if not configured\n */\nexport function getProcessedDirectory(): string | null {\n if (!serverConfig.initialized) {\n return null;\n }\n return serverConfig.processedDirectory;\n}\n\n/**\n * Check if server configuration is initialized\n */\nexport function isInitialized(): boolean {\n return serverConfig.initialized;\n}\n\n/**\n * Get the server mode\n * Returns 'local' if not initialized\n */\nexport function getServerMode(): ServerMode {\n return serverConfig.mode;\n}\n\n/**\n * Check if server is running in remote mode (pre-configured workspace)\n */\nexport function isRemoteMode(): boolean {\n return serverConfig.mode === 'remote';\n}\n\n","import winston from 'winston';\nimport { DATE_FORMAT_YEAR_MONTH_DAY_HOURS_MINUTES_SECONDS, PROGRAM_NAME } from './constants';\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nconst createLogger = (level: string = 'info') => {\n\n let format = winston.format.combine(\n winston.format.timestamp({ format: DATE_FORMAT_YEAR_MONTH_DAY_HOURS_MINUTES_SECONDS }),\n winston.format.errors({ stack: true }),\n winston.format.splat(),\n winston.format.json()\n );\n\n let transports = [\n new winston.transports.Console({\n format: winston.format.combine(\n winston.format.colorize(),\n winston.format.printf(({ timestamp, level, message, ...meta }) => {\n const metaStr = Object.keys(meta).length ? ` ${JSON.stringify(meta)}` : '';\n return `${timestamp} ${level}: ${message}${metaStr}`;\n })\n )\n })\n ];\n\n if (level === 'info') {\n format = winston.format.combine(\n winston.format.errors({ stack: true }),\n winston.format.splat(),\n );\n\n transports = [\n new winston.transports.Console({\n format: winston.format.combine(\n winston.format.colorize(),\n winston.format.printf(({ level, message }) => {\n return `${level}: ${message}`;\n })\n )\n })\n ];\n }\n\n return winston.createLogger({\n level,\n format,\n defaultMeta: { service: PROGRAM_NAME },\n transports,\n });\n};\n\nlet logger = createLogger();\n\nexport const setLogLevel = (level: string) => {\n logger = createLogger(level);\n};\n\nexport const getLogger = () => logger; "," \n/**\n * Shared types, constants, and utilities for MCP tools\n */\nimport { stat } from 'node:fs/promises';\nimport { resolve, relative, isAbsolute } from 'node:path';\nimport { Media, Util as Storage, Transcript } from '@redaksjon/protokoll-engine';\nimport { getLogger } from '@/logging';\n\n// Import transcript utilities\nconst transcriptExists = Transcript.transcriptExists;\nconst ensurePklExtension = Transcript.ensurePklExtension;\n\n/**\n * Check if input looks like a UUID (8+ hex chars)\n * Inlined to avoid import issues\n */\nfunction isUuidInput(input: string): boolean {\n return /^[a-f0-9]{8}/.test(input);\n}\n\n/**\n * Find transcript by UUID\n * Delegates to protokoll-engine\n */\nasync function findTranscriptByUuid(uuid: string, searchDirectories: string[]): Promise<string | null> {\n return Transcript.findTranscriptByUuid(uuid, searchDirectories);\n}\nimport type { Person, Project, Term, Company, IgnoredTerm, Entity } from '@/context/types';\nimport { parseUri, isProtokolUri } from '../uri';\n\n// ============================================================================\n// Shared Utilities\n// ============================================================================\n\nexport const logger = getLogger();\nexport const media = Media.create(logger);\nexport const storage = Storage.create({ log: logger.debug.bind(logger) });\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface ProcessingResult {\n outputPath: string;\n enhancedText: string;\n rawTranscript: string;\n routedProject?: string;\n routingConfidence: number;\n processingTime: number;\n toolsUsed: string[];\n correctionsApplied: number;\n}\n\nexport interface DiscoveredConfig {\n path: string;\n projectCount: number;\n peopleCount: number;\n termsCount: number;\n companiesCount: number;\n outputDirectory?: string;\n model?: string;\n}\n\nexport interface ProjectSuggestion {\n projectId: string;\n projectName: string;\n confidence: number;\n reason: string;\n destination?: string;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Helper for async file existence check\n */\nexport async function fileExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get a configured directory from server configuration\n * Uses workspace-level configuration instead of navigating up the directory tree\n */\nexport async function getConfiguredDirectory(\n key: 'inputDirectory' | 'outputDirectory' | 'processedDirectory',\n _contextDirectory?: string // Kept for backward compatibility but not used\n): Promise<string> {\n // Import here to avoid circular dependencies\n const ServerConfig = await import('../serverConfig');\n \n switch (key) {\n case 'inputDirectory':\n return ServerConfig.getInputDirectory();\n case 'outputDirectory':\n return ServerConfig.getOutputDirectory();\n case 'processedDirectory':\n return ServerConfig.getProcessedDirectory() || resolve(process.cwd(), './processed');\n }\n}\n\n/**\n * Get context directories from server configuration\n * Returns the contextDirectories array from protokoll-config.yaml if available\n */\nexport async function getContextDirectories(): Promise<string[] | undefined> {\n // Import here to avoid circular dependencies\n const ServerConfig = await import('../serverConfig');\n \n const config = ServerConfig.getServerConfig();\n return config.configFile?.contextDirectories as string[] | undefined;\n}\n\n/**\n * Validate that contextDirectory parameter is not provided in remote mode\n * In remote mode, the server is pre-configured with workspace directories\n * and tools should not accept directory parameters.\n * \n * @param contextDirectory - The contextDirectory parameter from tool args\n * @throws Error if contextDirectory is provided in remote mode\n */\nexport async function validateNotRemoteMode(contextDirectory?: string): Promise<void> {\n if (!contextDirectory) {\n return; // No directory parameter provided, OK\n }\n \n // Import here to avoid circular dependencies\n const ServerConfig = await import('../serverConfig');\n \n if (ServerConfig.isRemoteMode()) {\n throw new Error(\n 'Directory parameters are not accepted in remote mode. ' +\n 'This server is pre-configured with workspace directories from protokoll-config.yaml. ' +\n 'Use the protokoll_info tool to check server configuration.'\n );\n }\n}\n\n/**\n * Validate that a resolved path stays within a base directory\n * This prevents path traversal attacks using ../ sequences\n * \n * @param resolvedPath - The resolved absolute path to validate\n * @param baseDirectory - The base directory that paths must stay within\n * @throws Error if the path escapes the base directory\n */\nexport function validatePathWithinDirectory(\n resolvedPath: string,\n baseDirectory: string\n): void {\n // Normalize both paths to handle any ../ sequences\n const normalizedTarget = resolve(resolvedPath);\n const normalizedBase = resolve(baseDirectory);\n \n // Ensure base directory ends with separator for proper prefix matching\n const basePath = normalizedBase.endsWith('/') ? normalizedBase : normalizedBase + '/';\n \n // Check if the target path is within the base directory\n // Must either be exactly the base dir, or start with base dir + separator\n if (normalizedTarget !== normalizedBase && !normalizedTarget.startsWith(basePath)) {\n throw new Error(\n `Security error: Path \"${resolvedPath}\" is outside the allowed directory \"${baseDirectory}\". ` +\n `Path traversal is not allowed.`\n );\n }\n}\n\n/**\n * Async version of validatePathWithinDirectory that gets the output directory from config\n * \n * @param resolvedPath - The resolved absolute path to validate\n * @param contextDirectory - Optional context directory for config lookup\n * @throws Error if the path escapes the output directory\n */\nexport async function validatePathWithinOutputDirectory(\n resolvedPath: string,\n contextDirectory?: string\n): Promise<void> {\n const outputDirectory = await getConfiguredDirectory('outputDirectory', contextDirectory);\n validatePathWithinDirectory(resolvedPath, outputDirectory);\n}\n\n/**\n * Convert an absolute file path to a relative path (relative to output directory)\n * This ensures no absolute paths are exposed to HTTP MCP clients\n * \n * @param absolutePath - The absolute file path to convert\n * @param baseDirectory - The base directory to make relative to (default: output directory)\n * @returns Relative path, or the original path if it's already relative\n */\nexport async function sanitizePath(\n absolutePath: string,\n baseDirectory?: string\n): Promise<string> {\n // Guard against undefined/null/empty values\n if (!absolutePath || typeof absolutePath !== 'string') {\n // Return empty string for invalid paths to prevent errors downstream\n return absolutePath || '';\n }\n \n // If it's already a relative path (doesn't start with /), return as-is\n if (!absolutePath.startsWith('/') && !absolutePath.match(/^[A-Za-z]:/)) {\n return absolutePath;\n }\n \n // Get the base directory (output directory by default)\n const base = baseDirectory || await getConfiguredDirectory('outputDirectory');\n \n // Convert to relative path\n try {\n const relativePath = relative(base, absolutePath);\n // If relative() returns an absolute path (when paths are on different drives on Windows),\n // return just the filename as a fallback\n if (relativePath.startsWith('/') || relativePath.match(/^[A-Za-z]:/)) {\n // Extract just the filename\n const parts = absolutePath.split(/[/\\\\]/);\n return parts[parts.length - 1] || absolutePath;\n }\n return relativePath;\n } catch {\n // If conversion fails, return just the filename\n const parts = absolutePath.split(/[/\\\\]/);\n return parts[parts.length - 1] || absolutePath;\n }\n}\n\n/**\n * Slugify text for IDs and filenames\n */\nexport function slugify(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/--+/g, '-')\n .replace(/^-|-$/g, '');\n}\n\n/**\n * Get audio file metadata (creation time and hash)\n */\nexport async function getAudioMetadata(audioFile: string): Promise<{ creationTime: Date; hash: string }> {\n // Get creation time from audio file\n let creationTime = await media.getAudioCreationTime(audioFile);\n if (!creationTime) {\n creationTime = new Date();\n }\n\n // Calculate hash of the file\n const hash = (await storage.hashFile(audioFile, 100)).substring(0, 8);\n\n return { creationTime, hash };\n}\n\n/**\n * Format entity for response\n */\nexport function formatEntity(entity: Entity): Record<string, unknown> {\n const result: Record<string, unknown> = {\n id: entity.id,\n name: entity.name,\n type: entity.type,\n };\n\n if (entity.type === 'person') {\n const person = entity as Person;\n if (person.firstName) result.firstName = person.firstName;\n if (person.lastName) result.lastName = person.lastName;\n if (person.company) result.company = person.company;\n if (person.role) result.role = person.role;\n if (person.sounds_like) result.sounds_like = person.sounds_like;\n if (person.context) result.context = person.context;\n } else if (entity.type === 'project') {\n const project = entity as Project;\n if (project.description) result.description = project.description;\n if (project.classification) result.classification = project.classification;\n if (project.routing) result.routing = project.routing;\n if (project.sounds_like) result.sounds_like = project.sounds_like;\n result.active = project.active !== false;\n } else if (entity.type === 'term') {\n const term = entity as Term;\n if (term.expansion) result.expansion = term.expansion;\n if (term.domain) result.domain = term.domain;\n if (term.description) result.description = term.description;\n if (term.sounds_like) result.sounds_like = term.sounds_like;\n if (term.topics) result.topics = term.topics;\n if (term.projects) result.projects = term.projects;\n } else if (entity.type === 'company') {\n const company = entity as Company;\n if (company.fullName) result.fullName = company.fullName;\n if (company.industry) result.industry = company.industry;\n if (company.sounds_like) result.sounds_like = company.sounds_like;\n } else if (entity.type === 'ignored') {\n const ignored = entity as IgnoredTerm;\n if (ignored.reason) result.reason = ignored.reason;\n if (ignored.ignoredAt) result.ignoredAt = ignored.ignoredAt;\n }\n\n return result;\n}\n\n/**\n * Helper to merge arrays: handles replace, add, and remove operations\n */\nexport function mergeArray(\n existing: string[] | undefined,\n replace: string[] | undefined,\n add: string[] | undefined,\n remove: string[] | undefined\n): string[] | undefined {\n // If replace is provided, use it as the base\n if (replace !== undefined) {\n let result = [...replace];\n if (add) {\n result = [...result, ...add.filter(v => !result.includes(v))];\n }\n if (remove) {\n result = result.filter(v => !remove.includes(v));\n }\n return result.length > 0 ? result : undefined;\n }\n\n // Otherwise work with existing\n let result = existing ? [...existing] : [];\n if (add) {\n result = [...result, ...add.filter(v => !result.includes(v))];\n }\n if (remove) {\n result = result.filter(v => !remove.includes(v));\n }\n\n // Return undefined if empty (to remove the field from YAML)\n return result.length > 0 ? result : (existing ? undefined : existing);\n}\n\n/**\n * Resolve a transcript URI, path, or UUID to an absolute file path\n * \n * Accepts:\n * - UUID or UUID prefix: \"a1b2c3d4\" or \"a1b2c3d4-5e6f-7890-abcd-ef1234567890\"\n * - Protokoll URI: protokoll://transcript/2026/2/12-1606-meeting (preferred)\n * - Relative path: 2026/2/12-1606-meeting or 2026/2/12-1606-meeting.pkl\n * - Absolute path: /full/path/to/transcript.pkl (must be within output directory)\n * \n * Returns absolute path for internal file operations\n */\nexport async function resolveTranscriptPath(\n uriOrPathOrUuid: string,\n contextDirectory?: string\n): Promise<string> {\n if (!uriOrPathOrUuid || typeof uriOrPathOrUuid !== 'string') {\n throw new Error('transcriptPath is required and must be a non-empty string');\n }\n \n const outputDirectory = await getConfiguredDirectory('outputDirectory', contextDirectory);\n \n // Check if input is a UUID\n if (isUuidInput(uriOrPathOrUuid)) {\n const foundPath = await findTranscriptByUuid(uriOrPathOrUuid, [outputDirectory]);\n if (!foundPath) {\n throw new Error(`Transcript not found for UUID: ${uriOrPathOrUuid}`);\n }\n return foundPath;\n }\n \n let relativePath: string;\n \n // Check if input is a Protokoll URI\n if (isProtokolUri(uriOrPathOrUuid)) {\n const parsed = parseUri(uriOrPathOrUuid);\n if (parsed.resourceType !== 'transcript') {\n throw new Error(`Invalid URI: expected transcript URI, got ${parsed.resourceType}`);\n }\n // Extract the transcript path from the URI (without extension)\n // Type assertion is safe because we checked resourceType === 'transcript'\n relativePath = (parsed as any).transcriptPath;\n } else {\n // Handle as a file path (relative or absolute)\n if (isAbsolute(uriOrPathOrUuid)) {\n const normalizedAbsolute = resolve(uriOrPathOrUuid);\n const normalizedOutputDir = resolve(outputDirectory);\n \n if (normalizedAbsolute.startsWith(normalizedOutputDir + '/') || normalizedAbsolute === normalizedOutputDir) {\n // Convert absolute path to relative\n relativePath = normalizedAbsolute.substring(normalizedOutputDir.length + 1);\n } else {\n throw new Error(`Path must be within output directory: ${outputDirectory}`);\n }\n } else {\n // Relative path - normalize it\n relativePath = uriOrPathOrUuid.replace(/^[/\\\\]+/, '').replace(/\\\\/g, '/');\n }\n }\n \n // Remove .pkl extension if present (we'll add it back)\n relativePath = relativePath.replace(/\\.pkl$/i, '');\n \n // Resolve to absolute path\n const resolvedPath = resolve(outputDirectory, relativePath);\n validatePathWithinDirectory(resolvedPath, outputDirectory);\n \n // Ensure .pkl extension and check if file exists\n const pklPath = ensurePklExtension(resolvedPath);\n const existsResult = await transcriptExists(pklPath);\n if (!existsResult.exists || !existsResult.path) {\n throw new Error(`Transcript not found: ${uriOrPathOrUuid}`);\n }\n \n return existsResult.path;\n}\n","/**\n * Transcript Resources\n * \n * Handles reading individual transcripts and listing transcripts.\n */\n\nimport type { McpResourceContents } from '../types';\nimport { buildTranscriptUri, buildTranscriptsListUri } from '../uri';\nimport { resolve, relative } from 'node:path';\nimport { Transcript } from '@redaksjon/protokoll-engine';\nimport * as ServerConfig from '../serverConfig';\nimport { sanitizePath } from '../tools/shared';\n\nconst { listTranscripts, resolveTranscriptPath, readTranscriptContent, stripTranscriptExtension } = Transcript;\n\n/**\n * Read a single transcript resource\n * \n * transcriptPath can be:\n * - A path without extension (e.g., \"2026/1/29-2027-meeting\") - will resolve to .pkl\n * - A path with extension (e.g., \"2026/1/29-2027-meeting.pkl\") - will use that specific file\n */\nexport async function readTranscriptResource(transcriptPath: string): Promise<McpResourceContents> {\n // Guard against undefined/null paths\n if (!transcriptPath || typeof transcriptPath !== 'string') {\n throw new Error(`Invalid transcript path: ${transcriptPath}`);\n }\n \n // Get the configured output directory\n const outputDirectory = ServerConfig.getOutputDirectory();\n \n // Resolve the transcript path - handles extension resolution\n // If it's already absolute, use it directly (for backwards compatibility)\n const basePath = transcriptPath.startsWith('/')\n ? transcriptPath\n : resolve(outputDirectory, transcriptPath);\n\n // Resolve to actual .pkl file\n const resolved = await resolveTranscriptPath(basePath);\n \n if (!resolved.exists || !resolved.path) {\n throw new Error(`Transcript not found: ${basePath}`);\n }\n\n try {\n // Read content and metadata using PKL utilities\n const { content, metadata, title } = await readTranscriptContent(resolved.path);\n \n // Get raw transcript if available\n const { PklTranscript } = await import('@redaksjon/protokoll-format');\n const pklTranscript = PklTranscript.open(resolved.path, { readOnly: true });\n let rawTranscript = undefined;\n try {\n if (pklTranscript.hasRawTranscript) {\n const rawData = pklTranscript.rawTranscript;\n if (rawData) {\n rawTranscript = {\n text: rawData.text,\n model: rawData.model,\n duration: rawData.duration,\n transcribedAt: rawData.transcribedAt,\n };\n }\n }\n } finally {\n pklTranscript.close();\n }\n \n // Build the URI without extension (extension-agnostic identifier)\n const relativePath = resolved.path.startsWith('/')\n ? relative(outputDirectory, resolved.path)\n : transcriptPath;\n \n // Strip extension from the URI - the identifier should be extension-agnostic\n const identifierPath = stripTranscriptExtension(relativePath);\n \n // Return structured JSON response - clients should NOT parse this\n // All metadata is provided directly for display\n const structuredResponse = {\n uri: buildTranscriptUri(identifierPath),\n path: identifierPath,\n title: title || identifierPath.split('/').pop() || 'Untitled',\n metadata: {\n date: metadata.date,\n time: metadata.time,\n project: metadata.project,\n projectId: metadata.projectId,\n status: metadata.status,\n tags: metadata.tags || [],\n duration: metadata.duration,\n entities: metadata.entities || {},\n tasks: metadata.tasks || [],\n history: metadata.history || [],\n routing: metadata.destination ? {\n destination: metadata.destination,\n confidence: metadata.confidence,\n } : undefined,\n },\n content: content,\n rawTranscript: rawTranscript,\n };\n \n return {\n uri: buildTranscriptUri(identifierPath),\n mimeType: 'application/json',\n text: JSON.stringify(structuredResponse),\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Transcript not found: ${resolved.path}`);\n }\n throw error;\n }\n}\n\n/**\n * Read a list of transcripts with filtering\n */\nexport async function readTranscriptsListResource(options: {\n directory?: string;\n startDate?: string;\n endDate?: string;\n limit?: number;\n offset?: number;\n projectId?: string;\n}): Promise<McpResourceContents> {\n const { startDate, endDate, limit = 50, offset = 0, projectId } = options;\n \n // Get the configured output directory to use as fallback\n const outputDirectory = ServerConfig.getOutputDirectory();\n \n // Use provided directory or fall back to configured outputDirectory\n const directory = options.directory || outputDirectory;\n\n // Log request parameters\n // eslint-disable-next-line no-console\n console.log(`📋 Reading transcripts list:`);\n // eslint-disable-next-line no-console\n console.log(` Directory: ${directory}${options.directory ? '' : ' (from config)'}`);\n if (projectId) {\n // eslint-disable-next-line no-console\n console.log(` Project filter: ${projectId}`);\n }\n if (startDate || endDate) {\n // eslint-disable-next-line no-console\n console.log(` Date range: ${startDate || 'any'} to ${endDate || 'any'}`);\n }\n // eslint-disable-next-line no-console\n console.log(` Limit: ${limit}, Offset: ${offset}`);\n\n const result = await listTranscripts({\n directory,\n limit,\n offset,\n sortBy: 'date',\n startDate,\n endDate,\n projectId,\n });\n\n // Log results\n // eslint-disable-next-line no-console\n console.log(`✅ Transcripts list response:`);\n // eslint-disable-next-line no-console\n console.log(` Total found: ${result.total}`);\n // eslint-disable-next-line no-console\n console.log(` Returned: ${result.transcripts.length} (limit: ${limit}, offset: ${offset})`);\n // eslint-disable-next-line no-console\n console.log(` Has more: ${result.hasMore}`);\n\n // Convert to resource format with URIs\n // Convert absolute paths to relative paths (relative to outputDirectory)\n // Use sanitizePath to ensure no absolute paths are exposed\n // Strip file extensions from URIs - identifiers should be extension-agnostic\n const transcriptsWithUris = await Promise.all(\n result.transcripts.map(async (t: { path: string; filename: string; date: string; time?: string; title: string; hasRawTranscript: boolean; createdAt: Date; status?: string; openTasksCount?: number; contentSize?: number; entities?: any }) => {\n // Convert absolute path to relative path\n // Guard against undefined path - use filename as fallback\n const relativePath = await sanitizePath(t.path || t.filename || '', outputDirectory);\n \n // Strip extension from the identifier - URIs should be extension-agnostic\n const identifierPath = stripTranscriptExtension(relativePath);\n \n return {\n uri: buildTranscriptUri(identifierPath),\n path: identifierPath, // Use extension-less path as the identifier\n filename: t.filename,\n date: t.date,\n time: t.time,\n title: t.title,\n status: t.status,\n openTasksCount: t.openTasksCount,\n contentSize: t.contentSize,\n entities: t.entities,\n hasRawTranscript: t.hasRawTranscript,\n };\n })\n );\n\n const responseData = {\n directory,\n transcripts: transcriptsWithUris,\n pagination: {\n total: result.total,\n limit: result.limit,\n offset: result.offset,\n hasMore: result.hasMore,\n },\n filters: {\n startDate,\n endDate,\n },\n };\n\n // Build URI with the actual directory used (may be fallback from config)\n return {\n uri: buildTranscriptsListUri({\n directory,\n startDate,\n endDate,\n limit,\n offset,\n projectId,\n }),\n mimeType: 'application/json',\n text: JSON.stringify(responseData, null, 2),\n };\n}\n","/**\n * Entity Resources\n * \n * Handles reading individual entities and listing entities by type.\n */\n\nimport type { McpResourceContents } from '../types';\nimport { buildEntityUri, buildEntitiesListUri } from '../uri';\nimport * as Context from '@/context';\nimport * as yaml from 'js-yaml';\n\n/**\n * Read a single entity resource\n */\nexport async function readEntityResource(\n entityType: string,\n entityId: string,\n contextDirectory?: string\n): Promise<McpResourceContents> {\n const context = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n let entity;\n switch (entityType) {\n case 'person':\n entity = context.getPerson(entityId);\n break;\n case 'project':\n entity = context.getProject(entityId);\n break;\n case 'term':\n entity = context.getTerm(entityId);\n break;\n case 'company':\n entity = context.getCompany(entityId);\n break;\n case 'ignored':\n entity = context.getIgnored(entityId);\n break;\n default:\n throw new Error(`Unknown entity type: ${entityType}`);\n }\n\n if (!entity) {\n throw new Error(`${entityType} \"${entityId}\" not found`);\n }\n\n // Convert to YAML for readability\n const yamlContent = yaml.dump(entity);\n\n return {\n uri: buildEntityUri(entityType as any, entityId),\n mimeType: 'application/yaml',\n text: yamlContent,\n };\n}\n\n/**\n * Read a list of entities by type\n */\nexport async function readEntitiesListResource(\n entityType: string,\n contextDirectory?: string\n): Promise<McpResourceContents> {\n const context = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No Protokoll context found');\n }\n\n let entities: Array<{ id: string; name: string; [key: string]: unknown }>;\n \n switch (entityType) {\n case 'person':\n entities = context.getAllPeople().map(p => ({\n uri: buildEntityUri('person', p.id),\n id: p.id,\n name: p.name,\n company: p.company,\n role: p.role,\n }));\n break;\n case 'project':\n entities = context.getAllProjects().map(p => ({\n uri: buildEntityUri('project', p.id),\n id: p.id,\n name: p.name,\n active: p.active !== false,\n destination: p.routing?.destination,\n }));\n break;\n case 'term':\n entities = context.getAllTerms().map(t => ({\n uri: buildEntityUri('term', t.id),\n id: t.id,\n name: t.name,\n expansion: t.expansion,\n domain: t.domain,\n }));\n break;\n case 'company':\n entities = context.getAllCompanies().map(c => ({\n uri: buildEntityUri('company', c.id),\n id: c.id,\n name: c.name,\n fullName: c.fullName,\n industry: c.industry,\n }));\n break;\n case 'ignored':\n entities = context.getAllIgnored().map(i => ({\n uri: buildEntityUri('ignored', i.id),\n id: i.id,\n name: i.name,\n reason: i.reason,\n }));\n break;\n default:\n throw new Error(`Unknown entity type: ${entityType}`);\n }\n\n const responseData = {\n entityType,\n count: entities.length,\n entities,\n };\n\n return {\n uri: buildEntitiesListUri(entityType as any),\n mimeType: 'application/json',\n text: JSON.stringify(responseData, null, 2),\n };\n}\n","/**\n * Audio Resources\n * \n * Handles listing audio files (inbound and processed).\n */\n\nimport type { McpResourceContents } from '../types';\nimport { buildAudioInboundUri, buildAudioProcessedUri } from '../uri';\nimport { readdir, stat } from 'node:fs/promises';\nimport { resolve, join, extname } from 'node:path';\nimport * as Context from '@/context';\nimport { DEFAULT_AUDIO_EXTENSIONS } from '@/constants';\n\n/**\n * List audio files in a directory\n */\nasync function listAudioFiles(directory: string): Promise<Array<{\n filename: string;\n path: string;\n size: number;\n modified: string;\n extension: string;\n}>> {\n const dirPath = resolve(directory);\n \n try {\n const entries = await readdir(dirPath, { withFileTypes: true });\n const audioFiles = [];\n \n for (const entry of entries) {\n if (entry.isFile()) {\n const ext = extname(entry.name).toLowerCase().substring(1);\n if (DEFAULT_AUDIO_EXTENSIONS.includes(ext)) {\n const filePath = join(dirPath, entry.name);\n const stats = await stat(filePath);\n \n audioFiles.push({\n filename: entry.name,\n path: filePath,\n size: stats.size,\n modified: stats.mtime.toISOString(),\n extension: ext,\n });\n }\n }\n }\n \n // Sort by modification time, newest first\n audioFiles.sort((a, b) => \n new Date(b.modified).getTime() - new Date(a.modified).getTime()\n );\n \n return audioFiles;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return [];\n }\n throw error;\n }\n}\n\n/**\n * Format bytes to human-readable string\n */\nfunction formatBytes(bytes: number): string {\n if (bytes === 0) return '0 B';\n \n const k = 1024;\n const sizes = ['B', 'KB', 'MB', 'GB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;\n}\n\n/**\n * Read inbound audio files resource\n */\nexport async function readAudioInboundResource(\n directory?: string\n): Promise<McpResourceContents> {\n const context = await Context.create({\n startingDir: directory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No Protokoll context found');\n }\n\n const config = context.getConfig();\n const inputDirectory = directory || (config.inputDirectory as string) || './recordings';\n const audioFiles = await listAudioFiles(inputDirectory);\n \n const responseData = {\n directory: resolve(inputDirectory),\n count: audioFiles.length,\n totalSize: audioFiles.reduce((sum, f) => sum + f.size, 0),\n files: audioFiles.map(f => ({\n filename: f.filename,\n path: f.path,\n size: f.size,\n sizeHuman: formatBytes(f.size),\n modified: f.modified,\n extension: f.extension,\n })),\n supportedExtensions: DEFAULT_AUDIO_EXTENSIONS,\n };\n\n return {\n uri: buildAudioInboundUri(inputDirectory),\n mimeType: 'application/json',\n text: JSON.stringify(responseData, null, 2),\n };\n}\n\n/**\n * Read processed audio files resource\n */\nexport async function readAudioProcessedResource(\n directory?: string\n): Promise<McpResourceContents> {\n const context = await Context.create({\n startingDir: directory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No Protokoll context found');\n }\n\n const config = context.getConfig();\n const processedDirectory = directory || (config.processedDirectory as string) || './processed';\n const audioFiles = await listAudioFiles(processedDirectory);\n \n const responseData = {\n directory: resolve(processedDirectory),\n count: audioFiles.length,\n totalSize: audioFiles.reduce((sum, f) => sum + f.size, 0),\n files: audioFiles.map(f => ({\n filename: f.filename,\n path: f.path,\n size: f.size,\n sizeHuman: formatBytes(f.size),\n modified: f.modified,\n extension: f.extension,\n })),\n supportedExtensions: DEFAULT_AUDIO_EXTENSIONS,\n };\n\n return {\n uri: buildAudioProcessedUri(processedDirectory),\n mimeType: 'application/json',\n text: JSON.stringify(responseData, null, 2),\n };\n}\n","/**\n * Configuration Resource\n * \n * Handles reading Protokoll configuration.\n */\n\nimport type { McpResourceContents } from '../types';\nimport { buildConfigUri, buildEntitiesListUri } from '../uri';\nimport * as Context from '@/context';\n\n/**\n * Read configuration resource\n */\nexport async function readConfigResource(\n configPath?: string\n): Promise<McpResourceContents> {\n const startDir = configPath || process.cwd();\n \n const context = await Context.create({\n startingDir: startDir,\n });\n\n if (!context.hasContext()) {\n throw new Error(`No Protokoll context found at or above: ${startDir}`);\n }\n\n const dirs = context.getDiscoveredDirs();\n const config = context.getConfig();\n\n const configData = {\n hasContext: true,\n discoveredDirectories: dirs.map(d => ({\n path: d.path,\n level: d.level,\n isPrimary: d.level === 0,\n })),\n entityCounts: {\n projects: context.getAllProjects().length,\n people: context.getAllPeople().length,\n terms: context.getAllTerms().length,\n companies: context.getAllCompanies().length,\n ignored: context.getAllIgnored().length,\n },\n config: {\n outputDirectory: config.outputDirectory,\n outputStructure: config.outputStructure,\n model: config.model,\n smartAssistance: context.getSmartAssistanceConfig(),\n },\n // Include URIs for easy navigation\n resourceUris: {\n projects: buildEntitiesListUri('project'),\n people: buildEntitiesListUri('person'),\n terms: buildEntitiesListUri('term'),\n companies: buildEntitiesListUri('company'),\n },\n };\n\n return {\n uri: buildConfigUri(configPath),\n mimeType: 'application/json',\n text: JSON.stringify(configData, null, 2),\n };\n}\n","/**\n * MCP Resources - Exports all resource definitions and handlers\n */\n\nimport type {\n McpResource,\n McpResourceTemplate,\n McpResourceContents,\n TranscriptUri,\n EntityUri,\n ConfigUri,\n TranscriptsListUri,\n EntitiesListUri,\n AudioInboundUri,\n AudioProcessedUri,\n} from '../types';\nimport { parseUri } from '../uri';\n\n// Re-export all resource modules\nexport * from './definitions';\nexport * from './discovery';\nexport * from './transcriptResources';\nexport * from './entityResources';\nexport * from './audioResources';\nexport * from './configResource';\n\n// Import for use in handlers\nimport { directResources, resourceTemplates } from './definitions';\nimport { getDynamicResources } from './discovery';\nimport { readTranscriptResource, readTranscriptsListResource } from './transcriptResources';\nimport { readEntityResource, readEntitiesListResource } from './entityResources';\nimport { readAudioInboundResource, readAudioProcessedResource } from './audioResources';\nimport { readConfigResource } from './configResource';\n\n// ============================================================================\n// Main Handler Functions\n// ============================================================================\n\n/**\n * Handle resources/list request\n */\nexport async function handleListResources(contextDirectory?: string): Promise<{\n resources: McpResource[];\n resourceTemplates?: McpResourceTemplate[];\n}> {\n // Get dynamic resources from context if available\n const dynamicResources = await getDynamicResources(contextDirectory);\n \n return {\n resources: [...directResources, ...dynamicResources],\n resourceTemplates,\n };\n}\n\n/**\n * Handle resources/read request\n */\nexport async function handleReadResource(uri: string): Promise<McpResourceContents> {\n const parsed = parseUri(uri);\n\n switch (parsed.resourceType) {\n case 'transcript':\n return readTranscriptResource((parsed as TranscriptUri).transcriptPath);\n case 'entity': {\n const entityUri = parsed as EntityUri;\n return readEntityResource(entityUri.entityType, entityUri.entityId);\n }\n case 'config':\n return readConfigResource((parsed as ConfigUri).configPath);\n case 'transcripts-list': {\n const listUri = parsed as TranscriptsListUri;\n return readTranscriptsListResource({\n directory: listUri.directory,\n startDate: listUri.startDate,\n endDate: listUri.endDate,\n limit: listUri.limit,\n offset: listUri.offset,\n projectId: listUri.projectId,\n });\n }\n case 'entities-list':\n return readEntitiesListResource((parsed as EntitiesListUri).entityType);\n case 'audio-inbound':\n return readAudioInboundResource((parsed as AudioInboundUri).directory);\n case 'audio-processed':\n return readAudioProcessedResource((parsed as AudioProcessedUri).directory);\n default:\n throw new Error(`Unknown resource type: ${parsed.resourceType}`);\n }\n}\n","/**\n * MCP Prompt Handlers\n *\n * Provides workflow templates via MCP prompts.\n * Prompts are loaded from external markdown files in this directory.\n */\n\n// eslint-disable-next-line no-restricted-imports\nimport { readFileSync } from 'node:fs';\nimport { resolve, dirname } from 'node:path';\nimport { stat } from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\nimport type { McpPrompt, McpPromptMessage } from '../types';\nimport * as Context from '@/context';\nimport { buildConfigUri, buildEntitiesListUri } from '../uri';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n/**\n * Helper to resolve the prompts directory path\n */\nfunction getPromptsDir(): string {\n const isBundled = __dirname.includes('/dist') || __dirname.endsWith('dist') ||\n __filename.includes('dist/mcp-server.js') || __filename.includes('dist\\\\mcp-server.js');\n\n if (isBundled) {\n // When bundled, __dirname points to dist/mcp, prompts are in dist/mcp/prompts\n return resolve(__dirname, 'prompts');\n }\n // In source, __dirname already points to src/mcp/prompts\n return __dirname;\n}\n\n/**\n * Helper to load a prompt template from a markdown file\n */\nfunction loadTemplate(name: string): string {\n const promptsDir = getPromptsDir();\n const path = resolve(promptsDir, `${name}.md`);\n try {\n return readFileSync(path, 'utf-8').trim();\n } catch (error) {\n const isBundled = __dirname.includes('/dist');\n const debugInfo = [\n `Failed to load prompt template \"${name}\"`,\n `Attempted path: ${path}`,\n `Prompts directory: ${promptsDir}`,\n `Current __dirname: ${__dirname}`,\n `Current __filename: ${__filename}`,\n `Environment: ${isBundled ? 'bundled (dist)' : 'source (src)'}`,\n `Error: ${error}`,\n ].join('\\n ');\n throw new Error(debugInfo);\n }\n}\n\n/**\n * Helper to replace placeholders in a template\n */\nfunction fillTemplate(template: string, args: Record<string, string>): string {\n return template.replace(/\\${(\\w+)}/g, (_, key) => {\n return args[key] || '';\n });\n}\n\n/**\n * Get all available prompts\n */\nexport function getPrompts(): McpPrompt[] {\n return [\n {\n name: 'how_to_use_protokoll',\n description: 'Essential instructions for AI assistants on how to properly interact with Protokoll. ' +\n 'READ THIS FIRST before working with transcripts. Explains which tools to use and which to avoid.',\n arguments: [],\n },\n {\n name: 'transcribe_with_context',\n description: 'Intelligently transcribe audio with context discovery and project routing. ' +\n 'Guides you through finding the right configuration and confirms before processing.',\n arguments: [\n {\n name: 'audioFile',\n description: 'Absolute path to the audio file to transcribe',\n required: true,\n },\n {\n name: 'skipDiscovery',\n description: 'Skip context discovery if you already know the configuration',\n required: false,\n },\n ],\n },\n {\n name: 'setup_project',\n description: 'Create a new project with smart assistance for generating metadata. ' +\n 'Analyzes source content to suggest sounds_like, trigger phrases, topics, and description.',\n arguments: [\n {\n name: 'projectName',\n description: 'Name of the project to create',\n required: true,\n },\n {\n name: 'sourceUrl',\n description: 'URL or file path to analyze for metadata suggestions',\n required: false,\n },\n {\n name: 'destination',\n description: 'Output directory for transcripts',\n required: false,\n },\n ],\n },\n {\n name: 'review_transcript',\n description: 'Analyze a transcript and suggest corrections based on context. ' +\n 'Identifies potential name/term errors and offers to apply fixes. ' +\n 'IMPORTANT: This prompt instructs the AI to use ONLY Protokoll MCP tools, never direct file editing.',\n arguments: [\n {\n name: 'transcriptPath',\n description: 'Path to the transcript to review',\n required: true,\n },\n {\n name: 'focusArea',\n description: 'What to focus on: names, terms, technical, or all (defaults to \"all\")',\n required: false,\n },\n ],\n },\n {\n name: 'enrich_entity',\n description: 'Add or update an entity with smart assistance for generating metadata.',\n arguments: [\n {\n name: 'entityType',\n description: 'Type: person, project, term, or company',\n required: true,\n },\n {\n name: 'entityName',\n description: 'Name of the entity',\n required: true,\n },\n {\n name: 'sourceUrl',\n description: 'URL or file path to analyze for metadata',\n required: false,\n },\n ],\n },\n {\n name: 'batch_transcription',\n description: 'Set up and execute batch transcription for a directory of audio files.',\n arguments: [\n {\n name: 'directory',\n description: 'Directory containing audio files',\n required: true,\n },\n {\n name: 'extensions',\n description: 'Comma-separated file extensions (default: m4a,mp3,wav,webm)',\n required: false,\n },\n ],\n },\n {\n name: 'find_and_analyze',\n description: 'Search for transcripts and analyze their content.',\n arguments: [\n {\n name: 'directory',\n description: 'Directory to search',\n required: true,\n },\n {\n name: 'query',\n description: 'Search query',\n required: false,\n },\n {\n name: 'startDate',\n description: 'Filter from date (YYYY-MM-DD)',\n required: false,\n },\n {\n name: 'endDate',\n description: 'Filter to date (YYYY-MM-DD)',\n required: false,\n },\n ],\n },\n {\n name: 'edit_entity',\n description: 'Edit an existing entity (person, term, or project) with manual modifications. ' +\n 'Unlike update tools that regenerate from sources, this allows direct edits like ' +\n 'adding specific sounds_like variants, changing fields, or modifying array properties.',\n arguments: [\n {\n name: 'entityType',\n description: 'Type of entity to edit: person, term, or project',\n required: true,\n },\n {\n name: 'entityId',\n description: 'ID of the entity to edit',\n required: true,\n },\n {\n name: 'modification',\n description: 'What to modify (e.g., \"add sounds_like variant\", \"change domain\", \"add topics\")',\n required: false,\n },\n ],\n },\n ];\n}\n\n/**\n * Get a prompt by name\n */\nexport async function getPrompt(\n name: string,\n args: Record<string, string>\n): Promise<McpPromptMessage[]> {\n // Validate prompt exists\n const prompts = getPrompts();\n const prompt = prompts.find(p => p.name === name);\n\n if (!prompt) {\n throw new Error(`Unknown prompt: ${name}`);\n }\n\n // Validate required arguments\n for (const arg of prompt.arguments || []) {\n if (arg.required && !args[arg.name]) {\n throw new Error(`Missing required argument: ${arg.name}`);\n }\n }\n\n // Generate messages based on prompt type\n switch (name) {\n case 'how_to_use_protokoll':\n return generateHowToUseProtokolPrompt(args);\n case 'transcribe_with_context':\n return generateTranscribePrompt(args);\n case 'setup_project':\n return generateSetupProjectPrompt(args);\n case 'review_transcript':\n return generateReviewTranscriptPrompt(args);\n case 'enrich_entity':\n return generateEnrichEntityPrompt(args);\n case 'batch_transcription':\n return generateBatchTranscriptionPrompt(args);\n case 'find_and_analyze':\n return generateFindAndAnalyzePrompt(args);\n case 'edit_entity':\n return generateEditEntityPrompt(args);\n default:\n throw new Error(`Prompt handler not implemented: ${name}`);\n }\n}\n\n// ============================================================================\n// Prompt Generators\n// ============================================================================\n\nasync function generateHowToUseProtokolPrompt(\n _args: Record<string, string>\n): Promise<McpPromptMessage[]> {\n const template = loadTemplate('how_to_use_protokoll');\n\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: template,\n },\n },\n ];\n}\n\nasync function generateTranscribePrompt(\n args: Record<string, string>\n): Promise<McpPromptMessage[]> {\n const audioFile = args.audioFile;\n const skipDiscovery = args.skipDiscovery === 'true';\n\n if (!audioFile) {\n throw new Error('audioFile is required');\n }\n\n let discoverySection = '';\n\n if (skipDiscovery) {\n discoverySection = `I'll transcribe ${audioFile} using the current context configuration.\\n\\nWould you like me to start the transcription?`;\n } else {\n // Perform basic context discovery\n const audioPath = resolve(audioFile);\n\n try {\n await stat(audioPath);\n\n const context = await Context.create({\n startingDir: dirname(audioPath),\n });\n\n if (context.hasContext()) {\n const dirs = context.getDiscoveredDirs();\n const projects = context.getAllProjects().filter(p => p.active !== false);\n\n discoverySection = `## Context Discovery\\n\\n` +\n `**Configuration:** ${dirs[0]?.path}\\n` +\n `**Projects:** ${projects.length} active\\n` +\n `**Context URI:** ${buildConfigUri(dirs[0]?.path)}\\n` +\n `**Projects URI:** ${buildEntitiesListUri('project')}\\n\\n` +\n `Ready to transcribe with context-aware enhancement.`;\n } else {\n discoverySection = `## No Context Found\\n\\nProcessing without context (basic transcription only).`;\n }\n } catch {\n discoverySection = `## File Check Failed\\n\\nUnable to access: ${audioFile}`;\n }\n }\n\n const template = loadTemplate('transcribe_with_context');\n const content = fillTemplate(template, { audioFile, discoverySection });\n\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: content,\n },\n },\n ];\n}\n\nasync function generateSetupProjectPrompt(\n args: Record<string, string>\n): Promise<McpPromptMessage[]> {\n const projectName = args.projectName;\n\n if (!projectName) {\n throw new Error('projectName is required');\n }\n\n const sourceUrlLine = args.sourceUrl\n ? `\\n - sourceUrl: \"${args.sourceUrl}\" (for metadata analysis)`\n : '';\n const destinationLine = args.destination\n ? `\\n - destination: \"${args.destination}\"`\n : '';\n\n const template = loadTemplate('setup_project');\n const content = fillTemplate(template, {\n projectName,\n sourceUrlLine,\n destinationLine\n });\n\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: content,\n },\n },\n ];\n}\n\nasync function generateReviewTranscriptPrompt(\n args: Record<string, string>\n): Promise<McpPromptMessage[]> {\n const transcriptPath = args.transcriptPath;\n\n if (!transcriptPath) {\n throw new Error('transcriptPath is required');\n }\n\n const focusArea = args.focusArea || 'all';\n const focusText = focusArea === 'all' ? 'All corrections' : focusArea;\n\n const template = loadTemplate('review_transcript');\n const content = fillTemplate(template, {\n transcriptPath,\n focusArea: focusText\n });\n\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: content,\n },\n },\n ];\n}\n\nasync function generateEnrichEntityPrompt(\n args: Record<string, string>\n): Promise<McpPromptMessage[]> {\n const template = loadTemplate('enrich_entity');\n const content = fillTemplate(template, args);\n\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: content,\n },\n },\n ];\n}\n\nasync function generateBatchTranscriptionPrompt(\n args: Record<string, string>\n): Promise<McpPromptMessage[]> {\n const template = loadTemplate('batch_transcription');\n const content = fillTemplate(template, args);\n\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: content,\n },\n },\n ];\n}\n\nasync function generateFindAndAnalyzePrompt(\n args: Record<string, string>\n): Promise<McpPromptMessage[]> {\n const template = loadTemplate('find_and_analyze');\n const content = fillTemplate(template, args);\n\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: content,\n },\n },\n ];\n}\n\nasync function generateEditEntityPrompt(\n args: Record<string, string>\n): Promise<McpPromptMessage[]> {\n const entityType = args.entityType;\n const entityId = args.entityId;\n const modification = args.modification || '';\n\n if (!entityType || !entityId) {\n throw new Error('entityType and entityId are required');\n }\n\n const userMessage = modification\n ? `I want to edit the ${entityType} \"${entityId}\": ${modification}`\n : `I want to edit the ${entityType} \"${entityId}\"`;\n\n let entityGuidance = '';\n\n // Provide guidance based on entity type\n if (entityType === 'person') {\n entityGuidance = `**Available modifications for people:**\\n` +\n `- \\`name\\`, \\`firstName\\`, \\`lastName\\` - Update name fields\\n` +\n `- \\`company\\`, \\`role\\`, \\`context\\` - Update association info\\n` +\n `- \\`sounds_like\\` - Replace all phonetic variants\\n` +\n `- \\`add_sounds_like\\` - Add new phonetic variants\\n` +\n `- \\`remove_sounds_like\\` - Remove specific variants\\n\\n` +\n `**To proceed:**\\n` +\n `1. First, call \\`protokoll_get_entity\\` to see current values:\\n` +\n ` - entityType: \"person\"\\n` +\n ` - entityId: \"${entityId}\"\\n\\n` +\n `2. Then call \\`protokoll_edit_person\\` with the changes:\\n` +\n ` - id: \"${entityId}\"\\n` +\n ` - [your modifications]\\n`;\n } else if (entityType === 'term') {\n entityGuidance = `**Available modifications for terms:**\\n` +\n `- \\`expansion\\`, \\`domain\\`, \\`description\\` - Update basic fields\\n` +\n `- \\`sounds_like\\` - Replace all phonetic variants\\n` +\n `- \\`add_sounds_like\\` - Add new phonetic variants\\n` +\n `- \\`remove_sounds_like\\` - Remove specific variants\\n` +\n `- \\`topics\\` / \\`add_topics\\` / \\`remove_topics\\` - Modify topic keywords\\n` +\n `- \\`projects\\` / \\`add_projects\\` / \\`remove_projects\\` - Modify project associations\\n\\n` +\n `**To proceed:**\\n` +\n `1. First, call \\`protokoll_get_entity\\` to see current values:\\n` +\n ` - entityType: \"term\"\\n` +\n ` - entityId: \"${entityId}\"\\n\\n` +\n `2. Then call \\`protokoll_edit_term\\` with the changes:\\n` +\n ` - id: \"${entityId}\"\\n` +\n ` - [your modifications]\\n`;\n } else if (entityType === 'project') {\n entityGuidance = `**Available modifications for projects:**\\n` +\n `- \\`name\\`, \\`description\\` - Update basic info\\n` +\n `- \\`destination\\`, \\`structure\\` - Update routing\\n` +\n `- \\`contextType\\`, \\`active\\` - Update classification\\n` +\n `- \\`sounds_like\\` / \\`add_sounds_like\\` / \\`remove_sounds_like\\` - Phonetic variants\\n` +\n `- \\`topics\\` / \\`add_topics\\` / \\`remove_topics\\` - Topic keywords\\n` +\n `- \\`explicit_phrases\\` / \\`add_explicit_phrases\\` / \\`remove_explicit_phrases\\` - Trigger phrases\\n\\n` +\n `**To proceed:**\\n` +\n `1. First, call \\`protokoll_get_entity\\` to see current values:\\n` +\n ` - entityType: \"project\"\\n` +\n ` - entityId: \"${entityId}\"\\n\\n` +\n `2. Then call \\`protokoll_edit_project\\` with the changes:\\n` +\n ` - id: \"${entityId}\"\\n` +\n ` - [your modifications]\\n`;\n } else {\n entityGuidance = `**Note:** Entity type \"${entityType}\" does not support direct editing.\\n` +\n `Supported types: person, term, project\\n`;\n }\n\n const modificationNote = modification\n ? `\\n**Requested modification:** \"${modification}\"\\nWould you like me to retrieve the current entity and apply this change?`\n : '';\n\n const template = loadTemplate('edit_entity');\n const content = fillTemplate(template, {\n userMessage,\n entityType,\n entityId,\n entityGuidance,\n modificationNote\n });\n\n return [\n {\n role: 'user',\n content: {\n type: 'text',\n text: content,\n },\n },\n ];\n}\n\n// ============================================================================\n// MCP Protocol Handlers\n// ============================================================================\n\n/**\n * Export prompts list for testing and handler\n */\nexport const prompts = getPrompts();\n\n/**\n * Handle ListPrompts request\n */\nexport function handleListPrompts() {\n return { prompts };\n}\n\n/**\n * Handle GetPrompt request\n */\nexport async function handleGetPrompt(name: string, args: Record<string, string>) {\n const messages = await getPrompt(name, args);\n return { messages };\n}\n","/**\n * Discovery Tools - Configuration discovery and project suggestion\n */\n// eslint-disable-next-line import/extensions\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { resolve, dirname } from 'node:path';\nimport { stat } from 'node:fs/promises';\nimport * as Context from '@/context';\nimport { fileExists, sanitizePath, type DiscoveredConfig, type ProjectSuggestion } from './shared';\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Walk up the directory tree from a starting path to find .protokoll directories\n */\nexport async function findProtokolkConfigs(startPath: string, maxLevels: number = 10): Promise<string[]> {\n const configs: string[] = [];\n let currentPath = resolve(startPath);\n let levels = 0;\n\n while (levels < maxLevels) {\n const protokollPath = resolve(currentPath, '.protokoll');\n if (await fileExists(protokollPath)) {\n configs.push(protokollPath);\n }\n\n const parentPath = dirname(currentPath);\n if (parentPath === currentPath) break; // Reached root\n currentPath = parentPath;\n levels++;\n }\n\n return configs;\n}\n\n/**\n * Get information about a .protokoll configuration\n */\nexport async function getConfigInfo(protokollPath: string): Promise<DiscoveredConfig> {\n const context = await Context.create({ startingDir: dirname(protokollPath) });\n const config = context.getConfig();\n\n return {\n path: protokollPath,\n projectCount: context.getAllProjects().length,\n peopleCount: context.getAllPeople().length,\n termsCount: context.getAllTerms().length,\n companiesCount: context.getAllCompanies().length,\n outputDirectory: config.outputDirectory as string | undefined,\n model: config.model as string | undefined,\n };\n}\n\n/**\n * Suggest which project an audio file might belong to based on its location\n */\nexport async function suggestProjectsForFile(audioFile: string): Promise<{\n configs: DiscoveredConfig[];\n suggestions: ProjectSuggestion[];\n needsUserInput: boolean;\n message: string;\n}> {\n const audioPath = resolve(audioFile);\n const audioDir = dirname(audioPath);\n\n // Find all .protokoll configs in the hierarchy\n const configPaths = await findProtokolkConfigs(audioDir);\n\n if (configPaths.length === 0) {\n return {\n configs: [],\n suggestions: [],\n needsUserInput: true,\n message: `No .protokoll configuration found for ${audioFile}. ` +\n 'You can either: (1) Create a .protokoll directory with project configuration, ' +\n 'or (2) Specify a contextDirectory when calling protokoll_process_audio.',\n };\n }\n\n // Get info about each config\n const configs: DiscoveredConfig[] = [];\n const allSuggestions: ProjectSuggestion[] = [];\n\n for (const configPath of configPaths) {\n const info = await getConfigInfo(configPath);\n configs.push(info);\n\n // Get context to check projects\n const context = await Context.create({ startingDir: dirname(configPath) });\n const projects = context.getAllProjects().filter(p => p.active !== false);\n\n for (const project of projects) {\n // Check if the audio file's path matches any project's destination\n const destination = project.routing?.destination;\n if (destination) {\n const expandedDest = destination.startsWith('~')\n ? destination.replace('~', process.env.HOME || '')\n : destination;\n\n if (audioDir.includes(expandedDest) || expandedDest.includes(audioDir)) {\n allSuggestions.push({\n projectId: project.id,\n projectName: project.name,\n confidence: 0.9,\n reason: `Audio file is in or near project destination: ${destination}`,\n destination,\n });\n }\n }\n\n // Check if project has associated directories/paths\n if (project.classification?.explicit_phrases) {\n // Check if any phrases match the directory name\n const dirName = audioDir.split('/').pop() || '';\n for (const phrase of project.classification.explicit_phrases) {\n if (dirName.toLowerCase().includes(phrase.toLowerCase())) {\n allSuggestions.push({\n projectId: project.id,\n projectName: project.name,\n confidence: 0.7,\n reason: `Directory name matches project phrase: \"${phrase}\"`,\n destination: project.routing?.destination,\n });\n }\n }\n }\n }\n }\n\n // Deduplicate and sort suggestions by confidence\n const uniqueSuggestions = allSuggestions\n .filter((s, i, arr) => arr.findIndex(x => x.projectId === s.projectId) === i)\n .sort((a, b) => b.confidence - a.confidence);\n\n if (uniqueSuggestions.length === 0) {\n return {\n configs,\n suggestions: [],\n needsUserInput: configs[0].projectCount > 0,\n message: configs[0].projectCount > 0\n ? `Found ${configs[0].projectCount} projects but couldn't automatically determine which one this file belongs to. ` +\n 'Please specify the project or let me list them for you.'\n : 'Configuration found but no projects defined. Transcripts will use default routing.',\n };\n }\n\n if (uniqueSuggestions.length === 1 && uniqueSuggestions[0].confidence >= 0.8) {\n return {\n configs,\n suggestions: uniqueSuggestions,\n needsUserInput: false,\n message: `Detected project: ${uniqueSuggestions[0].projectName} (${uniqueSuggestions[0].reason})`,\n };\n }\n\n return {\n configs,\n suggestions: uniqueSuggestions,\n needsUserInput: true,\n message: `Found ${uniqueSuggestions.length} possible projects. Please confirm which project this file belongs to.`,\n };\n}\n\n// ============================================================================\n// Tool Definitions\n// ============================================================================\n\nexport const discoverConfigTool: Tool = {\n name: 'protokoll_discover_config',\n description:\n 'Discover Protokoll configurations for a given file or directory. ' +\n 'Walks up the directory tree to find .protokoll directories and returns information about each, ' +\n 'including project counts, people, terms, and output settings. ' +\n 'ALWAYS call this first when asked to transcribe a file to understand the available context. ' +\n 'This helps determine which project configuration to use.',\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to a file or directory to search from (searches up the tree)',\n },\n },\n required: ['path'],\n },\n};\n\nexport const suggestProjectTool: Tool = {\n name: 'protokoll_suggest_project',\n description:\n 'Suggest which project(s) an audio file might belong to based on its location. ' +\n 'Analyzes the file path against configured projects to determine the best match. ' +\n 'Returns suggestions with confidence levels and reasons. ' +\n 'If multiple projects match or no clear match is found, the response indicates that user input is needed.',\n inputSchema: {\n type: 'object',\n properties: {\n audioFile: {\n type: 'string',\n description: 'Path to the audio file to analyze',\n },\n },\n required: ['audioFile'],\n },\n};\n\n// ============================================================================\n// Tool Handlers\n// ============================================================================\n\nexport async function handleDiscoverConfig(args: { path: string }) {\n const searchPath = resolve(args.path);\n\n // Check if path exists\n if (!await fileExists(searchPath)) {\n throw new Error(`Path not found: ${searchPath}`);\n }\n\n // Determine if it's a file or directory\n const pathStat = await stat(searchPath);\n const startDir = pathStat.isDirectory() ? searchPath : dirname(searchPath);\n\n // Find all .protokoll configs\n const configPaths = await findProtokolkConfigs(startDir);\n\n // Get workspace root for path sanitization\n const ServerConfig = await import('../serverConfig');\n const workspaceRoot = ServerConfig.getWorkspaceRoot() || process.cwd();\n\n if (configPaths.length === 0) {\n // Sanitize searchedFrom path\n const sanitizedSearchedFrom = await sanitizePath(startDir, workspaceRoot);\n return {\n found: false,\n searchedFrom: sanitizedSearchedFrom,\n configs: [],\n message: 'No .protokoll configuration found in the directory hierarchy. ' +\n 'To use Protokoll, create a .protokoll directory with your context files (people, projects, terms).',\n suggestion: 'Run \"protokoll --init-config\" in your project directory to create initial configuration.',\n };\n }\n\n // Get info about each config and sanitize paths\n const configs: DiscoveredConfig[] = [];\n for (const configPath of configPaths) {\n const info = await getConfigInfo(configPath);\n // Sanitize the path in the config info\n const sanitizedPath = await sanitizePath(info.path, workspaceRoot);\n configs.push({\n ...info,\n path: sanitizedPath,\n });\n }\n\n // Primary config is the one closest to the search path\n const primaryConfig = configs[0];\n\n // Sanitize searchedFrom and primaryConfig paths\n const sanitizedSearchedFrom = await sanitizePath(startDir, workspaceRoot);\n\n return {\n found: true,\n searchedFrom: sanitizedSearchedFrom,\n primaryConfig: primaryConfig.path,\n configs,\n summary: {\n totalProjects: configs.reduce((sum, c) => sum + c.projectCount, 0),\n totalPeople: configs.reduce((sum, c) => sum + c.peopleCount, 0),\n totalTerms: configs.reduce((sum, c) => sum + c.termsCount, 0),\n totalCompanies: configs.reduce((sum, c) => sum + c.companiesCount, 0),\n },\n message: configs.length === 1\n ? `Found Protokoll configuration at ${primaryConfig.path}`\n : `Found ${configs.length} Protokoll configurations (using nearest: ${primaryConfig.path})`,\n };\n}\n\nexport async function handleSuggestProject(args: { audioFile: string }) {\n const audioFile = resolve(args.audioFile);\n\n if (!await fileExists(audioFile)) {\n throw new Error(`Audio file not found: ${audioFile}`);\n }\n\n const result = await suggestProjectsForFile(audioFile);\n\n return {\n audioFile,\n ...result,\n instructions: result.needsUserInput\n ? 'Please specify which project this file belongs to, or let me list available projects.'\n : 'Ready to process with the detected project configuration.',\n };\n}\n","/**\n * Audio Processing Tools - Process audio files through transcription pipeline\n */\n// eslint-disable-next-line import/extensions\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { resolve, join, basename } from 'node:path';\nimport { readdir } from 'node:fs/promises';\nimport { glob } from 'glob';\nimport { Pipeline } from '@redaksjon/protokoll-engine';\nimport {\n DEFAULT_AUDIO_EXTENSIONS,\n DEFAULT_OUTPUT_STRUCTURE,\n DEFAULT_OUTPUT_FILENAME_OPTIONS,\n DEFAULT_MAX_AUDIO_SIZE,\n DEFAULT_INTERMEDIATE_DIRECTORY,\n DEFAULT_MODEL,\n DEFAULT_TRANSCRIPTION_MODEL,\n DEFAULT_REASONING_LEVEL,\n DEFAULT_TEMP_DIRECTORY,\n} from '@/constants';\nimport { fileExists, getAudioMetadata, getConfiguredDirectory, sanitizePath, type ProcessingResult } from './shared';\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Find an audio file by filename or partial filename\n * Searches in the workspace's configured input directory\n */\nasync function findAudioFile(\n filenameOrPath: string\n): Promise<string> {\n // If it's already an absolute path that exists, use it\n if (filenameOrPath.startsWith('/') && await fileExists(filenameOrPath)) {\n return filenameOrPath;\n }\n\n // Get the input directory from workspace config\n const inputDirectory = await getConfiguredDirectory('inputDirectory');\n \n // Search for the audio file\n const entries = await readdir(inputDirectory, { withFileTypes: true });\n const matches: string[] = [];\n \n for (const entry of entries) {\n if (entry.isFile()) {\n const filename = entry.name;\n const ext = filename.split('.').pop()?.toLowerCase();\n \n // Check if it's an audio file\n if (ext && DEFAULT_AUDIO_EXTENSIONS.includes(ext)) {\n // Check if filename matches\n if (filename === filenameOrPath || \n filename.includes(filenameOrPath) ||\n basename(filename, `.${ext}`) === filenameOrPath) {\n matches.push(join(inputDirectory, filename));\n }\n }\n }\n }\n\n if (matches.length === 0) {\n throw new Error(\n `No audio file found matching \"${filenameOrPath}\" in ${inputDirectory}. ` +\n `Try using the protokoll://audio/inbound resource to see available audio files.`\n );\n }\n\n if (matches.length === 1) {\n return matches[0];\n }\n\n // Multiple matches\n const matchNames = matches.map(m => basename(m)).join(', ');\n throw new Error(\n `Multiple audio files match \"${filenameOrPath}\": ${matchNames}. ` +\n `Please be more specific.`\n );\n}\n\n// ============================================================================\n// Tool Definitions\n// ============================================================================\n\nexport const processAudioTool: Tool = {\n name: 'protokoll_process_audio',\n description:\n 'Process an audio file through Protokoll\\'s intelligent transcription pipeline. ' +\n 'You can provide either an absolute path OR just a filename/partial filename. ' +\n 'If you provide a filename, it will search in the workspace\\'s configured input directory. ' +\n 'This tool uses workspace-level configuration automatically - no need to specify directories. ' +\n 'Transcribes audio using Whisper, then enhances it with context-aware processing ' +\n 'that corrects names, terms, and routes the output to the appropriate project folder. ' +\n 'Returns the enhanced transcript text and output file path.',\n inputSchema: {\n type: 'object',\n properties: {\n audioFile: {\n type: 'string',\n description: \n 'Filename, partial filename, or absolute path to the audio file. ' +\n 'Examples: \"recording.m4a\", \"2026-01-29\", \"/full/path/to/audio.m4a\"',\n },\n projectId: {\n type: 'string',\n description: 'Specific project ID to use for routing (helpful when multiple projects exist)',\n },\n outputDirectory: {\n type: 'string',\n description: 'Override the workspace output directory',\n },\n model: {\n type: 'string',\n description: 'LLM model for enhancement (default: gpt-5.2)',\n },\n transcriptionModel: {\n type: 'string',\n description: 'Transcription model (default: whisper-1)',\n },\n },\n required: ['audioFile'],\n },\n};\n\nexport const batchProcessTool: Tool = {\n name: 'protokoll_batch_process',\n description:\n 'Process multiple audio files in a directory. ' +\n 'If no directory is specified, uses the workspace\\'s configured input directory. ' +\n 'This tool uses workspace-level configuration automatically - no need to specify directories. ' +\n 'Finds all audio files matching the configured extensions and processes them sequentially. ' +\n 'Returns a summary of all processed files with their output paths.',\n inputSchema: {\n type: 'object',\n properties: {\n inputDirectory: {\n type: 'string',\n description: \n 'Optional: Directory containing audio files. ' +\n 'If not specified, uses the workspace input directory.',\n },\n extensions: {\n type: 'array',\n items: { type: 'string' },\n description: 'Audio file extensions to process (default: [\".m4a\", \".mp3\", \".wav\", \".webm\"])',\n },\n outputDirectory: {\n type: 'string',\n description: 'Override the workspace output directory',\n },\n },\n required: [],\n },\n};\n\n// ============================================================================\n// Tool Handlers\n// ============================================================================\n\nexport async function handleProcessAudio(args: {\n audioFile: string;\n projectId?: string;\n outputDirectory?: string;\n model?: string;\n transcriptionModel?: string;\n}): Promise<ProcessingResult> {\n // Import server config\n const ServerConfig = await import('../serverConfig');\n \n // Find the audio file (handles both paths and filenames)\n const audioFile = await findAudioFile(args.audioFile);\n\n // Get workspace configuration\n const config = ServerConfig.getServerConfig();\n const context = config.context;\n \n if (!context) {\n throw new Error('Protokoll context not available. Ensure .protokoll directory exists in workspace.');\n }\n\n // Get configuration from context\n const contextConfig = context.getConfig();\n const outputDirectory = args.outputDirectory || config.outputDirectory;\n const outputStructure = (contextConfig.outputStructure as string) || DEFAULT_OUTPUT_STRUCTURE;\n const outputFilenameOptions = (contextConfig.outputFilenameOptions as string[]) || DEFAULT_OUTPUT_FILENAME_OPTIONS;\n const processedDirectory = config.processedDirectory ?? undefined;\n\n // Get audio file metadata (creation time and hash)\n const { creationTime, hash } = await getAudioMetadata(audioFile);\n\n // Create pipeline\n const pipeline = await Pipeline.create({\n model: args.model || DEFAULT_MODEL,\n transcriptionModel: args.transcriptionModel || DEFAULT_TRANSCRIPTION_MODEL,\n reasoningLevel: DEFAULT_REASONING_LEVEL,\n interactive: false, // MCP is non-interactive\n selfReflection: false,\n silent: true,\n debug: false,\n dryRun: false,\n contextDirectory: config.workspaceRoot || undefined,\n intermediateDir: DEFAULT_INTERMEDIATE_DIRECTORY,\n keepIntermediates: false,\n outputDirectory,\n outputStructure,\n outputFilenameOptions,\n processedDirectory: processedDirectory || undefined,\n maxAudioSize: DEFAULT_MAX_AUDIO_SIZE,\n tempDirectory: DEFAULT_TEMP_DIRECTORY,\n });\n\n // Process through pipeline\n const result = await pipeline.process({\n audioFile,\n creation: creationTime,\n hash,\n });\n\n // Sanitize outputPath to ensure no absolute paths are exposed\n const sanitizedOutputPath = await sanitizePath(result.outputPath, outputDirectory);\n\n return {\n outputPath: sanitizedOutputPath,\n enhancedText: result.enhancedText,\n rawTranscript: result.rawTranscript,\n routedProject: result.routedProject ?? undefined,\n routingConfidence: result.routingConfidence,\n processingTime: result.processingTime,\n toolsUsed: result.toolsUsed,\n correctionsApplied: result.correctionsApplied,\n };\n}\n\nexport async function handleBatchProcess(args: {\n inputDirectory?: string;\n extensions?: string[];\n outputDirectory?: string;\n}): Promise<{ processed: ProcessingResult[]; errors: { file: string; error: string }[] }> {\n // Get directory from args or workspace config\n const inputDir = args.inputDirectory \n ? resolve(args.inputDirectory)\n : await getConfiguredDirectory('inputDirectory');\n \n const extensions = args.extensions || ['.m4a', '.mp3', '.wav', '.webm'];\n\n if (!await fileExists(inputDir)) {\n throw new Error(`Input directory not found: ${inputDir}`);\n }\n\n const patterns = extensions.map(ext => `**/*${ext}`);\n const files = await glob(patterns, { cwd: inputDir, nodir: true, absolute: true });\n\n if (files.length === 0) {\n return { processed: [], errors: [] };\n }\n\n const processed: ProcessingResult[] = [];\n const errors: { file: string; error: string }[] = [];\n\n for (const file of files) {\n try {\n const result = await handleProcessAudio({\n audioFile: file,\n outputDirectory: args.outputDirectory,\n });\n processed.push(result);\n } catch (error) {\n // Sanitize file path in error to ensure no absolute paths are exposed\n const sanitizedFile = await sanitizePath(file, inputDir);\n errors.push({\n file: sanitizedFile,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n return { processed, errors };\n}\n","/**\n * Context Management Tools - View and search context entities\n */\n// eslint-disable-next-line import/extensions\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as Context from '@/context';\nimport type { ContextInstance } from '@/context';\nimport type { Entity, EntityType } from '@/context/types';\nimport { formatEntity } from './shared';\nimport { \n findPersonResilient, \n findCompanyResilient, \n findTermResilient, \n findProjectResilient,\n findIgnoredResilient \n} from '@redaksjon/protokoll-engine';\n\n/**\n * Get the context instance from ServerConfig, or create a new one if not available\n */\nasync function getContextInstance(contextDirectory?: string): Promise<ContextInstance> {\n // Import here to avoid circular dependencies\n const ServerConfig = await import('../serverConfig');\n \n // Validate that contextDirectory is not provided in remote mode\n if (contextDirectory && ServerConfig.isRemoteMode()) {\n throw new Error(\n 'contextDirectory parameter is not accepted in remote mode. ' +\n 'This server is pre-configured with workspace directories from protokoll-config.yaml. ' +\n 'Use the protokoll_info tool to check server configuration.'\n );\n }\n \n // If server has an initialized context, use it\n const serverContext = ServerConfig.getContext();\n if (serverContext) {\n return serverContext;\n }\n \n // Fallback: create a new context (for backwards compatibility)\n return Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n}\n\n// ============================================================================\n// Tool Definitions\n// ============================================================================\n\nexport const contextStatusTool: Tool = {\n name: 'protokoll_context_status',\n description:\n 'Get the status of the Protokoll context system. ' +\n 'Shows discovered .protokoll directories, entity counts, and configuration status. ' +\n 'Use this to understand what context is available for transcription enhancement.',\n inputSchema: {\n type: 'object',\n properties: {\n contextDirectory: {\n type: 'string',\n description: 'Path to start searching for .protokoll directories (default: cwd)',\n },\n },\n required: [],\n },\n};\n\nexport const listProjectsTool: Tool = {\n name: 'protokoll_list_projects',\n description:\n 'List all projects configured in the context. ' +\n 'Projects define routing rules for where transcripts should be saved ' +\n 'and what classification signals trigger them.',\n inputSchema: {\n type: 'object',\n properties: {\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n includeInactive: {\n type: 'boolean',\n description: 'Include inactive projects (default: false)',\n },\n },\n required: [],\n },\n};\n\nexport const listPeopleTool: Tool = {\n name: 'protokoll_list_people',\n description:\n 'List all people configured in the context. ' +\n 'People entries help Protokoll recognize and correctly spell names that ' +\n 'Whisper might mishear (using sounds_like phonetic variants).',\n inputSchema: {\n type: 'object',\n properties: {\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: [],\n },\n};\n\nexport const listTermsTool: Tool = {\n name: 'protokoll_list_terms',\n description:\n 'List all technical terms and abbreviations in the context. ' +\n 'Terms help Protokoll correctly transcribe domain-specific vocabulary.',\n inputSchema: {\n type: 'object',\n properties: {\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: [],\n },\n};\n\nexport const listCompaniesTool: Tool = {\n name: 'protokoll_list_companies',\n description:\n 'List all companies configured in the context. ' +\n 'Company entries help recognize organization names in transcripts.',\n inputSchema: {\n type: 'object',\n properties: {\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: [],\n },\n};\n\nexport const searchContextTool: Tool = {\n name: 'protokoll_search_context',\n description:\n 'Search across all context entity types (projects, people, terms, companies). ' +\n 'Returns matching entities with their type and key details.',\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search query to match against entity names, IDs, and sounds_like variants',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['query'],\n },\n};\n\nexport const getEntityTool: Tool = {\n name: 'protokoll_get_entity',\n description:\n 'Get detailed information about a specific context entity. ' +\n 'Returns the full YAML configuration including sounds_like variants, routing, etc.',\n inputSchema: {\n type: 'object',\n properties: {\n entityType: {\n type: 'string',\n enum: ['project', 'person', 'term', 'company', 'ignored'],\n description: 'Type of entity to retrieve',\n },\n entityId: {\n type: 'string',\n description: 'ID of the entity to retrieve',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['entityType', 'entityId'],\n },\n};\n\n// ============================================================================\n// Tool Handlers\n// ============================================================================\n\nexport async function handleContextStatus(args: { contextDirectory?: string }) {\n const context = await getContextInstance(args.contextDirectory);\n\n const dirs = context.getDiscoveredDirs();\n const config = context.getConfig();\n\n return {\n hasContext: context.hasContext(),\n discoveredDirectories: dirs.map(d => ({\n path: d.path,\n level: d.level,\n isPrimary: d.level === 0,\n })),\n entityCounts: {\n projects: context.getAllProjects().length,\n people: context.getAllPeople().length,\n terms: context.getAllTerms().length,\n companies: context.getAllCompanies().length,\n ignored: context.getAllIgnored().length,\n },\n config: {\n outputDirectory: config.outputDirectory,\n outputStructure: config.outputStructure,\n model: config.model,\n },\n };\n}\n\nexport async function handleListProjects(args: { contextDirectory?: string; includeInactive?: boolean }) {\n const context = await getContextInstance(args.contextDirectory);\n\n let projects = context.getAllProjects();\n if (!args.includeInactive) {\n projects = projects.filter(p => p.active !== false);\n }\n\n return {\n count: projects.length,\n projects: projects.map(p => ({\n id: p.id,\n name: p.name,\n active: p.active !== false,\n destination: p.routing?.destination,\n structure: p.routing?.structure,\n contextType: p.classification?.context_type,\n triggerPhrases: p.classification?.explicit_phrases,\n })),\n };\n}\n\nexport async function handleListPeople(args: { contextDirectory?: string }) {\n const context = await getContextInstance(args.contextDirectory);\n\n const people = context.getAllPeople();\n\n return {\n count: people.length,\n people: people.map(p => ({\n id: p.id,\n name: p.name,\n company: p.company,\n role: p.role,\n sounds_like: p.sounds_like,\n })),\n };\n}\n\nexport async function handleListTerms(args: { contextDirectory?: string }) {\n const context = await getContextInstance(args.contextDirectory);\n\n const terms = context.getAllTerms();\n\n return {\n count: terms.length,\n terms: terms.map(t => ({\n id: t.id,\n name: t.name,\n expansion: t.expansion,\n domain: t.domain,\n sounds_like: t.sounds_like,\n })),\n };\n}\n\nexport async function handleListCompanies(args: { contextDirectory?: string }) {\n const context = await getContextInstance(args.contextDirectory);\n\n const companies = context.getAllCompanies();\n\n return {\n count: companies.length,\n companies: companies.map(c => ({\n id: c.id,\n name: c.name,\n fullName: c.fullName,\n industry: c.industry,\n sounds_like: c.sounds_like,\n })),\n };\n}\n\nexport async function handleSearchContext(args: { query: string; contextDirectory?: string }) {\n const context = await getContextInstance(args.contextDirectory);\n\n const results = context.search(args.query);\n\n return {\n query: args.query,\n count: results.length,\n results: results.map(formatEntity),\n };\n}\n\nexport async function handleGetEntity(args: { entityType: EntityType; entityId: string; contextDirectory?: string }) {\n const context = await getContextInstance(args.contextDirectory);\n\n let entity: Entity;\n switch (args.entityType) {\n case 'project':\n entity = findProjectResilient(context, args.entityId);\n break;\n case 'person':\n entity = findPersonResilient(context, args.entityId);\n break;\n case 'term':\n entity = findTermResilient(context, args.entityId);\n break;\n case 'company':\n entity = findCompanyResilient(context, args.entityId);\n break;\n case 'ignored':\n entity = findIgnoredResilient(context, args.entityId);\n break;\n default:\n throw new Error(`Unknown entity type: ${args.entityType}`);\n }\n\n const filePath = context.getEntityFilePath(entity);\n\n return {\n ...formatEntity(entity),\n filePath,\n };\n}\n","/* eslint-disable import/extensions */\n/**\n * Entity Tools - Create, update, delete, and manage context entities\n */\n \nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as Context from '@/context';\nimport type { Person, Project, Term, Company, Entity, EntityRelationship } from '@/context/types';\nimport { \n findPersonResilient, \n findTermResilient, \n findCompanyResilient, \n findProjectResilient,\n findIgnoredResilient \n} from '@redaksjon/protokoll-engine';\n \nimport { formatEntity, slugify, mergeArray } from './shared.js';\n\n// ============================================================================\n// Tool Definitions\n// ============================================================================\n\nexport const addPersonTool: Tool = {\n name: 'protokoll_add_person',\n description:\n 'Add a new person to the context. ' +\n 'People entries help Protokoll recognize names that Whisper mishears. ' +\n 'Include sounds_like variants for phonetic matching.',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Full name of the person',\n },\n id: {\n type: 'string',\n description: 'Unique ID (default: slugified name)',\n },\n firstName: {\n type: 'string',\n description: 'First name',\n },\n lastName: {\n type: 'string',\n description: 'Last name',\n },\n company: {\n type: 'string',\n description: 'Company ID this person is associated with',\n },\n role: {\n type: 'string',\n description: 'Role or job title',\n },\n sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Phonetic variants (how Whisper might mishear the name)',\n },\n context: {\n type: 'string',\n description: 'Additional context about this person',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['name'],\n },\n};\n\nexport const editPersonTool: Tool = {\n name: 'protokoll_edit_person',\n description:\n 'Edit an existing person with manual modifications. ' +\n 'Allows direct edits: adding specific sounds_like variants, changing company, role, etc. ' +\n 'For the sounds_like array, use add_sounds_like to append or remove_sounds_like to delete specific values, ' +\n 'or use sounds_like to replace the entire array.',\n inputSchema: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Person ID to edit',\n },\n name: {\n type: 'string',\n description: 'Update the display name',\n },\n firstName: {\n type: 'string',\n description: 'Set the first name',\n },\n lastName: {\n type: 'string',\n description: 'Set the last name',\n },\n company: {\n type: 'string',\n description: 'Set the company ID this person is associated with',\n },\n role: {\n type: 'string',\n description: 'Set the role or job title',\n },\n context: {\n type: 'string',\n description: 'Set additional context about this person',\n },\n sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Replace all sounds_like variants with this array',\n },\n add_sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these sounds_like variants to existing ones',\n },\n remove_sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these sounds_like variants',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['id'],\n },\n};\n\nexport const addProjectTool: Tool = {\n name: 'protokoll_add_project',\n description:\n 'Add a new project to the context with optional smart assistance for generating metadata. ' +\n 'Projects define where transcripts should be routed based on classification signals. ' +\n 'Smart assistance auto-generates sounds_like (phonetic variants for transcription correction) and ' +\n 'explicit_phrases (content-matching trigger phrases for classification). ' +\n 'Provide a source URL or file path to also generate topics and description from content analysis.',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Project name (required)',\n },\n id: {\n type: 'string',\n description: 'Unique ID (default: slugified name)',\n },\n source: {\n type: 'string',\n description: 'URL or file path to analyze for generating topics, description, sounds_like, and explicit_phrases (optional)',\n },\n destination: {\n type: 'string',\n description: 'Output directory for this project\\'s transcripts',\n },\n structure: {\n type: 'string',\n enum: ['none', 'year', 'month', 'day'],\n description: 'Directory structure (default: month)',\n },\n contextType: {\n type: 'string',\n enum: ['work', 'personal', 'mixed'],\n description: 'Context type for classification (default: work)',\n },\n explicit_phrases: {\n type: 'array',\n items: { type: 'string' },\n description: 'Content-matching trigger phrases for classification (auto-generated if smart assistance enabled)',\n },\n sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Phonetic variants of project NAME for transcription correction (auto-generated if smart assistance enabled)',\n },\n topics: {\n type: 'array',\n items: { type: 'string' },\n description: 'Topic keywords for classification (auto-generated from source if provided)',\n },\n description: {\n type: 'string',\n description: 'Project description (auto-generated from source if provided)',\n },\n useSmartAssist: {\n type: 'boolean',\n description: 'Enable smart assistance for auto-generating metadata (default: true if configured)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['name'],\n },\n};\n\nexport const editProjectTool: Tool = {\n name: 'protokoll_edit_project',\n description:\n 'Edit an existing project with manual modifications. Unlike protokoll_update_project (which regenerates from a source), ' +\n 'this allows direct edits: adding specific sounds_like variants, changing routing, modifying classification, managing relationships, etc. ' +\n 'For array fields (sounds_like, topics, explicit_phrases, associated_people, associated_companies, children, siblings, related_terms), ' +\n 'use add_* to append or remove_* to delete specific values, or use the base field name to replace the entire array.',\n inputSchema: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Project ID to edit',\n },\n name: {\n type: 'string',\n description: 'Update the project name',\n },\n description: {\n type: 'string',\n description: 'Set the project description',\n },\n destination: {\n type: 'string',\n description: 'Set the output directory for transcripts',\n },\n structure: {\n type: 'string',\n enum: ['none', 'year', 'month', 'day'],\n description: 'Set the directory structure',\n },\n contextType: {\n type: 'string',\n enum: ['work', 'personal', 'mixed'],\n description: 'Set the context type for classification',\n },\n active: {\n type: 'boolean',\n description: 'Set whether the project is active',\n },\n sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Replace all sounds_like variants with this array',\n },\n add_sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these sounds_like variants to existing ones',\n },\n remove_sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these sounds_like variants',\n },\n topics: {\n type: 'array',\n items: { type: 'string' },\n description: 'Replace all classification topics with this array',\n },\n add_topics: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these topics to existing ones',\n },\n remove_topics: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these topics',\n },\n explicit_phrases: {\n type: 'array',\n items: { type: 'string' },\n description: 'Replace all explicit trigger phrases with this array',\n },\n add_explicit_phrases: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these explicit trigger phrases',\n },\n remove_explicit_phrases: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these explicit trigger phrases',\n },\n associated_people: {\n type: 'array',\n items: { type: 'string' },\n description: 'Replace all associated people (person IDs) with this array',\n },\n add_associated_people: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these person IDs to associated people',\n },\n remove_associated_people: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these person IDs from associated people',\n },\n associated_companies: {\n type: 'array',\n items: { type: 'string' },\n description: 'Replace all associated companies (company IDs) with this array',\n },\n add_associated_companies: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these company IDs to associated companies',\n },\n remove_associated_companies: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these company IDs from associated companies',\n },\n parent: {\n type: 'string',\n description: 'Set parent project ID (for project relationships)',\n },\n add_children: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these project IDs as children',\n },\n remove_children: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these project IDs from children',\n },\n add_siblings: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these project IDs as siblings',\n },\n remove_siblings: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these project IDs from siblings',\n },\n add_related_terms: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these term IDs as related terms (for project relationships)',\n },\n remove_related_terms: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these term IDs from related terms',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['id'],\n },\n};\n\nexport const updateProjectTool: Tool = {\n name: 'protokoll_update_project',\n description:\n 'Update an existing project by regenerating metadata from a source URL or file. ' +\n 'Fetches content and uses LLM to regenerate sounds_like, explicit_phrases, topics, and description.',\n inputSchema: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Project ID to update',\n },\n source: {\n type: 'string',\n description: 'URL or file path to analyze for regenerating metadata',\n },\n name: {\n type: 'string',\n description: 'Update project name (optional)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['id', 'source'],\n },\n};\n\nexport const addTermTool: Tool = {\n name: 'protokoll_add_term',\n description:\n 'Add a new technical term or abbreviation to the context. ' +\n 'Terms help Protokoll correctly transcribe domain-specific vocabulary and enable topic-based routing. ' +\n 'Include sounds_like variants for phonetic matching, description for clarity, and topics for classification.',\n inputSchema: {\n type: 'object',\n properties: {\n term: {\n type: 'string',\n description: 'The term or abbreviation',\n },\n id: {\n type: 'string',\n description: 'Unique ID (default: slugified term)',\n },\n expansion: {\n type: 'string',\n description: 'Full expansion if this is an acronym',\n },\n domain: {\n type: 'string',\n description: 'Domain or field (e.g., devops, engineering, security, finance)',\n },\n description: {\n type: 'string',\n description: 'Clear explanation of what the term means',\n },\n sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Phonetic variants (how Whisper might mishear the term)',\n },\n topics: {\n type: 'array',\n items: { type: 'string' },\n description: 'Related topic keywords for classification (e.g., containers, orchestration, devops)',\n },\n projects: {\n type: 'array',\n items: { type: 'string' },\n description: 'Associated project IDs where this term is relevant',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['term'],\n },\n};\n\nexport const editTermTool: Tool = {\n name: 'protokoll_edit_term',\n description:\n 'Edit an existing term with manual modifications. Unlike protokoll_update_term (which regenerates from a source), ' +\n 'this allows direct edits: adding specific sounds_like variants, changing description, modifying topics, etc. ' +\n 'For array fields (sounds_like, topics, projects), use add_* to append or remove_* to delete specific values, ' +\n 'or use the base field name to replace the entire array.',\n inputSchema: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Term ID to edit',\n },\n expansion: {\n type: 'string',\n description: 'Set the expansion (full form if acronym)',\n },\n domain: {\n type: 'string',\n description: 'Set the domain (e.g., devops, engineering)',\n },\n description: {\n type: 'string',\n description: 'Set the description',\n },\n sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Replace all sounds_like variants with this array',\n },\n add_sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these sounds_like variants to existing ones',\n },\n remove_sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these sounds_like variants',\n },\n topics: {\n type: 'array',\n items: { type: 'string' },\n description: 'Replace all topics with this array',\n },\n add_topics: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these topics to existing ones',\n },\n remove_topics: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these topics',\n },\n projects: {\n type: 'array',\n items: { type: 'string' },\n description: 'Replace all project associations with this array',\n },\n add_projects: {\n type: 'array',\n items: { type: 'string' },\n description: 'Add these project associations',\n },\n remove_projects: {\n type: 'array',\n items: { type: 'string' },\n description: 'Remove these project associations',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['id'],\n },\n};\n\nexport const updateTermTool: Tool = {\n name: 'protokoll_update_term',\n description:\n 'Update an existing term by regenerating metadata from a source URL or file. ' +\n 'Fetches content and uses LLM to regenerate description, topics, domain, and sounds_like.',\n inputSchema: {\n type: 'object',\n properties: {\n id: {\n type: 'string',\n description: 'Term ID to update',\n },\n source: {\n type: 'string',\n description: 'URL or file path to analyze for regenerating metadata',\n },\n expansion: {\n type: 'string',\n description: 'Update expansion (optional)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['id', 'source'],\n },\n};\n\nexport const mergeTermsTool: Tool = {\n name: 'protokoll_merge_terms',\n description:\n 'Merge two duplicate terms into one. Combines metadata (sounds_like, topics, projects) and deletes the source term.',\n inputSchema: {\n type: 'object',\n properties: {\n sourceId: {\n type: 'string',\n description: 'ID of the term to merge from (will be deleted)',\n },\n targetId: {\n type: 'string',\n description: 'ID of the term to merge into (will be kept and updated)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['sourceId', 'targetId'],\n },\n};\n\nexport const addCompanyTool: Tool = {\n name: 'protokoll_add_company',\n description:\n 'Add a new company to the context. ' +\n 'Company entries help recognize organization names in transcripts.',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Company name',\n },\n id: {\n type: 'string',\n description: 'Unique ID (default: slugified name)',\n },\n fullName: {\n type: 'string',\n description: 'Full legal name',\n },\n industry: {\n type: 'string',\n description: 'Industry or sector',\n },\n sounds_like: {\n type: 'array',\n items: { type: 'string' },\n description: 'Phonetic variants',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['name'],\n },\n};\n\nexport const deleteEntityTool: Tool = {\n name: 'protokoll_delete_entity',\n description:\n 'Delete an entity from the context. ' +\n 'Removes the entity\\'s YAML file from the context directory.',\n inputSchema: {\n type: 'object',\n properties: {\n entityType: {\n type: 'string',\n enum: ['project', 'person', 'term', 'company', 'ignored'],\n description: 'Type of entity to delete',\n },\n entityId: {\n type: 'string',\n description: 'ID of the entity to delete',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['entityType', 'entityId'],\n },\n};\n\n// ============================================================================\n// Tool Handlers\n// ============================================================================\n\nexport async function handleAddPerson(args: {\n name: string;\n id?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n role?: string;\n sounds_like?: string[];\n context?: string;\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No .protokoll directory found. Initialize context first.');\n }\n\n const id = args.id || slugify(args.name);\n\n if (context.getPerson(id)) {\n throw new Error(`Person with ID \"${id}\" already exists`);\n }\n\n const person: Person = {\n id,\n name: args.name,\n type: 'person',\n ...(args.firstName && { firstName: args.firstName }),\n ...(args.lastName && { lastName: args.lastName }),\n ...(args.company && { company: args.company }),\n ...(args.role && { role: args.role }),\n ...(args.sounds_like && { sounds_like: args.sounds_like }),\n ...(args.context && { context: args.context }),\n };\n\n await context.saveEntity(person);\n\n return {\n success: true,\n message: `Person \"${args.name}\" added successfully`,\n entity: formatEntity(person),\n };\n}\n\nexport async function handleEditPerson(args: {\n id: string;\n name?: string;\n firstName?: string;\n lastName?: string;\n company?: string;\n role?: string;\n context?: string;\n sounds_like?: string[];\n add_sounds_like?: string[];\n remove_sounds_like?: string[];\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No .protokoll directory found. Initialize context first.');\n }\n\n const existingPerson = findPersonResilient(context, args.id);\n\n const updatedSoundsLike = mergeArray(\n existingPerson.sounds_like,\n args.sounds_like,\n args.add_sounds_like,\n args.remove_sounds_like\n );\n\n // Build updated person\n const updatedPerson: Person = {\n ...existingPerson,\n ...(args.name !== undefined && { name: args.name }),\n ...(args.firstName !== undefined && { firstName: args.firstName }),\n ...(args.lastName !== undefined && { lastName: args.lastName }),\n ...(args.company !== undefined && { company: args.company }),\n ...(args.role !== undefined && { role: args.role }),\n ...(args.context !== undefined && { context: args.context }),\n updatedAt: new Date(),\n };\n\n // Handle sounds_like array\n if (updatedSoundsLike !== undefined) {\n updatedPerson.sounds_like = updatedSoundsLike;\n } else if (existingPerson.sounds_like && (args.sounds_like !== undefined || args.remove_sounds_like)) {\n delete updatedPerson.sounds_like;\n }\n\n await context.saveEntity(updatedPerson, true);\n\n // Build summary of changes\n const changes: string[] = [];\n if (args.name !== undefined) changes.push(`name: \"${args.name}\"`);\n if (args.firstName !== undefined) changes.push(`firstName: \"${args.firstName}\"`);\n if (args.lastName !== undefined) changes.push(`lastName: \"${args.lastName}\"`);\n if (args.company !== undefined) changes.push(`company: \"${args.company}\"`);\n if (args.role !== undefined) changes.push(`role: \"${args.role}\"`);\n if (args.context !== undefined) changes.push(`context updated`);\n if (args.sounds_like !== undefined) changes.push(`sounds_like replaced with ${args.sounds_like.length} items`);\n if (args.add_sounds_like?.length) changes.push(`added ${args.add_sounds_like.length} sounds_like variants`);\n if (args.remove_sounds_like?.length) changes.push(`removed ${args.remove_sounds_like.length} sounds_like variants`);\n\n return {\n success: true,\n message: `Updated person \"${existingPerson.name}\"`,\n changes,\n person: formatEntity(updatedPerson),\n };\n}\n\nexport async function handleAddProject(args: {\n name: string;\n id?: string;\n source?: string;\n destination?: string;\n structure?: 'none' | 'year' | 'month' | 'day';\n contextType?: 'work' | 'personal' | 'mixed';\n explicit_phrases?: string[];\n sounds_like?: string[];\n topics?: string[];\n description?: string;\n useSmartAssist?: boolean;\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No .protokoll directory found. Initialize context first.');\n }\n\n const id = args.id || slugify(args.name);\n\n if (context.getProject(id)) {\n throw new Error(`Project with ID \"${id}\" already exists`);\n }\n\n // Smart assistance integration\n const smartConfig = context.getSmartAssistanceConfig();\n const useSmartAssist = args.useSmartAssist !== false && smartConfig.enabled;\n\n const soundsLike = args.sounds_like || [];\n const triggerPhrases = args.explicit_phrases || [];\n const topics = args.topics || [];\n const description = args.description;\n const suggestedName: string | undefined = undefined;\n\n if (useSmartAssist) {\n // ProjectAssist temporarily unavailable - needs extraction from CLI\n throw new Error('Smart assistance temporarily unavailable');\n \n /* Unreachable code - commented out until ProjectAssist is re-implemented\n // const assist = ProjectAssist.create(smartConfig);\n\n // Analyze source if provided\n if (args.source) {\n const suggestions = await assist.analyzeSource(args.source, args.name);\n\n // Only use suggestions for fields not explicitly provided (undefined, not just empty)\n if (args.sounds_like === undefined) {\n soundsLike = suggestions.soundsLike;\n }\n if (args.explicit_phrases === undefined) {\n triggerPhrases = suggestions.triggerPhrases;\n }\n if (args.topics === undefined && suggestions.topics) {\n topics = suggestions.topics;\n }\n if (!args.description && suggestions.description) {\n description = suggestions.description;\n }\n if (suggestions.name) {\n suggestedName = suggestions.name;\n }\n } else {\n // Generate sounds_like and trigger phrases from name even without source\n if (args.sounds_like === undefined) {\n soundsLike = await assist.generateSoundsLike(args.name);\n }\n if (args.explicit_phrases === undefined) {\n triggerPhrases = await assist.generateTriggerPhrases(args.name);\n }\n }\n */\n }\n\n const project: Project = {\n id,\n name: args.name,\n type: 'project',\n classification: {\n context_type: args.contextType || 'work',\n explicit_phrases: triggerPhrases,\n ...(topics.length && { topics }),\n },\n routing: {\n ...(args.destination && { destination: args.destination }),\n structure: args.structure || 'month',\n filename_options: ['date', 'time', 'subject'],\n },\n // Include sounds_like if explicitly provided (even if empty) or if generated\n ...((args.sounds_like !== undefined || soundsLike.length) && { sounds_like: soundsLike }),\n ...(description && { description }),\n active: true,\n };\n\n await context.saveEntity(project);\n\n return {\n success: true,\n message: `Project \"${args.name}\" added successfully`,\n entity: formatEntity(project),\n smartAssistUsed: useSmartAssist,\n ...(suggestedName ? { suggestedName } : {}),\n generated: {\n soundsLike,\n triggerPhrases,\n topics,\n description,\n },\n };\n}\n\nexport async function handleEditProject(args: {\n id: string;\n name?: string;\n description?: string;\n destination?: string;\n structure?: 'none' | 'year' | 'month' | 'day';\n contextType?: 'work' | 'personal' | 'mixed';\n active?: boolean;\n sounds_like?: string[];\n add_sounds_like?: string[];\n remove_sounds_like?: string[];\n topics?: string[];\n add_topics?: string[];\n remove_topics?: string[];\n explicit_phrases?: string[];\n add_explicit_phrases?: string[];\n remove_explicit_phrases?: string[];\n associated_people?: string[];\n add_associated_people?: string[];\n remove_associated_people?: string[];\n associated_companies?: string[];\n add_associated_companies?: string[];\n remove_associated_companies?: string[];\n parent?: string;\n add_children?: string[];\n remove_children?: string[];\n add_siblings?: string[];\n remove_siblings?: string[];\n add_related_terms?: string[];\n remove_related_terms?: string[];\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No .protokoll directory found. Initialize context first.');\n }\n\n const existingProject = findProjectResilient(context, args.id);\n\n const updatedSoundsLike = mergeArray(\n existingProject.sounds_like,\n args.sounds_like,\n args.add_sounds_like,\n args.remove_sounds_like\n );\n\n const updatedTopics = mergeArray(\n existingProject.classification?.topics,\n args.topics,\n args.add_topics,\n args.remove_topics\n );\n\n const updatedExplicitPhrases = mergeArray(\n existingProject.classification?.explicit_phrases,\n args.explicit_phrases,\n args.add_explicit_phrases,\n args.remove_explicit_phrases\n );\n\n const updatedAssociatedPeople = mergeArray(\n existingProject.classification?.associated_people,\n args.associated_people,\n args.add_associated_people,\n args.remove_associated_people\n );\n\n const updatedAssociatedCompanies = mergeArray(\n existingProject.classification?.associated_companies,\n args.associated_companies,\n args.add_associated_companies,\n args.remove_associated_companies\n );\n\n // Handle relationships\n // Helper functions for relationships\n const createEntityUri = (type: string, id: string): string => `redaksjon://${type}/${id}`;\n const getIdFromUri = (uri: string): string | null => {\n const match = uri.match(/^redaksjon:\\/\\/[^/]+\\/(.+)$/);\n return match ? match[1] : null;\n };\n const getEntityIdsByRelationshipType = (relationships: EntityRelationship[] | undefined, relationshipType: string): string[] => {\n if (!relationships) return [];\n return relationships\n .filter(r => r.relationship === relationshipType)\n .map(r => getIdFromUri(r.uri))\n .filter((id): id is string => id !== null);\n };\n const setRelationships = (relationships: EntityRelationship[] | undefined, type: string, entityType: string, entityIds: string[]): EntityRelationship[] => {\n const rels = relationships || [];\n const filtered = rels.filter(r => r.relationship !== type);\n const newRels = entityIds.map(id => ({ uri: createEntityUri(entityType, id), relationship: type }));\n return [...filtered, ...newRels];\n };\n const addRelationship = (relationships: EntityRelationship[] | undefined, type: string, entityType: string, entityId: string): EntityRelationship[] => {\n const rels = relationships || [];\n const uri = createEntityUri(entityType, entityId);\n const filtered = rels.filter(r => !(r.relationship === type && r.uri === uri));\n return [...filtered, { uri, relationship: type }];\n };\n\n const existingChildren = getEntityIdsByRelationshipType(existingProject.relationships, 'child');\n const updatedChildren = mergeArray(\n existingChildren,\n undefined,\n args.add_children,\n args.remove_children\n );\n\n const existingSiblings = getEntityIdsByRelationshipType(existingProject.relationships, 'sibling');\n const updatedSiblings = mergeArray(\n existingSiblings,\n undefined,\n args.add_siblings,\n args.remove_siblings\n );\n\n const existingRelatedTerms = getEntityIdsByRelationshipType(existingProject.relationships, 'related_term');\n const updatedRelatedTerms = mergeArray(\n existingRelatedTerms,\n undefined,\n args.add_related_terms,\n args.remove_related_terms\n );\n\n // Build updated project\n const updatedProject: Project = {\n ...existingProject,\n ...(args.name !== undefined && { name: args.name }),\n ...(args.description !== undefined && { description: args.description }),\n ...(args.active !== undefined && { active: args.active }),\n classification: {\n ...existingProject.classification,\n ...(args.contextType !== undefined && { context_type: args.contextType }),\n },\n routing: {\n ...existingProject.routing,\n ...(args.destination !== undefined && { destination: args.destination }),\n ...(args.structure !== undefined && { structure: args.structure }),\n },\n updatedAt: new Date(),\n };\n\n // Handle sounds_like at project level\n if (updatedSoundsLike !== undefined) {\n updatedProject.sounds_like = updatedSoundsLike;\n } else if (existingProject.sounds_like && (args.sounds_like !== undefined || args.remove_sounds_like)) {\n delete updatedProject.sounds_like;\n }\n\n // Handle classification arrays\n if (updatedTopics !== undefined) {\n updatedProject.classification.topics = updatedTopics;\n } else if (existingProject.classification?.topics && (args.topics !== undefined || args.remove_topics)) {\n delete updatedProject.classification.topics;\n }\n\n if (updatedExplicitPhrases !== undefined) {\n updatedProject.classification.explicit_phrases = updatedExplicitPhrases;\n } else if (existingProject.classification?.explicit_phrases && (args.explicit_phrases !== undefined || args.remove_explicit_phrases)) {\n delete updatedProject.classification.explicit_phrases;\n }\n\n if (updatedAssociatedPeople !== undefined) {\n updatedProject.classification.associated_people = updatedAssociatedPeople;\n } else if (existingProject.classification?.associated_people && (args.associated_people !== undefined || args.remove_associated_people)) {\n delete updatedProject.classification.associated_people;\n }\n\n if (updatedAssociatedCompanies !== undefined) {\n updatedProject.classification.associated_companies = updatedAssociatedCompanies;\n } else if (existingProject.classification?.associated_companies && (args.associated_companies !== undefined || args.remove_associated_companies)) {\n delete updatedProject.classification.associated_companies;\n }\n\n // Handle relationships\n let relationships: EntityRelationship[] = existingProject.relationships ? [...existingProject.relationships] : [];\n \n if (args.parent !== undefined) {\n relationships = addRelationship(relationships, 'parent', 'project', args.parent);\n }\n \n if (updatedChildren !== undefined && updatedChildren !== existingChildren) {\n relationships = setRelationships(relationships, 'child', 'project', updatedChildren);\n }\n \n if (updatedSiblings !== undefined && updatedSiblings !== existingSiblings) {\n relationships = setRelationships(relationships, 'sibling', 'project', updatedSiblings);\n }\n \n if (updatedRelatedTerms !== undefined && updatedRelatedTerms !== existingRelatedTerms) {\n relationships = setRelationships(relationships, 'related_term', 'term', updatedRelatedTerms);\n }\n \n if (args.parent !== undefined || updatedChildren !== undefined || updatedSiblings !== undefined || updatedRelatedTerms !== undefined) {\n updatedProject.relationships = relationships.length > 0 ? relationships : undefined;\n }\n\n await context.saveEntity(updatedProject, true);\n\n // Build summary of changes\n const changes: string[] = [];\n if (args.name !== undefined) changes.push(`name: \"${args.name}\"`);\n if (args.description !== undefined) changes.push(`description updated`);\n if (args.destination !== undefined) changes.push(`destination: \"${args.destination}\"`);\n if (args.structure !== undefined) changes.push(`structure: \"${args.structure}\"`);\n if (args.contextType !== undefined) changes.push(`context_type: \"${args.contextType}\"`);\n if (args.active !== undefined) changes.push(`active: ${args.active}`);\n if (args.sounds_like !== undefined) changes.push(`sounds_like replaced with ${args.sounds_like.length} items`);\n if (args.add_sounds_like?.length) changes.push(`added ${args.add_sounds_like.length} sounds_like variants`);\n if (args.remove_sounds_like?.length) changes.push(`removed ${args.remove_sounds_like.length} sounds_like variants`);\n if (args.topics !== undefined) changes.push(`topics replaced with ${args.topics.length} items`);\n if (args.add_topics?.length) changes.push(`added ${args.add_topics.length} topics`);\n if (args.remove_topics?.length) changes.push(`removed ${args.remove_topics.length} topics`);\n if (args.explicit_phrases !== undefined) changes.push(`explicit_phrases replaced with ${args.explicit_phrases.length} items`);\n if (args.add_explicit_phrases?.length) changes.push(`added ${args.add_explicit_phrases.length} explicit phrases`);\n if (args.remove_explicit_phrases?.length) changes.push(`removed ${args.remove_explicit_phrases.length} explicit phrases`);\n if (args.associated_people !== undefined) changes.push(`associated_people replaced with ${args.associated_people.length} items`);\n if (args.add_associated_people?.length) changes.push(`added ${args.add_associated_people.length} associated people`);\n if (args.remove_associated_people?.length) changes.push(`removed ${args.remove_associated_people.length} associated people`);\n if (args.associated_companies !== undefined) changes.push(`associated_companies replaced with ${args.associated_companies.length} items`);\n if (args.add_associated_companies?.length) changes.push(`added ${args.add_associated_companies.length} associated companies`);\n if (args.remove_associated_companies?.length) changes.push(`removed ${args.remove_associated_companies.length} associated companies`);\n if (args.parent !== undefined) changes.push(`parent: \"${args.parent}\"`);\n if (args.add_children?.length) changes.push(`added ${args.add_children.length} children`);\n if (args.remove_children?.length) changes.push(`removed ${args.remove_children.length} children`);\n if (args.add_siblings?.length) changes.push(`added ${args.add_siblings.length} siblings`);\n if (args.remove_siblings?.length) changes.push(`removed ${args.remove_siblings.length} siblings`);\n if (args.add_related_terms?.length) changes.push(`added ${args.add_related_terms.length} related terms`);\n if (args.remove_related_terms?.length) changes.push(`removed ${args.remove_related_terms.length} related terms`);\n\n return {\n success: true,\n message: `Updated project \"${existingProject.name}\"`,\n changes,\n project: formatEntity(updatedProject),\n };\n}\n\nexport async function handleUpdateProject(args: {\n id: string;\n source: string;\n name?: string;\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No .protokoll directory found. Initialize context first.');\n }\n\n // Verify project exists\n findProjectResilient(context, args.id);\n\n const smartConfig = context.getSmartAssistanceConfig();\n if (!smartConfig.enabled) {\n throw new Error('Smart assistance is disabled in configuration.');\n }\n\n // ProjectAssist temporarily unavailable - needs extraction from CLI\n throw new Error('Smart assistance temporarily unavailable');\n \n /* Unreachable code - commented out until ProjectAssist is re-implemented\n // const assist = ProjectAssist.create(smartConfig);\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const projectName = args.name || existingProject.name;\n\n // Analyze source for new metadata\n const suggestions = await assist.analyzeSource(args.source, projectName);\n\n // Update project with regenerated metadata\n const updatedProject: Project = {\n ...existingProject,\n ...(args.name && { name: args.name }),\n ...(suggestions.description && { description: suggestions.description }),\n ...(suggestions.soundsLike.length > 0 && { sounds_like: suggestions.soundsLike }),\n classification: {\n ...existingProject.classification,\n ...(suggestions.triggerPhrases.length > 0 && { explicit_phrases: suggestions.triggerPhrases }),\n ...(suggestions.topics && suggestions.topics.length > 0 && { topics: suggestions.topics }),\n },\n updatedAt: new Date(),\n };\n\n await context.saveEntity(updatedProject, true);\n\n return {\n success: true,\n message: `Updated project \"${existingProject.name}\" from source`,\n project: formatEntity(updatedProject),\n generated: {\n soundsLike: suggestions.soundsLike,\n triggerPhrases: suggestions.triggerPhrases,\n topics: suggestions.topics,\n description: suggestions.description,\n },\n };\n */\n}\n\nexport async function handleAddTerm(args: {\n term: string;\n id?: string;\n expansion?: string;\n domain?: string;\n description?: string;\n sounds_like?: string[];\n topics?: string[];\n projects?: string[];\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No .protokoll directory found. Initialize context first.');\n }\n\n const id = args.id || slugify(args.term);\n\n if (context.getTerm(id)) {\n throw new Error(`Term with ID \"${id}\" already exists`);\n }\n\n const term: Term = {\n id,\n name: args.term,\n type: 'term',\n ...(args.expansion && { expansion: args.expansion }),\n ...(args.domain && { domain: args.domain }),\n ...(args.description && { description: args.description }),\n ...(args.sounds_like && { sounds_like: args.sounds_like }),\n ...(args.topics && { topics: args.topics }),\n ...(args.projects && { projects: args.projects }),\n };\n\n await context.saveEntity(term);\n\n return {\n success: true,\n message: `Term \"${args.term}\" added successfully`,\n entity: formatEntity(term),\n };\n}\n\nexport async function handleEditTerm(args: {\n id: string;\n expansion?: string;\n domain?: string;\n description?: string;\n sounds_like?: string[];\n add_sounds_like?: string[];\n remove_sounds_like?: string[];\n topics?: string[];\n add_topics?: string[];\n remove_topics?: string[];\n projects?: string[];\n add_projects?: string[];\n remove_projects?: string[];\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No .protokoll directory found. Initialize context first.');\n }\n\n const existingTerm = context.getTerm(args.id);\n if (!existingTerm) {\n throw new Error(`Term \"${args.id}\" not found`);\n }\n\n const updatedSoundsLike = mergeArray(\n existingTerm.sounds_like,\n args.sounds_like,\n args.add_sounds_like,\n args.remove_sounds_like\n );\n\n const updatedTopics = mergeArray(\n existingTerm.topics,\n args.topics,\n args.add_topics,\n args.remove_topics\n );\n\n const updatedProjects = mergeArray(\n existingTerm.projects,\n args.projects,\n args.add_projects,\n args.remove_projects\n );\n\n // Build updated term\n const updatedTerm: Term = {\n ...existingTerm,\n ...(args.expansion !== undefined && { expansion: args.expansion }),\n ...(args.domain !== undefined && { domain: args.domain }),\n ...(args.description !== undefined && { description: args.description }),\n updatedAt: new Date(),\n };\n\n // Handle array fields - only set if they have values\n if (updatedSoundsLike !== undefined) {\n updatedTerm.sounds_like = updatedSoundsLike;\n } else if (existingTerm.sounds_like && (args.sounds_like !== undefined || args.remove_sounds_like)) {\n delete updatedTerm.sounds_like;\n }\n\n if (updatedTopics !== undefined) {\n updatedTerm.topics = updatedTopics;\n } else if (existingTerm.topics && (args.topics !== undefined || args.remove_topics)) {\n delete updatedTerm.topics;\n }\n\n if (updatedProjects !== undefined) {\n updatedTerm.projects = updatedProjects;\n } else if (existingTerm.projects && (args.projects !== undefined || args.remove_projects)) {\n delete updatedTerm.projects;\n }\n\n await context.saveEntity(updatedTerm, true);\n\n // Build summary of changes\n const changes: string[] = [];\n if (args.expansion !== undefined) changes.push(`expansion: \"${args.expansion}\"`);\n if (args.domain !== undefined) changes.push(`domain: \"${args.domain}\"`);\n if (args.description !== undefined) changes.push(`description updated`);\n if (args.sounds_like !== undefined) changes.push(`sounds_like replaced with ${args.sounds_like.length} items`);\n if (args.add_sounds_like?.length) changes.push(`added ${args.add_sounds_like.length} sounds_like variants`);\n if (args.remove_sounds_like?.length) changes.push(`removed ${args.remove_sounds_like.length} sounds_like variants`);\n if (args.topics !== undefined) changes.push(`topics replaced with ${args.topics.length} items`);\n if (args.add_topics?.length) changes.push(`added ${args.add_topics.length} topics`);\n if (args.remove_topics?.length) changes.push(`removed ${args.remove_topics.length} topics`);\n if (args.projects !== undefined) changes.push(`projects replaced with ${args.projects.length} items`);\n if (args.add_projects?.length) changes.push(`added ${args.add_projects.length} project associations`);\n if (args.remove_projects?.length) changes.push(`removed ${args.remove_projects.length} project associations`);\n\n return {\n success: true,\n message: `Updated term \"${existingTerm.name}\"`,\n changes,\n term: formatEntity(updatedTerm),\n };\n}\n\nexport async function handleUpdateTerm(args: {\n id: string;\n source: string;\n expansion?: string;\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No .protokoll directory found. Initialize context first.');\n }\n\n // Verify term exists\n findTermResilient(context, args.id);\n\n const smartConfig = context.getSmartAssistanceConfig();\n if (!smartConfig.enabled || smartConfig.termsEnabled === false) {\n throw new Error('Term smart assistance is disabled in configuration.');\n }\n\n // ContentFetcher, TermAssist, TermContext temporarily unavailable\n throw new Error('Term assistance temporarily unavailable - business logic needs extraction from CLI');\n \n /* Unreachable code - commented out until modules are re-implemented\n // Fetch content from source\n const ContentFetcher = await import('@/cli/content-fetcher');\n const contentFetcher = ContentFetcher.create();\n const fetchResult = await contentFetcher.fetch(args.source);\n\n if (!fetchResult.success) {\n throw new Error(`Failed to fetch source: ${fetchResult.error}`);\n }\n\n // Gather context and generate suggestions\n const TermAssist = await import('@/cli/term-assist');\n const TermContext = await import('@/cli/term-context');\n\n const termAssist = TermAssist.create(smartConfig);\n const termContextHelper = TermContext.create(context);\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const internalContext = termContextHelper.gatherInternalContext(\n existingTerm.name,\n args.expansion || existingTerm.expansion\n );\n\n const analysisContext = TermContext.buildAnalysisContext(\n existingTerm.name,\n args.expansion || existingTerm.expansion,\n fetchResult,\n internalContext\n );\n\n const suggestions = await termAssist.generateAll(existingTerm.name, analysisContext);\n\n // Update term with regenerated metadata\n const updatedTerm: Term = {\n ...existingTerm,\n ...(args.expansion && { expansion: args.expansion }),\n ...(suggestions.description && { description: suggestions.description }),\n ...(suggestions.domain && { domain: suggestions.domain }),\n ...(suggestions.soundsLike.length > 0 && { sounds_like: suggestions.soundsLike }),\n ...(suggestions.topics.length > 0 && { topics: suggestions.topics }),\n updatedAt: new Date(),\n };\n\n // Suggest projects based on topics\n let suggestedProjects: string[] = [];\n if (suggestions.topics.length > 0) {\n const projects = termContextHelper.findProjectsByTopic(suggestions.topics);\n suggestedProjects = projects.map((p: any) => p.id);\n }\n\n await context.saveEntity(updatedTerm, true);\n\n return {\n success: true,\n message: `Updated term \"${existingTerm.name}\" from source`,\n term: formatEntity(updatedTerm),\n generated: {\n soundsLike: suggestions.soundsLike,\n description: suggestions.description,\n topics: suggestions.topics,\n domain: suggestions.domain,\n suggestedProjects,\n },\n };\n */\n}\n\n/* c8 ignore start */\nexport async function handleMergeTerms(args: {\n sourceId: string;\n targetId: string;\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No .protokoll directory found. Initialize context first.');\n }\n\n const sourceTerm = findTermResilient(context, args.sourceId);\n const targetTerm = findTermResilient(context, args.targetId);\n\n // Merge metadata\n const mergedTerm: Term = {\n ...targetTerm,\n sounds_like: [\n ...(targetTerm.sounds_like || []),\n ...(sourceTerm.sounds_like || []),\n ].filter((v, i, arr) => arr.indexOf(v) === i),\n topics: [\n ...(targetTerm.topics || []),\n ...(sourceTerm.topics || []),\n ].filter((v, i, arr) => arr.indexOf(v) === i),\n projects: [\n ...(targetTerm.projects || []),\n ...(sourceTerm.projects || []),\n ].filter((v, i, arr) => arr.indexOf(v) === i),\n description: targetTerm.description || sourceTerm.description,\n domain: targetTerm.domain || sourceTerm.domain,\n expansion: targetTerm.expansion || sourceTerm.expansion,\n updatedAt: new Date(),\n };\n\n // Remove empty arrays\n if (mergedTerm.sounds_like && mergedTerm.sounds_like.length === 0) {\n delete mergedTerm.sounds_like;\n }\n if (mergedTerm.topics && mergedTerm.topics.length === 0) {\n delete mergedTerm.topics;\n }\n if (mergedTerm.projects && mergedTerm.projects.length === 0) {\n delete mergedTerm.projects;\n }\n\n // Save merged term and delete source\n await context.saveEntity(mergedTerm);\n await context.deleteEntity(sourceTerm);\n\n return {\n success: true,\n message: `Merged \"${sourceTerm.name}\" into \"${targetTerm.name}\"`,\n mergedTerm: formatEntity(mergedTerm),\n deletedTerm: args.sourceId,\n };\n}\n/* c8 ignore stop */\n\nexport async function handleAddCompany(args: {\n name: string;\n id?: string;\n fullName?: string;\n industry?: string;\n sounds_like?: string[];\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n if (!context.hasContext()) {\n throw new Error('No .protokoll directory found. Initialize context first.');\n }\n\n const id = args.id || slugify(args.name);\n\n if (context.getCompany(id)) {\n throw new Error(`Company with ID \"${id}\" already exists`);\n }\n\n const company: Company = {\n id,\n name: args.name,\n type: 'company',\n ...(args.fullName && { fullName: args.fullName }),\n ...(args.industry && { industry: args.industry }),\n ...(args.sounds_like && { sounds_like: args.sounds_like }),\n };\n\n await context.saveEntity(company);\n\n return {\n success: true,\n message: `Company \"${args.name}\" added successfully`,\n entity: formatEntity(company),\n };\n}\n\nexport async function handleDeleteEntity(args: { entityType: string; entityId: string; contextDirectory?: string }) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n let entity: Entity;\n switch (args.entityType) {\n case 'project':\n entity = findProjectResilient(context, args.entityId);\n break;\n case 'person':\n entity = findPersonResilient(context, args.entityId);\n break;\n case 'term':\n entity = findTermResilient(context, args.entityId);\n break;\n case 'company':\n entity = findCompanyResilient(context, args.entityId);\n break;\n case 'ignored':\n entity = findIgnoredResilient(context, args.entityId);\n break;\n default:\n throw new Error(`Unknown entity type: ${args.entityType}`);\n }\n\n const deleted = await context.deleteEntity(entity);\n\n if (!deleted) {\n throw new Error(`Failed to delete ${args.entityType} \"${args.entityId}\"`);\n }\n\n return {\n success: true,\n message: `${args.entityType} \"${args.entityId}\" deleted successfully`,\n };\n}\n","/* eslint-disable import/extensions */\n/**\n * Smart Assistance Tools - Generate metadata suggestions for entities\n */\n \nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as Context from '@/context';\n\n// ============================================================================\n// Tool Definitions\n// ============================================================================\n\nexport const suggestProjectMetadataTool: Tool = {\n name: 'protokoll_suggest_project_metadata',\n description:\n 'Generate project metadata suggestions without creating the project. ' +\n 'Returns sounds_like (phonetic variants for transcription), explicit_phrases (content-matching trigger phrases), ' +\n 'topics and description from source content. Useful for interactive workflows where ' +\n 'AI assistant presents suggestions for user review before creating the project.',\n inputSchema: {\n type: 'object',\n properties: {\n name: {\n type: 'string',\n description: 'Project name for generating sounds_like and trigger phrases',\n },\n source: {\n type: 'string',\n description: 'URL or file path to analyze for topics, description, and suggested name',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n },\n};\n\nexport const suggestTermMetadataTool: Tool = {\n name: 'protokoll_suggest_term_metadata',\n description:\n 'Generate term metadata suggestions without creating the term. ' +\n 'Returns sounds_like (phonetic variants), description, topics, domain, and suggested projects. ' +\n 'Useful for interactive workflows where AI assistant presents suggestions for user review before creating the term.',\n inputSchema: {\n type: 'object',\n properties: {\n term: {\n type: 'string',\n description: 'Term name for generating metadata',\n },\n source: {\n type: 'string',\n description: 'URL or file path to analyze for richer suggestions (optional)',\n },\n expansion: {\n type: 'string',\n description: 'Full expansion if acronym (helps with analysis)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['term'],\n },\n};\n\n// ============================================================================\n// Tool Handlers\n// ============================================================================\n\nexport async function handleSuggestProjectMetadata(args: {\n name?: string;\n source?: string;\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n const smartConfig = context.getSmartAssistanceConfig();\n\n if (!smartConfig.enabled) {\n throw new Error('Smart assistance is disabled in configuration.');\n }\n\n // ProjectAssist moved to separate module - needs to be re-implemented\n throw new Error('Project assistance temporarily unavailable - business logic needs extraction from CLI');\n \n /* Unreachable code - commented out until ProjectAssist is re-implemented\n // const assist = ProjectAssist.create(smartConfig);\n\n const result: {\n soundsLike?: string[];\n triggerPhrases?: string[];\n topics?: string[];\n description?: string;\n suggestedName?: string;\n } = {};\n\n // Generate sounds_like and trigger phrases if name provided\n if (args.name) {\n // Generate in parallel for efficiency\n const [soundsLike, triggerPhrases] = await Promise.all([\n assist.generateSoundsLike(args.name),\n assist.generateTriggerPhrases(args.name),\n ]);\n result.soundsLike = soundsLike;\n result.triggerPhrases = triggerPhrases;\n }\n\n // Analyze source if provided\n if (args.source) {\n const suggestions = await assist.analyzeSource(args.source, args.name);\n\n if (!args.name && suggestions.name) {\n result.suggestedName = suggestions.name;\n result.soundsLike = suggestions.soundsLike;\n result.triggerPhrases = suggestions.triggerPhrases;\n }\n result.topics = suggestions.topics;\n result.description = suggestions.description;\n }\n\n return {\n success: true,\n data: result,\n };\n */\n}\n\nexport async function handleSuggestTermMetadata(args: {\n term: string;\n source?: string;\n expansion?: string;\n contextDirectory?: string;\n}) {\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n });\n\n const smartConfig = context.getSmartAssistanceConfig();\n\n if (!smartConfig.enabled || smartConfig.termsEnabled === false) {\n throw new Error('Term smart assistance is disabled in configuration.');\n }\n\n // TermAssist, TermContext, ContentFetcher moved to separate modules - need re-implementation\n throw new Error('Term assistance temporarily unavailable - business logic needs extraction from CLI');\n \n /* Unreachable code - commented out until TermAssist is re-implemented\n // const termAssist = TermAssist.create(smartConfig);\n // const termContextHelper = TermContext.create(context);\n // const contentFetcher = ContentFetcher.create();\n\n // Gather internal context\n const internalContext = termContextHelper.gatherInternalContext(args.term, args.expansion);\n\n // Fetch external content if source provided\n let fetchResult: ContentFetcher.FetchResult | undefined;\n if (args.source) {\n fetchResult = await contentFetcher.fetch(args.source);\n }\n\n // Build analysis context\n const analysisContext = TermContext.buildAnalysisContext(\n args.term,\n args.expansion,\n fetchResult,\n internalContext\n );\n\n // Generate suggestions\n const suggestions = await termAssist.generateAll(args.term, analysisContext);\n\n // Find related projects based on generated topics\n let suggestedProjects: string[] = [];\n if (suggestions.topics && suggestions.topics.length > 0) {\n const projects = termContextHelper.findProjectsByTopic(suggestions.topics);\n suggestedProjects = projects.map((p: any) => p.id);\n }\n\n return {\n success: true,\n data: {\n soundsLike: suggestions.soundsLike,\n description: suggestions.description,\n topics: suggestions.topics,\n domain: suggestions.domain,\n suggestedProjects,\n },\n };\n */\n}\n","/* eslint-disable import/extensions */\n/**\n * Transcript Tools - Read, list, edit, combine, and provide feedback on transcripts\n */\n \nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { resolve, dirname } from 'node:path';\nimport { mkdir } from 'node:fs/promises';\nimport * as Context from '@/context';\nimport { Reasoning, Transcript } from '@redaksjon/protokoll-engine';\nimport { DEFAULT_MODEL } from '@/constants';\n\nimport { fileExists, getConfiguredDirectory, getContextDirectories, sanitizePath, validatePathWithinDirectory, validatePathWithinOutputDirectory, validateNotRemoteMode, resolveTranscriptPath } from './shared.js';\nimport * as Metadata from '@redaksjon/protokoll-engine';\nimport { Transcript as TranscriptUtils } from '@redaksjon/protokoll-engine';\nconst { ensurePklExtension, transcriptExists } = TranscriptUtils;\nimport { \n PklTranscript, \n readTranscript as readTranscriptFromStorage,\n listTranscripts as listTranscriptsFromStorage,\n} from '@redaksjon/protokoll-format';\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n// ============================================================================\n// Tool Definitions\n// ============================================================================\n\nexport const readTranscriptTool: Tool = {\n name: 'protokoll_read_transcript',\n description:\n 'Read a transcript file and parse its metadata and content. ' +\n 'Path is relative to the configured output directory. ' +\n 'Returns structured data including title, metadata, routing info, and content.',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPath: {\n type: 'string',\n description: \n 'Transcript URI (preferred) or relative path from output directory. ' +\n 'URI format: \"protokoll://transcript/2026/2/12-1606-meeting\" (no file extension). ' +\n 'Path format: \"2026/2/12-1606-meeting\" or \"2026/2/12-1606-meeting.pkl\"',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPath'],\n },\n};\n\nexport const listTranscriptsTool: Tool = {\n name: 'protokoll_list_transcripts',\n description:\n 'List transcripts with pagination, filtering, and search. ' +\n 'If no directory is specified, uses the configured output directory. ' +\n 'Returns transcript metadata including date, time, title, and file path. ' +\n 'Supports sorting by date (default), filename, or title. ' +\n 'Can filter by date range and search within transcript content.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: {\n type: 'string',\n description: \n 'Optional: Directory to search for transcripts (searches recursively). ' +\n 'If not specified, uses the configured output directory.',\n },\n limit: {\n type: 'number',\n description: 'Maximum number of results to return (default: 50)',\n default: 50,\n },\n offset: {\n type: 'number',\n description: 'Number of results to skip for pagination (default: 0)',\n default: 0,\n },\n sortBy: {\n type: 'string',\n enum: ['date', 'filename', 'title'],\n description: 'Field to sort by (default: date)',\n default: 'date',\n },\n startDate: {\n type: 'string',\n description: 'Filter transcripts from this date onwards (YYYY-MM-DD format)',\n },\n endDate: {\n type: 'string',\n description: 'Filter transcripts up to this date (YYYY-MM-DD format)',\n },\n search: {\n type: 'string',\n description: 'Search for transcripts containing this text (searches filename and content)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: [],\n },\n};\n\nexport const editTranscriptTool: Tool = {\n name: 'protokoll_edit_transcript',\n description:\n 'Edit an existing transcript\\'s title, project assignment, tags, and/or status. ' +\n 'Path is relative to the configured output directory. ' +\n 'IMPORTANT: When you change the title, this tool RENAMES THE FILE to match the new title (slugified). ' +\n 'Always use this tool instead of directly editing transcript files when changing titles. ' +\n 'Changing the project will update metadata and may move the file to a new location ' +\n 'based on the project\\'s routing configuration.',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPath: {\n type: 'string',\n description: \n 'Transcript URI (preferred) or relative path from output directory. ' +\n 'URI format: \"protokoll://transcript/2026/2/12-1606-meeting\" (no file extension). ' +\n 'Path format: \"2026/2/12-1606-meeting\" or \"2026/2/12-1606-meeting.pkl\"',\n },\n title: {\n type: 'string',\n description: 'New title for the transcript. This will RENAME the file to match the slugified title.',\n },\n projectId: {\n type: 'string',\n description: 'New project ID to assign',\n },\n tagsToAdd: {\n type: 'array',\n items: { type: 'string' },\n description: 'Tags to add to the transcript (will be deduplicated with existing tags)',\n },\n tagsToRemove: {\n type: 'array',\n items: { type: 'string' },\n description: 'Tags to remove from the transcript',\n },\n status: {\n type: 'string',\n enum: ['initial', 'enhanced', 'reviewed', 'in_progress', 'closed', 'archived'],\n description: 'New lifecycle status. Status transitions are recorded in history.',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPath'],\n },\n};\n\nexport const changeTranscriptDateTool: Tool = {\n name: 'protokoll_change_transcript_date',\n description:\n 'Change the date of an existing transcript. ' +\n 'This will move the transcript file to a new location based on the new date and the project\\'s routing configuration. ' +\n 'The file will be moved to the appropriate YYYY/MM/ directory structure. ' +\n 'Path is relative to the configured output directory. ' +\n 'WARNING: This may remove the transcript from the current view if it moves to a different date folder.',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPath: {\n type: 'string',\n description: \n 'Transcript URI (preferred) or relative path from output directory. ' +\n 'URI format: \"protokoll://transcript/2026/2/12-1606-meeting\" (no file extension). ' +\n 'Path format: \"2026/2/12-1606-meeting\" or \"2026/2/12-1606-meeting.pkl\"',\n },\n newDate: {\n type: 'string',\n description: \n 'New date for the transcript in ISO 8601 format (YYYY-MM-DD or full ISO datetime). ' +\n 'Examples: \"2026-01-15\", \"2026-01-15T10:30:00Z\"',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPath', 'newDate'],\n },\n};\n\nexport const combineTranscriptsTool: Tool = {\n name: 'protokoll_combine_transcripts',\n description:\n 'Combine multiple transcripts into a single document. ' +\n 'Paths are relative to the configured output directory. ' +\n 'Source files are automatically deleted after combining. ' +\n 'Metadata from the first transcript is preserved, and content is organized into sections.',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPaths: {\n type: 'array',\n items: { type: 'string' },\n description: \n 'Array of relative paths from the output directory. ' +\n 'Examples: [\"meeting-1.pkl\", \"meeting-2.pkl\"] or [\"2026/2/01-1325.pkl\", \"2026/2/01-1400.pkl\"]',\n },\n title: {\n type: 'string',\n description: 'Title for the combined transcript',\n },\n projectId: {\n type: 'string',\n description: 'Project ID to assign to the combined transcript',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPaths'],\n },\n};\n\nexport const provideFeedbackTool: Tool = {\n name: 'protokoll_provide_feedback',\n description:\n 'Provide natural language feedback to correct a transcript. ' +\n 'Path is relative to the configured output directory. ' +\n 'The feedback is processed by an agentic model that can: ' +\n '- Fix spelling and term errors ' +\n '- Add new terms, people, or companies to context ' +\n '- Change project assignment ' +\n '- Update the title ' +\n 'Example: \"YB should be Wibey\" or \"San Jay Grouper is actually Sanjay Gupta\"',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPath: {\n type: 'string',\n description: \n 'Transcript URI (preferred) or relative path from output directory. ' +\n 'URI format: \"protokoll://transcript/2026/2/12-1606-meeting\" (no file extension). ' +\n 'Path format: \"2026/2/12-1606-meeting\" or \"2026/2/12-1606-meeting.pkl\"',\n },\n feedback: {\n type: 'string',\n description: 'Natural language feedback describing corrections needed',\n },\n model: {\n type: 'string',\n description: 'LLM model for processing feedback (default: gpt-5.2)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPath', 'feedback'],\n },\n};\n\nexport const updateTranscriptContentTool: Tool = {\n name: 'protokoll_update_transcript_content',\n description:\n 'Update the content section of a transcript file while preserving all metadata. ' +\n 'Path is relative to the configured output directory. ' +\n 'This tool replaces only the content between the --- delimiters, keeping all metadata intact. ' +\n 'IMPORTANT: The content parameter should contain ONLY the transcript body text (the text after the --- delimiter), ' +\n 'NOT the full transcript file with headers and metadata. If the full transcript is provided, ' +\n 'the tool will automatically extract only the content section to prevent duplication.',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPath: {\n type: 'string',\n description: \n 'Transcript URI (preferred) or relative path from output directory. ' +\n 'URI format: \"protokoll://transcript/2026/2/12-1606-meeting\" (no file extension). ' +\n 'Path format: \"2026/2/12-1606-meeting\" or \"2026/2/12-1606-meeting.pkl\"',\n },\n content: {\n type: 'string',\n description: \n 'New content to replace the transcript body. ' +\n 'Should contain ONLY the body text (content after the --- delimiter). ' +\n 'If the full transcript is provided, the tool will extract only the content section automatically.',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPath', 'content'],\n },\n};\n\nexport const updateTranscriptEntityReferencesTool: Tool = {\n name: 'protokoll_update_transcript_entity_references',\n description:\n 'Update the Entity References section of a transcript file while preserving all other content. ' +\n 'Path is relative to the configured output directory. ' +\n 'This tool replaces only the Entity References section at the end of the transcript, ' +\n 'preserving the title, metadata, and body content.',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPath: {\n type: 'string',\n description: \n 'Transcript URI (preferred) or relative path from output directory. ' +\n 'URI format: \"protokoll://transcript/2026/2/12-1606-meeting\" (no file extension). ' +\n 'Path format: \"2026/2/12-1606-meeting\" or \"2026/2/12-1606-meeting.pkl\"',\n },\n entities: {\n type: 'object',\n description: 'Entity references to update',\n properties: {\n people: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Entity ID (slugified identifier)' },\n name: { type: 'string', description: 'Display name' },\n },\n required: ['id', 'name'],\n },\n },\n projects: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Entity ID (slugified identifier)' },\n name: { type: 'string', description: 'Display name' },\n },\n required: ['id', 'name'],\n },\n },\n terms: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Entity ID (slugified identifier)' },\n name: { type: 'string', description: 'Display name' },\n },\n required: ['id', 'name'],\n },\n },\n companies: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Entity ID (slugified identifier)' },\n name: { type: 'string', description: 'Display name' },\n },\n required: ['id', 'name'],\n },\n },\n },\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPath', 'entities'],\n },\n};\n\nexport const createNoteTool: Tool = {\n name: 'protokoll_create_note',\n description:\n 'Create a new note/transcript file in the configured output directory. ' +\n 'The file will be created with proper metadata formatting and placed in a date-based directory structure (YYYY/MM/). ' +\n 'Returns the relative path to the created file.',\n inputSchema: {\n type: 'object',\n properties: {\n title: {\n type: 'string',\n description: 'Title for the note/transcript',\n },\n content: {\n type: 'string',\n description: 'Content/body text for the note (optional, can be empty)',\n default: '',\n },\n projectId: {\n type: 'string',\n description: 'Optional: Project ID to assign to the note',\n },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional: Tags to add to the note',\n },\n date: {\n type: 'string',\n description: 'Optional: Date for the note (ISO 8601 format, e.g., \"2026-02-02\"). Defaults to current date.',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['title'],\n },\n};\n\n// ============================================================================\n// Tool Handlers\n// ============================================================================\n\nexport async function handleReadTranscript(args: { \n transcriptPath: string;\n contextDirectory?: string;\n}) {\n // Find the transcript (returns absolute path for file operations)\n const absolutePath = await resolveTranscriptPath(args.transcriptPath, args.contextDirectory);\n\n // Use protokoll-format storage API directly - returns structured JSON\n const transcriptData = await readTranscriptFromStorage(absolutePath);\n\n // Convert to relative path for response\n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativePath = await sanitizePath(absolutePath, outputDirectory);\n\n // Return complete structured JSON for client display\n // Clients should NOT need to parse this - all data is ready to display\n return {\n filePath: relativePath,\n title: transcriptData.metadata.title || '',\n metadata: {\n date: transcriptData.metadata.date?.toISOString() || null,\n recordingTime: transcriptData.metadata.recordingTime || null,\n duration: transcriptData.metadata.duration || null,\n project: transcriptData.metadata.project || null,\n projectId: transcriptData.metadata.projectId || null,\n tags: transcriptData.metadata.tags || [],\n status: transcriptData.metadata.status || 'initial',\n confidence: transcriptData.metadata.confidence || null,\n routing: transcriptData.metadata.routing || null,\n history: transcriptData.metadata.history || [],\n tasks: transcriptData.metadata.tasks || [],\n entities: transcriptData.metadata.entities || {},\n },\n content: transcriptData.content,\n hasRawTranscript: transcriptData.hasRawTranscript,\n contentLength: transcriptData.content.length,\n };\n}\n\nexport async function handleListTranscripts(args: {\n directory?: string;\n limit?: number;\n offset?: number;\n sortBy?: 'date' | 'filename' | 'title';\n startDate?: string;\n endDate?: string;\n search?: string;\n contextDirectory?: string;\n}) {\n // Get directory from args or config\n const directory = args.directory \n ? resolve(args.directory)\n : await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n\n if (!await fileExists(directory)) {\n throw new Error(`Directory not found: ${directory}`);\n }\n\n // Use protokoll-format storage API directly\n const result = await listTranscriptsFromStorage({\n directory,\n limit: args.limit ?? 50,\n offset: args.offset ?? 0,\n sortBy: args.sortBy ?? 'date',\n startDate: args.startDate,\n endDate: args.endDate,\n search: args.search,\n });\n\n // Convert all paths to relative paths from output directory\n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativeTranscripts = await Promise.all(\n result.transcripts.map(async (t) => ({\n path: await sanitizePath(t.filePath, outputDirectory),\n relativePath: t.relativePath,\n title: t.title,\n date: t.date?.toISOString() || null,\n project: t.project || null,\n tags: t.tags,\n status: t.status,\n duration: t.duration || null,\n contentPreview: t.contentPreview,\n }))\n );\n\n return {\n directory: await sanitizePath(directory, outputDirectory) || '.',\n transcripts: relativeTranscripts,\n pagination: {\n total: result.total,\n limit: args.limit ?? 50,\n offset: args.offset ?? 0,\n hasMore: result.hasMore,\n nextOffset: result.hasMore ? (args.offset ?? 0) + (args.limit ?? 50) : null,\n },\n filters: {\n sortBy: args.sortBy ?? 'date',\n startDate: args.startDate,\n endDate: args.endDate,\n search: args.search,\n },\n };\n}\n\nexport async function handleEditTranscript(args: {\n transcriptPath: string;\n title?: string;\n projectId?: string;\n tagsToAdd?: string[];\n tagsToRemove?: string[];\n status?: string;\n contextDirectory?: string;\n}) {\n // Validate that contextDirectory is not provided in remote mode\n await validateNotRemoteMode(args.contextDirectory);\n \n // Get the output directory first to ensure consistent validation\n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n \n // Find the transcript (returns absolute path for file operations)\n const absolutePath = await resolveTranscriptPath(args.transcriptPath, args.contextDirectory);\n\n // Validate status if provided\n if (args.status && !Metadata.isValidStatus(args.status)) {\n throw new Error(\n `Invalid status \"${args.status}\". ` +\n `Valid statuses are: ${Metadata.VALID_STATUSES.join(', ')}`\n );\n }\n\n if (!args.title && !args.projectId && !args.tagsToAdd && !args.tagsToRemove && !args.status) {\n throw new Error('Must specify at least one of: title, projectId, tagsToAdd, tagsToRemove, or status');\n }\n\n let finalOutputPath = absolutePath;\n let wasRenamed = false;\n \n // Handle title/project/tags changes via existing editTranscript function\n // The editTranscript function handles PKL files directly\n if (args.title || args.projectId || args.tagsToAdd || args.tagsToRemove) {\n // Get context directories from server config (from protokoll-config.yaml)\n const contextDirectories = await getContextDirectories();\n \n const result = await Transcript.editTranscript(absolutePath, {\n title: args.title,\n projectId: args.projectId,\n tagsToAdd: args.tagsToAdd,\n tagsToRemove: args.tagsToRemove,\n contextDirectory: args.contextDirectory,\n contextDirectories,\n });\n\n // Validate that the output path stays within the output directory\n validatePathWithinDirectory(result.outputPath, outputDirectory);\n\n // editTranscript handles file operations internally for PKL files\n if (result.outputPath !== absolutePath) {\n wasRenamed = true;\n }\n \n finalOutputPath = result.outputPath;\n }\n\n // Handle status change using PklTranscript\n let statusChanged = false;\n let previousStatus: string | undefined;\n \n if (args.status) {\n const pklPath = ensurePklExtension(finalOutputPath);\n const transcript = PklTranscript.open(pklPath, { readOnly: false });\n try {\n previousStatus = transcript.metadata.status || 'reviewed';\n \n if (previousStatus !== args.status) {\n transcript.updateMetadata({ status: args.status as Metadata.TranscriptStatus });\n statusChanged = true;\n // eslint-disable-next-line no-console\n console.log('✅ Status update completed successfully');\n }\n } finally {\n transcript.close();\n }\n }\n\n // Convert to relative paths for response\n const relativeOriginalPath = await sanitizePath(absolutePath || '', outputDirectory);\n const relativeOutputPath = await sanitizePath(finalOutputPath || '', outputDirectory);\n\n // Build message\n const changes: string[] = [];\n if (wasRenamed) changes.push(`moved to ${relativeOutputPath}`);\n if (args.title) changes.push(`title updated`);\n if (args.projectId) changes.push(`project changed`);\n if (args.tagsToAdd?.length) changes.push(`${args.tagsToAdd.length} tag(s) added`);\n if (args.tagsToRemove?.length) changes.push(`${args.tagsToRemove.length} tag(s) removed`);\n if (statusChanged) changes.push(`status: ${previousStatus} → ${args.status}`);\n if (!statusChanged && args.status) changes.push(`status unchanged (already ${args.status})`);\n\n return {\n success: true,\n originalPath: relativeOriginalPath,\n outputPath: relativeOutputPath,\n renamed: wasRenamed,\n statusChanged,\n message: changes.length > 0 ? `Transcript updated: ${changes.join(', ')}` : 'No changes made',\n };\n}\n\nexport async function handleChangeTranscriptDate(args: {\n transcriptPath: string;\n newDate: string;\n contextDirectory?: string;\n}) {\n const fsPromises = await import('node:fs/promises');\n const path = await import('node:path');\n \n // Get the output directory\n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n \n // Find the transcript (returns absolute path)\n const absolutePath = await resolveTranscriptPath(args.transcriptPath, args.contextDirectory);\n \n // Parse the new date\n const newDate = new Date(args.newDate);\n if (isNaN(newDate.getTime())) {\n throw new Error(`Invalid date format: ${args.newDate}. Use ISO 8601 format (e.g., \"2026-01-15\" or \"2026-01-15T10:30:00Z\")`);\n }\n \n // Determine the new directory structure based on the date\n // Use YYYY/M structure (month-level organization, no zero-padding to match router convention)\n // Use UTC methods to avoid timezone issues with date-only strings\n const year = newDate.getUTCFullYear();\n const month = (newDate.getUTCMonth() + 1).toString(); // No zero-padding (e.g., \"8\" not \"08\")\n const newDirPath = path.join(outputDirectory, String(year), month);\n \n // Get the filename from the original path\n const filename = path.basename(absolutePath);\n const newAbsolutePath = path.join(newDirPath, filename);\n \n // Check if the file would move to a different location\n if (absolutePath === newAbsolutePath) {\n // Still update the date in metadata even if not moving\n const pklPath = ensurePklExtension(absolutePath);\n const transcript = PklTranscript.open(pklPath, { readOnly: false });\n try {\n transcript.updateMetadata({ date: newDate });\n } finally {\n transcript.close();\n }\n \n return {\n success: true,\n originalPath: await sanitizePath(pklPath, outputDirectory),\n outputPath: await sanitizePath(pklPath, outputDirectory),\n moved: false,\n message: 'Transcript date updated. No move needed (already in correct directory).',\n };\n }\n \n // Validate that the new path stays within the output directory\n validatePathWithinDirectory(newAbsolutePath, outputDirectory);\n \n // Create the new directory if it doesn't exist\n await mkdir(newDirPath, { recursive: true });\n \n // Check if a file already exists at the destination\n const destExists = await transcriptExists(newAbsolutePath);\n if (destExists.exists) {\n throw new Error(\n `A file already exists at the destination: ${await sanitizePath(destExists.path || newAbsolutePath, outputDirectory)}. ` +\n `Please rename the transcript first or choose a different date.`\n );\n }\n \n // Ensure we're working with PKL files\n const pklPath = ensurePklExtension(absolutePath);\n const newPklPath = ensurePklExtension(newAbsolutePath);\n \n // Update the date in metadata\n const transcript = PklTranscript.open(pklPath, { readOnly: false });\n try {\n transcript.updateMetadata({ date: newDate });\n } finally {\n transcript.close();\n }\n \n // Move the file to the new location\n await fsPromises.rename(pklPath, newPklPath);\n \n // Also move any associated WAL/SHM files if they exist\n const walPath = pklPath + '-wal';\n const shmPath = pklPath + '-shm';\n try {\n await fsPromises.rename(walPath, newPklPath + '-wal');\n } catch { /* ignore if doesn't exist */ }\n try {\n await fsPromises.rename(shmPath, newPklPath + '-shm');\n } catch { /* ignore if doesn't exist */ }\n \n // Convert to relative paths for response\n const relativeOriginalPath = await sanitizePath(pklPath, outputDirectory);\n const relativeOutputPath = await sanitizePath(newPklPath, outputDirectory);\n \n return {\n success: true,\n originalPath: relativeOriginalPath,\n outputPath: relativeOutputPath,\n moved: true,\n message: `Transcript moved from ${relativeOriginalPath} to ${relativeOutputPath}`,\n };\n}\n\nexport async function handleCombineTranscripts(args: {\n transcriptPaths: string[];\n title?: string;\n projectId?: string;\n contextDirectory?: string;\n}) {\n // Validate that contextDirectory is not provided in remote mode\n await validateNotRemoteMode(args.contextDirectory);\n \n if (args.transcriptPaths.length < 2) {\n throw new Error('At least 2 transcript files are required');\n }\n\n // Find all transcripts (returns absolute paths for file operations)\n const absolutePaths: string[] = [];\n for (const relativePath of args.transcriptPaths) {\n const absolute = await resolveTranscriptPath(relativePath, args.contextDirectory);\n absolutePaths.push(absolute);\n }\n\n // Get context directories from server config (from protokoll-config.yaml)\n const contextDirectories = await getContextDirectories();\n \n const result = await Transcript.combineTranscripts(absolutePaths, {\n title: args.title,\n projectId: args.projectId,\n contextDirectory: args.contextDirectory,\n contextDirectories,\n });\n\n // Validate that the output path stays within the output directory\n // This prevents project routing from writing files outside the allowed directory\n await validatePathWithinOutputDirectory(result.outputPath, args.contextDirectory);\n\n // The combineTranscripts function in operations.ts now creates the PKL file directly\n // No additional validation or writing needed here - the file is already saved\n\n // Delete source files\n const fsPromises = await import('node:fs/promises');\n const deletedFiles: string[] = [];\n for (const sourcePath of absolutePaths) {\n try {\n await fsPromises.unlink(sourcePath);\n deletedFiles.push(sourcePath);\n } catch {\n // Ignore deletion errors\n }\n }\n\n // Convert to relative paths for response\n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativeOutputPath = await sanitizePath(result.outputPath || '', outputDirectory);\n const relativeSourceFiles = await Promise.all(\n absolutePaths.map(p => sanitizePath(p || '', outputDirectory))\n );\n const relativeDeletedFiles = await Promise.all(\n deletedFiles.map(p => sanitizePath(p || '', outputDirectory))\n );\n\n return {\n success: true,\n outputPath: relativeOutputPath,\n sourceFiles: relativeSourceFiles,\n deletedFiles: relativeDeletedFiles,\n message: `Combined ${absolutePaths.length} transcripts into: ${relativeOutputPath}`,\n };\n}\n\nexport async function handleUpdateTranscriptContent(args: {\n transcriptPath: string;\n content: string;\n contextDirectory?: string;\n}) {\n // Find the transcript (returns absolute path for file operations)\n const absolutePath = await resolveTranscriptPath(args.transcriptPath, args.contextDirectory);\n\n // Ensure we're working with a PKL file\n const pklPath = ensurePklExtension(absolutePath);\n \n const transcript = PklTranscript.open(pklPath, { readOnly: false });\n try {\n // Update the content - PklTranscript handles history tracking automatically\n transcript.updateContent(args.content);\n } finally {\n transcript.close();\n }\n\n // Convert to relative path for response\n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativePath = await sanitizePath(pklPath, outputDirectory);\n\n return {\n success: true,\n filePath: relativePath,\n message: 'Transcript content updated successfully',\n };\n}\n\nexport async function handleUpdateTranscriptEntityReferences(args: {\n transcriptPath: string;\n entities: {\n people?: Array<{ id: string; name: string }>;\n projects?: Array<{ id: string; name: string }>;\n terms?: Array<{ id: string; name: string }>;\n companies?: Array<{ id: string; name: string }>;\n };\n contextDirectory?: string;\n}) {\n // Find the transcript (returns absolute path for file operations)\n const absolutePath = await resolveTranscriptPath(args.transcriptPath, args.contextDirectory);\n\n // Validate and sanitize entity IDs\n const validateEntityId = (id: string, name: string, type: string): string => {\n if (!id || typeof id !== 'string') {\n throw new Error(`Invalid entity ID for ${type} \"${name}\": ID must be a non-empty string`);\n }\n \n // Check for common JSON parsing errors\n if (id.includes('},') || id.includes('{') || id.includes('}') || id.includes(',')) {\n throw new Error(\n `Invalid entity ID \"${id}\" for ${type} \"${name}\". ` +\n `Entity IDs should be slugified identifiers (e.g., \"jack-smith\", \"discursive\"), ` +\n `not JSON syntax. Please provide a valid slugified ID.`\n );\n }\n \n // Basic validation: entity IDs should be alphanumeric with hyphens/underscores\n if (!/^[a-z0-9_-]+$/i.test(id)) {\n throw new Error(\n `Invalid entity ID \"${id}\" for ${type} \"${name}\". ` +\n `Entity IDs should only contain letters, numbers, hyphens, and underscores.`\n );\n }\n \n return id.trim();\n };\n\n // Convert incoming entities to EntityReference format with validation\n const entityReferences: Metadata.EntityReference[] = [];\n \n if (args.entities.people) {\n entityReferences.push(...args.entities.people.map(e => ({\n id: validateEntityId(e.id, e.name, 'person'),\n name: e.name.trim(),\n type: 'person' as const,\n })));\n }\n \n if (args.entities.projects) {\n entityReferences.push(...args.entities.projects.map(e => ({\n id: validateEntityId(e.id, e.name, 'project'),\n name: e.name.trim(),\n type: 'project' as const,\n })));\n }\n \n if (args.entities.terms) {\n entityReferences.push(...args.entities.terms.map(e => ({\n id: validateEntityId(e.id, e.name, 'term'),\n name: e.name.trim(),\n type: 'term' as const,\n })));\n }\n \n if (args.entities.companies) {\n entityReferences.push(...args.entities.companies.map(e => ({\n id: validateEntityId(e.id, e.name, 'company'),\n name: e.name.trim(),\n type: 'company' as const,\n })));\n }\n\n // Group by type\n const entities: NonNullable<Metadata.TranscriptMetadata['entities']> = {\n people: entityReferences.filter(e => e.type === 'person'),\n projects: entityReferences.filter(e => e.type === 'project'),\n terms: entityReferences.filter(e => e.type === 'term'),\n companies: entityReferences.filter(e => e.type === 'company'),\n };\n\n // Ensure we're working with a PKL file\n const pklPath = ensurePklExtension(absolutePath);\n \n const transcript = PklTranscript.open(pklPath, { readOnly: false });\n try {\n // Update entities in metadata\n transcript.updateMetadata({ entities });\n } finally {\n transcript.close();\n }\n\n // Convert to relative path for response\n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativePath = await sanitizePath(pklPath, outputDirectory);\n\n return {\n success: true,\n filePath: relativePath,\n message: 'Transcript entity references updated successfully',\n };\n}\n\nexport async function handleProvideFeedback(args: {\n transcriptPath: string;\n feedback: string;\n model?: string;\n contextDirectory?: string;\n}) {\n // Find the transcript (returns absolute path for file operations)\n const absolutePath = await resolveTranscriptPath(args.transcriptPath, args.contextDirectory);\n\n // Ensure we're working with a PKL file\n const pklPath = ensurePklExtension(absolutePath);\n \n const transcript = PklTranscript.open(pklPath, { readOnly: false });\n try {\n const transcriptContent = transcript.content;\n const contextDirectories = await getContextDirectories();\n const context = await Context.create({\n startingDir: args.contextDirectory || dirname(pklPath),\n contextDirectories,\n });\n const reasoning = Reasoning.create({ model: args.model || DEFAULT_MODEL });\n\n // Create a feedback context\n const feedbackCtx: Transcript.FeedbackContext = {\n transcriptPath: pklPath,\n transcriptContent,\n originalContent: transcriptContent,\n context,\n changes: [],\n verbose: false,\n dryRun: true, // Set to dry run so we can apply changes ourselves\n };\n\n await Transcript.processFeedback(args.feedback, feedbackCtx, reasoning);\n\n // Apply content changes to the PKL file\n if (feedbackCtx.changes.length > 0) {\n // Update content if it changed\n if (feedbackCtx.transcriptContent !== transcriptContent) {\n transcript.updateContent(feedbackCtx.transcriptContent);\n }\n \n // Handle title changes\n const titleChange = feedbackCtx.changes.find(c => c.type === 'title_changed');\n if (titleChange && titleChange.details.new_title) {\n transcript.updateMetadata({ title: titleChange.details.new_title as string });\n }\n \n // Handle project changes\n const projectChange = feedbackCtx.changes.find(c => c.type === 'project_changed');\n if (projectChange && projectChange.details.project_id) {\n transcript.updateMetadata({ \n projectId: projectChange.details.project_id as string,\n project: projectChange.details.project_name as string | undefined,\n });\n }\n }\n\n // Convert to relative path for response\n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativeOutputPath = await sanitizePath(pklPath, outputDirectory);\n\n return {\n success: true,\n changesApplied: feedbackCtx.changes.length,\n changes: feedbackCtx.changes.map(c => ({\n type: c.type,\n description: c.description,\n })),\n outputPath: relativeOutputPath,\n moved: false,\n };\n } finally {\n transcript.close();\n }\n}\n\nexport async function handleCreateNote(args: {\n title: string;\n content?: string;\n projectId?: string;\n tags?: string[];\n date?: string;\n contextDirectory?: string;\n}) {\n // Get the output directory\n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n \n // Parse the date or use current date\n const noteDate = args.date ? new Date(args.date) : new Date();\n const year = noteDate.getFullYear();\n const month = String(noteDate.getMonth() + 1).padStart(2, '0');\n const day = String(noteDate.getDate()).padStart(2, '0');\n const hours = String(noteDate.getHours()).padStart(2, '0');\n const minutes = String(noteDate.getMinutes()).padStart(2, '0');\n const timestamp = String(noteDate.getTime());\n \n // Create a slug from the title for the filename\n const titleSlug = args.title\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .substring(0, 50); // Limit length\n \n // Use .pkl extension for PKL format\n const filename = `${day}-${hours}${minutes}-${timestamp.substring(0, 14)}-${titleSlug}.pkl`;\n const relativePath = `${year}/${month}/${filename}`;\n const absolutePath = resolve(outputDirectory, relativePath);\n \n // Validate that the path stays within the output directory\n validatePathWithinDirectory(absolutePath, outputDirectory);\n \n // Build metadata\n let projectName: string | undefined;\n \n // If projectId is provided, try to get project name from context\n if (args.projectId) {\n try {\n const contextDirectories = await getContextDirectories();\n const context = await Context.create({\n startingDir: args.contextDirectory || process.cwd(),\n contextDirectories,\n });\n const project = await context.getProject(args.projectId);\n if (project) {\n projectName = project.name;\n }\n } catch {\n // Ignore errors - project name is optional\n }\n }\n \n // Build entities\n const entities = {\n people: [] as Metadata.EntityReference[],\n projects: args.projectId && projectName ? [{\n id: args.projectId,\n name: projectName,\n type: 'project' as const,\n }] : [] as Metadata.EntityReference[],\n terms: [] as Metadata.EntityReference[],\n companies: [] as Metadata.EntityReference[],\n };\n \n // Build PKL metadata\n const pklMetadata = {\n id: '', // Will be auto-generated by PklTranscript.create()\n title: args.title,\n date: noteDate,\n projectId: args.projectId,\n project: projectName,\n tags: args.tags || [],\n entities,\n status: 'reviewed' as const, // Default status for new notes\n };\n \n // Create directory if it doesn't exist\n await mkdir(dirname(absolutePath), { recursive: true });\n \n // Create PKL transcript\n const transcript = PklTranscript.create(absolutePath, pklMetadata);\n try {\n if (args.content) {\n transcript.updateContent(args.content);\n }\n } finally {\n transcript.close();\n }\n \n // Convert to relative path for response\n const relativeOutputPath = await sanitizePath(absolutePath, outputDirectory);\n \n return {\n success: true,\n filePath: relativeOutputPath,\n filename: filename,\n message: `Note \"${args.title}\" created successfully`,\n };\n}\n","/**\n * System Tools - Version and system information\n */\n\n// eslint-disable-next-line import/extensions\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { VERSION, PROGRAM_NAME } from '@/constants';\nimport * as ServerConfig from '../serverConfig';\n\n// ============================================================================\n// Tool Definitions\n// ============================================================================\n\nexport const getVersionTool: Tool = {\n name: 'protokoll_get_version',\n description: 'Get the current version of Protokoll including git information and system details. ' +\n 'Useful for diagnosing if you are using the latest version.',\n inputSchema: {\n type: 'object',\n properties: {},\n required: [],\n },\n};\n\nexport const getInfoTool: Tool = {\n name: 'protokoll_info',\n description: \n 'Get server configuration information including mode (local/remote) and workspace directories. ' +\n 'IMPORTANT: Check this tool first to understand if the server is running in:\\n' +\n '- \"remote\" mode: Server is pre-configured with workspace directories. Directory parameters are NOT accepted and will cause errors.\\n' +\n '- \"local\" mode: Server performs dynamic discovery. Directory parameters are optional and accepted.\\n\\n' +\n 'Use this to determine whether you need to provide contextDirectory parameters to other tools.',\n inputSchema: {\n type: 'object',\n properties: {},\n required: [],\n },\n};\n\n// ============================================================================\n// Handlers\n// ============================================================================\n\nexport interface GetVersionResult {\n version: string;\n programName: string;\n fullVersion: string;\n}\n\nexport async function handleGetVersion(): Promise<GetVersionResult> {\n return {\n version: VERSION,\n programName: PROGRAM_NAME,\n fullVersion: `${PROGRAM_NAME} ${VERSION}`,\n };\n}\n\nexport interface GetInfoResult {\n mode: 'local' | 'remote';\n modeDescription: string;\n acceptsDirectoryParameters: boolean;\n workspaceRoot: string | null;\n inputDirectory: string | null;\n outputDirectory: string | null;\n processedDirectory: string | null;\n contextDirectories: string[] | null;\n configFilePath: string | null;\n}\n\nexport async function handleGetInfo(): Promise<GetInfoResult> {\n const mode = ServerConfig.getServerMode();\n const isRemote = mode === 'remote';\n \n let config;\n try {\n config = ServerConfig.getServerConfig();\n } catch {\n // Not initialized - return minimal info\n return {\n mode: 'local',\n modeDescription: 'Server is running in local mode with dynamic discovery',\n acceptsDirectoryParameters: true,\n workspaceRoot: null,\n inputDirectory: null,\n outputDirectory: null,\n processedDirectory: null,\n contextDirectories: null,\n configFilePath: null,\n };\n }\n \n return {\n mode,\n modeDescription: isRemote\n ? 'Server is running in remote mode with pre-configured workspace directories'\n : 'Server is running in local mode with dynamic discovery',\n acceptsDirectoryParameters: !isRemote,\n workspaceRoot: config.workspaceRoot,\n inputDirectory: config.inputDirectory,\n outputDirectory: config.outputDirectory,\n processedDirectory: config.processedDirectory,\n contextDirectories: config.configFile?.contextDirectories as string[] | null,\n configFilePath: config.configFilePath,\n };\n}\n","/* eslint-disable import/extensions */\n/**\n * Relationship Tools - Manage entity relationships\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as Context from '@/context';\nimport type { Entity } from '@/context/types';\nimport type { ContextInstance } from '@/context';\nimport { parseEntityUri, createRelationship, type EntityRelationship } from '@redaksjon/context';\nimport { \n findPersonResilient, \n findCompanyResilient, \n findTermResilient, \n findProjectResilient \n} from '@redaksjon/protokoll-engine';\n\n// ============================================================================\n// Type Extensions\n// ============================================================================\n\n/**\n * Entity with relationships field\n */\ntype EntityWithRelationships = Entity & { relationships?: EntityRelationship[] };\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Get an entity by type and ID from context\n */\nfunction getEntityByType(\n context: ContextInstance,\n entityType: string,\n entityId: string\n): Entity | undefined {\n switch (entityType) {\n case 'person':\n return findPersonResilient(context, entityId);\n case 'company':\n return findCompanyResilient(context, entityId);\n case 'term':\n return findTermResilient(context, entityId);\n case 'project':\n return findProjectResilient(context, entityId);\n default:\n return undefined;\n }\n}\n\n// ============================================================================\n// Tool Definitions\n// ============================================================================\n\nexport const addRelationshipTool: Tool = {\n name: 'protokoll_add_relationship',\n description:\n 'Add a relationship between two entities. ' +\n 'Relationships use URIs (redaksjon://{type}/{id}) to reference entities. ' +\n 'Common relationship types: works_at, manages, reports_to, used_in, part_of, expert_in, etc.',\n inputSchema: {\n type: 'object',\n properties: {\n entityType: {\n type: 'string',\n enum: ['person', 'company', 'term', 'project'],\n description: 'Type of the source entity',\n },\n entityId: {\n type: 'string',\n description: 'ID of the source entity',\n },\n targetType: {\n type: 'string',\n enum: ['person', 'company', 'term', 'project'],\n description: 'Type of the target entity',\n },\n targetId: {\n type: 'string',\n description: 'ID of the target entity',\n },\n relationship: {\n type: 'string',\n description: 'Type of relationship (e.g., works_at, manages, used_in, part_of)',\n },\n notes: {\n type: 'string',\n description: 'Optional notes about this relationship',\n },\n metadata: {\n type: 'object',\n description: 'Optional metadata (key-value pairs)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['entityType', 'entityId', 'targetType', 'targetId', 'relationship'],\n },\n};\n\nexport const removeRelationshipTool: Tool = {\n name: 'protokoll_remove_relationship',\n description:\n 'Remove a specific relationship from an entity. ' +\n 'Identifies the relationship by target URI and relationship type.',\n inputSchema: {\n type: 'object',\n properties: {\n entityType: {\n type: 'string',\n enum: ['person', 'company', 'term', 'project'],\n description: 'Type of the source entity',\n },\n entityId: {\n type: 'string',\n description: 'ID of the source entity',\n },\n targetUri: {\n type: 'string',\n description: 'URI of the target entity (redaksjon://{type}/{id})',\n },\n relationship: {\n type: 'string',\n description: 'Type of relationship to remove',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['entityType', 'entityId', 'targetUri', 'relationship'],\n },\n};\n\nexport const listRelationshipsTool: Tool = {\n name: 'protokoll_list_relationships',\n description:\n 'List all relationships for an entity. ' +\n 'Returns the relationships array with URIs, types, notes, and metadata.',\n inputSchema: {\n type: 'object',\n properties: {\n entityType: {\n type: 'string',\n enum: ['person', 'company', 'term', 'project'],\n description: 'Type of the entity',\n },\n entityId: {\n type: 'string',\n description: 'ID of the entity',\n },\n relationshipType: {\n type: 'string',\n description: 'Optional: filter by relationship type',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['entityType', 'entityId'],\n },\n};\n\nexport const findRelatedEntitiesTool: Tool = {\n name: 'protokoll_find_related_entities',\n description:\n 'Find all entities related to a given entity. ' +\n 'Can filter by relationship type and target entity type.',\n inputSchema: {\n type: 'object',\n properties: {\n entityType: {\n type: 'string',\n enum: ['person', 'company', 'term', 'project'],\n description: 'Type of the source entity',\n },\n entityId: {\n type: 'string',\n description: 'ID of the source entity',\n },\n relationshipType: {\n type: 'string',\n description: 'Optional: filter by relationship type (e.g., works_at, manages)',\n },\n targetType: {\n type: 'string',\n enum: ['person', 'company', 'term', 'project'],\n description: 'Optional: filter by target entity type',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['entityType', 'entityId'],\n },\n};\n\n// ============================================================================\n// Handlers\n// ============================================================================\n\nexport async function handleAddRelationship(args: {\n entityType: string;\n entityId: string;\n targetType: string;\n targetId: string;\n relationship: string;\n notes?: string;\n metadata?: Record<string, unknown>;\n contextDirectory?: string;\n}): Promise<{ success: boolean; message: string; relationship: EntityRelationship }> {\n const { entityType, entityId, targetType, targetId, relationship, notes, metadata, contextDirectory } = args;\n\n // Get context\n const contextInstance = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n // Get the entity\n const entity = getEntityByType(contextInstance, entityType, entityId);\n if (!entity) {\n throw new Error(`Entity not found: ${entityType}/${entityId}`);\n }\n\n // Verify target entity exists\n const targetEntity = getEntityByType(contextInstance, targetType, targetId);\n if (!targetEntity) {\n throw new Error(`Target entity not found: ${targetType}/${targetId}`);\n }\n\n // Create the relationship\n const newRelationship = createRelationship(targetType, targetId, relationship, notes, metadata);\n\n // Add to entity's relationships array\n const updatedEntity = {\n ...entity,\n relationships: [...((entity as EntityWithRelationships).relationships || []), newRelationship],\n };\n\n // Save the entity\n await contextInstance.saveEntity(updatedEntity as Entity);\n\n return {\n success: true,\n message: `Added ${relationship} relationship from ${entityType}/${entityId} to ${targetType}/${targetId}`,\n relationship: newRelationship,\n };\n}\n\nexport async function handleRemoveRelationship(args: {\n entityType: string;\n entityId: string;\n targetUri: string;\n relationship: string;\n contextDirectory?: string;\n}): Promise<{ success: boolean; message: string }> {\n const { entityType, entityId, targetUri, relationship, contextDirectory } = args;\n\n // Get context\n const contextInstance = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n // Get the entity\n const entity = getEntityByType(contextInstance, entityType, entityId);\n if (!entity) {\n throw new Error(`Entity not found: ${entityType}/${entityId}`);\n }\n\n // Filter out the relationship\n const relationships = (entity as EntityWithRelationships).relationships || [];\n const filteredRelationships = relationships.filter(\n (r: EntityRelationship) => !(r.uri === targetUri && r.relationship === relationship)\n );\n\n if (filteredRelationships.length === relationships.length) {\n throw new Error(`Relationship not found: ${relationship} to ${targetUri}`);\n }\n\n // Update entity\n const updatedEntity = {\n ...entity,\n relationships: filteredRelationships,\n };\n\n // Save the entity\n await contextInstance.saveEntity(updatedEntity as Entity);\n\n return {\n success: true,\n message: `Removed ${relationship} relationship to ${targetUri}`,\n };\n}\n\nexport async function handleListRelationships(args: {\n entityType: string;\n entityId: string;\n relationshipType?: string;\n contextDirectory?: string;\n}): Promise<{ entityId: string; entityType: string; relationships: EntityRelationship[] }> {\n const { entityType, entityId, relationshipType, contextDirectory } = args;\n\n // Get context\n const contextInstance = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n // Get the entity\n const entity = getEntityByType(contextInstance, entityType, entityId);\n if (!entity) {\n throw new Error(`Entity not found: ${entityType}/${entityId}`);\n }\n\n // Get relationships\n let relationships = (entity as EntityWithRelationships).relationships || [];\n\n // Filter by relationship type if specified\n if (relationshipType) {\n relationships = relationships.filter((r: EntityRelationship) => r.relationship === relationshipType);\n }\n\n return {\n entityId,\n entityType,\n relationships,\n };\n}\n\nexport async function handleFindRelatedEntities(args: {\n entityType: string;\n entityId: string;\n relationshipType?: string;\n targetType?: string;\n contextDirectory?: string;\n}): Promise<{\n entityId: string;\n entityType: string;\n relatedEntities: Array<{\n relationship: string;\n targetType: string;\n targetId: string;\n targetName: string;\n notes?: string;\n }>;\n}> {\n const { entityType, entityId, relationshipType, targetType, contextDirectory } = args;\n\n // Get context\n const contextInstance = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n // Get the entity\n const entity = getEntityByType(contextInstance, entityType, entityId);\n if (!entity) {\n throw new Error(`Entity not found: ${entityType}/${entityId}`);\n }\n\n // Get relationships\n let relationships = (entity as EntityWithRelationships).relationships || [];\n\n // Filter by relationship type if specified\n if (relationshipType) {\n relationships = relationships.filter((r: EntityRelationship) => r.relationship === relationshipType);\n }\n\n // Parse URIs and fetch target entities\n const relatedEntities = relationships\n .map((rel: EntityRelationship) => {\n const parsed = parseEntityUri(rel.uri);\n if (!parsed) return null;\n\n // Filter by target type if specified\n if (targetType && parsed.type !== targetType) return null;\n\n // Get the target entity\n const targetEntity = getEntityByType(contextInstance, parsed.type, parsed.id);\n\n if (!targetEntity) return null;\n\n return {\n relationship: rel.relationship,\n targetType: parsed.type,\n targetId: parsed.id,\n targetName: targetEntity.name,\n notes: rel.notes,\n };\n })\n .filter((item): item is NonNullable<typeof item> => item !== null);\n\n return {\n entityId,\n entityType,\n relatedEntities,\n };\n}\n","/* eslint-disable import/extensions */\n/**\n * Content Tools - Manage entity content (URLs, text, documents, etc.)\n */\n\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport * as Context from '@/context';\nimport type { Entity } from '@/context/types';\nimport type { ContextInstance } from '@/context';\nimport { \n findPersonResilient, \n findCompanyResilient, \n findTermResilient, \n findProjectResilient \n} from '@redaksjon/protokoll-engine';\nimport {\n createUrlContent,\n createTextContent,\n createMarkdownContent,\n createCodeContent,\n createDocumentContent,\n type EntityContentItem,\n} from '@redaksjon/context';\n\n// ============================================================================\n// Type Extensions\n// ============================================================================\n\n/**\n * Entity with content field\n */\ntype EntityWithContent = Entity & { content?: EntityContentItem[] };\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Get an entity by type and ID from context\n */\nfunction getEntityByType(\n context: ContextInstance,\n entityType: string,\n entityId: string\n): Entity | undefined {\n switch (entityType) {\n case 'person':\n return findPersonResilient(context, entityId);\n case 'company':\n return findCompanyResilient(context, entityId);\n case 'term':\n return findTermResilient(context, entityId);\n case 'project':\n return findProjectResilient(context, entityId);\n default:\n return undefined;\n }\n}\n\n// ============================================================================\n// Tool Definitions\n// ============================================================================\n\nexport const addContentTool: Tool = {\n name: 'protokoll_add_content',\n description:\n 'Add content to an entity (URL, text, markdown, code, document, etc.). ' +\n 'Content items have a type, title, content string, and optional metadata. ' +\n 'Common types: url, text, markdown, html, code, document, image, video.',\n inputSchema: {\n type: 'object',\n properties: {\n entityType: {\n type: 'string',\n enum: ['person', 'company', 'term', 'project'],\n description: 'Type of the entity',\n },\n entityId: {\n type: 'string',\n description: 'ID of the entity',\n },\n type: {\n type: 'string',\n description: 'Content type (url, text, markdown, html, code, document, image, video, etc.)',\n },\n content: {\n type: 'string',\n description: 'The actual content (URL, text, markdown, code, file path, etc.)',\n },\n title: {\n type: 'string',\n description: 'Title or label for this content',\n },\n mimeType: {\n type: 'string',\n description: 'Optional MIME type (text/plain, text/markdown, application/pdf, etc.)',\n },\n source: {\n type: 'string',\n description: 'Optional source or origin of this content',\n },\n notes: {\n type: 'string',\n description: 'Optional notes about this content',\n },\n metadata: {\n type: 'object',\n description: 'Optional metadata (key-value pairs)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['entityType', 'entityId', 'type', 'content'],\n },\n};\n\nexport const removeContentTool: Tool = {\n name: 'protokoll_remove_content',\n description:\n 'Remove a specific content item from an entity. ' +\n 'Identifies the content by title or by index in the content array.',\n inputSchema: {\n type: 'object',\n properties: {\n entityType: {\n type: 'string',\n enum: ['person', 'company', 'term', 'project'],\n description: 'Type of the entity',\n },\n entityId: {\n type: 'string',\n description: 'ID of the entity',\n },\n title: {\n type: 'string',\n description: 'Title of the content item to remove',\n },\n index: {\n type: 'number',\n description: 'Index of the content item to remove (0-based)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['entityType', 'entityId'],\n },\n};\n\nexport const listContentTool: Tool = {\n name: 'protokoll_list_content',\n description:\n 'List all content items for an entity. ' +\n 'Returns the content array with types, titles, and metadata. ' +\n 'Can filter by content type.',\n inputSchema: {\n type: 'object',\n properties: {\n entityType: {\n type: 'string',\n enum: ['person', 'company', 'term', 'project'],\n description: 'Type of the entity',\n },\n entityId: {\n type: 'string',\n description: 'ID of the entity',\n },\n contentType: {\n type: 'string',\n description: 'Optional: filter by content type (url, text, markdown, etc.)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['entityType', 'entityId'],\n },\n};\n\nexport const getContentTool: Tool = {\n name: 'protokoll_get_content',\n description:\n 'Get a specific content item from an entity. ' +\n 'Returns the full content including the content string.',\n inputSchema: {\n type: 'object',\n properties: {\n entityType: {\n type: 'string',\n enum: ['person', 'company', 'term', 'project'],\n description: 'Type of the entity',\n },\n entityId: {\n type: 'string',\n description: 'ID of the entity',\n },\n title: {\n type: 'string',\n description: 'Title of the content item',\n },\n index: {\n type: 'number',\n description: 'Index of the content item (0-based)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Path to the .protokoll context directory',\n },\n },\n required: ['entityType', 'entityId'],\n },\n};\n\n// ============================================================================\n// Handlers\n// ============================================================================\n\nexport async function handleAddContent(args: {\n entityType: string;\n entityId: string;\n type: string;\n content: string;\n title?: string;\n mimeType?: string;\n source?: string;\n notes?: string;\n metadata?: Record<string, unknown>;\n contextDirectory?: string;\n}): Promise<{ success: boolean; message: string; contentItem: EntityContentItem }> {\n const { entityType, entityId, type, content, title, mimeType, source, notes, metadata, contextDirectory } = args;\n\n // Get context\n const contextInstance = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n // Get the entity\n const entity = getEntityByType(contextInstance, entityType, entityId);\n if (!entity) {\n throw new Error(`Entity not found: ${entityType}/${entityId}`);\n }\n\n // Create the content item based on type\n let contentItem: EntityContentItem;\n \n switch (type) {\n case 'url':\n contentItem = createUrlContent(content, title, source, notes);\n break;\n case 'text':\n contentItem = createTextContent(content, title, source, notes);\n break;\n case 'markdown':\n contentItem = createMarkdownContent(content, title, source, notes);\n break;\n case 'code':\n contentItem = createCodeContent(\n content,\n metadata?.language as string || 'text',\n title,\n source,\n notes\n );\n break;\n case 'document':\n contentItem = createDocumentContent(content, title, mimeType, notes);\n break;\n default:\n // Generic content item\n contentItem = {\n type,\n title,\n content,\n mimeType,\n source,\n timestamp: new Date().toISOString(),\n notes,\n metadata,\n };\n }\n\n // Add to entity's content array\n const updatedEntity = {\n ...entity,\n content: [...((entity as EntityWithContent).content || []), contentItem],\n };\n\n // Save the entity\n await contextInstance.saveEntity(updatedEntity as Entity);\n\n return {\n success: true,\n message: `Added ${type} content to ${entityType}/${entityId}`,\n contentItem,\n };\n}\n\nexport async function handleRemoveContent(args: {\n entityType: string;\n entityId: string;\n title?: string;\n index?: number;\n contextDirectory?: string;\n}): Promise<{ success: boolean; message: string }> {\n const { entityType, entityId, title, index, contextDirectory } = args;\n\n if (title === undefined && index === undefined) {\n throw new Error('Either title or index must be provided');\n }\n\n // Get context\n const contextInstance = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n // Get the entity\n const entity = getEntityByType(contextInstance, entityType, entityId);\n if (!entity) {\n throw new Error(`Entity not found: ${entityType}/${entityId}`);\n }\n\n const content = (entity as EntityWithContent).content || [];\n\n // Find and remove the content item\n let filteredContent: EntityContentItem[];\n let removedTitle: string;\n\n if (index !== undefined) {\n if (index < 0 || index >= content.length) {\n throw new Error(`Invalid index: ${index}. Content array has ${content.length} items.`);\n }\n removedTitle = content[index].title || `item at index ${index}`;\n filteredContent = content.filter((_: EntityContentItem, i: number) => i !== index);\n } else {\n const foundIndex = content.findIndex((c: EntityContentItem) => c.title === title);\n if (foundIndex === -1) {\n throw new Error(`Content item not found with title: ${title}`);\n }\n removedTitle = title!;\n filteredContent = content.filter((c: EntityContentItem) => c.title !== title);\n }\n\n // Update entity\n const updatedEntity = {\n ...entity,\n content: filteredContent,\n };\n\n // Save the entity\n await contextInstance.saveEntity(updatedEntity as Entity);\n\n return {\n success: true,\n message: `Removed content \"${removedTitle}\" from ${entityType}/${entityId}`,\n };\n}\n\nexport async function handleListContent(args: {\n entityType: string;\n entityId: string;\n contentType?: string;\n contextDirectory?: string;\n}): Promise<{\n entityId: string;\n entityType: string;\n content: Array<{\n index: number;\n type: string;\n title?: string;\n mimeType?: string;\n source?: string;\n timestamp?: string;\n hasNotes: boolean;\n contentLength: number;\n }>;\n}> {\n const { entityType, entityId, contentType, contextDirectory } = args;\n\n // Get context\n const contextInstance = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n // Get the entity\n const entity = getEntityByType(contextInstance, entityType, entityId);\n if (!entity) {\n throw new Error(`Entity not found: ${entityType}/${entityId}`);\n }\n\n // Get content\n let content = (entity as EntityWithContent).content || [];\n\n // Filter by content type if specified\n if (contentType) {\n content = content.filter((c: EntityContentItem) => c.type === contentType);\n }\n\n // Return summary (without full content strings for brevity)\n const contentSummary = content.map((item: EntityContentItem, index: number) => ({\n index,\n type: item.type,\n title: item.title,\n mimeType: item.mimeType,\n source: item.source,\n timestamp: item.timestamp,\n hasNotes: !!item.notes,\n contentLength: item.content.length,\n }));\n\n return {\n entityId,\n entityType,\n content: contentSummary,\n };\n}\n\nexport async function handleGetContent(args: {\n entityType: string;\n entityId: string;\n title?: string;\n index?: number;\n contextDirectory?: string;\n}): Promise<{ entityId: string; entityType: string; contentItem: EntityContentItem }> {\n const { entityType, entityId, title, index, contextDirectory } = args;\n\n if (title === undefined && index === undefined) {\n throw new Error('Either title or index must be provided');\n }\n\n // Get context\n const contextInstance = await Context.create({\n startingDir: contextDirectory || process.cwd(),\n });\n\n // Get the entity\n const entity = getEntityByType(contextInstance, entityType, entityId);\n if (!entity) {\n throw new Error(`Entity not found: ${entityType}/${entityId}`);\n }\n\n const content = (entity as EntityWithContent).content || [];\n\n // Find the content item\n let contentItem: EntityContentItem | undefined;\n\n if (index !== undefined) {\n if (index < 0 || index >= content.length) {\n throw new Error(`Invalid index: ${index}. Content array has ${content.length} items.`);\n }\n contentItem = content[index];\n } else {\n contentItem = content.find((c: EntityContentItem) => c.title === title);\n if (!contentItem) {\n throw new Error(`Content item not found with title: ${title}`);\n }\n }\n\n return {\n entityId,\n entityType,\n contentItem: contentItem!,\n };\n}\n","/**\n * Status and Task Tools - MCP tools for managing transcript lifecycle status and tasks\n * \n * PKL-only implementation - all transcripts are stored in PKL format.\n */\n// eslint-disable-next-line import/extensions\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\nimport { \n isValidStatus, \n VALID_STATUSES,\n} from '@redaksjon/protokoll-engine';\nimport { getConfiguredDirectory, sanitizePath, resolveTranscriptPath } from './shared';\nimport { PklTranscript } from '@redaksjon/protokoll-format';\nimport type { Task as PklTask, TranscriptStatus } from '@redaksjon/protokoll-format';\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n// ============================================================================\n// Tool Definitions\n// ============================================================================\n\nexport const setStatusTool: Tool = {\n name: 'protokoll_set_status',\n description:\n 'Change the lifecycle status of a transcript. ' +\n 'Valid statuses: initial, enhanced, reviewed, in_progress, closed, archived. ' +\n 'Status transitions are recorded in history with timestamps. ' +\n 'Use this to track transcript progress through your workflow.',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPath: {\n type: 'string',\n description:\n 'Transcript URI (preferred) or relative path from output directory. ' +\n 'URI format: \"protokoll://transcript/2026/2/12-1606-meeting\" (no file extension). ' +\n 'Path format: \"2026/2/12-1606-meeting\" or \"2026/2/12-1606-meeting.pkl\"',\n },\n status: {\n type: 'string',\n enum: VALID_STATUSES,\n description:\n 'New status to set. ' +\n 'initial/enhanced: Pipeline states. ' +\n 'reviewed: User has reviewed. ' +\n 'in_progress: Has tasks to complete. ' +\n 'closed: All work done. ' +\n 'archived: Long-term storage.',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPath', 'status'],\n },\n};\n\nexport const createTaskTool: Tool = {\n name: 'protokoll_create_task',\n description:\n 'Add a new task to a transcript. Tasks are follow-up actions to complete. ' +\n 'Returns the generated task ID for later reference.',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPath: {\n type: 'string',\n description:\n 'Transcript URI (preferred) or relative path from output directory. ' +\n 'URI format: \"protokoll://transcript/2026/2/12-1606-meeting\" (no file extension). ' +\n 'Path format: \"2026/2/12-1606-meeting\" or \"2026/2/12-1606-meeting.pkl\"',\n },\n description: {\n type: 'string',\n description: 'Description of the task (1-2 sentences)',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPath', 'description'],\n },\n};\n\nexport const completeTaskTool: Tool = {\n name: 'protokoll_complete_task',\n description: 'Mark a task as done. Sets the completed timestamp.',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPath: {\n type: 'string',\n description:\n 'Transcript URI (preferred) or relative path from output directory. ' +\n 'URI format: \"protokoll://transcript/2026/2/12-1606-meeting\" (no file extension). ' +\n 'Path format: \"2026/2/12-1606-meeting\" or \"2026/2/12-1606-meeting.pkl\"',\n },\n taskId: {\n type: 'string',\n description: 'ID of the task to complete (e.g., \"task-1234567890-abc123\")',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPath', 'taskId'],\n },\n};\n\nexport const deleteTaskTool: Tool = {\n name: 'protokoll_delete_task',\n description: 'Remove a task from a transcript permanently.',\n inputSchema: {\n type: 'object',\n properties: {\n transcriptPath: {\n type: 'string',\n description:\n 'Transcript URI (preferred) or relative path from output directory. ' +\n 'URI format: \"protokoll://transcript/2026/2/12-1606-meeting\" (no file extension). ' +\n 'Path format: \"2026/2/12-1606-meeting\" or \"2026/2/12-1606-meeting.pkl\"',\n },\n taskId: {\n type: 'string',\n description: 'ID of the task to delete (e.g., \"task-1234567890-abc123\")',\n },\n contextDirectory: {\n type: 'string',\n description: 'Optional: Path to the .protokoll context directory',\n },\n },\n required: ['transcriptPath', 'taskId'],\n },\n};\n\n// ============================================================================\n// Tool Handlers\n// ============================================================================\n\nexport async function handleSetStatus(args: {\n transcriptPath: string;\n status: string;\n contextDirectory?: string;\n}) {\n // Validate status\n if (!isValidStatus(args.status)) {\n throw new Error(\n `Invalid status \"${args.status}\". ` +\n `Valid statuses are: ${VALID_STATUSES.join(', ')}`\n );\n }\n \n const newStatus = args.status as TranscriptStatus;\n \n // Find the transcript\n const absolutePath = await resolveTranscriptPath(args.transcriptPath, args.contextDirectory);\n \n const transcript = PklTranscript.open(absolutePath, { readOnly: false });\n try {\n const oldStatus = transcript.metadata.status || 'reviewed';\n \n // Check if status is actually changing\n if (oldStatus === newStatus) {\n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativePath = await sanitizePath(absolutePath, outputDirectory);\n \n return {\n success: true,\n filePath: relativePath,\n previousStatus: oldStatus,\n newStatus: newStatus,\n changed: false,\n message: `Status is already '${newStatus}'`,\n };\n }\n \n // Update status\n transcript.updateMetadata({ status: newStatus });\n \n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativePath = await sanitizePath(absolutePath, outputDirectory);\n \n return {\n success: true,\n filePath: relativePath,\n previousStatus: oldStatus,\n newStatus: newStatus,\n changed: true,\n message: `Status changed from '${oldStatus}' to '${newStatus}'`,\n };\n } finally {\n transcript.close();\n }\n}\n\n// ============================================================================\n// Task Handlers\n// ============================================================================\n\nexport async function handleCreateTask(args: {\n transcriptPath: string;\n description: string;\n contextDirectory?: string;\n}) {\n if (!args.description || typeof args.description !== 'string' || args.description.trim() === '') {\n throw new Error('Task description is required and must be a non-empty string');\n }\n \n // Find the transcript\n const absolutePath = await resolveTranscriptPath(args.transcriptPath, args.contextDirectory);\n \n const transcript = PklTranscript.open(absolutePath, { readOnly: false });\n try {\n // Create a new task\n const taskId = `task-${Date.now()}`;\n const newTask: PklTask = {\n id: taskId,\n description: args.description.trim(),\n status: 'open',\n created: new Date(),\n };\n \n // Get existing tasks and add the new one\n const existingTasks = transcript.metadata.tasks || [];\n transcript.updateMetadata({ tasks: [...existingTasks, newTask] });\n \n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativePath = await sanitizePath(absolutePath, outputDirectory);\n \n return {\n success: true,\n filePath: relativePath,\n task: {\n id: newTask.id,\n description: newTask.description,\n status: newTask.status,\n created: newTask.created.toISOString(),\n },\n message: `Task created: ${newTask.id}`,\n };\n } finally {\n transcript.close();\n }\n}\n\nexport async function handleCompleteTask(args: {\n transcriptPath: string;\n taskId: string;\n contextDirectory?: string;\n}) {\n if (!args.taskId || typeof args.taskId !== 'string') {\n throw new Error('Task ID is required');\n }\n \n // Find the transcript\n const absolutePath = await resolveTranscriptPath(args.transcriptPath, args.contextDirectory);\n \n const transcript = PklTranscript.open(absolutePath, { readOnly: false });\n try {\n // Find the task\n const tasks = transcript.metadata.tasks || [];\n const task = tasks.find(t => t.id === args.taskId);\n if (!task) {\n throw new Error(`Task not found: ${args.taskId}`);\n }\n \n // Update the task to done\n const updatedTasks = tasks.map(t => \n t.id === args.taskId \n ? { ...t, status: 'done' as const, completed: new Date() }\n : t\n );\n transcript.updateMetadata({ tasks: updatedTasks });\n \n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativePath = await sanitizePath(absolutePath, outputDirectory);\n \n return {\n success: true,\n filePath: relativePath,\n taskId: args.taskId,\n description: task.description,\n message: `Task completed: ${args.taskId}`,\n };\n } finally {\n transcript.close();\n }\n}\n\nexport async function handleDeleteTask(args: {\n transcriptPath: string;\n taskId: string;\n contextDirectory?: string;\n}) {\n if (!args.taskId || typeof args.taskId !== 'string') {\n throw new Error('Task ID is required');\n }\n \n // Find the transcript\n const absolutePath = await resolveTranscriptPath(args.transcriptPath, args.contextDirectory);\n \n const transcript = PklTranscript.open(absolutePath, { readOnly: false });\n try {\n // Find the task before deleting\n const tasks = transcript.metadata.tasks || [];\n const task = tasks.find(t => t.id === args.taskId);\n if (!task) {\n throw new Error(`Task not found: ${args.taskId}`);\n }\n \n // Remove the task\n const updatedTasks = tasks.filter(t => t.id !== args.taskId);\n transcript.updateMetadata({ tasks: updatedTasks });\n \n const outputDirectory = await getConfiguredDirectory('outputDirectory', args.contextDirectory);\n const relativePath = await sanitizePath(absolutePath, outputDirectory);\n \n return {\n success: true,\n filePath: relativePath,\n taskId: args.taskId,\n description: task.description,\n message: `Task deleted: ${args.taskId}`,\n };\n } finally {\n transcript.close();\n }\n}\n\n// Export all tools from this module\nexport const statusTools: Tool[] = [\n setStatusTool,\n createTaskTool,\n completeTaskTool,\n deleteTaskTool,\n];\n","/**\n * MCP Tools - Exports all tool definitions and handlers\n */\n\n// eslint-disable-next-line import/extensions\nimport type { Tool } from '@modelcontextprotocol/sdk/types.js';\n\nimport * as DiscoveryTools from './discoveryTools';\nimport * as AudioTools from './audioTools';\nimport * as ContextTools from './contextTools';\nimport * as EntityTools from './entityTools';\nimport * as AssistTools from './assistTools';\nimport * as TranscriptTools from './transcriptTools';\nimport * as SystemTools from './systemTools';\nimport * as RelationshipTools from './relationshipTools';\nimport * as ContentTools from './contentTools';\nimport * as StatusTools from './statusTools';\n\n// Re-export all handlers for testing\nexport * from './discoveryTools';\nexport * from './audioTools';\nexport * from './contextTools';\nexport * from './entityTools';\nexport * from './assistTools';\nexport * from './transcriptTools';\nexport * from './systemTools';\nexport * from './relationshipTools';\nexport * from './contentTools';\nexport * from './statusTools';\nexport * from './shared';\n\n// ============================================================================\n// All Tools\n// ============================================================================\n\nexport const tools: Tool[] = [\n // System Information\n SystemTools.getVersionTool,\n SystemTools.getInfoTool,\n\n // Discovery & Configuration\n DiscoveryTools.discoverConfigTool,\n DiscoveryTools.suggestProjectTool,\n\n // Audio Processing\n AudioTools.processAudioTool,\n AudioTools.batchProcessTool,\n\n // Context Management\n ContextTools.contextStatusTool,\n ContextTools.listProjectsTool,\n ContextTools.listPeopleTool,\n ContextTools.listTermsTool,\n ContextTools.listCompaniesTool,\n ContextTools.searchContextTool,\n ContextTools.getEntityTool,\n\n // Entity CRUD\n EntityTools.addPersonTool,\n EntityTools.editPersonTool,\n EntityTools.addProjectTool,\n EntityTools.editProjectTool,\n EntityTools.updateProjectTool,\n EntityTools.addTermTool,\n EntityTools.editTermTool,\n EntityTools.updateTermTool,\n EntityTools.mergeTermsTool,\n EntityTools.addCompanyTool,\n EntityTools.deleteEntityTool,\n\n // Relationship Management\n RelationshipTools.addRelationshipTool,\n RelationshipTools.removeRelationshipTool,\n RelationshipTools.listRelationshipsTool,\n RelationshipTools.findRelatedEntitiesTool,\n\n // Content Management\n ContentTools.addContentTool,\n ContentTools.removeContentTool,\n ContentTools.listContentTool,\n ContentTools.getContentTool,\n\n // Smart Assistance\n AssistTools.suggestProjectMetadataTool,\n AssistTools.suggestTermMetadataTool,\n\n // Transcript Operations\n TranscriptTools.readTranscriptTool,\n TranscriptTools.listTranscriptsTool,\n TranscriptTools.editTranscriptTool,\n TranscriptTools.changeTranscriptDateTool,\n TranscriptTools.combineTranscriptsTool,\n TranscriptTools.provideFeedbackTool,\n TranscriptTools.updateTranscriptContentTool,\n TranscriptTools.updateTranscriptEntityReferencesTool,\n TranscriptTools.createNoteTool,\n\n // Lifecycle Status & Tasks\n StatusTools.setStatusTool,\n StatusTools.createTaskTool,\n StatusTools.completeTaskTool,\n StatusTools.deleteTaskTool,\n];\n\n// ============================================================================\n// Tool Handler Router\n// ============================================================================\n\nexport async function handleToolCall(name: string, args: unknown): Promise<unknown> {\n switch (name) {\n // System Information\n case 'protokoll_get_version':\n return SystemTools.handleGetVersion();\n case 'protokoll_info':\n return SystemTools.handleGetInfo();\n\n // Discovery & Configuration\n case 'protokoll_discover_config':\n return DiscoveryTools.handleDiscoverConfig(args as Parameters<typeof DiscoveryTools.handleDiscoverConfig>[0]);\n case 'protokoll_suggest_project':\n return DiscoveryTools.handleSuggestProject(args as Parameters<typeof DiscoveryTools.handleSuggestProject>[0]);\n\n // Audio Processing\n case 'protokoll_process_audio':\n return AudioTools.handleProcessAudio(args as Parameters<typeof AudioTools.handleProcessAudio>[0]);\n case 'protokoll_batch_process':\n return AudioTools.handleBatchProcess(args as Parameters<typeof AudioTools.handleBatchProcess>[0]);\n\n // Context Management\n case 'protokoll_context_status':\n return ContextTools.handleContextStatus(args as Parameters<typeof ContextTools.handleContextStatus>[0]);\n case 'protokoll_list_projects':\n return ContextTools.handleListProjects(args as Parameters<typeof ContextTools.handleListProjects>[0]);\n case 'protokoll_list_people':\n return ContextTools.handleListPeople(args as Parameters<typeof ContextTools.handleListPeople>[0]);\n case 'protokoll_list_terms':\n return ContextTools.handleListTerms(args as Parameters<typeof ContextTools.handleListTerms>[0]);\n case 'protokoll_list_companies':\n return ContextTools.handleListCompanies(args as Parameters<typeof ContextTools.handleListCompanies>[0]);\n case 'protokoll_search_context':\n return ContextTools.handleSearchContext(args as Parameters<typeof ContextTools.handleSearchContext>[0]);\n case 'protokoll_get_entity':\n return ContextTools.handleGetEntity(args as Parameters<typeof ContextTools.handleGetEntity>[0]);\n\n // Entity CRUD\n case 'protokoll_add_person':\n return EntityTools.handleAddPerson(args as Parameters<typeof EntityTools.handleAddPerson>[0]);\n case 'protokoll_edit_person':\n return EntityTools.handleEditPerson(args as Parameters<typeof EntityTools.handleEditPerson>[0]);\n case 'protokoll_add_project':\n return EntityTools.handleAddProject(args as Parameters<typeof EntityTools.handleAddProject>[0]);\n case 'protokoll_edit_project':\n return EntityTools.handleEditProject(args as Parameters<typeof EntityTools.handleEditProject>[0]);\n case 'protokoll_update_project':\n return EntityTools.handleUpdateProject(args as Parameters<typeof EntityTools.handleUpdateProject>[0]);\n case 'protokoll_add_term':\n return EntityTools.handleAddTerm(args as Parameters<typeof EntityTools.handleAddTerm>[0]);\n case 'protokoll_edit_term':\n return EntityTools.handleEditTerm(args as Parameters<typeof EntityTools.handleEditTerm>[0]);\n case 'protokoll_update_term':\n return EntityTools.handleUpdateTerm(args as Parameters<typeof EntityTools.handleUpdateTerm>[0]);\n case 'protokoll_merge_terms':\n return EntityTools.handleMergeTerms(args as Parameters<typeof EntityTools.handleMergeTerms>[0]);\n case 'protokoll_add_company':\n return EntityTools.handleAddCompany(args as Parameters<typeof EntityTools.handleAddCompany>[0]);\n case 'protokoll_delete_entity':\n return EntityTools.handleDeleteEntity(args as Parameters<typeof EntityTools.handleDeleteEntity>[0]);\n\n // Smart Assistance\n case 'protokoll_suggest_project_metadata':\n return AssistTools.handleSuggestProjectMetadata(args as Parameters<typeof AssistTools.handleSuggestProjectMetadata>[0]);\n case 'protokoll_suggest_term_metadata':\n return AssistTools.handleSuggestTermMetadata(args as Parameters<typeof AssistTools.handleSuggestTermMetadata>[0]);\n\n // Relationship Management\n case 'protokoll_add_relationship':\n return RelationshipTools.handleAddRelationship(args as Parameters<typeof RelationshipTools.handleAddRelationship>[0]);\n case 'protokoll_remove_relationship':\n return RelationshipTools.handleRemoveRelationship(args as Parameters<typeof RelationshipTools.handleRemoveRelationship>[0]);\n case 'protokoll_list_relationships':\n return RelationshipTools.handleListRelationships(args as Parameters<typeof RelationshipTools.handleListRelationships>[0]);\n case 'protokoll_find_related_entities':\n return RelationshipTools.handleFindRelatedEntities(args as Parameters<typeof RelationshipTools.handleFindRelatedEntities>[0]);\n\n // Content Management\n case 'protokoll_add_content':\n return ContentTools.handleAddContent(args as Parameters<typeof ContentTools.handleAddContent>[0]);\n case 'protokoll_remove_content':\n return ContentTools.handleRemoveContent(args as Parameters<typeof ContentTools.handleRemoveContent>[0]);\n case 'protokoll_list_content':\n return ContentTools.handleListContent(args as Parameters<typeof ContentTools.handleListContent>[0]);\n case 'protokoll_get_content':\n return ContentTools.handleGetContent(args as Parameters<typeof ContentTools.handleGetContent>[0]);\n\n // Transcript Operations\n case 'protokoll_read_transcript':\n return TranscriptTools.handleReadTranscript(args as Parameters<typeof TranscriptTools.handleReadTranscript>[0]);\n case 'protokoll_list_transcripts':\n return TranscriptTools.handleListTranscripts(args as Parameters<typeof TranscriptTools.handleListTranscripts>[0]);\n case 'protokoll_edit_transcript':\n return TranscriptTools.handleEditTranscript(args as Parameters<typeof TranscriptTools.handleEditTranscript>[0]);\n case 'protokoll_change_transcript_date':\n return TranscriptTools.handleChangeTranscriptDate(args as Parameters<typeof TranscriptTools.handleChangeTranscriptDate>[0]);\n case 'protokoll_combine_transcripts':\n return TranscriptTools.handleCombineTranscripts(args as Parameters<typeof TranscriptTools.handleCombineTranscripts>[0]);\n case 'protokoll_provide_feedback':\n return TranscriptTools.handleProvideFeedback(args as Parameters<typeof TranscriptTools.handleProvideFeedback>[0]);\n case 'protokoll_update_transcript_content':\n return TranscriptTools.handleUpdateTranscriptContent(args as Parameters<typeof TranscriptTools.handleUpdateTranscriptContent>[0]);\n case 'protokoll_update_transcript_entity_references':\n return TranscriptTools.handleUpdateTranscriptEntityReferences(args as Parameters<typeof TranscriptTools.handleUpdateTranscriptEntityReferences>[0]);\n case 'protokoll_create_note':\n return TranscriptTools.handleCreateNote(args as Parameters<typeof TranscriptTools.handleCreateNote>[0]);\n\n // Lifecycle Status & Tasks\n case 'protokoll_set_status':\n return StatusTools.handleSetStatus(args as Parameters<typeof StatusTools.handleSetStatus>[0]);\n case 'protokoll_create_task':\n return StatusTools.handleCreateTask(args as Parameters<typeof StatusTools.handleCreateTask>[0]);\n case 'protokoll_complete_task':\n return StatusTools.handleCompleteTask(args as Parameters<typeof StatusTools.handleCompleteTask>[0]);\n case 'protokoll_delete_task':\n return StatusTools.handleDeleteTask(args as Parameters<typeof StatusTools.handleDeleteTask>[0]);\n\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n}\n","/**\n * Shared Configuration Discovery\n * \n * Uses CardiganTime to discover protokoll-config.yaml files hierarchically,\n * matching the behavior of protokoll-cli. This module is shared between\n * the stdio server (server.ts) and HTTP server (server-http.ts).\n */\n\nimport * as Cardigantime from '@utilarium/cardigantime';\nimport type { Logger } from '@utilarium/cardigantime';\nimport { resolve, dirname, basename } from 'node:path';\n\nexport const DEFAULT_CONFIG_FILE = 'protokoll-config.yaml';\n\n/**\n * Check if debug mode is enabled via environment or will be via config\n */\nfunction isDebugEnabled(): boolean {\n return process.env.PROTOKOLL_DEBUG === 'true' || process.env.DEBUG === 'true';\n}\n\n/**\n * Create a quiet logger that only outputs when debug is enabled\n * and formats messages in a cleaner way\n */\nfunction createQuietLogger(): Logger {\n const debugEnabled = isDebugEnabled();\n \n const noop = () => { /* intentionally empty */ };\n \n const debugLog = debugEnabled \n ? (message: string, ...args: unknown[]) => {\n // Format the message more cleanly\n // eslint-disable-next-line no-console\n console.error(`[config] ${message}`, ...args);\n }\n : noop;\n \n return {\n debug: noop, // Suppress verbose debug messages\n info: noop, // Suppress info messages during discovery\n warn: (message: string, ...args: unknown[]) => {\n // eslint-disable-next-line no-console\n console.error(`[config:warn] ${message}`, ...args);\n },\n error: (message: string, ...args: unknown[]) => {\n // eslint-disable-next-line no-console\n console.error(`[config:error] ${message}`, ...args);\n },\n verbose: debugLog,\n silly: noop,\n };\n}\n\n/**\n * Parse a CLI argument value from argv\n */\nexport function getArgValue(argv: string[], flag: string): string | undefined {\n const idx = argv.indexOf(flag);\n if (idx === -1) return undefined;\n const value = argv[idx + 1];\n if (!value || value.startsWith('-')) return undefined;\n return value;\n}\n\n/**\n * Read configuration from a directory using CardiganTime\n */\nexport async function readCardigantimeConfigFromDirectory(\n directory: string,\n configFile: string,\n features: Array<'config' | 'hierarchical'>\n): Promise<Record<string, unknown>> {\n const cardigantime = Cardigantime.create({\n defaults: {\n configDirectory: '.',\n configFile,\n isRequired: false,\n // Tell CardiganTime to resolve these path fields relative to the config file's directory\n // Note: contextDirectories must be in BOTH pathFields AND resolvePathArray - \n // pathFields determines which fields are processed, resolvePathArray determines\n // if array elements should be resolved individually\n pathResolution: {\n pathFields: ['inputDirectory', 'outputDirectory', 'processedDirectory', 'contextDirectories'],\n resolvePathArray: ['contextDirectories'],\n },\n },\n configShape: {},\n features,\n logger: createQuietLogger(),\n });\n\n const previousCwd = process.cwd();\n try {\n process.chdir(directory);\n return await cardigantime.read({});\n } finally {\n process.chdir(previousCwd);\n }\n}\n\n/**\n * Load configuration using CardiganTime from the workspace root\n * This respects environment variables and hierarchical config files\n */\nexport async function loadCardigantimeConfig(): Promise<Record<string, unknown>> {\n const workspaceRoot = process.env.WORKSPACE_ROOT || process.cwd();\n return await readCardigantimeConfigFromDirectory(workspaceRoot, DEFAULT_CONFIG_FILE, ['config', 'hierarchical']);\n}\n\n/**\n * Initialize working directory and WORKSPACE_ROOT from CLI args and config discovery.\n * \n * Supports:\n * - `--cwd <dir>` to change working directory\n * - `-c <path>` or `--config <path>` to specify config file (matching protokoll-cli)\n * - `PROTOKOLL_CONFIG` environment variable\n * - Hierarchical discovery of protokoll-config.yaml up the directory tree\n */\nexport async function initializeWorkingDirectoryFromArgsAndConfig(): Promise<void> {\n const argv = process.argv.slice(2);\n const cwdArg = getArgValue(argv, '--cwd');\n // Support both -c and --config (matching protokoll-cli)\n const configArg = getArgValue(argv, '-c') || getArgValue(argv, '--config') || process.env.PROTOKOLL_CONFIG;\n\n if (cwdArg) {\n process.chdir(resolve(cwdArg));\n }\n\n // Use CardiganTime (like protokoll-cli) to locate protokoll-config.yaml up the tree.\n // If an explicit config file path is provided, use only that file.\n if (configArg) {\n const configPath = resolve(configArg);\n const configDir = dirname(configPath);\n const configFile = basename(configPath);\n\n // Expose for downstream code; also makes it easier to debug.\n process.env.PROTOKOLL_CONFIG = configPath;\n process.env.WORKSPACE_ROOT = configDir;\n\n // Ensure it's readable early (and preserves CardiganTime semantics).\n await readCardigantimeConfigFromDirectory(configDir, configFile, ['config']);\n return;\n }\n\n const discoveryStart = process.env.WORKSPACE_ROOT || process.cwd();\n const config = await readCardigantimeConfigFromDirectory(\n discoveryStart,\n DEFAULT_CONFIG_FILE,\n ['config', 'hierarchical']\n );\n\n const resolvedConfigDirs = (config as any).resolvedConfigDirs;\n if (Array.isArray(resolvedConfigDirs) && resolvedConfigDirs.length > 0) {\n process.env.WORKSPACE_ROOT = resolvedConfigDirs[0];\n } else {\n process.env.WORKSPACE_ROOT = discoveryStart;\n }\n}\n"],"names":["createContext","Context.create","DEFAULT_CONFIG_FILE","level","logger","transcriptExists","ensurePklExtension","Storage","result","resolveTranscriptPath","ServerConfig.getOutputDirectory","__filename","__dirname","prompts","sanitizedSearchedFrom","relationships","TranscriptUtils","readTranscriptFromStorage","listTranscriptsFromStorage","pklPath","transcript","ServerConfig.getServerMode","ServerConfig.getServerConfig","getEntityByType","parseEntityUri","outputDirectory","relativePath","SystemTools.getVersionTool","SystemTools.getInfoTool","DiscoveryTools.discoverConfigTool","DiscoveryTools.suggestProjectTool","AudioTools.processAudioTool","AudioTools.batchProcessTool","ContextTools.contextStatusTool","ContextTools.listProjectsTool","ContextTools.listPeopleTool","ContextTools.listTermsTool","ContextTools.listCompaniesTool","ContextTools.searchContextTool","ContextTools.getEntityTool","EntityTools.addPersonTool","EntityTools.editPersonTool","EntityTools.addProjectTool","EntityTools.editProjectTool","EntityTools.updateProjectTool","EntityTools.addTermTool","EntityTools.editTermTool","EntityTools.updateTermTool","EntityTools.mergeTermsTool","EntityTools.addCompanyTool","EntityTools.deleteEntityTool","RelationshipTools.addRelationshipTool","RelationshipTools.removeRelationshipTool","RelationshipTools.listRelationshipsTool","RelationshipTools.findRelatedEntitiesTool","ContentTools.addContentTool","ContentTools.removeContentTool","ContentTools.listContentTool","ContentTools.getContentTool","AssistTools.suggestProjectMetadataTool","AssistTools.suggestTermMetadataTool","TranscriptTools.readTranscriptTool","TranscriptTools.listTranscriptsTool","TranscriptTools.editTranscriptTool","TranscriptTools.changeTranscriptDateTool","TranscriptTools.combineTranscriptsTool","TranscriptTools.provideFeedbackTool","TranscriptTools.updateTranscriptContentTool","TranscriptTools.updateTranscriptEntityReferencesTool","TranscriptTools.createNoteTool","StatusTools.setStatusTool","StatusTools.createTaskTool","StatusTools.completeTaskTool","StatusTools.deleteTaskTool","SystemTools.handleGetVersion","SystemTools.handleGetInfo","DiscoveryTools.handleDiscoverConfig","DiscoveryTools.handleSuggestProject","AudioTools.handleProcessAudio","AudioTools.handleBatchProcess","ContextTools.handleContextStatus","ContextTools.handleListProjects","ContextTools.handleListPeople","ContextTools.handleListTerms","ContextTools.handleListCompanies","ContextTools.handleSearchContext","ContextTools.handleGetEntity","EntityTools.handleAddPerson","EntityTools.handleEditPerson","EntityTools.handleAddProject","EntityTools.handleEditProject","EntityTools.handleUpdateProject","EntityTools.handleAddTerm","EntityTools.handleEditTerm","EntityTools.handleUpdateTerm","EntityTools.handleMergeTerms","EntityTools.handleAddCompany","EntityTools.handleDeleteEntity","AssistTools.handleSuggestProjectMetadata","AssistTools.handleSuggestTermMetadata","RelationshipTools.handleAddRelationship","RelationshipTools.handleRemoveRelationship","RelationshipTools.handleListRelationships","RelationshipTools.handleFindRelatedEntities","ContentTools.handleAddContent","ContentTools.handleRemoveContent","ContentTools.handleListContent","ContentTools.handleGetContent","TranscriptTools.handleReadTranscript","TranscriptTools.handleListTranscripts","TranscriptTools.handleEditTranscript","TranscriptTools.handleChangeTranscriptDate","TranscriptTools.handleCombineTranscripts","TranscriptTools.handleProvideFeedback","TranscriptTools.handleUpdateTranscriptContent","TranscriptTools.handleUpdateTranscriptEntityReferences","TranscriptTools.handleCreateNote","StatusTools.handleSetStatus","StatusTools.handleCreateTask","StatusTools.handleCompleteTask","StatusTools.handleDeleteTask"],"mappings":";;;;;;;;;;;;;;AAyBA,MAAM,MAAA,GAAS,WAAA;AAKR,SAAS,SAAS,GAAA,EAAgC;AACrD,EAAA,IAAI,CAAC,GAAA,CAAI,UAAA,CAAW,CAAA,EAAG,MAAM,KAAK,CAAA,EAAG;AACjC,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,oBAAA,EAAuB,GAAG,CAAA,uBAAA,CAAyB,CAAA;AAAA,EACvE;AAEA,EAAA,MAAM,gBAAgB,GAAA,CAAI,SAAA,CAAU,CAAA,EAAG,MAAM,MAAM,MAAM,CAAA;AACzD,EAAA,MAAM,CAAC,QAAA,EAAU,SAAS,CAAA,GAAI,aAAA,CAAc,MAAM,GAAG,CAAA;AACrD,EAAA,MAAM,QAAA,GAAW,SAAS,KAAA,CAAM,GAAG,EAAE,MAAA,CAAO,CAAA,CAAA,KAAK,CAAA,CAAE,MAAA,GAAS,CAAC,CAAA;AAE7D,EAAA,IAAI,QAAA,CAAS,WAAW,CAAA,EAAG;AACvB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,aAAA,EAAgB,GAAG,CAAA,6BAAA,CAA+B,CAAA;AAAA,EACtE;AAEA,EAAA,MAAM,YAAA,GAAe,SAAS,CAAC,CAAA;AAC/B,EAAA,MAAM,MAAA,G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