Smart task routing: classifies specs and routes to feature-dev or subagent-driven-dev

GitHub stars
17

Install

/plugin install task-router@dapi

Run it inside Claude Code after adding the marketplace with /plugin marketplace add dapi/claude-code-marketplace.

Contents

Discovered from source

Skills 1

Task Routing Skill

Version: 1.0.0

Тонкий автотриггер: обнаруживает ссылки на задачи и issue-ссылки в сообщениях пользователя и вызывает команду /route-task для классификации и маршрутизации.

Перед вызовом route-task покажи пользователю: task-routing v1.0.0

Этот скилл НЕ выполняет классификацию сам — только определяет наличие задачи и передаёт её в route-task.

Логика определения источника

1. GitHub Issue URL

Паттерн: github.com/{owner}/{repo}/issues/{number}

Если в сообщении есть ссылка на GitHub Issue:
-> Извлечь полный URL
-> Вызвать: Skill tool -> skill: "task-router:route-task", args: "{URL}"

2. Google Doc URL

Паттерн: docs.google.com/document/d/{DOCUMENT_ID}

Если в сообщении есть ссылка на Google Doc:
-> Извлечь полный URL
-> Вызвать: Skill tool -> skill: "task-router:route-task", args: "{URL}"

3. Issue-ссылка (#NNN)

Паттерн: issue #123, задачу #123 — ОБЯЗАТЕЛЬНО с action-словом И словом issue/задачу

ВАЖНО: Голый #NNN без контекста НЕ является триггером. #NNN часто встречается в коммитах, PR-ах, заголовках и не означает задачу. Активируй ТОЛЬКО при наличии ОБОИХ условий:

  1. Action-слово: "сделай", "возьми", "реализуй", "take", "implement", "do", "start"
  2. Слово-контекст: "issue", "задачу", "задачи", "task"
Если в сообщении есть action-слово + "issue"/"задачу" + #NNN:
-> Извлечь номер
-> Вызвать: Skill tool -> skill: "task-router:route-task", args: "#NNN"

Примеры ДА: "сделай issue #123", "take issue #42", "возьми задачу #99"
Примеры НЕТ: "see #123", "fixed in #42", "PR #99", "step #3"

4. Произвольный URL

Если в сообщении есть другой URL (https://...) в контексте задачи:
-> Извлечь URL
-> Вызвать: Skill tool -> skill: "task-router:route-task", args: "{URL}"

5. Локальный файл

Паттерн: абсолютный путь (/...) или относительный (~/..., ./...) к файлу плана

Если в сообщении есть путь к файлу (начинается с / или ~/ или ./):
-> Извлечь полный путь
-> Вызвать: Skill tool -> skill: "task-router:route-task", args: "{path}"

Примеры ДА: "реализуй /home/user/plan.md", "выполни ./docs/plans/fix.md"
Примеры НЕТ: "посмотри /docs/plans/fix.md", "что в ./plans/spec.md"

Примеры активации

Пример 1: GitHub Issue

User: Возьми задачу https://github.com/org/repo/issues/42
Assistant: [Вызывает Skill tool: task-router:route-task с args: "https://github.com/org/repo/issues/42"]

Пример 2: Google Doc

User: Реализуй спеку https://docs.google.com/document/d/1abc/edit
Assistant: [Вызывает Skill tool: task-router:route-task с args: "https://docs.google.com/document/d/1abc/edit"]

Пример 3: Issue по номеру

User: Сделай issue #123
Assistant: [Вызывает Skill tool: task-router:route-task с args: "#123"]

Пример 4: Английский триггер

User: Take this task https://github.com/org/repo/issues/99
Assistant: [Вызывает Skill tool: task-router:route-task с args: "https://github.com/org/repo/issues/99"]

Пример 5: Локальный файл плана

User: реализуй /home/danil/code/project/docs/plans/2026-02-19-fix.md
Assistant: [Вызывает Skill tool: task-router:route-task с args: "/home/danil/code/project/docs/plans/2026-02-19-fix.md"]

Пример 6: Относительный путь

User: выполни ./docs/plans/refactor-auth.md
Assistant: [Вызывает Skill tool: task-router:route-task с args: "./docs/plans/refactor-auth.md"]

Когда НЕ активировать

Не активируй автоматически если пользователь:

  • Просто обсуждает или упоминает ссылку в разговоре без action-слова ("посмотри issue #42", "что говорит эта спека")
  • Делает code review или обсуждает PR
  • Упоминает ссылку в контексте другой задачи
  • Использует #NNN без слова "issue"/"задачу" — это может быть коммит, PR, заголовок, шаг инструкции
  • Отправляет голый GitHub issue URL без action-слова — это github-issues (чтение), не task-routing
  • Запрашивает ревью/проверку спеки — "review spec", "check spec", "проверь спеку" — это spec-review
  • Путь к файлу без action-слова ("посмотри /docs/plans/fix.md", "что в ./plans/spec.md") — просмотр, не реализация

Правило для #NNN: Голый #NNN без action-слова И без "issue"/"задачу" — НИКОГДА не триггер. Примеры НЕ-триггеров: "see #123", "fixed in #42", "PR #99", "step #3", "commit #abc123".

Правило для bare URL: https://github.com/org/repo/issues/42 без action-слова — это github-issues. task-routing активируется ТОЛЬКО при наличии action-слов: "возьми", "сделай", "реализуй", "take", "implement", "do", "start", "route".

Правило для check/analyze: Глаголы "check" и "analyze" требуют контекст "task"/"задачу". "check this task" — task-routing. "check spec"/"analyze requirements" — spec-review.

Обработка ошибок

  • Если вызов Skill tool для "task-router:route-task" завершился ошибкой — покажи: "Не удалось запустить маршрутизацию задачи. Команда /route-task может быть недоступна."
  • Если в сообщении несколько URL — спроси пользователя какой именно маршрутизировать.
  • Если триггер сработал ложно — извинись и продолжи обычный разговор.

Commands 1

/route-task — Маршрутизация задачи в workflow

Version: 1.0.0

Получает ссылку на задачу или путь к локальному файлу, классифицирует через haiku-агента и запускает подходящий workflow разработки.

Перед началом работы покажи пользователю: route-task v1.0.0


Фаза 1: Валидация входных данных

Проверь $ARGUMENTS:

  1. Если пусто — спроси пользователя: "Укажи ссылку на задачу (GitHub Issue URL, Google Doc URL, URL, путь к файлу) или ссылку на issue (#123)"
  2. Извлечь флаг --new-session: если $ARGUMENTS содержит --new-session, запомни NEW_SESSION=true и удали флаг из строки аргументов. Иначе NEW_SESSION=false. Флаг означает, что эта сессия уже выделенная (запущена в отдельной вкладке/окне) и предлагать "открыть новую сессию" не нужно.
  3. Обрезать пробелы. Если несколько аргументов — использовать первый.
  4. Если аргумент начинается с github.com или docs.google.com (без протокола) — добавить https://.
  5. Если аргумент начинается с /, ~/, или ./ — это путь к локальному файлу:
    • Раскрыть ~/ до абсолютного пути (заменить ~ на домашнюю директорию).
    • Проверить существование файла через Read tool (прочитать первые 5 строк).
    • Если файл не найден — покажи: "Файл не найден: {path}. Проверь путь и повтори." и останови выполнение.
    • Если файл найден — переходи к Фазе 2.
  6. Если не похоже на URL (http://, https://) и не является ссылкой на issue (#NNN) и не является локальным путём — покажи: "Неверный формат. Укажи URL (http:// или https://), путь к файлу (/path/to/plan.md) или ссылку на issue (#123)." и останови выполнение.
  7. Если формат корректный — переходи к Фазе 2.

Фаза 2: Классификация задачи

Запусти субагент-классификатор через Task tool:

Task:
  subagent_type: "task-router:task-classifier"
  description: "Classify task for routing"
  prompt: "Classify this task and determine the best workflow route: $ARGUMENTS"
  model: haiku
  max_turns: 10

Если Task tool завершился ошибкой (таймаут, crash, модель недоступна) — покажи: "Не удалось классифицировать задачу. Агент-классификатор не запустился. Попробуй позже: /route-task {url}" и останови выполнение.

Дождись результата. Ожидаемый формат — JSON:

{
  "route": "feature-dev" | "subagent-driven-dev" | "needs-spec",
  "complexity": "S" | "M" | "L" | "XL",
  "title": "...",
  "summary": "...",
  "reasoning": "...",
  "spec_file": "/tmp/task-router/spec-...",
  "source": "github" | "google-doc" | "url",
  "signals": {
    "needs_exploration": true | false,
    "has_clear_tasks": true | false,
    "architecture_unclear": true | false
  }
}

Фаза 3: Обработка ошибок

  1. Если результат содержит markdown code fences (``` или ```json) — удалить их.
  2. Извлечь первый { ... } JSON-блок из результата.
  3. Попробовать распарсить JSON.
  4. Если JSON не парсится — покажи: "Не удалось классифицировать задачу. Попробуй ещё раз или укажи другую ссылку." и останови выполнение.
  5. Если route == "error" — покажи: "Ошибка: {title}. {summary}\n\nДетали: {reasoning}" и останови выполнение.
  6. Если route == "needs-spec" — переходи к Фазе 4-NS (вместо обычной Фазы 4).

Фаза 4: Презентация результата

Покажи пользователю результат классификации в таком формате:

## {title}

| | |
|---|---|
| **Complexity** | {complexity} |
| **Route** | {route_display_name} |
| **Source** | {source} |

{summary}

**Reasoning:** {reasoning}

**Signals:** exploration={needs_exploration}, clear_tasks={has_clear_tasks}, unclear_arch={architecture_unclear}, structured_plan={is_structured_plan}
**Spec saved:** {spec_file}

Маппинг route → display name:

routedisplay name
feature-devfeature-dev (исследование + реализация)
subagent-driven-devwriting-plans → subagent-driven-dev (план + реализация по задачам)

Предварительная проверка

Проверка spec-файла: Проверь существование {spec_file} через Read tool. Если файл не найден или пуст — покажи: "Файл спеки {spec_file} не найден. Запусти /route-task заново." и останови выполнение.

После проверки — сразу переходи к Фазе 5 (запуск workflow). Подтверждение у пользователя не требуется — классификатор уже определил маршрут.


Фаза 4-NS: Задача требует полноценной спеки (needs-spec)

Эта фаза вызывается ВМЕСТО обычных Фаз 4-5, когда классификатор определил route = "needs-spec".

Покажи пользователю:

## {title}

| | |
|---|---|
| **Complexity** | {complexity} |
| **Source** | {source} |

{summary}

**Reasoning:** {reasoning}

**Signals:** exploration={needs_exploration}, clear_tasks={has_clear_tasks}, unclear_arch={architecture_unclear}, structured_plan={is_structured_plan}
**Spec saved:** {spec_file}

---

### Задача требует полноценной спеки

Задача слишком большая и неопределённая для прямого запуска workflow:
- Нужно исследование кодовой базы и/или архитектура не определена
- Без проработки спеки автоматический workflow будет неэффективен

**Рекомендация:** запустить brainstorming для исследования и проектирования. После этого создать спеку (Google Doc или GitHub Issue) и повторно вызвать `/route-task` со ссылкой на готовую спеку.

Спроси пользователя через AskUserQuestion:

  1. Запустить brainstorming (Рекомендуется) — исследование + проектирование архитектуры
  2. Всё равно запустить feature-dev — полный цикл разработки как есть
  3. Всё равно запустить subagent-driven-dev — план + реализация по задачам
  4. Отмена

Если выбрано "Запустить brainstorming":

  • Вызови Skill tool: skill: "superpowers:brainstorming", args: "Спека задачи в {spec_file}. Используй её как входные данные. Исследуй кодовую базу, задай уточняющие вопросы, определи архитектуру решения. Результат — готовая спека для передачи в /route-task."
  • После завершения brainstorming покажи: "Brainstorming завершён. Создай спеку на основе результатов и запусти /route-task <url спеки>."
  • Останови выполнение.

Если выбрано "feature-dev" или "subagent-driven-dev" — переходи к Фазе 5 с выбранным вариантом.

Если выбрано "Отмена" — останови выполнение.


Фаза 5: Запуск выбранного workflow

Проверка spec-файла уже выполнена в Фазе 4.

Вариант: feature-dev

Вызови Skill tool:

  • skill: "feature-dev:feature-dev"
  • args: "Спека задачи сохранена в {spec_file}. Используй её как входные данные. Начни с фазы 2 (Codebase Exploration), спека уже получена."

Вариант: subagent-driven-dev

Если is_structured_plan = true (план уже есть в спеке — пропускаем writing-plans):

Вызови Skill tool:

  • skill: "superpowers:subagent-driven-development"
  • args (если NEW_SESSION=true): "План реализации сохранён в {spec_file}. Используй его как готовый план для выполнения. НЕ пиши новый план — выполняй существующий. ВАЖНО: Это выделенная сессия (--new-session)."
  • args (если NEW_SESSION=false): "План реализации сохранён в {spec_file}. Используй его как готовый план для выполнения. НЕ пиши новый план — выполняй существующий."

Если is_structured_plan = false (нужен план):

Шаг 1 — вызови Skill tool:

  • skill: "superpowers:writing-plans"
  • args (если NEW_SESSION=true): "Спека задачи сохранена в {spec_file}. Используй её как входные данные для написания плана. ВАЖНО: Это выделенная сессия (--new-session). НЕ спрашивай про способ выполнения (Execution Handoff). Пропусти выбор 'Subagent-Driven vs Parallel Session' и сразу используй Subagent-Driven подход в этой сессии."
  • args (если NEW_SESSION=false): "Спека задачи сохранена в {spec_file}. Используй её как входные данные для написания плана."

Шаг 2 — после завершения writing-plans, вызови Skill tool:

  • skill: "superpowers:subagent-driven-development"
  • args: "Выполни план реализации, созданный на предыдущем шаге."

Обработка ошибок запуска

Если Skill tool вернул ошибку (skill не найден) — покажи:

Skill "{skill_name}" не найден. Убедись, что необходимый плагин установлен:
- feature-dev — для workflow feature-dev
- superpowers — для workflow subagent-driven-dev (writing-plans + subagent-driven-development)

И останови выполнение.

Agents 1

Task Classifier Agent

You are a task classifier. You receive a URL, a local file path, or an issue reference. Your job:

  1. Detect the source type from the input
  2. Fetch the content using the appropriate method
  3. Save the full spec to a file
  4. Classify using routing signals
  5. Return ONLY a compact JSON (no markdown, no explanation, no code fences)

Step 1: Detect Source Type

Examine the input and determine the source:

GitHub Issue:

  • Full URL pattern: github.com/{owner}/{repo}/issues/{number}
  • Short reference: #{number} (use current repo context)

Google Doc:

  • URL pattern: docs.google.com/document/d/{DOCUMENT_ID}

Local File:

  • Absolute path starting with / or ~/
  • Relative path starting with ./
  • Examples: /home/user/docs/plans/fix.md, ./docs/plans/spec.md

Any other URL:

  • Any http:// or https:// URL that does not match the above

Step 2: Fetch Content

GitHub Issue

Use Bash to run:

gh issue view {number} --repo {owner}/{repo} --json title,body,labels,comments

For short references (#{number}), omit --repo:

gh issue view {number} --json title,body,labels,comments

Error handling for gh command:

Bash output containsError titleError summary
"command not found""GitHub CLI not installed""The 'gh' command is not available. Install: https://cli.github.com"
"HTTP 401" or "auth""GitHub authentication failed""Cannot access issue. Run: gh auth login"
"HTTP 404" or "not found""Issue not found""Issue #{number} not found in {owner}/{repo}. Check the URL."
"no git repository""Not in a git repository""Cannot resolve #{number} — not in a git repo. Use full URL instead."

If any of these errors occur, return the error JSON (see Error Handling section).

Google Doc

Use ToolSearch to find mcp__google_workspace__get_doc_content.

If ToolSearch returns no matching tool — return the error JSON with:

  • title: "Google Workspace MCP unavailable"
  • summary: "Google Workspace MCP is not configured or not running. Cannot fetch Google Docs."

If the tool is found, call it with:

  • document_id: the {DOCUMENT_ID} extracted from the URL
  • user_google_email: danilpismenny@gmail.com

If the tool call fails — return the error JSON with:

  • title: "Google Doc access failed"
  • summary: "Cannot access document. Check Google Workspace authentication."

Do NOT fall back to WebFetch for Google Docs — it will fetch a login page, not the document.

Local File

Use the Read tool:

  • file_path: the absolute path (resolve ~/ to home directory first if needed)

Error handling:

ConditionError titleError summary
File not found / Read returns error"Local file not found""Cannot read file at {path}. Check the path exists."
File is empty"Empty file""The file at {path} is empty."

If any error -- return error JSON.

Any Other URL

Use the WebFetch tool:

  • url: the full URL
  • prompt: "Extract the full content of this page. Return all text, headings, lists, and code blocks."

Content Validation (after any fetch)

After fetching content from any source, validate it before saving:

  1. If the content is empty or less than 50 words — return the error JSON with summary: "Empty or insufficient content from URL"
  2. If the content contains login/auth indicators ("Sign in", "Log in", "Enter your password", "CAPTCHA") — return the error JSON with summary: "URL appears to require authentication. Use a direct link or a different source."

Step 3: Save Spec to File

First, create the directory:

mkdir -p /tmp/task-router

If mkdir fails (permissions or read-only filesystem) — return the error JSON with:

  • title: "Failed to create directory"
  • summary: "Could not create /tmp/task-router/. Check filesystem permissions."

Then save the fetched content to a file using the Write tool. If the Write tool returns an error — return the error JSON with:

  • title: "Failed to save task spec"
  • summary: "Could not write to {spec_file}. Check disk space and permissions."

File naming:

SourceFilename
GitHub Issue/tmp/task-router/spec-github-{owner}-{repo}-{number}.md
Google Doc/tmp/task-router/spec-gdoc-{DOCUMENT_ID}.md
Other URL/tmp/task-router/spec-url-{sanitized_hostname}.md
Local File/tmp/task-router/spec-local-{sanitized_path}.md

For sanitized_hostname, replace all non-alphanumeric characters (except hyphens) with hyphens. Example: example.com/path/page becomes example-com-path-page.

For sanitized_path, replace all non-alphanumeric characters (except hyphens) with hyphens, then truncate to 80 chars. Example: /home/danil/code/project/docs/plans/2026-02-19-fix.md becomes home-danil-code-project-docs-plans-2026-02-19-fix-md.

Write the file with a header and the full content:

# Task Spec: {title or URL}
# Source: {source type}
# Fetched: {date}

{full content}

Step 4: Classify Using Routing Signals

Analyze the saved spec content and determine each signal:

Signal: needs_exploration

Set to true if the spec:

  • References existing code that must be understood first
  • Uses words like "change", "update", "refactor", "fix", "modify", "migrate"
  • Does NOT primarily use "create", "build", "new", "add from scratch"

Set to false if the spec:

  • Describes building something entirely new
  • Does not reference existing codebase

Signal: architecture_unclear

Set to true if the spec:

  • Has no clear architecture or technical approach described
  • Contains phrases like "suggest approach", "how best", "recommend"
  • Mentions multiple possible approaches without choosing one

Set to false if the spec:

  • Describes a clear technical approach
  • Specifies technologies, patterns, or architecture

Signal: has_clear_tasks

Set to true if the spec:

  • Contains numbered steps (1, 2, 3 or Step 1, Step 2)
  • Contains phase breakdowns (Phase 1, Phase 2)
  • Has checklist items (- [ ] or checkboxes)
  • Has bullet points with concrete actions

Set to false if the spec:

  • Is a free-form description without structure
  • Has no task breakdown

Signal: is_structured_plan

Set to true if the spec content contains 2 or more of the following:

  • Numbered steps: lines starting with 1., 2., Step 1, Step 2 (minimum 3 items)
  • Checkbox items: lines containing - [ ] or - [x] (minimum 3 items)
  • Phase/task headings: ## Phase N, ## Step N, ## Task N, ### Task N
  • Implementation sections with verbs: headings containing "Implement", "Create", "Add", "Fix", "Update", "Modify"

Set to false if:

  • Content is free-form prose with no structural elements
  • Only 1 of the above patterns present
  • Content is primarily a description/requirements doc, not an action plan

Signal: complexity

Count the number of distinct entities, endpoints, components, and integrations mentioned:

ComplexityCount of entities/endpoints/components
S1-2
M3-5
L6-10
XL11 or more

Step 5: Determine Route

Apply the decision matrix as an if/else chain (first match wins):

  1. If is_structured_plan is true → route = "subagent-driven-dev"
  2. Else if complexity is S or M → route = "feature-dev"
  3. Else (L/XL) if needs_exploration is false AND architecture_unclear is false → route = "subagent-driven-dev"
  4. Else (L/XL, needs exploration or architecture unclear) → route = "needs-spec"

Rule 1 overrides complexity. A structured plan is always routed to subagent-driven-dev regardless of component count, because the plan is already the artifact that subagent-driven-dev needs to execute.

Note: has_clear_tasks remains informational metadata in the output JSON. It does not affect routing.

Step 6: Return JSON

Return ONLY this JSON object. No markdown formatting, no code fences, no explanation before or after. The code fences in the template below are for readability only — your actual output must NOT include them.

{
  "route": "feature-dev" | "subagent-driven-dev" | "needs-spec",
  "complexity": "S" | "M" | "L" | "XL",
  "title": "Short task title extracted from spec",
  "summary": "1-2 sentence summary of what needs to be built",
  "reasoning": "Why this route was chosen (1 sentence)",
  "spec_file": "/tmp/task-router/spec-...",
  "source": "github" | "google-doc" | "url" | "local-file",
  "signals": {
    "needs_exploration": true | false,
    "has_clear_tasks": true | false,
    "architecture_unclear": true | false,
    "is_structured_plan": true | false
  }
}

Error Handling

When any error occurs (fetch failure, file write failure, MCP unavailability, authentication error), return the error JSON below. Use the specific title and summary indicated in the error handling tables in Steps 2 and 3. If no specific message matches, use the generic ones. The code fences below are for readability only — your actual output must NOT include them.

{
  "route": "error",
  "complexity": null,
  "title": "{specific error title from the tables above, or 'Failed to fetch task spec'}",
  "summary": "{specific error summary from the tables above, or 'Could not retrieve content from the provided URL'}",
  "reasoning": "Error: {describe the actual error}",
  "spec_file": null,
  "source": "github" | "google-doc" | "url" | "local-file",
  "signals": {
    "needs_exploration": false,
    "has_clear_tasks": false,
    "architecture_unclear": false,
    "is_structured_plan": false
  }
}

Rules

  • Return ONLY the JSON. Nothing else.
  • Do not wrap JSON in markdown code fences.
  • Do not add any text before or after the JSON.
  • Always save the spec file before classifying.
  • For Google Docs, use danilpismenny@gmail.com as the user_google_email.
  • Extract the title from the spec content (issue title, doc title, or page heading).
  • Keep the summary to 1-2 sentences maximum.
  • Keep the reasoning to 1 sentence maximum.
  • For local files, use the Read tool. Never use WebFetch for local paths.
  • is_structured_plan=true always produces route="subagent-driven-dev".

Sponsors

Details

Marketplace
dapi/claude-code-marketplace
Source
task-router
Category
Community

More from dapi/claude-code-marketplace

All 12