# Specs Kit Spec To Tasks

> Provides capability to convert functional specifications into executable and trackable tasks. Use when needing to transform a spec from /skill:specs-kit-brainstorm into a task list. Output: docs/specs/[id]/YYYY-MM-DD-feature-name--tasks.md, data-model.md, contracts/, and individual task files

- Skill: `giuseppe-trisciuoglio/specs-kit-spec-to-tasks` (Agent Skill, multi-file: 4 files)
- Install (CLI): `npx skillmds@latest add giuseppe-trisciuoglio/specs-kit-spec-to-tasks`
- Raw SKILL.md: https://api.skillmd.com/api/skills/giuseppe-trisciuoglio/specs-kit-spec-to-tasks/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: giuseppe-trisciuoglio (https://skillmd.com/u/giuseppe-trisciuoglio)
- Updated: 2026-09-17
- Page: https://skillmd.com/skills/giuseppe-trisciuoglio/specs-kit-spec-to-tasks

---


# Specification to Tasks

Converts a functional specification into a list of executable, trackable tasks. This is the bridge between WHAT (specification) and HOW (implementation).

## Overview

This command reads a functional specification generated by `/skill:specs-kit-brainstorm` and converts it into atomic, executable tasks.

**Input**: `docs/specs/[id]/YYYY-MM-DD--feature-name.md`
**Output**:
- Task list: `docs/specs/[id]/YYYY-MM-DD--feature-name--tasks.md`
- Data model: `docs/specs/[id]/data-model.md`
- Contracts: `docs/specs/[id]/contracts/*`
- Individual tasks: `docs/specs/[id]/tasks/TASK-XXX.md`

### Task Structure

Each task includes:
- **Title**: Descriptive name for the task
- **Description**: Functional description of what to implement
- **Acceptance Criteria**: Testable conditions for completion
- **Dependencies**: Other tasks that must complete first (if any)
- **Implementation Command**: Pre-filled command to execute this task

### Workflow Position

```
Idea → Functional Specification → Architecture & Ontology Definition → Tasks → Implementation → Review → Code Cleanup → Done
              (brainstorm)         (this: Phase 1.5)                   (this)   (task-implementation)  (task-review)   (code-cleanup)
```

### Task Count Limit

**CRITICAL**: If task decomposition produces **more than 15 implementation tasks**, the specification is too large for a single implementation cycle and MUST be rejected:

1. **Detect oversized spec**: After Phase 4 (Task Decomposition), count implementation tasks (excluding documentation and cleanup tasks)
2. **If > 15 tasks**:
   - STOP task generation immediately
   - Inform the user with this message:

   ```
   Specification Too Large

   This specification would generate X implementation tasks, which exceeds the maximum of 15.
   The scope is too large for a single implementation cycle.

   Recommended action:
   1. Return to /skill:specs-kit-brainstorm
   2. Split your idea into 2 or more smaller, focused specifications
   3. Run /skill:specs-kit-spec-to-tasks for each specification separately

   Example split strategy:
   - Spec Part 1: Core functionality (must-have for initial release)
   - Spec Part 2: Extended features (phase 2 or nice-to-have)
   - Spec Part 3: Additional capabilities (future iterations)

   This ensures each specification has a clear functional scope and manageable implementation scope.
   ```

   - Use **ask_user_question** to offer options:
     - Options:
       - "Return to /skill:specs-kit-brainstorm to split this idea" (recommended)
       - "Continue anyway with this large specification" (not recommended - proceed at user risk)
   - If user chooses "Return to brainstorm": abort task generation and suggest running `/skill:specs-kit-brainstorm` with the split idea
   - If user chooses "Continue anyway": proceed with warning logged in summary

3. **If <= 15 tasks**: Proceed normally with task generation

## Usage

```bash
# Basic usage - specify spec file or folder
/skill:specs-kit-spec-to-tasks docs/specs/001-hotel-search-aggregation/
/skill:specs-kit-spec-to-tasks docs/specs/001-hotel-search-aggregation/2026-03-07--hotel-search-aggregation.md
```

## Arguments

| Argument | Required | Description |
|----------|----------|-------------|
| `--spec` | No | Path to spec folder (e.g., `docs/specs/001-feature-name/`) |
| `--kg-only` | No | Only refresh the codebase graph, skip task generation |

## Examples

### Basic Usage

```bash
/skill:specs-kit-spec-to-tasks docs/specs/001-feature/
```

### KG-Only Mode

```bash
/skill:specs-kit-spec-to-tasks docs/specs/001-feature/ --kg-only
```

## Inputs

