#!/bin/bash
# Hook: route prompt/tool signals to the smallest useful installed skill set.
# Used from UserPromptSubmit and PreToolUse so end users do not need to name skills.

INPUT=$(cat)
PROJECT_ROOT="${CLAUDE_PROJECT_DIR:-$PWD}"

# Worktree early-exit: when the tool call is scoped to a disposable .worktrees/task-*
# tree, there is nothing to route — exit before spawning the router. Reads
# tool_input.file_path / tool_input.path / tool_input.command (never tool_input.pattern).
# Skips only when ".worktrees/" starts a path component. Fails OPEN: any parse
# problem, missing field, or node error falls through to the normal hook path below.
# Pure-bash pre-check first: the node guard can only ever match when the literal
# ".worktrees/" substring is present, so this case is a strict superset and avoids
# paying the node spawn cost on the far more common non-worktree call.
case "$INPUT" in
  *".worktrees/"*)
    if printf '%s' "$INPUT" | node -e '
const chunks = [];
process.stdin.on("data", (c) => chunks.push(c));
process.stdin.on("end", () => {
  try {
    const payload = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
    const toolInput = (payload && typeof payload === "object" && payload.tool_input
      && typeof payload.tool_input === "object") ? payload.tool_input : {};
    const candidates = [toolInput.file_path, toolInput.path, toolInput.command];
    const QMARKS = String.fromCharCode(34, 39, 96);
    const worktreeComponent = new RegExp("(^|[\\/\\s=" + QMARKS + "])\\.worktrees/");
    process.exit(candidates.some((v) => typeof v === "string" && worktreeComponent.test(v)) ? 0 : 1);
  } catch {
    process.exit(1);
  }
});
' >/dev/null 2>&1; then
      exit 0
    fi
    ;;
esac

STATE_FILE="$PROJECT_ROOT/.claude/ukit/skill-router-state.json"
HOOK_DIR="$(cd "$(dirname "$0")" && pwd)"
THRESHOLD_SCRIPT="$HOOK_DIR/../ukit/runtime/compact-threshold.mjs"

INPUT="$INPUT" PROJECT_ROOT="$PROJECT_ROOT" STATE_FILE="$STATE_FILE" HOOK_DIR="$HOOK_DIR" node <<'NODE'
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { pathToFileURL } = require('url');

