#!/usr/bin/env node
// index.ts — Planu SDD MCP Server entry point.
// Creates the MCP server, registers tools & resources, and starts stdio transport.
// CLI detection — intercept known commands before MCP server setup (SPEC-124)
const KNOWN_COMMANDS = [
    'init',
    'create',
    'list',
    'status',
    'estimate',
    'validate',
    'dashboard',
    'audit',
    'serve',
    'handoff',
    'search',
    'install',
    'publish',
    'watch',
    'help',
    'version',
];
const firstArg = process.argv[2];
if (firstArg && KNOWN_COMMANDS.includes(firstArg)) {
    const { route } = await import('./cli/router.js');
    await route(process.argv.slice(2));
    process.exit(0);
}
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { selectTransport } from './transports/transport-factory.js';
import { registerResources } from './resources/registry.js';
import { registerSpecTools } from './tools/register-spec-tools.js';
import { registerPlatformTools } from './tools/register-platform-tools.js';
import { registerLearningTools } from './tools/register-learning-tools.js';
import { registerSecurityTools } from './tools/register-security-tools.js';
import { registerMigrationTools } from './tools/register-migration-tools.js';
import { registerGovernanceTools } from './tools/register-governance-tools.js';
import { registerEventTools } from './tools/register-event-tools.js';
import { registerContextTools } from './tools/register-context-tools.js';
import { registerFacilitatorTools } from './tools/register-facilitator-tools.js';
import { registerScopeTools } from './tools/register-scope-tools.js';
import { registerReadinessTools } from './tools/register-readiness-tools.js';
import { registerMemoryTools } from './tools/register-memory-tools.js';
import { registerStackTools } from './tools/register-stack-tools.js';
import { registerCheckConfigHealthTool } from './tools/check-config-health.js';
import { registerAgentTools } from './tools/register-agent-tools.js';
import { registerWorkflowTools } from './tools/register-workflow-tools.js';
import { registerLicenseTools } from './tools/register-license-tools.js';
import { registerUsageTools } from './tools/register-usage-tools.js';
import { registerChangelogTools } from './tools/register-changelog-tools.js';
import { registerCoverageTools } from './tools/register-coverage-tools.js';
import { registerDashboardTools } from './tools/register-dashboard-tools.js';
import { registerAiCostTools } from './tools/register-ai-cost-tools.js';
import { registerWebhookTools } from './tools/register-webhook-tools.js';
import { registerCITools } from './tools/register-ci-tools.js';
import { registerHooksTools } from './tools/register-hooks-tools.js';
import { registerTemplateTools } from './tools/register-template-tools.js';
import { registerRegistryTools } from './tools/register-registry-tools.js';
import { registerToolGroupTools } from './tools/register-tool-groups.js';
import { registerModelTools } from './tools/register-model-tools.js';
import { registerSearchTools } from './tools/register-search-tools.js';
import { registerTransformTools } from './tools/register-transform-tools.js';
import { registerSessionTools } from './tools/register-session-tools.js';
import { registerIdeTools } from './tools/register-ide-tools.js';
import { registerDeleteTools } from './tools/register-delete-tools.js';
import { registerRuntimeSecurityTools } from './tools/register-runtime-security-tools.js';
import { registerWorkerTools } from './tools/register-worker-tools.js';
import { registerOrchestratorTools } from './tools/register-orchestrator-tools.js';
import { registerTokenTools } from './tools/register-token-tools.js';
import { registerLLMProviderTools } from './tools/register-llm-provider-tools.js';
import { registerPluginTools } from './tools/register-plugin-tools.js';
import { registerGitHubTools } from './tools/register-github-tools.js';
import { registerTeamTools } from './tools/register-team-tools.js';
import { registerWorkspaceTools } from './tools/register-workspace-tools.js';
import { registerExportTools } from './tools/register-export-tools.js';
import { registerLivingSpecTools } from './tools/register-living-spec-tools.js';
import { registerLivingSpecAdvancedTools } from './tools/register-living-spec-advanced-tools.js';
import { registerSpecRegistryTools } from './tools/register-spec-registry-tools.js';
import { PLANU_VERSION } from './config/version.js';
import { handleActivateLicense } from './tools/activate-license.js';
import { GroupManager } from './engine/tool-groups/group-manager.js';
import { setGroupManager } from './tools/tool-group-handler.js';
import { withToolTracking, getRegisteredTools } from './tools/tool-registry.js';
import { registerPrompts } from './prompts/index.js';
// ---------------------------------------------------------------------------
// Server setup
// ---------------------------------------------------------------------------
const SERVER_INSTRUCTIONS = [
    'You are Planu — a friendly assistant that helps people plan and organize software projects.',
    '',
    'CRITICAL UX RULES — follow these in EVERY interaction:',
    '',
    '1. ALWAYS explain technical terms in plain language. Your users may not be developers.',
    '   - "spec" → "a detailed plan for a feature — like a blueprint before building a house"',
    '   - "draft" → "a first version that is not finished yet — you can still change it"',
    '   - "review" → "the plan is ready for someone to check before approving it"',
    '   - "approved" → "the plan has been approved and is ready to be built"',
    '   - "implementing" → "someone is actively building this feature right now"',
    '   - "done" → "the feature is finished and matches what the plan described"',
    '   - "drift" → "when the code no longer matches what the plan says — like building a house that does not match the blueprint"',
    '   - "constitution" → "a set of rules your project always follows — like ground rules for quality"',
    '   - "ADR" → "a record of an important technical decision — why you chose X over Y"',
    '   - "schema" → "the structure of your database — what tables and fields store your data"',
    '   - "UI contract" → "a description of how your screens work — what each component shows and does"',
    '   - "acceptance criteria" → "a checklist of conditions that must be true for a feature to be considered done"',
    '   - "coverage" → "how much of the plan has actually been built — shown as a percentage"',
    '   - "audit" → "a health check of your code — finds problems and gives you a score"',
    '   - "PII" → "personal data like names, emails, or phone numbers that need special protection"',
    '   - "migration" → "moving your project from one technology to another"',
    '   - "stack" → "the set of technologies your project uses (language, framework, database, etc.)"',
    '   - "orchestration" → "coordinating multiple AI agents to work on different parts of your project at the same time"',
    '   - "handoff" → "a package of instructions so an AI agent knows exactly what to build"',
    '   - "readiness" → "whether a plan has enough detail to start building"',
    '   - "reconcile" → "updating a plan to match changes that happened during building"',
    '',
    '2. Be conversational and warm. Guide the user step by step.',
    '3. After every tool result, summarize what happened in simple terms.',
    '4. When presenting lists or results, use plain language headers — not jargon.',
    '5. If the user seems confused, offer to explain further. Never assume knowledge.',
    "6. Adapt your language to the user's locale (English, Spanish, or Portuguese).",
    '',
    'GIT WORKFLOW — automatic branch management:',
    '- Planu automatically detects your git workflow (gitflow, github-flow, or trunk-based) by checking which branches exist.',
    '- When creating a spec, Planu auto-creates a feature branch from the correct base branch (develop for gitflow, main for github-flow).',
    '- The base branch is fetched and updated before creating the feature branch — no manual git pull needed.',
    '- If there are uncommitted changes, Planu warns instead of risking data loss.',
    '- Use manage_git with action "auto-setup" to manually trigger branch setup for an existing spec.',
    '- Available git actions: create-branch, generate-pr, link-commits, generate-changelog, setup-hooks, check-branch, status, sync-branch, check-gitflow, resolve-conflict, breaking-check, release, hotfix, promote, auto-setup.',
    '- Branch naming convention: feat/SPEC-XXX-short-name for features, fix/SPEC-XXX-short-name for fixes.',
    '- Explain why: "Working in a separate branch keeps your main code safe while you build this feature. When it is ready, you merge it back."',
    '',
    'SPEC APPROVAL FLOW — MANDATORY after every create_spec:',
    '- After creating a spec, ALWAYS present a clear summary to the user and ask: "Do you approve this spec, or do you have changes/observations?"',
    '- If the user APPROVES: call update_status to move the spec from "draft" to "review", then to "approved".',
    '- If the user has OBSERVATIONS or wants changes: call update_status with status="draft" and include their feedback in the reviewNotes field. Then revise the spec and ask again.',
    '- NEVER start implementing a spec without explicit user approval. The spec is a contract — both sides must agree.',
    '- When creating multiple specs at once, present ALL specs for review and let the user approve/reject each one individually.',
    '- The reviewNotes field stores a history of all feedback — implementers can see what was requested and why.',
].join('\n');
function createMcpServer() {
    const s = withToolTracking(new McpServer({ name: 'planu', version: PLANU_VERSION }, { instructions: SERVER_INSTRUCTIONS }));
    registerResources(s);
    registerSpecTools(s);
    registerPlatformTools(s);
    registerLearningTools(s);
    registerSecurityTools(s);
    registerMigrationTools(s);
    registerGovernanceTools(s);
    registerEventTools(s);
    registerContextTools(s);
    registerFacilitatorTools(s);
    registerScopeTools(s);
    registerReadinessTools(s);
    registerMemoryTools(s);
    registerStackTools(s);
    registerCheckConfigHealthTool(s);
    registerAgentTools(s);
    registerWorkflowTools(s);
    registerLicenseTools(s);
    registerUsageTools(s);
    registerChangelogTools(s);
    registerCoverageTools(s);
    registerDashboardTools(s);
    registerAiCostTools(s);
    registerWebhookTools(s);
    registerCITools(s);
    registerHooksTools(s);
    registerTemplateTools(s);
    registerRegistryTools(s);
    registerToolGroupTools(s);
    registerModelTools(s);
    registerSearchTools(s);
    registerTransformTools(s);
    registerSessionTools(s);
    registerIdeTools(s);
    registerDeleteTools(s);
    registerRuntimeSecurityTools(s);
    registerWorkerTools(s);
    registerOrchestratorTools(s);
    registerTokenTools(s);
    registerLLMProviderTools(s);
    registerPluginTools(s);
    registerGitHubTools(s);
    registerTeamTools(s);
    registerWorkspaceTools(s);
    registerExportTools(s);
    registerLivingSpecTools(s);
    registerLivingSpecAdvancedTools(s);
    registerSpecRegistryTools(s);
    registerPrompts(s);
    return s;
}
// Primary server instance (used for stdio and group manager init)
const server = createMcpServer();
// ---------------------------------------------------------------------------
// Start server
// ---------------------------------------------------------------------------
async function main() {
    // Auto-activate license from environment variable if present
    const envKey = process.env.SDD_LICENSE_KEY;
    if (envKey) {
        await handleActivateLicense({ licenseKey: envKey }).catch(() => {
            // Silent failure: env-based activation is best-effort
        });
    }
    // SPEC-074: Initialize tool group manager after all tools are registered.
    // Uses local tool registry instead of SDK-internal _registeredTools.
    const toolMap = getRegisteredTools();
    const groupManager = new GroupManager(toolMap, () => {
        server.sendToolListChanged();
    });
    await groupManager.init();
    setGroupManager(groupManager);
    await selectTransport(server, process.argv.slice(2), createMcpServer);
}
process.on('uncaughtException', (error) => {
    /* v8 ignore next 1 */
    console.error('[Planu] Uncaught exception:', error);
});
process.on('unhandledRejection', (reason) => {
    /* v8 ignore next 1 */
    console.error('[Planu] Unhandled rejection:', reason);
});
main().catch((error) => {
    console.error('Planu MCP Server failed to start:', error);
    process.exit(1);
});
//# sourceMappingURL=index.js.map