Determine the target specification from the invocation context:
- when invoked directly, the spec folder (`--spec=`) arrives as a skill argument;
- otherwise infer the spec folder from the current working directory.

Resolve, in order:
- `spec` → the spec folder path (required); if not provided, ask the user
- `--kg-only` → restrict to codebase graph refresh when set

If no spec folder can be determined, stop and inform the user.

---

You are converting a functional specification into executable tasks. Follow a systematic approach: analyze requirements, identify dependencies, generate atomic tasks, and create a trackable task list.

## Core Principles

- **Atomic tasks**: Each task should be implementable in a single focused effort
- **Clear dependencies**: Explicitly state which tasks depend on others
- **Testable criteria**: Each task must have clear acceptance criteria
- **Technical detail**: Tasks include technical context from codebase analysis
- **Codebase-aware**: Tasks reference existing patterns, APIs, and structures in the project
- **Use a checklist**: Track all progress throughout
- **No time estimates**: DO NOT provide or request time estimates
- **Test instructions**: **Each task MUST include explicit and detailed instructions on what to test, specifying test types (unit, integration) and behaviors to verify, NEVER including test code.**
- **Mandatory final tasks**: Every spec MUST end with (1) a documentation task and (2) a code cleanup task
- **Spec size limit**: If > 15 implementation tasks, reject and recommend returning to brainstorm

---

## Phase 1: Specification Analysis

**Goal**: Read and understand the functional specification

**Input**: the skill arguments (spec file or folder path)

**Actions**:

1. Create todo list with all phases
2. Parse the skill arguments to extract:
   - `spec-path` (path to spec file or folder)
3. Determine the spec folder:
   - If a file path is provided: use its parent directory and that file as the specification
   - If a folder path is provided: use the folder directly
   - Resolve the specification file with this priority:
     1. `YYYY-MM-DD--feature-name.md`
     2. the only dated spec-like markdown file in the folder excluding `--tasks.md`, `decision-log.md`, `traceability-matrix.md`, `user-request.md`, and `brainstorming-notes.md`
4. Read the resolved functional specification file
5. **CRITICAL: Look for user context files in the spec folder**:
   - Search for these specific files that contain the original user request:
     - `user-request.md` - Original user request (from brainstorming - **PRIMARY**)
     - `brainstorming-notes.md` - Notes from brainstorming session (**SECONDARY**)
   - Read these files and incorporate their content into your analysis
   - These files are created by the brainstorming command and contain critical context
6. Extract the spec ID from folder name (e.g., `001-hotel-search-aggregation`)
7. Verify the specification exists and is valid
8. If file not found:
   - First auto-detect from the folder using the rules above
   - Only ask the user if multiple plausible spec files exist or none can be resolved

9. **Quality Pre-Check (Soft Gate)**:
   - Check for section `## Clarifications` in the spec file (added by spec-check)
   - Search for vague terms: grep for "suitable|efficient|robust|fast|intuitive"
   - If Clarifications section is missing AND vague terms are found:
     - Warning: "Spec not reviewed. Vague terms detected: [list terms found]"
     - Ask via ask_user_question:
       - Options:
         - "Continue anyway" (proceed at user risk)
         - "Run spec-check first" (recommended: `/skill:specs-kit-spec-check docs/specs/[id]/`)
   - If Clarifications section exists OR no vague terms found: proceed without warning

---

## Phase 1.5: Architecture & Ontology Definition

**Goal**: Ensure the project-level architecture and ontology documents exist and are consistent before generating tasks. This phase bridges the gap between WHAT (functional specification) and HOW (technical tasks).

**Context**: The architecture and ontology documents live at the `docs/specs/` level (shared across all specifications):
- `docs/specs/architecture.md` — Formalizes technological and infrastructural choices
- `docs/specs/ontology.md` — Establishes common domain language (Ubiquitous Language)

### Step 1: Architecture Definition (`docs/specs/architecture.md`)