(async () => {
  const STOPWORDS = new Set([
    'the', 'a', 'an', 'and', 'or', 'to', 'for', 'of', 'with', 'in', 'on', 'is', 'are',
    'this', 'that', 'it', 'as', 'by', 'be', 'use', 'using', 'implement', 'fix', 'task',
    'cần', 'và', 'là', 'cho', 'một', 'những', 'dùng',
  ]);

  function readJson(filePath, fallback = null) {
    try {
      return JSON.parse(fs.readFileSync(filePath, 'utf8'));
    } catch {
      return fallback;
    }
  }

  function ensureDir(filePath) {
    fs.mkdirSync(path.dirname(filePath), { recursive: true });
  }

  function defaultRuntimeConfig() {
    return {
      memory: {
        enabled: true,
        progressiveRetrieval: true,
      },
    };
  }

  function deepMerge(base, override) {
    if (!override || typeof override !== 'object' || Array.isArray(override)) {
      return override === undefined ? base : override;
    }

    const merged = { ...base };
    for (const [key, value] of Object.entries(override)) {
      if (
        value
        && typeof value === 'object'
        && !Array.isArray(value)
        && merged[key]
        && typeof merged[key] === 'object'
        && !Array.isArray(merged[key])
      ) {
        merged[key] = deepMerge(merged[key], value);
        continue;
      }

      merged[key] = value;
    }

    return merged;
  }

  function buildRuntimePaths(projectRoot) {
    const runtimeRoot = path.join(projectRoot, '.ukit');
    const storageRoot = path.join(runtimeRoot, 'storage');
    const memoryRoot = path.join(storageRoot, 'memory');

    return {
      configPath: path.join(storageRoot, 'config.json'),
      userMemoryPath: path.join(memoryRoot, 'user.json'),
      projectsDir: path.join(memoryRoot, 'projects'),
      sessionsDir: path.join(memoryRoot, 'sessions'),
    };
  }

  function loadRuntimeConfig(projectRoot) {
    const runtimePaths = buildRuntimePaths(projectRoot);
    const raw = readJson(runtimePaths.configPath, {});
    return deepMerge(defaultRuntimeConfig(), raw && typeof raw === 'object' ? raw : {});
  }

  function readIndexGeneratedAtMs(projectRoot) {
    const artifact = readJson(path.join(projectRoot, '.cache', 'index', 'files.json'), null);
    const generatedAtRaw = String(artifact?.generatedAt || '').trim();
    if (!generatedAtRaw) {
      return null;
    }

    const generatedAtMs = Date.parse(generatedAtRaw);
    return Number.isNaN(generatedAtMs) ? null : generatedAtMs;
  }

  async function loadRouteCatalog(projectRoot) {
    const routeCatalogPath = path.join(projectRoot, '.claude', 'ukit', 'index', 'route-catalog.mjs');
    if (!fs.existsSync(routeCatalogPath)) {
      return [];
    }

    try {
      const mod = await import(pathToFileURL(routeCatalogPath).href);
      return Array.isArray(mod.ROUTE_CATALOG) ? mod.ROUTE_CATALOG : [];
    } catch {
      return [];
    }
  }

  async function loadLanguageTools(projectRoot) {
    const candidatePaths = [
      path.join(projectRoot, '.claude', 'ukit', 'index', 'lib', 'index-core.mjs'),
      process.env.HOOK_DIR
        ? path.resolve(process.env.HOOK_DIR, '..', 'ukit', 'index', 'lib', 'index-core.mjs')
        : null,
    ].filter(Boolean);

    for (const indexCorePath of candidatePaths) {
      if (!fs.existsSync(indexCorePath)) {
        continue;
      }

      try {
        const mod = await import(pathToFileURL(indexCorePath).href);
        if (typeof mod.buildRouteSignalText === 'function') {
          return {
            buildRouteSignalText: mod.buildRouteSignalText,
          };
        }
      } catch {}
    }

    return {
      buildRouteSignalText: (...values) => values
        .map((value) => String(value || '').trim())
        .filter(Boolean)
        .join('\n')
        .toLowerCase(),
    };
  }

  function existsSkill(projectRoot, relativePath) {
    return fs.existsSync(path.join(projectRoot, relativePath));
  }

  function scoreSkillRouteEntry(entry, routeSignals = {}) {
    let score = 0;
    const reasons = [];

    for (const signal of entry.signals) {
      const { directText, normalizedText } = getSignalTexts(signal.type, routeSignals);
      signal.regex.lastIndex = 0;
      const directMatch = signal.regex.test(directText);
      signal.regex.lastIndex = 0;
      const normalizedMatch = !directMatch && Boolean(normalizedText) && signal.regex.test(normalizedText);
      if (!directMatch && !normalizedMatch) continue;
      score += directMatch
        ? signal.score
        : Math.max(1, signal.score - 1);
      reasons.push(signal.type);
    }

    score += deriveSkillPriorityBoost(entry.id, routeSignals);

    return {
      id: entry.id,
      path: entry.path,
      contextMode: entry.contextMode || 'indexed',
      score,
      order: entry.order,
      reasons: [...new Set(reasons)],
    };
  }

  function shouldKeepRouteEntryForIntent(entry, intentMode) {
    if (entry.id === 'next-step' && ['scoped-advice', 'docs-specific'].includes(intentMode)) {
      return false;
    }

    if (entry.id === 'update-status' && intentMode === 'docs-specific') {
      return false;
    }

    if (entry.id === 'docs-quality' && ['open-ended-status', 'status-update'].includes(intentMode)) {
      return false;
    }

    if (entry.id === 'code-review' && intentMode === 'implement-specific') {
      return false;
    }

    return true;
  }

  function deriveSkillPriorityBoost(skillId, routeSignals = {}) {
    const combinedPromptSignals = [
      routeSignals.promptRawText || '',
      routeSignals.promptNormalizedText || '',
      routeSignals.commandRawText || '',
      routeSignals.commandNormalizedText || '',
    ].join('\n');
    const rawPromptSignals = [
      routeSignals.promptRawText || '',
      routeSignals.commandRawText || '',
    ].join('\n');

    if (
      skillId === 'testing-quality'
      && /\b(test|tests|spec|coverage|mock|fixture|assert|vitest|jest|playwright)\b/.test(combinedPromptSignals)
    ) {
      return 1;
    }

    if (
      skillId === 'code-review'
      && /\b(implement|build|create|add|ship|deliver|refactor|integrate|integration|scaffold|feature|update|change|modify|inject|apply)\b/.test(rawPromptSignals)
      && !/\b(review|audit|diff|pr feedback|code review|kiem tra|soat)\b/.test(rawPromptSignals)
    ) {
      return -4;
    }

    return 0;
  }

  function getSignalTexts(signalType, routeSignals = {}) {
    if (signalType === 'command') {
      return {
        directText: routeSignals.commandRawText || '',
        normalizedText: routeSignals.commandNormalizedText || '',
      };
    }

    if (signalType === 'file') {
      return {
        directText: routeSignals.fileText || '',
        normalizedText: '',
      };
    }

    return {
      directText: routeSignals.promptRawText || '',
      normalizedText: routeSignals.promptNormalizedText || '',
    };
  }

  function deriveIntentMode({ promptText = '', commandText = '', targetFile = null } = {}) {
    const lower = buildRouteSignalText(promptText, commandText);
    const raw = `${promptText || ''}\n${commandText || ''}`.toLowerCase();
    const taskQueueNext = hasTaskQueueNextSignal(lower, raw);
    const docsSpecific = hasDocsSpecificTaskSignal(lower, raw, targetFile, { taskQueueNext });
    const statusUpdate = hasStatusUpdateSignal(lower, raw);
    const openEndedStatus = hasOpenEndedStatusSignal(lower, raw) || taskQueueNext;
    const concreteTask = hasConcreteTaskSignal(lower, raw, targetFile, { taskQueueNext });

    if (docsSpecific) {
      return 'docs-specific';
    }

    if (statusUpdate) {
      return 'status-update';
    }

    if (concreteTask && openEndedStatus) {
      return 'scoped-advice';
    }

    if (openEndedStatus) {
      return 'open-ended-status';
    }

    if (concreteTask) {
      if (/\b(bug|debug|error|crash|broken|failing|stack trace|triage|fix|timeout)\b/.test(lower)) {
        return 'debug-specific';
      }
      if (/\b(review|audit|diff|pr feedback|code review|kiem tra|soat)\b/.test(raw)) {
        return 'review-specific';
      }
      if (/\b(implement|build|create|add|ship|deliver|refactor|integrate|integration|scaffold|feature|update|change|modify|inject|apply)\b/.test(raw)) {
        return 'implement-specific';
      }
    }

    return null;
  }

  function hasStatusUpdateSignal(lower, raw) {
    return /\b(update|refresh|write|sync|record|capture|summarize|summarise).{0,64}\b(status\.md|project status|current state|next candidates|session state)\b/.test(lower)
      || /\b(status\.md|project status).{0,64}\b(update|refresh|write|sync|record|capture|summarize|summarise)\b/.test(lower)
      || /\b(wrap up|handoff|end this session|ending this session|session summary|before final)\b/.test(lower)
      || /\b(cap nhat|ghi lai|tong ket|chot session|ban giao).{0,64}\b(status|trang thai|viec tiep theo)\b/.test(lower)
      || /\b(cập nhật|ghi lại|tổng kết|chốt session|bàn giao).{0,64}\b(status|trạng thái|việc tiếp theo)\b/.test(raw);
  }

  function hasOpenEndedStatusSignal(lower, raw) {
    return /\b(what next|what is next|what's next|next step|next steps|project status|current status|where are we|continue|continue from last session|roadmap|status\.md|task queue|tasks\.md|next queued task|pick next task|work from tasks)\b/.test(lower)
      || /\b(lam gi tiep|buoc tiep theo|tiep theo lam gi|lam tiep|dang o dau|trang thai project|tinh trang project|task tiep theo|viec tiep theo trong tasks)\b/.test(lower)
      || /\b(làm gì tiếp|bước tiếp theo|tiếp theo làm gì|làm tiếp|đang ở đâu|trạng thái project|tình trạng project|task tiếp theo|việc tiếp theo trong tasks)\b/.test(raw);
  }

  function hasTaskQueueNextSignal(lower, raw) {
    return /\b(task queue|tasks\.md|next queued task|pick next task|work from tasks|next task from tasks|ready for ai)\b/.test(lower)
      || /\b(task tiếp theo|việc tiếp theo trong tasks|làm task trong tasks|lấy task tiếp theo)\b/.test(raw);
  }

  function hasConcreteTaskSignal(lower, raw, targetFile, { taskQueueNext = false } = {}) {
    if (targetFile && !isStatusFileTarget(targetFile) && !(taskQueueNext && isTasksFileTarget(targetFile))) {
      return true;
    }

    return /\b(bug|debug|error|crash|broken|failing|stack trace|triage|fix|implement|build|create|add|ship|deliver|refactor|integrate|integration|scaffold|feature|update|change|modify|inject|apply|review|audit|diff|pr feedback|code review|auth|login|api|endpoint|test|spec)\b/.test(lower)
      || /\b(sửa|fix|lỗi|bug|debug|implement|cài|thêm|review|kiểm tra|soát|đăng nhập)\b/.test(raw);
  }

  function hasDocsSpecificTaskSignal(lower, raw, targetFile, { taskQueueNext = false } = {}) {
    if (!targetFile || !isDocsTarget(targetFile)) {
      return /\b(clean tasks|cleanup tasks|prune tasks|dedupe tasks|clear completed tasks|dọn tasks|dọn task)\b/.test(lower)
        || /\b(dọn tasks|dọn task|dọn danh sách task|xóa task đã xong)\b/.test(raw);
    }

    if (taskQueueNext && isTasksFileTarget(targetFile) && !/\b(clean|cleanup|prune|dedupe|edit|template|wording|format|structure)\b/.test(lower)) {
      return false;
    }

    const targetName = path.posix.basename(String(targetFile || '').replaceAll('\\', '/')).toLowerCase();
    const explicitStatusUpdate = hasExplicitStatusUpdateSignal(lower, raw);

    if (!isStatusFileTarget(targetFile)) {
      if (explicitStatusUpdate && !mentionsTargetDoc(lower, targetName)) {
        return false;
      }

      return mentionsTargetDoc(lower, targetName)
        || /\b(edit|write|improve|document|docs?|readme|changelog|worklog|memory|code map|template|wording|copy|grammar|format|structure|heading|section|handoff notes?)\b/.test(lower)
        || /\b(câu chữ|chỉnh|sửa chữ|ngữ pháp|định dạng|cấu trúc|tài liệu|ghi chú bàn giao)\b/.test(raw);
    }

    return /\b(template|wording|edit|copy|grammar|format|structure|heading|section|docs?)\b/.test(lower)
      || /\b(mẫu|câu chữ|chỉnh|sửa chữ|ngữ pháp|định dạng|cấu trúc|tài liệu)\b/.test(raw);
  }

  function hasExplicitStatusUpdateSignal(lower, raw) {
    return /\b(update|refresh|write|sync|record|capture|summarize|summarise).{0,64}\b(status\.md|project status|current state|next candidates|session state)\b/.test(lower)
      || /\b(status\.md|project status).{0,64}\b(update|refresh|write|sync|record|capture|summarize|summarise)\b/.test(lower)
      || /\b(cap nhat|ghi lai|tong ket|chot session|ban giao).{0,64}\b(status|trang thai|viec tiep theo)\b/.test(lower)
      || /\b(cập nhật|ghi lại|tổng kết|chốt session|bàn giao).{0,64}\b(status|trạng thái|việc tiếp theo)\b/.test(raw);
  }

  function mentionsTargetDoc(lower, targetName) {
    if (!targetName) {
      return false;
    }

    const escaped = targetName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const withoutExt = escaped.replace(/\\\.md$/i, '');
    return new RegExp(`\\b(?:${escaped}|${withoutExt})\\b`, 'i').test(lower);
  }

  function isStatusFileTarget(targetFile) {
    return /(?:^|\/)docs\/STATUS\.md$|(?:^|\/)STATUS\.md$/i.test(String(targetFile || ''));
  }

  function isTasksFileTarget(targetFile) {
    return /(?:^|\/)docs\/TASKS\.md$|(?:^|\/)TASKS\.md$/i.test(String(targetFile || ''));
  }

  function isDocsTarget(targetFile) {
    const normalized = String(targetFile || '').replaceAll('\\', '/');
    return /(?:^|\/)docs\/.+\.md$|(?:^|\/)(?:README|CHANGELOG|AGENTS|CLAUDE|STATUS)\.md$/i.test(normalized);
  }

  function shouldUseIndexedContext({ activeSkills = [], targetFile = null } = {}) {
    if (activeSkills.length === 0) {
      return Boolean(targetFile);
    }

    const primarySkill = activeSkills[0] || null;
    const primaryIsStandalone = primarySkill?.contextMode === 'standalone';
    if (!primaryIsStandalone) {
      return true;
    }

    if (isStandaloneNonIndexedTarget(primarySkill, targetFile)) {
      return false;
    }

    if (activeSkills.some((skill) => skill?.contextMode !== 'standalone')) {
      return true;
    }

    return isCodeIndexedTarget(targetFile);
  }

  function isStandaloneNonIndexedTarget(primarySkill, targetFile) {
    if (typeof targetFile !== 'string' || !targetFile.trim()) {
      return false;
    }

    const normalized = targetFile.replaceAll('\\', '/');
    if (primarySkill?.id === 'docker-packaging') {
      return /(?:^|\/)(?:Dockerfile|docker-compose(?:\.ya?ml)?|compose\.ya?ml|\.dockerignore)$/i.test(normalized);
    }

    return false;
  }

  function isCodeIndexedTarget(filePath) {
    if (typeof filePath !== 'string' || !filePath.trim()) {
      return false;
    }

    const normalized = filePath.replaceAll('\\', '/');
    if (/\.(?:[cm]?js|jsx|tsx?|vue|py|rb|go|rs|java|kt|swift|php|cs|c|cc|cpp|cxx|h|hpp|m|mm|scala|sh|bash|zsh|sql|psql|css|scss|sass|less|html|xml|json|ya?ml|toml)$/i.test(normalized)) {
      return true;
    }

    return /(?:^|\/)(?:src|test|tests|app|lib|components|pages|screens|layouts|composables|api|routes?|controllers?|services?|db|database|migrations?|prisma|SQL)\//i.test(normalized);
  }

  function extractPrompt(payload) {
    const candidates = [
      payload.prompt,
      payload.user_prompt,
      payload.text,
      payload.message,
      payload.input,
    ];
    return candidates.find((value) => typeof value === 'string' && value.trim()) || '';
  }

  function normalizeRelativeFile(projectRoot, rawFilePath) {
    if (typeof rawFilePath !== 'string' || !rawFilePath.trim()) {
      return null;
    }

    const trimmed = rawFilePath.trim();
    if (path.isAbsolute(trimmed)) {
      const relative = path.relative(projectRoot, trimmed);
      if (relative && !relative.startsWith('..') && !path.isAbsolute(relative)) {
        return relative.replaceAll('\\', '/');
      }
      return trimmed.replaceAll('\\', '/');
    }

    return trimmed.replace(/^\.\/+/, '').replaceAll('\\', '/');
  }

  function buildRouteRequestKey({
    commandNamespace = '.claude',
    indexGeneratedAtMs = null,
    projectFingerprint = null,
    activeSkills = [],
    routingContext = {},
    previousContextFingerprint = null,
  }) {
    return buildCompactMachineKey('route-v2', {
      commandNamespace,
      indexGeneratedAtMs,
      projectFingerprint,
      skillIds: activeSkills.map((item) => item.id),
      skillPaths: activeSkills.map((item) => item.path),
      skillContextModes: activeSkills.map((item) => item.contextMode || 'indexed'),
      promptText: routingContext.promptText || '',
      lastExplicitUserPromptText: routingContext.lastExplicitUserPromptText || '',
      commandText: routingContext.commandText || '',
      targetFile: routingContext.targetFile || '',
      contextIntent: routingContext.contextIntent || '',
      taskType: routingContext.taskType || '',
      executionMode: routingContext.executionMode || '',
      previousContextFingerprint: previousContextFingerprint || null,
    });
  }

  function buildRouteStateFingerprint({
    activeSkills = [],
    routingContext = {},
    previousContext = null,
    routeSummary = null,
  } = {}) {
    return buildCompactMachineKey('routefp-v3', {
      skills: activeSkills.map((item) => item.id),
      taskType: routingContext?.taskType || null,
      executionMode: routeSummary?.executionMode || null,
      approachRiskLevel: routeSummary?.approachSelector?.riskLevel || null,
      approachContextPolicy: routeSummary?.approachSelector?.contextPolicy || null,
      approachVerificationPolicy: routeSummary?.approachSelector?.verificationPolicy || null,
      approachCompletionRule: routeSummary?.approachSelector?.completionRule || null,
      continuationRequired: routeSummary?.continuationState?.required || null,
      continuationReasons: unique(routeSummary?.continuationState?.reasons ?? []),
      continuationMilestone: routeSummary?.continuationState?.nextMilestone || null,
      continuationRepeatCount: routeSummary?.continuationState?.repeatCount || null,
      continuationStuckRisk: routeSummary?.continuationState?.stuckRisk || null,
      continuationRescueMode: routeSummary?.continuationState?.rescueMode || null,
      previousContextLine: previousContext?.line || null,
      previousContextIds: unique(previousContext?.selectedIds ?? []),
      policyMode: routeSummary?.policyMode || null,
      delegateHint: routeSummary?.delegateHint || null,
      nextActionType: routeSummary?.nextActionType || null,
      nextActionCommand: routeSummary?.nextActionCommand || null,
      helperHint: routeSummary?.helperHint || null,
      completionRule: routeSummary?.executionContract?.completionRule || null,
      completionMissingEvidence: unique(routeSummary?.completionState?.missingEvidence ?? []),
      primaryCommands: [...new Set((routeSummary?.primaryCommands || []).filter(Boolean))],
      fallbackCommands: [...new Set((routeSummary?.fallbackCommands || []).filter(Boolean))],
      preferredOrder: [...new Set((routeSummary?.preferredOrder || []).filter(Boolean))],
    });
  }

  function buildCompactMachineKey(prefix, payload) {
    return `${prefix}:${stableMachineDigest(payload)}`;
  }

  function stableMachineDigest(payload) {
    return crypto
      .createHash('sha256')
      .update(JSON.stringify(payload))
      .digest('base64url');
  }

  function unique(values = []) {
    return [...new Set((values || []).filter(Boolean))];
  }

  function deriveContextIntent({ promptText, commandText, targetFile, selectedIds }) {
    if (promptText.trim()) {
      return promptText.trim();
    }

    if (commandText.includes('triage.mjs')) {
      return `debug ${commandText.trim()}`.trim();
    }

    if (commandText.includes('query-index.mjs')) {
      return `investigate ${commandText.trim()}`.trim();
    }

    if (/\b(test|vitest|jest|playwright|cypress)\b/i.test(commandText)) {
      return targetFile ? `fix failing test around ${targetFile}` : 'fix failing test';
    }

    if (targetFile) {
      if (/^docs\//i.test(targetFile)) {
        return `update docs for ${targetFile}`;
      }
      return `work on ${targetFile}`;
    }

    if (selectedIds.includes('docs-quality')) return 'update documentation';
    if (selectedIds.includes('debugging-toolkit')) return 'debug failing issue';
    if (selectedIds.includes('testing-quality')) return 'write targeted test';
    if (selectedIds.includes('code-review')) return 'review change for regressions';
    if (selectedIds.includes('repo-maintenance')) return 'refresh stale workspace';
    if (selectedIds.includes('discover-security')) return 'review security-sensitive change';
    return '';
  }

  function inferTaskType({ promptText, commandText, selectedIds, buildRouteSignalText, targetFile = null }) {
    const lower = buildRouteSignalText(promptText, commandText);

    if (
      selectedIds.includes('discover-security')
      || selectedIds.includes('repo-maintenance')
      || /\b(auth|security|token|permission|secret|migration|uninstall|delete all|drop table|race|flaky|timeout)\b/.test(lower)
    ) {
      return 'non-trivial';
    }

    let inferred = 'simple';
    if (/\b(typo|label|text|rename|color|spacing|toggle|comment)\b/.test(lower)) {
      inferred = 'trivial';
    }

    if ((inferred === 'simple' || inferred === 'trivial') && isSharedImpactFile(targetFile)) {
      return 'shared-simple';
    }

    return inferred;
  }

  function shellEscape(value) {
    if (typeof value !== 'string') return '';
    return `'${value.replace(/'/g, `'\\''`)}'`;
  }

  function buildContextCommand({ intent, targetFile, taskType }) {
    const parts = ['node .claude/ukit/index/resolve-context.mjs'];
    if (intent) {
      parts.push(shellEscape(intent));
    }
    if (targetFile) {
      parts.push('--target', shellEscape(targetFile));
    }
    if (taskType) {
      parts.push('--type', taskType);
    }
    return parts.join(' ');
  }

  function buildVerificationHelperCommand({ intent, targetFile, taskType }) {
    const parts = ['node .claude/ukit/index/verify-context.mjs'];
    if (intent) {
      parts.push(shellEscape(intent));
    }
    if (targetFile) {
      parts.push('--target', shellEscape(targetFile));
    }
    if (taskType) {
      parts.push('--type', taskType);
    }
    return parts.join(' ');
  }

  async function buildContextRecommendation({ projectRoot, intent, targetFile, taskType }) {
    if (!intent && !targetFile) {
      return null;
    }

    const recommendation = {
      command: buildContextCommand({ intent, targetFile, taskType }),
      preview: null,
    };

    const indexCorePath = path.join(projectRoot, '.claude', 'ukit', 'index', 'lib', 'index-core.mjs');
    if (!fs.existsSync(indexCorePath)) {
      return recommendation;
    }

    try {
      const mod = await import(pathToFileURL(indexCorePath).href);
      if (typeof mod.resolveContext !== 'function') {
        return recommendation;
      }

      const result = await mod.resolveContext({
        rootDir: projectRoot,
        intent,
        targetFile,
        taskType,
      });

      recommendation.preview = {
        taskType: result.taskType,
        primaryTargets: result.primaryTargets ?? [],
        analogFiles: result.analogFiles ?? [],
        sharedAbstractions: result.sharedAbstractions ?? [],
        relatedTests: result.relatedTests ?? [],
        styleFiles: result.styleFiles ?? [],
      };
      return recommendation;
    } catch {
      return recommendation;
    }
  }

  function readProjectPackage(projectRoot) {
    return readJson(path.join(projectRoot, 'package.json'), null);
  }

  function readProjectVerificationFingerprint(projectRoot) {
    let pkg = null;
    const entries = [];

    try {
      const packageJsonPath = path.join(projectRoot, 'package.json');
      const raw = fs.readFileSync(packageJsonPath, 'utf8');
      const stat = fs.statSync(packageJsonPath);
      pkg = JSON.parse(raw);
      entries.push({
        filePath: 'package.json',
        size: stat.size,
        mtimeMs: stat.mtimeMs,
      });
    } catch {
      entries.push({
        filePath: 'package.json',
        size: null,
        mtimeMs: null,
      });
    }

    const trackedFiles = getDeclaredPackageManager(pkg)
      ? []
      : [
          'package-lock.json',
          'pnpm-lock.yaml',
          'yarn.lock',
          'bun.lockb',
          'bun.lock',
        ];
    entries.push(...trackedFiles.map((relativePath) => {
      try {
        const stat = fs.statSync(path.join(projectRoot, relativePath));
        return {
          filePath: relativePath,
          size: stat.size,
          mtimeMs: stat.mtimeMs,
        };
      } catch {
        return {
          filePath: relativePath,
          size: null,
          mtimeMs: null,
        };
      }
    }));

    return {
      pkg,
      entries,
      fingerprint: JSON.stringify(entries),
    };
  }

  function getDeclaredPackageManager(pkg) {
    const declared = typeof pkg?.packageManager === 'string'
      ? pkg.packageManager.split('@')[0]
      : null;
    if (declared && ['npm', 'yarn', 'pnpm', 'bun'].includes(declared)) {
      return declared;
    }

    return null;
  }

  function detectProjectId(projectRoot) {
    const pkg = readJson(path.join(projectRoot, 'package.json'), null);
    if (typeof pkg?.name === 'string' && pkg.name.trim()) {
      return pkg.name.trim();
    }

    return path.basename(projectRoot);
  }

  function readDirectoryJsonItems(dirPath) {
    let entries = [];
    try {
      entries = fs.readdirSync(dirPath, { withFileTypes: true });
    } catch {
      return [];
    }

    const items = [];
    for (const entry of entries) {
      if (!entry.isFile() || !entry.name.endsWith('.json')) {
        continue;
      }

      const fullPath = path.join(dirPath, entry.name);
      const content = readJson(fullPath, null);
      if (content && typeof content === 'object') {
        items.push({
          fileName: entry.name,
          filePath: fullPath,
          content,
        });
      }
    }

    return items.sort((left, right) => left.fileName.localeCompare(right.fileName));
  }

  function listMemoryItems(projectRoot) {
    const runtimePaths = buildRuntimePaths(projectRoot);
    const userMemory = readJson(runtimePaths.userMemoryPath, null) ?? { preferences: {}, rules: [] };
    const projectMemories = readDirectoryJsonItems(runtimePaths.projectsDir);
    const sessionMemories = readDirectoryJsonItems(runtimePaths.sessionsDir);

    return [
      {
        id: 'user:user',
        type: 'user',
        content: userMemory,
      },
      ...projectMemories.map((item) => ({
        id: `project:${item.content.id ?? item.fileName.replace(/\.json$/, '')}`,
        type: 'project',
        content: item.content,
      })),
      ...sessionMemories.map((item) => ({
        id: `session:${item.content.id ?? item.fileName.replace(/\.json$/, '')}`,
        type: 'session',
        content: item.content,
      })),
    ];
  }

  function normalizeMemoryText(text) {
    return String(text ?? '')
      .toLowerCase()
      .replace(/[^\p{L}\p{N}\s./:_-]/gu, ' ')
      .replace(/\s+/g, ' ')
      .trim();
  }

  function tokenizeMemoryText(text) {
    return normalizeMemoryText(text)
      .split(/\s+/)
      .filter((token) => token && !STOPWORDS.has(token) && token.length > 1);
  }

  function getMemoryTimestamp(item) {
    return item.content?.updatedAt
      ?? item.content?.endedAt
      ?? item.content?.startedAt
      ?? 0;
  }

  function buildMemorySegments(item) {
    const content = item.content ?? {};
    if (item.type === 'project') {
      return [
        { text: content.name, weight: 2 },
        { text: content.architecture, weight: 3 },
        { text: (content.techStack ?? []).join(' '), weight: 2 },
        { text: (content.activeRules ?? []).join(' '), weight: 2 },
        { text: (content.decisions ?? []).map((decision) => `${decision.what} ${decision.why}`).join(' '), weight: 7 },
      ];
    }

    if (item.type === 'session') {
      return [
        { text: content.taskDescription, weight: 4 },
        { text: content.outcome, weight: 1 },
        { text: (content.keyActions ?? []).join(' '), weight: 3 },
        { text: (content.nextSteps ?? []).join(' '), weight: 2 },
        { text: (content.filesChanged ?? []).join(' '), weight: 1 },
        { text: (content.decisionsMade ?? []).map((decision) => `${decision.what} ${decision.why}`).join(' '), weight: 4 },
      ];
    }

    return [
      { text: JSON.stringify(content.preferences ?? {}), weight: 1 },
      { text: (content.rules ?? []).join(' '), weight: 2 },
    ];
  }

  function scoreMemoryItem(item, queryTokens) {
    if (queryTokens.length === 0) {
      return 0;
    }

    let score = 0;
    for (const segment of buildMemorySegments(item)) {
      const segmentTokens = new Set(tokenizeMemoryText(segment.text));
      for (const token of queryTokens) {
        if (segmentTokens.has(token)) {
          score += segment.weight;
        }
      }
    }

    if (score === 0) {
      return 0;
    }

    const recencyBonus = getMemoryTimestamp(item) > 0 ? Math.min(1, getMemoryTimestamp(item) / Date.now()) : 0;
    return score + recencyBonus;
  }

  function buildPreviousContextSnippet(item) {
    const content = item.content ?? {};
    if (item.type === 'project') {
      const decisions = (content.decisions ?? []).map((decision) => decision.what).slice(0, 2).join('; ');
      const rules = (content.activeRules ?? []).slice(0, 2).join('; ');
      return `[project] ${content.name ?? content.id ?? 'project'} — decisions: ${decisions || 'n/a'}${rules ? ` — rules: ${rules}` : ''}`;
    }

    if (item.type === 'session') {
      const actions = (content.keyActions ?? []).slice(0, 2).join('; ');
      const nextSteps = (content.nextSteps ?? []).slice(0, 1).join('; ');
      return `[session] ${content.taskDescription ?? item.id} — outcome: ${content.outcome ?? 'unknown'}${actions ? ` — actions: ${actions}` : ''}${nextSteps ? ` — next: ${nextSteps}` : ''}`;
    }

    const rules = (content.rules ?? []).slice(0, 2).join('; ');
    return `[user] rules: ${rules || 'n/a'}`;
  }

  function buildPreviousContextSnapshot({
    projectRoot,
    routingContext = {},
    config = defaultRuntimeConfig(),
  } = {}) {
    if (!config?.memory?.enabled || !config?.memory?.progressiveRetrieval) {
      return null;
    }

    const taskQuery = String(
      routingContext?.lastExplicitUserPromptText
      || routingContext?.promptText
      || routingContext?.targetFile
      || ''
    ).trim();
    if (!taskQuery) {
      return null;
    }

    const projectId = detectProjectId(projectRoot);
    const items = listMemoryItems(projectRoot);
    const queryTokens = tokenizeMemoryText(taskQuery);
    const rankedItems = items
      .filter((item) => item.type !== 'user')
      .filter((item) => (
        item.type === 'project'
          ? (item.content?.id === projectId)
          : (item.type === 'session' ? item.content?.projectId === projectId : true)
      ))
      .map((item) => ({
        item,
        score: scoreMemoryItem(item, queryTokens),
      }))
      .filter((entry) => entry.score > 0)
      .sort((left, right) => (
        right.score - left.score
        || getMemoryTimestamp(right.item) - getMemoryTimestamp(left.item)
      ))
      .slice(0, 2)
      .map((entry) => entry.item);

    if (rankedItems.length === 0) {
      return null;
    }

    return {
      line: rankedItems.map((item) => buildPreviousContextSnippet(item)).join(' | '),
      selectedIds: rankedItems.map((item) => item.id),
      fingerprint: buildCompactMachineKey('route-memory-v1', {
        taskQuery: normalizeMemoryText(taskQuery),
        projectId,
        items: rankedItems.map((item) => ({
          id: item.id,
          timestamp: getMemoryTimestamp(item),
        })),
      }),
    };
  }

  function detectPackageManager(projectRoot, pkg) {
    const declared = getDeclaredPackageManager(pkg);
    if (declared) return declared;

    if (fs.existsSync(path.join(projectRoot, 'pnpm-lock.yaml'))) return 'pnpm';
    if (fs.existsSync(path.join(projectRoot, 'yarn.lock'))) return 'yarn';
    if (fs.existsSync(path.join(projectRoot, 'bun.lockb')) || fs.existsSync(path.join(projectRoot, 'bun.lock'))) return 'bun';
    return 'npm';
  }

  function buildScriptCommand(packageManager, scriptName, args = []) {
    const safeArgs = args.filter(Boolean);

    if (packageManager === 'npm') {
      if (scriptName === 'test') {
        return ['npm', 'test', safeArgs.length > 0 ? '--' : '', ...safeArgs]
          .filter(Boolean)
          .join(' ');
      }

      return ['npm', 'run', scriptName, safeArgs.length > 0 ? '--' : '', ...safeArgs]
        .filter(Boolean)
        .join(' ');
    }

    return [packageManager, scriptName, ...safeArgs].join(' ');
  }

  function buildVerificationRecommendation({
    projectRoot,
    selectedIds,
    contextRecommendation,
    contextIntent,
    targetFile,
    taskType,
    pkg = null,
  }) {
    const resolvedPkg = pkg || readProjectPackage(projectRoot) || {};
    const scripts = typeof resolvedPkg.scripts === 'object' && resolvedPkg.scripts ? resolvedPkg.scripts : {};
    const packageManager = detectPackageManager(projectRoot, resolvedPkg);
    const preview = contextRecommendation?.preview || {};
    const relatedTests = [...new Set([
      ...(Array.isArray(preview.relatedTests) ? preview.relatedTests : []),
      ...(targetFile && /\.(test|spec)\./.test(targetFile) ? [targetFile] : []),
    ])];
    const primaryTargets = [...new Set([
      ...(Array.isArray(preview.primaryTargets) ? preview.primaryTargets : []),
      ...(targetFile ? [targetFile] : []),
    ])];
    const commands = [];
    const fallbackCommands = [];
    const reasons = [];
    const notes = [];
    const docsOnly = primaryTargets.length > 0
      && primaryTargets.every((filePath) => /^docs\//.test(filePath));
    const highRisk = taskType === 'non-trivial'
      || selectedIds.some((id) => id === 'discover-security' || id === 'repo-maintenance');

    let mode = 'minimal';

    if (docsOnly) {
      mode = 'docs-only';
      reasons.push('docsOnly');
      if (scripts.lint) {
        fallbackCommands.push(buildScriptCommand(packageManager, 'lint'));
      }
      notes.push('Docs-focused change: prefer docs syntax/format checks if available; broad test runs are not the default.');
      const commandList = [...new Set(commands)];
      const fallbackList = [...new Set(fallbackCommands.filter((command) => !commandList.includes(command)))];
      const reasonList = [...new Set(reasons)];
      return {
        packageManager,
        mode,
        helperCommand: buildVerificationHelperCommand({ intent: contextIntent, targetFile, taskType }),
        commands: commandList,
        fallbackCommands: fallbackList,
        reasons: reasonList,
        notes,
        relatedTests,
        primaryTargets,
        executionPolicy: deriveExecutionPolicy({
          taskType: preview.taskType || taskType,
          mode,
          commands: commandList,
          fallbackCommands: fallbackList,
          reasons: reasonList,
          context: {
            primaryTargets,
            sharedAbstractions: Array.isArray(preview.sharedAbstractions) ? preview.sharedAbstractions : [],
            relatedTests,
          },
        }),
      };
    }

    if (relatedTests.length > 0) {
      mode = 'targeted-tests-first';
      reasons.push('relatedTests');
      if (scripts.test) {
        for (const testFile of relatedTests.slice(0, 2)) {
          commands.push(buildScriptCommand(packageManager, 'test', [testFile]));
        }
      } else {
        notes.push(`Run the most relevant related tests first: ${relatedTests.slice(0, 2).join(', ')}`);
      }
    }

    if (highRisk) {
      reasons.push('riskySkillOrTask');
      if (scripts.test) {
        const broaderTest = buildScriptCommand(packageManager, 'test');
        if (!commands.includes(broaderTest)) {
          fallbackCommands.push(broaderTest);
        }
      }
    }

    if (selectedIds.some((id) => ['debugging-toolkit', 'testing-quality', 'code-review', 'discover-security', 'repo-maintenance'].includes(id))) {
      if (scripts.lint) {
        fallbackCommands.push(buildScriptCommand(packageManager, 'lint'));
      }
      if (scripts.typecheck) {
        fallbackCommands.push(buildScriptCommand(packageManager, 'typecheck'));
      }
    }

    if (commands.length === 0 && scripts.test && (highRisk || selectedIds.some((id) => ['testing-quality', 'code-review'].includes(id)))) {
      mode = highRisk ? 'broader-verification' : 'default-test-first';
      reasons.push(highRisk ? 'highRiskFallback' : 'defaultTestScript');
      commands.push(buildScriptCommand(packageManager, 'test'));
    }

    if (commands.length === 0 && fallbackCommands.length === 0) {
      notes.push('Match verification effort to scope; no project test/lint/typecheck scripts were detected.');
    }

    const commandList = [...new Set(commands)];
    const fallbackList = [...new Set(fallbackCommands.filter((command) => !commandList.includes(command)))];
    const reasonList = [...new Set(reasons)];

    return {
      packageManager,
      mode,
      helperCommand: buildVerificationHelperCommand({ intent: contextIntent, targetFile, taskType }),
      commands: commandList,
      fallbackCommands: fallbackList,
      reasons: reasonList,
      notes: [...new Set(notes)],
      relatedTests,
      primaryTargets,
      executionPolicy: deriveExecutionPolicy({
        taskType: preview.taskType || taskType,
        mode,
        commands: commandList,
        fallbackCommands: fallbackList,
        reasons: reasonList,
        context: {
          primaryTargets,
          sharedAbstractions: Array.isArray(preview.sharedAbstractions) ? preview.sharedAbstractions : [],
          relatedTests,
        },
      }),
    };
  }

  function deriveExecutionPolicy({
    taskType = 'simple',
    mode = 'minimal',
    commands = [],
    fallbackCommands = [],
    reasons = [],
    context = {},
  }) {
    const relatedTests = Array.isArray(context.relatedTests) ? context.relatedTests : [];
    const sharedAbstractions = Array.isArray(context.sharedAbstractions) ? context.sharedAbstractions : [];
    const docsOnly = mode === 'docs-only' || reasons.includes('docsOnly');
    const risky = taskType === 'non-trivial'
      || reasons.includes('riskySkillOrTask')
      || reasons.includes('highRiskFallback');
    const hasPrimaryCommands = commands.length > 0;
    const hasTargetedPrimaryCommands = mode === 'targeted-tests-first' && hasPrimaryCommands;
    const sharedScope = sharedAbstractions.length > 0;
    const noRelatedTests = relatedTests.length === 0;
    const broadOnlyPrimary = hasPrimaryCommands && !hasTargetedPrimaryCommands && noRelatedTests;
    const autonomyLevel = runtimeConfig?.autonomy?.level || 'balanced';
    const isConservative = autonomyLevel === 'conservative';
    const isFreeRun = autonomyLevel === 'free-run';
    const requiresHumanConfirmationForBroadOrRisky = !isFreeRun && risky && broadOnlyPrimary;
    const shouldAutoRunPrimaryCommands = hasPrimaryCommands && !docsOnly && !requiresHumanConfirmationForBroadOrRisky;
    const shouldEscalateToFallbacks = !docsOnly && fallbackCommands.length > 0 && (risky || sharedScope);
    const shouldAutoRunFallbacks = shouldEscalateToFallbacks && !requiresHumanConfirmationForBroadOrRisky && !isConservative;

    let policyMode = 'recommend-only';
    if (docsOnly) {
      policyMode = 'docs-light';
    } else if (hasTargetedPrimaryCommands && shouldEscalateToFallbacks) {
      policyMode = 'auto-run-targeted-then-fallback';
    } else if (hasTargetedPrimaryCommands) {
      policyMode = 'auto-run-targeted';
    } else if (requiresHumanConfirmationForBroadOrRisky) {
      policyMode = 'confirm-then-broad';
    } else if (shouldAutoRunPrimaryCommands) {
      policyMode = 'auto-run-primary';
    }

    return {
      policyMode,
      shouldAutoRunPrimaryCommands,
      shouldAutoRunTargetedVerification: hasTargetedPrimaryCommands && shouldAutoRunPrimaryCommands,
      shouldEscalateToFallbacks,
      shouldAutoRunFallbacks,
      requiresHumanConfirmationForBroadOrRisky,
      preferredOrder: [...commands, ...fallbackCommands],
      reasons: [...new Set([
        ...reasons,
        sharedScope ? 'sharedScope' : null,
        noRelatedTests ? 'noRelatedTests' : null,
      ].filter(Boolean))],
    };
  }

  function deriveNextAction({
    activeSkills = [],
    contextRecommendation = null,
    verificationRecommendation = null,
  }) {
    const policy = verificationRecommendation?.executionPolicy || null;
    const primaryCommands = Array.isArray(verificationRecommendation?.commands) ? verificationRecommendation.commands : [];
    const fallbackCommands = Array.isArray(verificationRecommendation?.fallbackCommands) ? verificationRecommendation.fallbackCommands : [];

    if (policy?.requiresHumanConfirmationForBroadOrRisky) {
      return {
        type: 'ask-user-confirmation',
        reason: 'Ask before broad verification because index evidence could not localize a safe targeted lane.',
        followUpCommands: [...primaryCommands, ...fallbackCommands],
      };
    }

    if (policy?.shouldAutoRunPrimaryCommands && primaryCommands.length > 0) {
      return {
        type: 'run-primary-verification',
        command: primaryCommands[0],
        reason: 'Targeted related verification is available from indexed context.',
        followUpCommands: fallbackCommands,
      };
    }

    if (policy?.shouldAutoRunFallbacks && fallbackCommands.length > 0) {
      return {
        type: 'run-fallback-verification',
        command: fallbackCommands[0],
        reason: 'No primary verification command was auto-runnable, but routed fallbacks are allowed.',
        followUpCommands: fallbackCommands.slice(1),
      };
    }

    if (contextRecommendation?.command) {
      return {
        type: 'pull-indexed-context',
        command: contextRecommendation.command,
        reason: 'Resolve the minimal indexed file bundle before widening reads.',
      };
    }

    if (activeSkills.length > 0) {
      return {
        type: 'read-skill-instructions',
        skillPaths: activeSkills.map((item) => item.path),
        reason: 'Open the matching project-local skill before acting.',
      };
    }

    return {
      type: 'inspect-structure',
      reason: 'No strong route found; inspect repository structure and indexed files first.',
    };
  }

  function deriveDelegationRecommendation({
    activeSkills = [],
    routingContext = {},
    contextRecommendation = null,
    verificationRecommendation = null,
  } = {}) {
    const skillIds = activeSkills.map((item) => item.id);
    const lower = `${routingContext.promptText || ''}\n${routingContext.commandText || ''}`.toLowerCase();
    const preview = contextRecommendation?.preview || {};
    const contextBreadth = countDelegationContextBreadth(preview);
    const hasExplicitTarget = Boolean(routingContext.targetFile);
    const localizedIndexedLane = hasExplicitTarget && contextBreadth > 0 && contextBreadth <= 3;
    const hasRelatedTests = Array.isArray(preview.relatedTests) && preview.relatedTests.length > 0;
    const when = contextRecommendation?.command ? 'after-context' : 'now';

    if (routingContext.taskType === 'trivial') {
      return null;
    }

    if (
      skillIds.includes('executing-plans')
      || /\b(execute this plan|follow this plan|implementation plan|rollout plan|controlled batches?|review checkpoints?|batch execution|execute in batches)\b/.test(lower)
    ) {
      return {
        hint: 'subagent-driven-development',
        when,
        reason: 'Explicit plan/batch execution is separable enough for deliberate subagent passes.',
      };
    }

    const noisyDebugLane = skillIds.includes('debugging-toolkit') && (
      Boolean(String(routingContext.commandText || '').trim())
      || /\b(debug|error|crash|stack(?: trace)?|failing|flake|flaky|timeout|triage|root cause)\b/.test(lower)
      || verificationRecommendation?.executionPolicy?.policyMode === 'confirm-then-broad'
    );
    if (noisyDebugLane && (!localizedIndexedLane || !hasRelatedTests || contextBreadth >= 4)) {
      return {
        hint: 'bug-debugger',
        when,
        reason: 'A noisy reproduce/trace/fix loop benefits from isolated debugging context.',
      };
    }

    const hasImplementationSkill = skillIds.some((id) => DELEGATABLE_IMPLEMENTATION_SKILL_IDS.has(id));
    const clearImplementationSignal = /\b(implement|build|create|add|ship|deliver|refactor|integrat(?:e|ion)|scaffold|feature)\b/.test(lower);
    const multiLaneSignal = /\b(multiple|several|parallel|independent|across files|across modules|batch)\b/.test(lower);
    if (
      hasImplementationSkill
      && clearImplementationSignal
      && routingContext.taskType === 'non-trivial'
      && (!localizedIndexedLane || !hasExplicitTarget || contextBreadth >= 4 || multiLaneSignal)
    ) {
      return {
        hint: 'feature-implementer',
        when,
        reason: 'A broader implementation lane can be delegated without dragging all details through the main context.',
      };
    }

    return null;
  }

  function buildRouteSummary({
    activeSkills = [],
    routingContext = {},
    contextRecommendation = null,
    verificationRecommendation = null,
    nextAction = null,
  }) {
    const delegationRecommendation = deriveDelegationRecommendation({
      activeSkills,
      routingContext,
      contextRecommendation,
      verificationRecommendation,
    });
    const preview = contextRecommendation?.preview || {};
    const primaryTargets = summarizeCompactList(Array.isArray(preview.primaryTargets) ? preview.primaryTargets : [], 2);
    const relatedTests = summarizeCompactList(Array.isArray(preview.relatedTests) ? preview.relatedTests : [], 2);
    const styleFiles = summarizeCompactList(Array.isArray(preview.styleFiles) ? preview.styleFiles : [], 1);
    const primaryCommands = [...new Set(Array.isArray(verificationRecommendation?.commands) ? verificationRecommendation.commands.filter(Boolean) : [])];
    const fallbackCommands = [...new Set(Array.isArray(verificationRecommendation?.fallbackCommands) ? verificationRecommendation.fallbackCommands.filter(Boolean) : [])];
    const preferredOrder = [...new Set(
      Array.isArray(verificationRecommendation?.executionPolicy?.preferredOrder)
        ? verificationRecommendation.executionPolicy.preferredOrder.filter(Boolean)
        : [...primaryCommands, ...fallbackCommands]
    )];
    const policyMode = verificationRecommendation?.executionPolicy?.policyMode || null;
    const compactHelperLane = nextAction?.type === 'pull-indexed-context'
      && typeof contextRecommendation?.command === 'string'
      && contextRecommendation.command.trim();
    const executionMode = routingContext.executionMode || null;
    const executionScores = routingContext.executionScores || null;
    const executionCandidates = routingContext.executionCandidates || null;
    const approachSelector = buildApproachSelectorResult({
      executionMode,
      executionScores,
      executionCandidates,
    });
    const executionContract = buildExecutionContract(executionMode);
    const completionState = buildCompletionState({
      executionMode,
      verificationRecommendation,
    });
    const continuationState = buildContinuationState({
      nextActionType: nextAction?.type || null,
      completionState,
    });
    const helperHint = compactHelperHint(
      compactHelperLane
        ? contextRecommendation?.command
        : (
          nextAction?.command
            ? null
            : verificationRecommendation?.helperCommand
        ),
    );
    const nextActionCommand = compactHelperLane ? null : nextAction?.command || null;
    const line = [
      routingContext.taskType ? `task=${routingContext.taskType}` : null,
      formatCompactSegment('targets', primaryTargets),
      formatCompactSegment('tests', relatedTests),
      formatCompactSegment('styles', styleFiles),
      policyMode ? `policy=${policyMode}` : null,
    ].filter(Boolean).join(' | ');

    return {
      primaryCommands,
      fallbackCommands,
      preferredOrder,
      policyMode,
      executionMode,
      executionScores,
      executionCandidates,
      approachSelector,
      executionContract,
      completionState,
      continuationState,
      delegateHint: delegationRecommendation?.hint || null,
      nextActionType: nextAction?.type || null,
      nextActionCommand,
      helperHint,
      line: line || 'task=unknown',
    };
  }

  function deriveExecutionScores({
    promptText = '',
    commandText = '',
    targetFile = null,
    intentMode = null,
    taskType = null,
  } = {}) {
    const raw = `${promptText || ''}\n${commandText || ''}`.toLowerCase();
    const sharedRisk = isSharedImpactFile(targetFile);
    const directTransformSignal = /\b(change|replace|set|rename|convert|swap)\b/.test(raw) || /\bchange\s+.+\s+to\s+.+\b/.test(raw);
    const smallFixSignal = /\b(adjust|tweak|patch|fix|modify|update|apply)\b/.test(raw);
    const buildSignal = /\b(build|create|add|implement|feature)\b/.test(raw);
    const debugSignal = intentMode === 'debug-specific' || /\b(root cause|debug|triage|flaky|investigate|why)\b/.test(raw);
    const reviewSignal = intentMode === 'review-specific' || /\b(review|audit|verify|release readiness)\b/.test(raw);
    const failureSignal = /\b(failing|failed|broken|error|crash|timeout|undefined|exception|eacces|trace)\b/.test(raw);
    const impactSignal = /\b(map impact|impact|blast radius|all affected|across (?:runtime|templates|helpers|adapters|mirrors)|affected adapters|affected mirrors|inspect impact)\b/.test(raw);
    const boundedEditSignal = /\b(one[- ]line|small|tiny|single|local|guard|log line|loading message|label)\b/.test(raw);
    const implementSignal = /\b(implement|apply|update|modify|add|create|ship|deliver|fix)\b/.test(raw)
      || /\bchange\s+.+\s+to\s+.+\b/.test(raw);
    const explicitTarget = Boolean(targetFile);

    let editCertainty = 0;
    if (directTransformSignal) {
      editCertainty = 3;
    } else if (smallFixSignal) {
      editCertainty = 2;
    } else if (buildSignal) {
      editCertainty = 1;
    }

    let investigationNeed = 0;
    if (debugSignal) {
      investigationNeed = 3;
    } else if (failureSignal) {
      investigationNeed = 2;
    }

    let blastRadius = 0;
    if (sharedRisk) {
      blastRadius = 3;
    } else if (taskType === 'non-trivial' || taskType === 'shared-simple') {
      blastRadius = 2;
    } else if (!targetFile) {
      blastRadius = 1;
    }

    let verificationBurden = 1;
    if (reviewSignal || sharedRisk) {
      verificationBurden = 3;
    } else if (debugSignal || taskType === 'non-trivial') {
      verificationBurden = 2;
    }

    let ambiguity = 0;
    if (!targetFile) {
      ambiguity = 2;
    } else if (buildSignal && !directTransformSignal && !smallFixSignal) {
      ambiguity = 1;
    }

    return {
      editCertainty,
      investigationNeed,
      blastRadius,
      verificationBurden,
      ambiguity,
      sharedRisk,
      directTransformSignal,
      smallFixSignal,
      buildSignal,
      debugSignal,
      reviewSignal,
      failureSignal,
      impactSignal,
      boundedEditSignal,
      implementSignal,
      explicitTarget,
    };
  }

  function deriveExecutionMode({
    promptText = '',
    commandText = '',
    targetFile = null,
    intentMode = null,
    executionScores = {},
    executionCandidates = null,
  } = {}) {
    const raw = `${promptText || ''}\n${commandText || ''}`.toLowerCase();
    const scores = executionScores;
    const candidates = executionCandidates ?? buildExecutionModeCandidates({
      promptText,
      commandText,
      targetFile,
      intentMode,
      executionScores,
    });
    const explicitReviewLead = /\b(review this|audit this|review\b.*\brelease readiness|verify\b.*\brelease readiness)\b/.test(raw);
    const strongImpactLead = scores.sharedRisk
      && (scores.impactSignal || /\b(check all affected|map all affected|across all affected)\b/.test(raw));
    const boundedLocalBuildCandidate = scores.buildSignal && scores.boundedEditSignal && scores.explicitTarget && !scores.sharedRisk;

    if ((intentMode === 'review-specific' || explicitReviewLead) && !scores.implementSignal) {
      return 'review-release';
    }

    if (strongImpactLead || (scores.blastRadius >= 3 && (scores.ambiguity >= 2 || scores.investigationNeed >= 2))) {
      return 'map-impact';
    }

    if (scores.sharedRisk && scores.failureSignal && scores.investigationNeed >= 2 && !scores.impactSignal) {
      return 'shared-edit';
    }

    if (scores.blastRadius >= 3 || scores.sharedRisk) {
      return 'shared-edit';
    }

    if (scores.investigationNeed >= 3 || (scores.failureSignal && scores.investigationNeed >= 2)) {
      return 'find-cause';
    }

    if (scores.directTransformSignal && !scores.explicitTarget && scores.investigationNeed === 0 && !scores.sharedRisk) {
      return 'local-build';
    }

    if (
      scores.editCertainty >= 3
      && scores.ambiguity <= 1
      && scores.blastRadius === 0
      && scores.verificationBurden <= 1
    ) {
      return 'tiny-fix';
    }

    if (boundedLocalBuildCandidate && scores.investigationNeed === 0) {
      return 'local-fix';
    }

    if (
      /\b(build|create|add|implement|feature|summary card)\b/.test(raw)
      && scores.investigationNeed === 0
      && scores.blastRadius < 3
      && !scores.boundedEditSignal
    ) {
      return 'local-build';
    }

    if (scores.editCertainty >= 2 && scores.investigationNeed === 0 && scores.blastRadius === 0) {
      return 'local-fix';
    }

    return applySafeUpwardBias(candidates, 'local-build');
  }

  function buildExecutionModeCandidates({
    promptText = '',
    commandText = '',
    targetFile = null,
    intentMode = null,
    executionScores = {},
  } = {}) {
    const scores = executionScores;
    const raw = `${promptText || ''}\n${commandText || ''}`.toLowerCase();
    const explicitReviewLead = (intentMode === 'review-specific' || /\b(review this|audit this|review\b.*\brelease readiness|verify\b.*\brelease readiness)\b/.test(raw))
      && !scores.implementSignal;

    const modeScores = {
      'tiny-fix': (
        (scores.editCertainty * 4)
        + (scores.directTransformSignal ? 4 : 0)
        + (scores.explicitTarget ? 1 : 0)
        - (scores.failureSignal ? 4 : 0)
        - (scores.blastRadius * 4)
        - (scores.ambiguity * 2)
      ),
      'local-fix': (
        (scores.editCertainty * 3)
        + (scores.boundedEditSignal ? 3 : 0)
        + (scores.explicitTarget ? 1 : 0)
        - (scores.failureSignal ? 2 : 0)
        - (scores.blastRadius * 4)
      ),
      'local-build': (
        (scores.buildSignal ? 6 : 0)
        + (scores.editCertainty * 1)
        + (scores.explicitTarget ? 1 : 0)
        - (scores.boundedEditSignal ? 3 : 0)
        - (scores.failureSignal ? 3 : 0)
        - (scores.blastRadius * 4)
      ),
      'find-cause': (
        (scores.investigationNeed * 4)
        + (scores.failureSignal ? 3 : 0)
        + (scores.debugSignal ? 2 : 0)
        - (scores.blastRadius >= 3 ? 1 : 0)
      ),
      'shared-edit': (
        (scores.sharedRisk ? 8 : 0)
        + (scores.editCertainty * 1)
        + (scores.buildSignal ? 1 : 0)
        - (scores.impactSignal ? 2 : 0)
      ),
      'map-impact': (
        (scores.sharedRisk ? 7 : 0)
        + (scores.impactSignal ? 5 : 0)
        + (scores.ambiguity * 2)
        + scores.investigationNeed
      ),
      'review-release': (
        (explicitReviewLead ? 10 : 0)
        + (scores.reviewSignal ? 3 : 0)
        - (scores.implementSignal ? 5 : 0)
      ),
    };

    return Object.entries(modeScores)
      .map(([mode, score]) => ({ mode, score }))
      .sort((a, b) => b.score - a.score || executionModeRank(a.mode) - executionModeRank(b.mode));
  }

  function applySafeUpwardBias(candidates = [], fallbackMode = 'local-build') {
    const [topCandidate, competingCandidate] = candidates;
    if (!topCandidate) {
      return fallbackMode;
    }

    if (!competingCandidate) {
      return topCandidate.mode;
    }

    const scoreGap = Number(topCandidate.score ?? 0) - Number(competingCandidate.score ?? 0);
    const rankGap = executionModeRank(competingCandidate.mode) - executionModeRank(topCandidate.mode);
    if (scoreGap <= 1 && rankGap === 1) {
      return competingCandidate.mode;
    }

    return topCandidate.mode;
  }

  function executionModeRank(mode = '') {
    const orderedModes = [
      'tiny-fix',
      'local-fix',
      'local-build',
      'find-cause',
      'shared-edit',
      'map-impact',
      'review-release',
    ];

    const index = orderedModes.indexOf(mode);
    return index >= 0 ? index : orderedModes.length;
  }

  function buildExecutionContract(executionMode = null) {
    if (!executionMode) {
      return null;
    }

    const contracts = {
      'tiny-fix': {
        maxReadPasses: 0,
        maxContextPulls: 0,
        verificationPolicy: 'minimal-or-targeted',
        completionRule: 'never-claim-done-without-write',
        delegationPolicy: 'disallow',
        completionEvidence: ['write-evidence'],
      },
      'local-fix': {
        maxReadPasses: 1,
        maxContextPulls: 1,
        verificationPolicy: 'targeted-if-covered',
        completionRule: 'require-write',
        delegationPolicy: 'disallow',
        completionEvidence: ['write-evidence'],
      },
      'local-build': {
        maxReadPasses: 2,
        maxContextPulls: 1,
        verificationPolicy: 'targeted-if-covered',
        completionRule: 'require-write',
        delegationPolicy: 'disallow-by-default',
        completionEvidence: ['write-evidence'],
      },
      'find-cause': {
        maxReadPassesBeforeReassess: 3,
        verificationPolicy: 'root-cause-then-targeted',
        completionRule: 'never-claim-fixed-without-write-and-verification',
        delegationPolicy: 'allow-specialized-debug-lane',
        completionEvidence: ['write-evidence', 'verification-evidence'],
      },
      'shared-edit': {
        maxReadPasses: 2,
        maxContextPulls: 2,
        verificationPolicy: 'targeted-then-widen-on-risk',
        completionRule: 'require-write-and-verification',
        delegationPolicy: 'allow-qualified-sidecar',
        completionEvidence: ['write-evidence', 'verification-evidence'],
        mirrorConsistencyRequired: true,
      },
      'map-impact': {
        maxReadPasses: 3,
        maxContextPulls: 3,
        verificationPolicy: 'impact-first-then-targeted-then-widen-on-risk',
        completionRule: 'require-impact-evidence-before-edit-claim',
        delegationPolicy: 'allow-impact-sidecar',
        completionEvidence: ['impact-evidence', 'write-evidence', 'verification-evidence'],
        mirrorConsistencyRequired: true,
      },
      'review-release': {
        verificationPolicy: 'evidence-first',
        completionRule: 'report-findings-not-implementation',
        delegationPolicy: 'allow-review-sidecar',
        completionEvidence: ['verification-evidence'],
      },
    };

    return contracts[executionMode] ? { ...contracts[executionMode] } : null;
  }

  function buildApproachSelectorResult({
    executionMode = null,
    executionScores = null,
    executionCandidates = null,
  } = {}) {
    if (!executionMode) {
      return null;
    }

    const executionContract = buildExecutionContract(executionMode);
    const policyByMode = {
      'tiny-fix': {
        riskLevel: 'minimal',
        contextPolicy: 'confirm-target-only',
      },
      'local-fix': {
        riskLevel: 'local',
        contextPolicy: 'bounded-local',
      },
      'local-build': {
        riskLevel: 'local',
        contextPolicy: 'bounded-with-related-files',
      },
      'find-cause': {
        riskLevel: 'investigation',
        contextPolicy: 'trace-then-bounded-context',
      },
      'shared-edit': {
        riskLevel: 'shared',
        contextPolicy: 'bounded-with-related-tests',
      },
      'map-impact': {
        riskLevel: 'wide',
        contextPolicy: 'impact-map-first',
      },
      'review-release': {
        riskLevel: 'release',
        contextPolicy: 'evidence-review-only',
      },
    };
    const selectedPolicy = policyByMode[executionMode] ?? {
      riskLevel: 'local',
      contextPolicy: 'bounded-local',
    };

    return {
      executionMode,
      executionScores: executionScores ? { ...executionScores } : null,
      riskLevel: selectedPolicy.riskLevel,
      contextPolicy: selectedPolicy.contextPolicy,
      verificationPolicy: executionContract?.verificationPolicy ?? null,
      completionRule: executionContract?.completionRule ?? null,
      competingMode: executionCandidates?.[1]?.mode ?? null,
      competingScoreGap: executionCandidates?.length >= 2
        ? Number(executionCandidates[0]?.score ?? 0) - Number(executionCandidates[1]?.score ?? 0)
        : null,
      candidateModes: (executionCandidates ?? []).slice(0, 3).map((entry) => ({
        mode: entry.mode,
        score: entry.score,
      })),
    };
  }

  function buildCompletionState({ executionMode = null, verificationRecommendation = null } = {}) {
    if (!executionMode) {
      return null;
    }

    const contract = buildExecutionContract(executionMode);
    const missingEvidence = [...(contract?.completionEvidence ?? [])];
    const requiresVerification = missingEvidence.includes('verification-evidence');
    if (
      requiresVerification
      && verificationRecommendation
      && !(verificationRecommendation.commands?.length || verificationRecommendation.fallbackCommands?.length)
    ) {
      missingEvidence.push('verification-plan');
    }

    let reason = 'completion evidence is still required';
    if (['tiny-fix', 'local-fix', 'local-build', 'shared-edit'].includes(executionMode)) {
      reason = 'implement request has not produced an edit yet';
    } else if (executionMode === 'review-release') {
      reason = 'review/release evidence is still required before final claim';
    } else if (executionMode === 'map-impact') {
      reason = 'impact evidence is still required before safe completion claim';
    }

    return {
      claimAllowed: false,
      missingEvidence,
      reason,
    };
  }

  function buildContinuationState({
    nextActionType = null,
    completionState = null,
  } = {}) {
    const reasons = [];
    const missingEvidence = unique(completionState?.missingEvidence ?? []);

    if (nextActionType === 'pull-indexed-context') {
      reasons.push('pending-bounded-context');
    }

    if (nextActionType === 'read-skill-instructions') {
      reasons.push('pending-skill-read');
    }

    if (missingEvidence.includes('write-evidence')) {
      reasons.push('missing-write-evidence');
    }

    if (missingEvidence.includes('verification-evidence') || missingEvidence.includes('verification-plan')) {
      reasons.push('missing-verification-evidence');
    }

    if (missingEvidence.includes('impact-evidence')) {
      reasons.push('missing-impact-evidence');
    }

    const nextMilestone = reasons.includes('pending-bounded-context')
      ? 'complete-bounded-context-then-continue'
      : (
        reasons.includes('missing-write-evidence')
          ? 'produce-write-evidence'
          : (
            reasons.includes('missing-verification-evidence')
              ? 'produce-verification-evidence'
              : (
                reasons.includes('missing-impact-evidence')
                  ? 'produce-impact-evidence'
                  : null
              )
          )
      );

    return {
      required: reasons.length > 0,
      reasons,
      doneLanguageBlocked: reasons.length > 0,
      stopAllowedOnlyFor: reasons.length > 0 ? ['real-blocker'] : [],
      nextMilestone,
      repeatCount: reasons.length > 0 ? 1 : 0,
      stuckRisk: null,
      rescueMode: null,
      wideningBlocked: false,
      milestonePriority: reasons.length > 0 ? 'normal' : null,
    };
  }

  function advanceContinuationState(continuationState = null, previousContinuationState = null) {
    if (!continuationState || typeof continuationState !== 'object') {
      return continuationState;
    }

    if (!continuationState.required) {
      return {
        ...continuationState,
        repeatCount: 0,
        stuckRisk: null,
        rescueMode: null,
        wideningBlocked: false,
        milestonePriority: null,
      };
    }

    const currentReasons = unique(continuationState.reasons ?? []);
    const previousReasons = unique(previousContinuationState?.reasons ?? []);
    const sameMilestone = Boolean(
      previousContinuationState?.required
      && continuationState.nextMilestone
      && previousContinuationState.nextMilestone === continuationState.nextMilestone
      && JSON.stringify(previousReasons) === JSON.stringify(currentReasons)
    );
    const repeatCount = sameMilestone
      ? Math.max(1, Number(previousContinuationState?.repeatCount ?? 1) + 1)
      : 1;
    const rescueMode = repeatCount >= 2
      ? (
        currentReasons.includes('pending-bounded-context')
          ? 'finish-current-milestone-before-more-reading'
          : (
            currentReasons.includes('missing-write-evidence')
              ? 'finish-write-before-more-analysis'
              : 'finish-required-milestone-before-widening'
          )
      )
      : null;
    const stuckRisk = repeatCount >= 3
      ? 'high'
      : (repeatCount === 2 ? 'elevated' : null);
    const wideningBlocked = repeatCount >= 2 && Boolean(rescueMode);
    const nextMilestone = repeatCount >= 2 && currentReasons.includes('missing-write-evidence')
      ? 'finish-write-before-more-analysis'
      : (
        repeatCount >= 2 && currentReasons.includes('pending-bounded-context')
          ? 'finish-current-milestone-before-more-reading'
          : continuationState.nextMilestone
      );

    return {
      ...continuationState,
      nextMilestone,
      repeatCount,
      stuckRisk,
      rescueMode,
      wideningBlocked,
      milestonePriority: wideningBlocked ? 'execute-current-milestone' : 'normal',
    };
  }

  function applyRescueBiasToRouteSummary(routeSummary = null) {
    if (!routeSummary || typeof routeSummary !== 'object') {
      return routeSummary;
    }

    const continuationState = routeSummary.continuationState;
    if (
      continuationState?.repeatCount >= 2
      && continuationState?.wideningBlocked
      && (continuationState.reasons ?? []).includes('missing-write-evidence')
    ) {
      routeSummary.nextActionType = 'execute-current-milestone';
      routeSummary.nextActionCommand = null;
      routeSummary.helperHint = null;
    }

    return routeSummary;
  }

  const SHARED_IMPACT_PATTERNS = [
    /^\.claude\/hooks\//,
    /^\.claude\/ukit\//,
    /^\.codex\//,
    /^src\/index\//,
    /^src\/core\/(runInstallPipeline|applyPlan|buildPlan|diffPlan|metadata|migrateLegacy|uninstall|runtimeConfig|runtimePaths)\.js$/,
    /^src\/core\/(output|token|compact)\//,
    /^templates\/\.claude\/hooks\//,
    /^templates\/\.claude\/ukit\//,
    /^manifests\/platform\.full\.yaml$/,
    /^templates\//,
  ];

  function isSharedImpactFile(filePath) {
    const normalized = String(filePath ?? '').trim().replace(/\\/g, '/').replace(/^\.\//, '');
    if (!normalized) {
      return false;
    }
    return SHARED_IMPACT_PATTERNS.some((pattern) => pattern.test(normalized));
  }

  function summarizeCompactList(values, limit = 2) {
    const normalized = [...new Set((values || []).filter(Boolean))];
    return {
      items: normalized.slice(0, limit),
      total: normalized.length,
    };
  }

  function countDelegationContextBreadth(preview = {}) {
    return [
      ...new Set([
        ...((Array.isArray(preview.primaryTargets) ? preview.primaryTargets : []).filter(Boolean)),
        ...((Array.isArray(preview.analogFiles) ? preview.analogFiles : []).filter(Boolean)),
        ...((Array.isArray(preview.sharedAbstractions) ? preview.sharedAbstractions : []).filter(Boolean)),
        ...((Array.isArray(preview.relatedTests) ? preview.relatedTests : []).filter(Boolean)),
      ]),
    ].length;
  }

  function formatCompactSegment(label, summary) {
    const items = summary?.items || [];
    if (items.length === 0) {
      return null;
    }

    const extraCount = Math.max((summary?.total || items.length) - items.length, 0);
    return `${label}=${items.join(',')}${extraCount > 0 ? `,+${extraCount}` : ''}`;
  }

  function compactHelperHint(command) {
    if (typeof command !== 'string' || !command.trim()) {
      return null;
    }

    const normalized = command.trim().replace(/\s+/g, ' ');
    const scriptMatch = normalized.match(/^node\s+([^\s]+)(?:\s+(.*))?$/i);
    if (!scriptMatch) {
      return normalized.length > 96 ? `${normalized.slice(0, 93)}...` : normalized;
    }

    const scriptName = scriptMatch[1].split('/').pop() || scriptMatch[1];
    const rest = scriptMatch[2] || '';
    const targetMatch = rest.match(/--target\s+("[^"]+"|'[^']+'|\S+)/);
    const typeMatch = rest.match(/--type\s+(\S+)/);
    const parts = [scriptName];

    if (targetMatch) {
      parts.push(`target=${stripShellQuotes(targetMatch[1])}`);
    }
    if (typeMatch) {
      parts.push(`type=${typeMatch[1]}`);
    }

    return parts.join(' ');
  }

  function stripShellQuotes(value) {
    return String(value || '').replace(/^['"]|['"]$/g, '');
  }

  function deriveCanonicalSkillPath(skillId) {
    const normalized = String(skillId || '').trim();
    if (!normalized) {
      return null;
    }

    return `.claude/skills/${normalized}/SKILL.md`;
  }

  function getActiveSkillPath(skill = {}) {
    const explicitPath = typeof skill?.path === 'string' ? skill.path.trim() : '';
    if (explicitPath) {
      return explicitPath;
    }

    return deriveCanonicalSkillPath(skill?.id);
  }

  function getActiveSkillPaths(activeSkills = []) {
    return unique(activeSkills.map((item) => getActiveSkillPath(item)).filter(Boolean));
  }

  function compactActiveSkills(activeSkills = []) {
    return activeSkills.map((item) => ({
      id: item.id,
    }));
  }

  function compactPreviousContext(previousContext = null) {
    if (!previousContext || typeof previousContext !== 'object') {
      return null;
    }

    const line = typeof previousContext.line === 'string' ? previousContext.line.trim() : '';
    if (!line) {
      return null;
    }

    return {
      line,
      selectedIds: unique(previousContext.selectedIds ?? []).slice(0, 3),
    };
  }

  function compactRoutingContext(routingContext = {}) {
    return {
      lastExplicitUserPromptText: routingContext.lastExplicitUserPromptText || '',
      taskType: routingContext.taskType || null,
      intentMode: routingContext.intentMode || null,
      executionMode: routingContext.executionMode || null,
    };
  }

  function compactHelpers({
    verificationRecommendation = null,
    routeSummary = null,
  } = {}) {
    const verificationHelperHint = routeSummary?.helperHint
      ? null
      : compactHelperHint(verificationRecommendation?.helperCommand || null);

    if (!verificationHelperHint) {
      return null;
    }

    return {
      verificationHelperHint,
    };
  }

  function compactRouteSummary(routeSummary = null) {
    if (!routeSummary) {
      return null;
    }

    return {
      line: routeSummary.line || 'task=unknown',
      primaryCommands: [...new Set((routeSummary.primaryCommands || []).filter(Boolean))].slice(0, 2),
      fallbackCommands: [...new Set((routeSummary.fallbackCommands || []).filter(Boolean))].slice(0, 3),
      preferredOrder: [...new Set((routeSummary.preferredOrder || []).filter(Boolean))].slice(0, 5),
      policyMode: routeSummary.policyMode || null,
      executionMode: routeSummary.executionMode || null,
      executionScores: routeSummary.executionScores || null,
      approachSelector: routeSummary.approachSelector || null,
      executionContract: routeSummary.executionContract || null,
      completionState: routeSummary.completionState || null,
      continuationState: routeSummary.continuationState || null,
      delegateHint: routeSummary.delegateHint || null,
      nextActionType: routeSummary.nextActionType || null,
      nextActionCommand: routeSummary.nextActionCommand || null,
      helperHint: routeSummary.helperHint || null,
    };
  }

  function buildRouteAuditEntry({
    routingContext = {},
    routeSummary = {},
    state = null,
  } = {}) {
    const candidateModes = Array.isArray(routeSummary?.approachSelector?.candidateModes)
      ? routeSummary.approachSelector.candidateModes
      : [];

    return {
      ts: Date.now(),
      source: state?.source || 'skill-router',
      requestKey: state?.requestKey || null,
      adapter: routingContext.adapter || 'claude',
      promptFingerprint: stableMachineDigest({
        prompt: routingContext.lastExplicitUserPromptText || '',
        adapter: routingContext.adapter || 'claude',
      }),
      targetFile: routingContext.targetFile || null,
      taskType: routingContext.taskType || null,
      executionMode: routeSummary.executionMode || null,
      competingMode: routeSummary?.approachSelector?.competingMode || null,
      competingScoreGap: routeSummary?.approachSelector?.competingScoreGap || null,
      candidateModes: candidateModes.slice(0, 3),
      nextActionType: routeSummary.nextActionType || null,
      nextMilestone: routeSummary?.continuationState?.nextMilestone || null,
      repeatCount: routeSummary?.continuationState?.repeatCount || null,
      rescueMode: routeSummary?.continuationState?.rescueMode || null,
      wideningBlocked: routeSummary?.continuationState?.wideningBlocked || null,
    };
  }

  function appendRouteAuditEntry(filePath, entry) {
    if (!entry || typeof entry !== 'object') {
      return;
    }

    let parsed = { entries: [] };
    if (fs.existsSync(filePath)) {
      try {
        parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
      } catch {
        parsed = { entries: [] };
      }
    }

    const entries = Array.isArray(parsed?.entries) ? parsed.entries : [];
    const dedupeKey = stableMachineDigest({
      requestKey: entry.requestKey,
      executionMode: entry.executionMode,
      nextActionType: entry.nextActionType,
      nextMilestone: entry.nextMilestone,
      repeatCount: entry.repeatCount,
      rescueMode: entry.rescueMode,
    });
    const filtered = entries.filter((item) => {
      const itemKey = stableMachineDigest({
        requestKey: item?.requestKey || null,
        executionMode: item?.executionMode || null,
        nextActionType: item?.nextActionType || null,
        nextMilestone: item?.nextMilestone || null,
        repeatCount: item?.repeatCount || null,
        rescueMode: item?.rescueMode || null,
      });
      return itemKey !== dedupeKey;
    });

    ensureDir(filePath);
    fs.writeFileSync(filePath, JSON.stringify({
      entries: [entry, ...filtered].slice(0, 40),
    }));
  }

  function shouldIncludePreviousContext({ routingContext = {}, useIndexedContext = true } = {}) {
    const taskType = String(routingContext?.taskType || '').trim();
    const hasExplicitTarget = Boolean(String(routingContext?.targetFile || '').trim());

    if (!hasExplicitTarget) {
      return true;
    }

    if (!useIndexedContext) {
      return true;
    }

    return taskType !== 'simple' && taskType !== 'trivial';
  }

  function hasRouteSummaryField(routeSummary, field) {
    return Boolean(
      routeSummary
      && typeof routeSummary === 'object'
      && Object.prototype.hasOwnProperty.call(routeSummary, field),
    );
  }

  function extractRouteLineSegment(line, label) {
    if (typeof line !== 'string' || !line.trim()) {
      return null;
    }

    const match = line.match(new RegExp(`(?:^|\\|\\s*)${label}=([^|]+)`, 'i'));
    return match ? `${label}=${String(match[1] || '').trim()}` : null;
  }

  function formatDisplayRouteSummary(routeSummary = null, routingContext = {}) {
    const line = String(routeSummary?.line ?? '').trim();
    const taskSegment = routingContext?.taskType
      ? `task=${routingContext.taskType}`
      : extractRouteLineSegment(line, 'task');
    const policySegment = routeSummary?.policyMode
      ? `policy=${routeSummary.policyMode}`
      : (
        hasRouteSummaryField(routeSummary, 'policyMode')
          ? null
          : extractRouteLineSegment(line, 'policy')
      );

    const segments = [
      taskSegment,
      extractRouteLineSegment(line, 'targets'),
      extractRouteLineSegment(line, 'tests'),
      extractRouteLineSegment(line, 'styles'),
      policySegment,
    ].filter(Boolean);

    return segments.join(' | ') || 'task=unknown';
  }

  function formatDisplayNextAction(routeSummary = null) {
    if (!routeSummary || typeof routeSummary !== 'object') {
      return '';
    }

    const nextActionCommand = String(routeSummary.nextActionCommand ?? '').trim();
    if (nextActionCommand) {
      return nextActionCommand;
    }

    const nextActionType = String(routeSummary.nextActionType ?? '').trim();
    if (!nextActionType || nextActionType === 'read-skill-instructions' || nextActionType === 'pull-indexed-context') {
      return '';
    }

    return nextActionType;
  }

  const DELEGATABLE_IMPLEMENTATION_SKILL_IDS = new Set([
    'delivery',
    'frontend',
    'frontend-vue',
    'backend-api',
    'postgres',
    'sql-optimization-patterns',
  ]);

  function compactRouteCacheState(sharedState = {}) {
    if (!sharedState || typeof sharedState !== 'object') {
      return sharedState;
    }

    const compactState = { ...sharedState };
    delete compactState.source;
    delete compactState.ts;
    return compactState;
  }

  const rawInput = process.env.INPUT || '';
  const projectRoot = process.env.PROJECT_ROOT || process.cwd();
  const statePath = process.env.STATE_FILE || path.join(projectRoot, '.claude', 'ukit', 'skill-router-state.json');
  const routeCachePath = path.join(projectRoot, '.claude', 'ukit', 'route-cache.json');
  const routeAuditPath = path.join(projectRoot, '.ukit', 'storage', 'cache', 'route-audit.json');
  const cacheUtilsPath = path.join(projectRoot, '.claude', 'ukit', 'index', 'cache-utils.mjs');
  const previous = readJson(statePath, {});
  const runtimeConfig = loadRuntimeConfig(projectRoot);

  let payload = {};
  try {
    payload = JSON.parse(rawInput || '{}');
  } catch {
    payload = {};
  }

  const promptText = extractPrompt(payload);
  const commandText = payload.tool_input?.command || payload.command || '';
  const filePath = normalizeRelativeFile(projectRoot, payload.tool_input?.file_path || payload.file_path || '');
  const { buildRouteSignalText } = await loadLanguageTools(projectRoot);
  const routeSignals = {
    promptRawText: String(promptText || '').toLowerCase(),
    promptNormalizedText: buildRouteSignalText(promptText),
    commandRawText: String(commandText || '').toLowerCase(),
    commandNormalizedText: buildRouteSignalText(commandText),
    fileText: String(filePath || '').toLowerCase(),
  };
  const intentMode = deriveIntentMode({
    promptText,
    commandText,
    targetFile: filePath,
  });

  const catalog = await loadRouteCatalog(projectRoot);

  const active = catalog
    .map((entry) => scoreSkillRouteEntry(entry, routeSignals))
    .filter((entry) => entry.score > 0 && existsSkill(projectRoot, entry.path))
    .filter((entry) => shouldKeepRouteEntryForIntent(entry, intentMode));

  const now = Date.now();
  const debounceMs = 10 * 60 * 1000;
  const previousTs = Number(previous?.ts || 0);

  if (active.length === 0) {
    const lastExplicitUserPromptText = promptText.trim()
      || previous?.routingContext?.lastExplicitUserPromptText
      || '';
    const routingContext = {
      promptText,
      lastExplicitUserPromptText,
      commandText,
      targetFile: filePath,
      contextIntent: '',
      taskType: '',
    };
    const previousContext = buildPreviousContextSnapshot({
      projectRoot,
      routingContext,
      config: runtimeConfig,
    });
    const fingerprint = buildRouteStateFingerprint({
      activeSkills: [],
      routingContext,
      previousContext,
      routeSummary: null,
    });

    if (
      previous?.fingerprint === fingerprint
      && !previous?.routeSummary
      && Array.isArray(previous?.activeSkills)
      && previous.activeSkills.length === 0
      && now - previousTs < debounceMs
    ) {
      process.exit(0);
    }

    ensureDir(statePath);
    fs.writeFileSync(statePath, JSON.stringify({
      fingerprint,
      ts: now,
      source: 'skill-router',
      activeSkills: [],
      routingContext: compactRoutingContext(routingContext),
      ...(previousContext ? { previousContext: compactPreviousContext(previousContext) } : {}),
    }));
    process.exit(0);
  }

  active.sort((a, b) => b.score - a.score || a.order - b.order);
  const selected = active.slice(0, 2);
  const selectedIds = selected.map((entry) => entry.id);
  const contextIntent = deriveContextIntent({
    promptText,
    commandText,
    targetFile: filePath,
    selectedIds,
  });
  const taskType = inferTaskType({
    promptText,
    commandText,
    selectedIds,
    buildRouteSignalText,
  });
  const executionScores = deriveExecutionScores({
    promptText,
    commandText,
    targetFile: filePath,
    intentMode,
    taskType,
  });
  const executionCandidates = buildExecutionModeCandidates({
    promptText,
    commandText,
    targetFile: filePath,
    intentMode,
    executionScores,
  });
  const executionMode = deriveExecutionMode({
    promptText,
    commandText,
    targetFile: filePath,
    intentMode,
    executionScores,
    executionCandidates,
  });
  const lastExplicitUserPromptText = promptText.trim()
    || previous?.routingContext?.lastExplicitUserPromptText
    || '';
  const routingContext = {
    promptText,
    lastExplicitUserPromptText,
    commandText,
    targetFile: filePath,
    contextIntent,
    taskType,
    intentMode,
    executionScores,
    executionCandidates,
    executionMode,
  };
  const useIndexedContext = shouldUseIndexedContext({
    activeSkills: selected,
    targetFile: filePath,
  });
  const previousContext = shouldIncludePreviousContext({
    routingContext,
    useIndexedContext,
  })
    ? buildPreviousContextSnapshot({
        projectRoot,
        routingContext,
        config: runtimeConfig,
      })
    : null;
  const indexGeneratedAtMs = useIndexedContext
    ? readIndexGeneratedAtMs(projectRoot)
    : null;
  const projectVerification = useIndexedContext
    ? readProjectVerificationFingerprint(projectRoot)
    : null;
  const requestKey = buildRouteRequestKey({
    commandNamespace: '.claude',
    indexGeneratedAtMs,
    projectFingerprint: projectVerification?.fingerprint || null,
    activeSkills: selected,
    routingContext,
    previousContextFingerprint: previousContext?.fingerprint || null,
  });
  let cacheUtils = null;
  if (fs.existsSync(cacheUtilsPath)) {
    try {
      cacheUtils = await import(pathToFileURL(cacheUtilsPath).href);
    } catch {
      cacheUtils = null;
    }
  }

  if (
    previous?.requestKey === requestKey
    && previous?.routeSummary
    && now - previousTs < debounceMs
  ) {
    process.exit(0);
  }

  const cachedRouteState = typeof cacheUtils?.readRecentCacheEntry === 'function'
    ? await cacheUtils.readRecentCacheEntry(routeCachePath, requestKey, {
        maxEntries: cacheUtils.DEFAULT_RECENT_CACHE_MAX_ENTRIES,
        touch: true,
      })
    : null;
  if (
    cachedRouteState?.requestKey === requestKey
    && cachedRouteState?.routeSummary
    && Array.isArray(cachedRouteState?.activeSkills)
  ) {
    const rescuedRouteSummary = cachedRouteState.routeSummary
      ? {
          ...cachedRouteState.routeSummary,
          continuationState: advanceContinuationState(
            cachedRouteState.routeSummary.continuationState || null,
            cachedRouteState.routeSummary.continuationState || null,
          ),
        }
      : null;
    if (rescuedRouteSummary) {
      applyRescueBiasToRouteSummary(rescuedRouteSummary);
    }
    const reusedState = {
      ...cachedRouteState,
      source: 'skill-router',
      ts: now,
      requestKey,
      routeSummary: rescuedRouteSummary,
    };
    reusedState.fingerprint = buildRouteStateFingerprint(reusedState);

    if (previous?.fingerprint === reusedState.fingerprint && now - previousTs < debounceMs) {
      process.exit(0);
    }

    ensureDir(statePath);
    fs.writeFileSync(statePath, JSON.stringify(reusedState));
    appendRouteAuditEntry(routeAuditPath, buildRouteAuditEntry({
      state: reusedState,
    }));

    process.stdout.write(`[ukit-skill-router] Read skills: ${getActiveSkillPaths(reusedState.activeSkills || []).join(', ')}\n`);
    process.stdout.write(`[ukit-skill-router] Route: ${formatDisplayRouteSummary(reusedState.routeSummary, reusedState.routingContext)}\n`);
    const reusedNextDisplay = formatDisplayNextAction(reusedState.routeSummary);
    if (reusedNextDisplay) {
      process.stdout.write(`[ukit-skill-router] Next: ${reusedNextDisplay}\n`);
    }
    if (reusedState.routeSummary?.delegateHint) {
      process.stdout.write(`[ukit-skill-router] Delegate: ${reusedState.routeSummary.delegateHint}\n`);
    }
    if (
      reusedState.routeSummary?.helperHint
      && !reusedState.routeSummary?.nextActionCommand
      && reusedState.routeSummary?.nextActionType !== 'pull-indexed-context'
    ) {
      process.stdout.write(`[ukit-skill-router] Helper: ${reusedState.routeSummary.helperHint}\n`);
    }
    process.exit(0);
  }

  const contextRecommendation = useIndexedContext
    ? await buildContextRecommendation({
        projectRoot,
        intent: contextIntent,
        targetFile: filePath,
        taskType,
      })
    : null;
  const verificationRecommendation = useIndexedContext
    ? buildVerificationRecommendation({
        projectRoot,
        selectedIds,
        contextRecommendation,
        contextIntent,
        targetFile: filePath,
        taskType,
        pkg: projectVerification?.pkg,
      })
    : null;
  const nextAction = deriveNextAction({
    activeSkills: selected,
    contextRecommendation,
    verificationRecommendation,
  });
    const routeSummary = buildRouteSummary({
      activeSkills: selected,
      routingContext,
      contextRecommendation,
      verificationRecommendation,
      nextAction,
    });
    routeSummary.continuationState = advanceContinuationState(
      routeSummary.continuationState,
      previous?.routeSummary?.continuationState || null,
    );
    applyRescueBiasToRouteSummary(routeSummary);

  const fingerprint = buildRouteStateFingerprint({
    activeSkills: selected,
    routingContext,
    previousContext,
    routeSummary,
  });

  if (previous?.fingerprint === fingerprint && now - previousTs < debounceMs) {
    process.exit(0);
  }

  ensureDir(statePath);
  const helpers = compactHelpers({
    verificationRecommendation,
    routeSummary,
  });
  const sharedState = {
    requestKey,
    fingerprint,
    ts: now,
    source: 'skill-router',
    activeSkills: compactActiveSkills(selected),
    routingContext: compactRoutingContext(routingContext),
    ...(previousContext ? { previousContext: compactPreviousContext(previousContext) } : {}),
    ...(helpers ? { helpers } : {}),
    routeSummary: compactRouteSummary(routeSummary),
  };
  fs.writeFileSync(statePath, JSON.stringify(sharedState));
  appendRouteAuditEntry(routeAuditPath, buildRouteAuditEntry({
    routingContext,
    routeSummary,
    state: sharedState,
  }));
  if (typeof cacheUtils?.writeRecentCacheEntry === 'function') {
    await cacheUtils.writeRecentCacheEntry(routeCachePath, compactRouteCacheState(sharedState), {
      maxEntries: cacheUtils.DEFAULT_RECENT_CACHE_MAX_ENTRIES,
    });
  }

  process.stdout.write(`[ukit-skill-router] Read skills: ${getActiveSkillPaths(selected).join(', ')}\n`);
  process.stdout.write(`[ukit-skill-router] Route: ${formatDisplayRouteSummary(routeSummary, routingContext)}\n`);
  const nextDisplay = formatDisplayNextAction(routeSummary);
  if (nextDisplay) {
    process.stdout.write(`[ukit-skill-router] Next: ${nextDisplay}\n`);
  }
  if (routeSummary.delegateHint) {
    process.stdout.write(`[ukit-skill-router] Delegate: ${routeSummary.delegateHint}\n`);
  }
    if (
      routeSummary.helperHint
      && !routeSummary.nextActionCommand
      && routeSummary.nextActionType !== 'pull-indexed-context'
    ) {
      process.stdout.write(`[ukit-skill-router] Helper: ${routeSummary.helperHint}\n`);
    }
})().catch(() => {
  process.exit(0);
});
NODE

if [ -f "$THRESHOLD_SCRIPT" ]; then
  printf '%s' "$INPUT" | CLAUDE_PROJECT_DIR="$PROJECT_ROOT" node "$THRESHOLD_SCRIPT" prompt 2>/dev/null || true
fi

exit 0