1. **Check if `docs/specs/architecture.md` exists**:

   - **If the file does NOT exist**:
     1. Inform the user: "No project architecture document found. Before generating tasks, we need to define the project architecture."
     2. Use **ask_user_question** to gather architecture information through targeted questions:

        **Question 1 — Software Stack**:
        ```
        What is the primary technology stack for this project?
        ```
        - Options:
          - "Java / Spring Boot"
          - "TypeScript / NestJS"
          - "TypeScript / React"
          - "Python / Django or FastAPI"
          - "PHP / Laravel or Symfony"
          - Freeform: allow custom answer

        **Question 2 — Data Architecture**:
        ```
        What database and data management approach does the project use?
        ```
        - Options:
          - "PostgreSQL (relational)"
          - "MySQL (relational)"
          - "MongoDB (document-based)"
          - "Multiple databases (polyglot persistence)"
          - Freeform: allow custom answer

        **Question 3 — Infrastructure**:
        ```
        What hosting and infrastructure approach is used?
        ```
        - Options:
          - "AWS (EC2, ECS, Lambda, etc.)"
          - "Docker / Docker Compose (local or self-hosted)"
          - "Kubernetes"
          - "Serverless (AWS Lambda, GCP Cloud Functions)"
          - "Not yet decided"
          - Freeform: allow custom answer

     3. Create `docs/specs/architecture.md` using the gathered information:
        - Read the architecture template using this lookup order: `templates/architecture.md`, then `templates/architecture.md` inside the installed skill folder for non-Claude agents
        - Fill the gathered answers into the placeholder sections of the template
        - Set `**Created**` and `**Last Updated**` to the current date
        - Write the result to `docs/specs/architecture.md`

        The template defines these sections:
        | # | Section | Source Question |
        |---|---------|----------------|
        | 1 | Logical Architecture | Gather from user or leave as scaffold |
        | 2 | Infrastructure Architecture | Question 3 above |
        | 3 | Software Architecture | Questions 1 & 2 above |
        | 4 | Security Constraints | Default template values |
        | 5 | AI Guardrails | Default template values |

     4. Log the creation and present to the user for final confirmation

   - **If the file ALREADY exists**:
     1. Read `docs/specs/architecture.md`
     2. Load the architecture context into memory for use in task generation (Phase 4)
     3. Briefly summarize what was loaded:
        ```
        Loaded project architecture:
        - Logical Architecture: [bounded contexts summary]
        - Infrastructure: [hosting/scaling summary]
        - Stack: [detected from the codebase]
        - Database: [database]
        ```

### Step 2: Ontology Definition (`docs/specs/ontology.md`)

1. **Check if `docs/specs/ontology.md` exists**:

   - **If the file does NOT exist**:
     1. Extract domain terms from the specification loaded in Phase 1
     2. Use **ask_user_question** to present identified terms and gather additional ones:
        ```
        I identified the following domain terms from the specification:
        - [Term 1]: [proposed definition]
        - [Term 2]: [proposed definition]
        - ...

        Should I create the project ontology with these terms? You can also add or adjust terms.
        ```
        - Options:
          - "Yes, create with these terms" (recommended)
          - "Yes, but let me adjust the terms first"
          - "Skip ontology creation for now"
     3. If confirmed, create `docs/specs/ontology.md`:
        ```markdown
        # Project Ontology — Ubiquitous Language

        **Created**: [current date YYYY-MM-DD]
        **Last Updated**: [current date YYYY-MM-DD]

        ## Domain Glossary

        | Term | Definition | Bounded Context |
        |------|-----------|-----------------|
        | [Term 1] | [Definition] | [Context where this term applies] |
        | [Term 2] | [Definition] | [Context where this term applies] |

        ## Bounded Contexts

        | Context | Description | Key Terms |
        |---------|-------------|-----------|
        | [Context 1] | [Description of this bounded context] | [Key terms] |

        ## Conceptual Mapping

        [Relationships between key domain entities]
        ```

   - **If the file ALREADY exists**:
     1. Read `docs/specs/ontology.md`
     2. Load the ontology context into memory for use in task generation
     3. Extract domain terms from the current specification
     4. Compare against existing glossary entries
     5. If NEW terms are identified:
        - Append them to the Domain Glossary table
        - Update the `Last Updated` date
        - Inform the user of the additions
     6. If no new terms: continue silently

### Step 3: Context Summary

After both documents are processed, produce a brief summary:

```
Architecture & Ontology Context:
- Architecture: [loaded/created] — [stack summary]
- Ontology: [loaded/created/skipped] — [N terms in glossary]
- Both documents will inform task generation in Phase 4.
```

---

## Phase 2: Requirement Extraction

**Goal**: Extract and organize requirements from the specification

**Actions**:

1. Analyze the specification for:
   - User stories and use cases
   - Business rules
   - Acceptance criteria
   - Integration requirements

2. **CRITICAL: Include technical requirements from context files**:
   - Review user-request.md and brainstorming-notes.md found in Phase 1
   - Extract technical details that were provided during brainstorming:
     - Architecture patterns (message queues, caching, async processing)
     - Specific technologies mentioned (Redis, RabbitMQ, specific databases)
     - Integration patterns and external services
     - Any implementation hints or technical constraints
   - These technical requirements must be reflected in the task decomposition
   - Example: If context mentions "RabbitMQ queues", there must be tasks for queue configuration and consumers

3. Group related requirements:
   - Identify naturally atomic units of work
   - Note dependencies between requirements
   - Prioritize based on dependencies (what can be done first)

4. **CRITICAL: Verify against original user request**:
   - Using the `user-request.md` content already read in Phase 1
   - Compare the extracted requirements against the original user request
   - Identify any requirements that are mentioned in the original request but NOT captured in the specification
   - If discrepancies found, use ask_user_question to present them to the user:
     - "I found requirements from your original request that may not be in the specification:"
       - [list missing requirements]
     - Options:
       - "Add missing requirements to task list" (recommended)
       - "Regenerate specification to include them"
       - "Continue with current specification"

5. Present the extracted requirements structure (including technical requirements) to user for confirmation

6. **Assign unique REQ-IDs to each extracted requirement**:
   - For each requirement identified (from user stories, business rules, acceptance criteria), assign a unique identifier: REQ-001, REQ-002, etc.
   - Document REQ-IDs in a requirements list for later traceability:
     ```
     REQ-001: [User story / requirement text]
     REQ-002: [Business rule / requirement text]
     REQ-003: [Acceptance criterion / requirement text]
     ...
     ```
   - These REQ-IDs will be used in the Traceability Matrix to map requirements → tasks → tests → code

---

## Phase 2.5: Check/Load Codebase Graph

**Goal**: Load the codebase graph produced by graphify, if it exists and is fresh

**Prerequisite**: Requires the spec folder path

**Actions**:

1. **Check for the codebase graph**:
   - Look for `graphify-out/graph.json` in the project root
   - If it does not exist, run `/graphify <project-root>` once to materialise it (this is the single graph the rest of the workflow reads), then proceed
   - If graphify is not installed, skip to Phase 3 (in-session Codebase Analysis) and note that the graph is unavailable

2. **If the graph exists**:
   - Read its `updated_at` timestamp
   - Calculate age: `current_time - updated_at`
   - Load and summarize key findings:
     - Count of patterns discovered
     - Count of components (controllers, services, repositories)
     - Count of APIs (internal/external)
     - Technology stack identified

3. **Present summary to user**:
   ```
   Found codebase graph from X days ago:
   - Y architectural patterns (Repository, Service Layer, etc.)
   - Z components (N controllers, M services, K repositories)
   - Q API endpoints documented
   - Technology stack: [framework] [version]

   The graph is [fresh/getting stale/old].
   ```

4. **Choose reuse strategy automatically unless the case is borderline**:
   - If the graph is < 7 days old: use it automatically
   - If the graph is > 30 days old: re-run `/graphify <project-root> --update` automatically
   - If the graph is 7-30 days old: ask user via ask_user_question whether to reuse or refresh

5. **Based on the chosen strategy**:
   - **Use cached**: Load the graph into context, skip Phase 3, proceed to Phase 4
   - **Refresh**: Re-run `/graphify <project-root> --update`, then load it and proceed to Phase 4 (Phase 3 is only for the in-session exploration the graph cannot replace)

6. **If using the cached graph**:
   - Read patterns, components and APIs directly from `graphify-out/graph.json`
   - Store results in context for Phase 4 (Task Decomposition)
   - Note: "Proceeding with the codebase graph from X days ago"

The graph is project-wide by construction (graphify indexes the whole codebase),
so there is no separate "global" graph to load — `graphify-out/graph.json` already
 covers project-level patterns and conventions.

---

## Phase 3: Codebase Analysis

**Goal**: Understand existing codebase to generate technically accurate tasks

**Prerequisite**: Requires the spec folder path

**Actions**:

1. Explore the codebase yourself (there is no subagent dispatch; do it in this session). Detect the stack from the project's manifest files (`package.json`, `pom.xml`/`build.gradle`, `composer.json`, `pyproject.toml`/`requirements.txt`, `go.mod`, etc.) and adapt the focus below to what you find:

```
Explore the codebase to understand:

1. **Project Structure**:
   - Main directories and their purpose
   - Configuration files and build tooling
   - Entry points and main modules

2. **Existing Patterns**:
   - Data models/schemas and persistence approach (ORM, raw queries, migrations)
   - API patterns (REST, GraphQL, RPC) and their conventions
   - Authentication/authorization patterns
   - Error handling and logging conventions

3. **Technology Stack**:
   - Frameworks and libraries in use (detected from manifests/lock files)
   - Database systems and external service integrations
   - Build, test and deployment tooling

4. **Integration Points**:
   - Existing APIs the new feature must integrate with
   - Shared utilities, helpers or common components
   - Configuration management

5. **Code Organization & Testing**:
   - Layering and module boundaries
   - Dependency injection / composition patterns
   - Test directory structure, framework and conventions

Provide a summary that will inform task generation with the detected stack's specific context.
```

2. Collect and synthesize the codebase analysis
3. Document key findings that will influence task generation:
   - Existing patterns to follow
   - APIs to integrate with
   - Shared components to use
   - Conventions to respect

---

## Phase 3.5: Specification Artifact Generation

**Goal**: Always derive stable specification artifacts before task generation

**Prerequisite**: Phase 2 (Requirement Extraction) must have completed. Phase 3 findings may be used only to align naming with the existing codebase.

**Actions**:

1. **Generate `data-model.md` from the specification**:
   - Create/update `docs/specs/[id]/data-model.md`
   - Use the resolved specification, `user-request.md`, and `brainstorming-notes.md` as the source of truth
   - Incorporate canonical terminology from `docs/specs/ontology.md` when available
   - Capture:
     - Core entities, value objects, and aggregates
     - Relationships and cardinality
     - Lifecycle/state transitions if relevant
     - Business invariants and validation rules
     - Persistence or integration notes explicitly stated in the specification

2. **Create/update the `contracts/` directory**:
   - Ensure `docs/specs/[id]/contracts/` exists
   - Extract every explicit interface or integration boundary described by the specification
   - Create one contract artifact per boundary using the most appropriate format:
     - HTTP/API boundary: `[name].openapi.yaml`
     - Async event/message boundary: `[name].event.md`
     - Internal service/UI boundary without a formal schema: `[name].md`

3. **Populate each contract artifact with implementation-neutral details**:
   - Required inputs and outputs
   - Validation rules and required fields
   - Success responses or emitted events
   - Error cases and failure modes
   - Versioning or backward-compatibility notes if stated in the spec

4. **Handle specs without explicit external contracts**:
   - Still create `docs/specs/[id]/contracts/`
   - Add `contracts/README.md` summarizing why no standalone interface contract files were extracted yet
   - Document any implicit boundaries that tasks must preserve

5. **ARTIFACT FIDELITY GATE (prevents Over-Specification Drift)**:
   - Before proceeding to Phase 4, verify that every entity, field, and relationship in `data-model.md` can be traced back to the functional specification
   - For each element in `data-model.md`, ask: "Is this explicitly required by the spec, or is it my technical interpretation?"
   - **If an element is NOT derivable from the spec**: 
     - Mark it with `(derived)` in the data-model.md
     - Do NOT create acceptance criteria around it in task files
     - It may appear in "Technical Context" as an implementation suggestion, never as a requirement
   - Example: `WorktreeState` struct is NOT in the spec — it is a derived implementation detail. It must be marked `(derived)` and never appear as "WorktreeState must be defined" in any task's AC.

6. **Treat artifacts as advisory inputs for task generation**:
   - Phase 4 and Phase 5 may read `data-model.md` and `contracts/*` for context
   - Tasks must use these artifacts ONLY to inform implementation choices, NEVER as source of truth for acceptance criteria
   - The **functional specification** (with its `[IMP]`/`[SEF]`/`[EXT]` taxonomy) is the ONLY source of truth for acceptance criteria
   - **Critical distinction**: If `data-model.md` defines `WorktreeManager` but the spec does NOT mention it, the task cannot have "WorktreeManager interface must be defined" as an AC. The task AC must reflect the spec's language (e.g., "Worktree can be created via CLI command").

7. **Do NOT update agent context files in this phase**:
   - Do not call `/skill:specs-kit-spec-sync-context`
   - Do not create or modify `graphify-out/graph.json` (graphify owns it)
   - Do not rewrite task files or any other context cache as part of artifact generation

8. **Log and report**:
   ```
   Specification artifacts generated:
   - Data model: docs/specs/[ID]/data-model.md
   - Contracts directory: docs/specs/[ID]/contracts/
   - Contract files: [list generated files]
   - Fidelity Gate: [N] elements from spec, [M] elements derived (marked)
   ```

**Note**: This phase always runs, even when the cached codebase graph is reused in Phase 2.5.

---

## Phase 4: Technical Task Decomposition

**Goal**: Break down `[IMP]` requirements into atomic, executable tasks. Respect bounded context boundaries and avoid over-specification.

**CRITICAL: Spec Fidelity Gate** — Before decomposing tasks, verify:
1. The functional specification contains acceptance criteria tagged with `[IMP]`, `[SEF]`, or `[EXT]`
2. If tags are MISSING: apply taxonomy retroactively based on the spec's content, then proceed
3. If the spec has a "Bounded Context Impact Statement" (Section 6): load it and use it for boundary validation
4. If the spec has NO `[IMP]` criteria: STOP — the spec is purely descriptive. Return to brainstorming.

**Actions**:

1. **Filter requirements by taxonomy — ONLY `[IMP]` criteria generate implementation tasks**:
   - Read the functional specification's acceptance criteria
   - Select ONLY criteria tagged `[IMP]` (Implementable) for task decomposition
   - **`[SEF]` criteria**: Do NOT generate standalone tasks. They will be verified in the documentation task (TASK-N-1).
   - **`[EXT]` criteria**: Do NOT generate standalone tasks. They will be listed as checkpoints in the documentation task.
   - Example: If AC-5 (`git worktree list` shows worktree) is `[SEF]`, it does NOT get a task. It is a natural side effect of using `git worktree add`, which is covered by AC-1's task.
   - **Why this matters**: Creating tasks for `[SEF]` criteria produces "false work" — tasks that verify natural behavior rather than implement functionality. In spec 025, AC-5 (`git worktree list`) and AC-2 (second run reuses) are `[SEF]` and should not generate dedicated tasks.

1.1. **If codebase graph context is available** (from Phase 2.5 cached only):
   - Review KG patterns: Architectural patterns to follow in each task
   - Review KG components: Existing components to reuse or integrate with
   - Review KG APIs: Internal/external APIs relevant to tasks
   - Review KG conventions: Naming, testing, and coding standards
   - Use KG context to enrich "Technical Context" section of each task
   - Example: "Follow existing Repository Pattern - extend JpaRepository"
   - Example: "Integrate with existing HotelService.searchHotels() method"

1.2. **BOUNDED CONTEXT BOUNDARY CHECK (prevents Boundary Confusion Drift)**:
   - Load `docs/specs/ontology.md` and extract the bounded context definitions
   - Load the spec's "Bounded Context Impact Statement" (Section 6) if present
   - For each task, before assigning file targets, determine the bounded context of each file
   - **If a task targets files in a bounded context DIFFERENT from the feature's primary context**:
     - Flag the task as `CROSS-BOUNDARY`
     - Add a warning in the task's Technical Context:
       ```
       ⚠️ BOUNDARY CROSSING: This task modifies [file] which belongs to [bounded context].
       Primary context of this feature: [primary context].
       Justification required: Why is this modification in [bounded context] necessary?
       Recommended: Coordinate with [bounded context] owner or consider if the change belongs there.
       ```
     - Example: TASK-005 modifies `cmd/specs-kit/task_run.go` (Core Engine) for a Git Worktree feature. This is a HIGH RISK cross-boundary modification and must be flagged.
   - **If Architecture context is available** (from Phase 1.5):
     - Use the technology stack to inform implementation details in each task
     - Ensure tasks reference the correct frameworks, libraries, and patterns from `docs/specs/architecture.md`
     - **Framework version migration notes**: when the framework version detected in the codebase
       is a major release (e.g. Spring Boot 4.x, React 19, Angular 18), include any known
       migration impacts in the task's Technical Context under the `Framework & Version` bullet:
       relocated packages, renamed annotations, new required dependencies, deprecated APIs the
       task might reference. Draw these from the agent's own training knowledge — the goal is to
       save the implementation agent from a compile-error → web-search → fix cycle.
     - If tasks require new infrastructure components not in the architecture document, flag them
       for ADR tracking using the `adr-drafting` skill

1.3. **EXTERNAL DEPENDENCY PRE-FLIGHT (prevents Dependency Blindness)**:
   - Before generating a task that depends on an external interface (e.g., "ADR-038 BranchCreator", "existing API", "third-party service"):
     - Verify that the interface exists in the codebase OR is documented in a contract
     - If the interface does NOT exist:
       - Mark the task as `EXTERNAL_DEPENDENCY_RISK`
       - Add a warning in the task's Technical Context:
         ```
         ⚠️ EXTERNAL DEPENDENCY: This task depends on [interface] which was not found in the codebase.
         Risk: If [interface] does not exist or has a different signature, this task may fail at contract validation (T-3.6).
         Mitigation: Verify [interface] exists before implementing this task, or implement it first.
         ```
     - Example: TASK-007 depends on `BranchCreator.EnsureBranch(specID, specName)` from ADR-038. If ADR-038 is not yet implemented, this task must be flagged.

1.5. **AGENT-EXECUTABILITY GATE (prevents tasks no agent can close)**:
   - For every candidate task, each acceptance criterion and each Definition of Done item must be
     satisfiable by an agent working in the repository — by writing a file, running a command, or
     asserting a test.
   - If any item requires an account, a credential, a signature, a purchase, a human decision or
     access the agent does not have, **the task is not emitted**. There is no tag that makes such a
     task runnable: a title carrying `[PROCUREMENT]` or `[MANUAL]` is the signal that the task
     should not have been generated at all.
   - The underlying need does not disappear, it moves out of the loop's reach:
     - record it in the `## Preconditions (operator)` section of the tasks document, one line per
       action a person must have completed before the run starts;
     - the agent-executable residue of that work, if any, becomes an ordinary task — "author the ADR
       recording the chosen provider and its verification" is a good task; "put the credential in the
       vault" is not, and belongs in the preconditions;
     - a task that consumes a precondition states its resolution in its DoR, exactly as it does for a
       task dependency.
   - Why this matters: the implementation cannot satisfy such a criterion, the review is right to
     reject it every time, and the retries spend the task's whole spawn allowance before the run
     stops on it — taking every task after it with it. A task file that carries operator-only work is
     also refused at load, before a single agent session is spent.

1.4. **If Ontology context is available** (from Phase 1.5):
   - Use domain terms from `docs/specs/ontology.md` consistently in task titles, descriptions, and acceptance criteria
   - Ensure task descriptions use the canonical term from the glossary (avoid synonyms not defined in the ontology)
   - If a task introduces NEW domain concepts not in the ontology, add them to `docs/specs/ontology.md` and update the `Last Updated` date
   - Example: If ontology defines "Reservation" (not "Booking"), use "Reservation" in all task descriptions

2. For each requirement group, create one or more tasks:
   - Each task should be implementable in 1-2 hours max
   - Tasks should have clear, testable completion criteria
   - Avoid tasks that span multiple user stories

2. For each task, define:
   - **Title**: Concise, descriptive name (e.g., "User login functionality")
   - **Description**: What the task covers functionally — must map to one or more `[IMP]` acceptance criteria
   - **AC-ID Mapping**: List the acceptance criteria IDs this task implements (e.g., AC-1, AC-3)
   - **REQ-ID Mapping**: List the requirement IDs this task covers (e.g., REQ-001)
   - **Acceptance Criteria**: 2-4 testable conditions derived ONLY from `[IMP]` spec criteria
   - **Definition of Ready (DoR)**: Clear preconditions for starting (dependencies complete, technical context understood, blockers resolved)
   - **Definition of Done (DoD)**: Clear completion conditions covering implementation, tests, and task handoff
   - **Dependencies**: List task IDs this depends on (if any)
   - **Cross-Boundary**: YES/NO — whether this task modifies files outside the feature's primary bounded context
   - **External Dependency Risk**: YES/NO — whether this task depends on an unverified external interface
   - **Agent-Executable**: every AC and DoD item is satisfiable by an agent (see 1.5). A task that is
     not agent-executable is not emitted: its operator half goes to `## Preconditions (operator)` and
     its agent half, if any, becomes an ordinary task

3. Map dependencies explicitly:
   - Identify which tasks must complete before others can start
   - **CRITICAL: List ALL dependencies explicitly for each task BEFORE generating files**
   - For each task, document: "This task depends on: [TASK-ID-1, TASK-ID-2] (or 'None')"
   - Identify potential circular dependencies (Task A depends on B, B depends on A)
   - Order tasks accordingly

4. **FILE COLLISION DETECTION (prevents File Collision Drift)**:
   - Before generating files, build a file-to-task mapping:
   ```
   File: pkg/domain/worktree.go
     - TASK-001: creates WorktreeState
     - TASK-003: creates WorktreeManager interface
     → ⚠️ COLLISION: Two tasks create/modify the same file
   
   File: cmd/specs-kit/task_run.go
     - TASK-005: adds cleanup call
     - TASK-006: adds preserve-on-failure logic
     → ⚠️ COLLISION: Two tasks modify the same file
   ```
   - **If collisions are detected**:
     - Merge the colliding tasks into a SINGLE task with combined acceptance criteria
     - OR split the file responsibilities so each task targets a different file
     - Add a note in the merged task explaining the collision and the merge decision
   - **For new files**: If two tasks create the same file, merge them.
   - **For existing files**: If two tasks modify the same file, merge them OR split by having one task create a hook/extension point and the other use it.

5. Validate dependencies before generating files:
   - Present the dependency structure in a clear table format:

   | Task ID | Title | Dependencies | Cross-Boundary? | Ext. Dependency Risk? |
   |---------|-------|--------------|-----------------|----------------------|
   | TASK-001 | [Title] | None | No | No |
   | TASK-002 | [Title] | TASK-001 | No | Yes — ADR-038 |
   | TASK-003 | [Title] | TASK-001 | **YES** — Core Engine | No |
   | ... | ... | ... | ... | ... |

   - If there are circular dependencies, high coupling, or unclear ordering, use ask_user_question to confirm a fix
   - **If cross-boundary tasks exist without justification**: warn and ask for confirmation
   - Otherwise proceed directly and include the dependency table in the generated summary

5. **Identify Test Requirements for Each Task**:
    For each identified task, you must now precisely and mandatorily define what needs to be tested. This analysis will guide the generation of the "Test Instructions" section in the task file.

    - **Analyze involved classes/components**: For each file that the task will create or modify, determine its complexity level and testing importance.
        - **High Priority (Mandatory Tests)**: Classes with business logic, state management, validation rules, complex calculations, algorithms, interactions with external services (API, database). Examples: Service, UseCase, Controller/Handler, Validator, complex Entities.
        - **Medium Priority (Recommended Tests)**: Utility classes, helpers, simple data transformers, repositories (if not auto-generated).
        - **Low Priority (Optional Tests)**: Simple DTOs, POCOs, configurations.

    - **Define behaviors to test**: For each high-priority component, list specific test scenarios. Do not generate code, but describe the behavior.
        - **Unit Tests**: Verify the behavior of a single unit in isolation.
            - *Example (user registration task)*: "Test that the `register(userData)` method in `UserService` calls `UserRepository.save()` only if the email is unique and valid."
            - *Example (price calculation task)*: "Test that the `calculateTotal(price, tax, discount)` function returns the correct value for valid inputs, for zero taxes, and for maximum discounts."
        - **Integration Tests**: Verify the interaction between multiple components (e.g., controller, service, database).
            - *Example (user registration task)*: "Test that a POST request to the `/api/register` endpoint with valid data saves a new user in the database and returns status 201."
            - *Example (payment integration task)*: "Test that the complete 'checkout' flow correctly calls the mock payment gateway and handles a success response."

    - **Suggest test files to create**: For each source file requiring tests, indicate the corresponding test file according to language conventions.
        - Java: `UserService.java` → `UserServiceTest.java`
        - TypeScript/NestJS: `user.service.ts` → `user.service.spec.ts`
        - Python: `user_service.py` → `test_user_service.py`

    - **Link Tests to Acceptance Criteria**: Ensure that for each functional acceptance criterion, there is at least one test scenario that verifies it. This step is critical for guaranteeing traceability.

    **5.1 TEST INSTRUCTIONS FIDELITY CHECK (prevents Self-Referential Test Drift)**:
    - After generating test instructions, validate each test scenario against the functional specification:
      - Ask: "Is this behavior explicitly mentioned in the spec's acceptance criteria or business rules?"
      - **If YES**: Keep the test scenario
      - **If NO — the scenario is a 'best practice' or 'common edge case'**: 
        - Remove it from the task's test instructions
        - Instead, add it to the documentation task (TASK-N-1) as a "Supplemental Verification" — a nice-to-have check, not a blocking requirement
    - **Banned test scenarios** (unless explicitly in the spec):
      - Network errors for local filesystem operations (e.g., git worktree)
      - Mocking requirements for external tools unless the spec requires testability
      - Performance tests unless the spec defines performance criteria
      - Concurrency/race condition tests unless the spec mentions concurrent access
    - **Example from spec 025**: 
      - "Network error during branch creation" → REMOVE (git worktree is local filesystem)
      - "Tests use mocking for git commands" → REMOVE (not a spec requirement)
      - "Git is not available on system" → KEEP only if spec explicitly mentions it (AC-3 in 025 does)

6. Present task structure to the user only if major restructuring, optional tasks, or scope gaps were detected. Otherwise generate the files directly and summarize the resulting plan.

7. **CRITICAL: Add Mandatory Final Tasks** — After generating all implementation tasks, ALWAYS add these two final tasks:

   **TASK-N-1: Documentation Task** (where N is the next task number)
   - **Title**: "Documentation for [Feature Name]"
   - **Description**: Produce comprehensive documentation for the implemented feature
   - **Dependencies**: ALL previous implementation tasks (TASK-001 through TASK-N-2)
   - **Purpose**: Ensure the feature is properly documented for users, agents, and developers
   - **Documentation artifacts to produce**:
     - **README**: Feature-level README covering overview, usage examples, configuration, and troubleshooting
     - **AGENTS**: Update or create AGENTS.md files for any agents that interact with or operate this feature
     - **Technical Notes**: Developer-facing documentation covering architecture decisions, API contracts, integration patterns, and operational runbooks
   - **Files to Create/Update**:
     - `docs/specs/[id]/README.md` — Feature README wi

…(truncated)
