---
# No checklists needed - document processing task with built-in validation via md-tree tool
tools:
  - github-cli
---

# Document Sharding Task

## Purpose

- Split a large document into multiple smaller documents based on level 2 sections
- Create a folder structure to organize the sharded documents
- Maintain all content integrity including code blocks, diagrams, and markdown formatting

## Primary Method: Automatic with markdown-tree

[[LLM: First, check if markdownExploder is set to true in .aiox-core/core-config.yaml. If it is, attempt to run the command: `md-tree explode {input file} {output path}`.

If the command succeeds, inform the user that the document has been sharded successfully and STOP - do not proceed further.

If the command fails (especially with an error indicating the command is not found or not available), inform the user: "The markdownExploder setting is enabled but the md-tree command is not available. Please either:

1. Install @kayvan/markdown-tree-parser globally with: `npm install -g @kayvan/markdown-tree-parser`
2. Or set markdownExploder to false in .aiox-core/core-config.yaml

**IMPORTANT: STOP HERE - do not proceed with manual sharding until one of the above actions is taken.**"

If markdownExploder is set to false, inform the user: "The markdownExploder setting is currently false. For better performance and reliability, you should:

1. Set markdownExploder to true in .aiox-core/core-config.yaml
2. Install @kayvan/markdown-tree-parser globally with: `npm install -g @kayvan/markdown-tree-parser`

I will now proceed with the manual sharding process."

Then proceed with the manual method below ONLY if markdownExploder is false.]]

### Installation and Usage

1. **Install globally**:

   ```bash
   npm install -g @kayvan/markdown-tree-parser
   ```

2. **Use the explode command**:

   ```bash
   # For PRD
   md-tree explode docs/prd.md docs/prd

   # For Architecture
   md-tree explode docs/architecture.md docs/architecture

   # For any document
   md-tree explode [source-document] [destination-folder]
   ```

3. **What it does**:
   - Automatically splits the document by level 2 sections
   - Creates properly named files
   - Adjusts heading levels appropriately
   - Handles all edge cases with code blocks and special markdown

If the user has @kayvan/markdown-tree-parser installed, use it and skip the manual process below.

---

## Execution Modes

**Choose your execution mode:**

### 1. YOLO Mode - Fast, Autonomous (0-1 prompts)
- Autonomous decision making with logging
- Minimal user interaction
- **Best for:** Simple, deterministic tasks

### 2. Interactive Mode - Balanced, Educational (5-10 prompts) **[DEFAULT]**
- Explicit decision checkpoints
- Educational explanations
- **Best for:** Learning, complex decisions

### 3. Pre-Flight Planning - Comprehensive Upfront Planning
- Task analysis phase (identify all ambiguities)
- Zero ambiguity execution
- **Best for:** Ambiguous requirements, critical work

**Parameter:** `mode` (optional, default: `interactive`)

---

## Task Definition (AIOX Task Format V1.0)

```yaml
task: shardDoc()
responsável: Morgan (Strategist)
responsavel_type: Agente
atomic_layer: Template

**Entrada:**
- campo: task
  tipo: string
  origem: User Input
  obrigatório: true
  validação: Must be registered task

- campo: parameters
  tipo: object
  origem: User Input
  obrigatório: false
  validação: Valid task parameters

- campo: mode
  tipo: string
  origem: User Input
  obrigatório: false
  validação: yolo|interactive|pre-flight

**Saída:**
- campo: execution_result
  tipo: object
  destino: Memory
  persistido: false

- campo: logs
  tipo: array
  destino: File (.ai/logs/*)
  persistido: true

- campo: state
  tipo: object
  destino: State management
  persistido: true
```

---

## Pre-Conditions

**Purpose:** Validate prerequisites BEFORE task execution (blocking)

**Checklist:**

```yaml
pre-conditions:
  - [ ] Task is registered; required parameters provided; dependencies met
    tipo: pre-condition
    blocker: true
    validação: |
      Check task is registered; required parameters provided; dependencies met
    error_message: "Pre-condition failed: Task is registered; required parameters provided; dependencies met"
```

---

## Post-Conditions

**Purpose:** Validate execution success AFTER task completes

**Checklist:**

```yaml
post-conditions:
  - [ ] Task completed; exit code 0; expected outputs created
    tipo: post-condition
    blocker: true
    validação: |
      Verify task completed; exit code 0; expected outputs created
    error_message: "Post-condition failed: Task completed; exit code 0; expected outputs created"
```

---

## Acceptance Criteria

**Purpose:** Definitive pass/fail criteria for task completion

**Checklist:**

```yaml
acceptance-criteria:
  - [ ] Task completed as expected; side effects documented
    tipo: acceptance-criterion
    blocker: true
    validação: |
      Assert task completed as expected; side effects documented
    error_message: "Acceptance criterion not met: Task completed as expected; side effects documented"
```

---

## Tools

**External/shared resources used by this task:**

- **Tool:** task-runner
  - **Purpose:** Task execution and orchestration
  - **Source:** .aiox-core/core/task-runner.js

- **Tool:** logger
  - **Purpose:** Execution logging and error tracking
  - **Source:** .aiox-core/utils/logger.js

---

## Scripts

**Agent-specific code for this task:**

- **Script:** execute-task.js
  - **Purpose:** Generic task execution wrapper
  - **Language:** JavaScript
  - **Location:** .aiox-core/scripts/execute-task.js

---

## Error Handling

**Strategy:** retry

**Common Errors:**

1. **Error:** Task Not Found
   - **Cause:** Specified task not registered in system
   - **Resolution:** Verify task name and registration
   - **Recovery:** List available tasks, suggest similar

2. **Error:** Invalid Parameters
   - **Cause:** Task parameters do not match expected schema
   - **Resolution:** Validate parameters against task definition
   - **Recovery:** Provide parameter template, reject execution

3. **Error:** Execution Timeout
   - **Cause:** Task exceeds maximum execution time
   - **Resolution:** Optimize task or increase timeout
   - **Recovery:** Kill task, cleanup resources, log state

---

## Performance

**Expected Metrics:**

```yaml
duration_expected: 3-8 min (estimated)
cost_estimated: $0.002-0.005
token_usage: ~1,500-5,000 tokens
```

**Optimization Notes:**
- Cache template compilation; minimize data transformations; lazy load resources

---

## Metadata

```yaml
story: N/A
version: 1.0.0
dependencies:
  - N/A
tags:
  - automation
  - workflow
updated_at: 2025-11-17
```

---


## Manual Method (if @kayvan/markdown-tree-parser is not available or user indicated manual method)

### Task Instructions

1. Identify Document and Target Location

- Determine which document to shard (user-provided path)
- Create a new folder under `docs/` with the same name as the document (without extension)
- Example: `docs/prd.md` → create folder `docs/prd/`

2. Parse and Extract Sections

CRITICAL AEGNT SHARDING RULES:

1. Read the entire document content
2. Identify all level 2 sections (## headings)
3. For each level 2 section:
   - Extract the section heading and ALL content until the next level 2 section
   - Include all subsections, code blocks, diagrams, lists, tables, etc.
   - Be extremely careful with:
     - Fenced code blocks (```) - ensure you capture the full block including closing backticks and account for potential misleading level 2's that are actually part of a fenced section example
     - Mermaid diagrams - preserve the complete diagram syntax
     - Nested markdown elements
     - Multi-line content that might contain ## inside code blocks

CRITICAL: Use proper parsing that understands markdown context. A ## inside a code block is NOT a section header.]]

### 3. Create Individual Files

For each extracted section:

#### CRITICAL: Filename Translation Rules (Portuguese → English)

**All filenames MUST be created in English, regardless of document language.**

**Common Portuguese → English Translations:**

```yaml
# Document Structure
índice: index
metadados: metadata
documento: document
seção: section

# Product/Business
visão: vision
produto: product
problema: problem
solução: solution
objetivos: objectives
metas: goals
stakeholders: stakeholders
premissas: assumptions
restrições: constraints
glossário: glossary
terminologia: terminology

# Requirements
requisitos: requirements
funcionalidades: features
características: characteristics
necessidades: needs

# Technical
arquitetura: architecture
tecnologia: technology
pilha: stack
pilha-tecnológica: tech-stack
padrões: standards
padrões-de-código: coding-standards
estrutura: structure
estrutura-do-projeto: project-structure
árvore-de-origem: source-tree
componentes: components

# Development
desenvolvimento: development
implementação: implementation
testes: tests
estratégia: strategy
estratégia-de-testes: testing-strategy
qualidade: quality
validação: validation

# Data & API
dados: data
banco-de-dados: database
esquema: schema
modelo: model
modelos-de-dados: data-models
api: api
design: design
especificação: specification
endpoints: endpoints

# Infrastructure
infraestrutura: infrastructure
pipeline: pipeline
implantação: deployment
monitoramento: monitoring
alertas: alerts

# Security & Performance
segurança: security
desempenho: performance
escalabilidade: scalability
confiabilidade: reliability
conformidade: compliance
disponibilidade: availability

# Risks & Planning
riscos: risks
técnicos: technical
negócio: business
cronograma: timeline
fases: phases
épicos: epics
histórias: stories
decisões: decisions

# NFRs
requisitos-não-funcionais: non-functional-requirements
nfrs: nfrs
```

**Filename Generation Algorithm:**

1. **Extract heading text**: Remove `##` and trim
2. **Translate Portuguese terms**:
   - Check if heading contains any Portuguese term from map above
   - Replace with English equivalent
   - For compound terms, translate each part (e.g., "Padrões de Código" → "Coding Standards")
3. **Normalize to lowercase-dash-case**:
   - Convert to lowercase
   - Replace spaces with dashes
   - Remove accents and special characters (á→a, ã→a, ç→c, etc.)
4. **Clean up**:
   - Remove consecutive dashes
   - Remove leading/trailing dashes

**Examples:**

```
Portuguese Heading              → Translation Process              → Final Filename
----------------------------------------------------------------------------------
## Visão do Produto            → Vision of Product                 → product-vision.md
## Pilha Tecnológica           → Tech Stack                        → tech-stack.md
## Padrões de Código           → Coding Standards                  → coding-standards.md
## Estrutura do Projeto        → Project Structure                 → project-structure.md
## Índice                      → Index                             → index.md
## Metadados do Documento      → Document Metadata                 → document-metadata.md
## Requisitos Funcionais       → Functional Requirements           → functional-requirements.md
## Estratégia de Testes        → Testing Strategy                  → testing-strategy.md
## Banco de Dados - Esquema    → Database Schema                   → database-schema.md
## API Design (tRPC)           → API Design (tRPC)                 → api-design-trpc.md
## Riscos Técnicos             → Technical Risks                   → technical-risks.md
```

**Special Cases:**

- **Numbers in headings**: Preserve (e.g., "1.1 Visão" → "product-vision.md", remove numbering)
- **Parentheses/brackets**: Keep in translation, then convert (e.g., "API (tRPC)" → "api-trpc.md")
- **Acronyms**: Keep as-is (API, RLS, CI/CD, NFR)
- **Mixed language**: If heading already has English terms, keep them (e.g., "Tech Stack Overview")

**If heading is not Portuguese:**
- Apply standard lowercase-dash-case conversion
- No translation needed

1. **Generate filename using translation rules above**:

   - **FIRST**: Check if document language appears to be Portuguese (look for accents, common PT words)
   - **IF Portuguese**: Apply translation from map above
   - **THEN**: Convert to lowercase-dash-case
   - Remove special characters and accents
   - Replace spaces with dashes
   - Example (English): "## Tech Stack" → `tech-stack.md`
   - Example (Portuguese): "## Pilha Tecnológica" → `tech-stack.md`

2. **Adjust heading levels**:

   - The level 2 heading becomes level 1 (# instead of ##) in the sharded new document
   - All subsection levels decrease by 1:

   ```txt
     - ### → ##
     - #### → ###
     - ##### → ####
     - etc.
   ```

3. **Write content**: Save the adjusted content to the new file

### 4. Create Index File

Create an `index.md` file in the sharded folder that:

1. Contains the original level 1 heading and any content before the first level 2 section
2. Lists all the sharded files with links:

```markdown
# Original Document Title

[Original introduction content if any]

## Sections

- [Section Name 1](./section-name-1.md)
- [Section Name 2](./section-name-2.md)
- [Section Name 3](./section-name-3.md)
  ...
```

### 5. Preserve Special Content

1. **Code blocks**: Must capture complete blocks including:

   ```language
   content
   ```

2. **Mermaid diagrams**: Preserve complete syntax:

   ```mermaid
   graph TD
   ...
   ```

3. **Tables**: Maintain proper markdown table formatting

4. **Lists**: Preserve indentation and nesting

5. **Inline code**: Preserve backticks

6. **Links and references**: Keep all markdown links intact

7. **Template markup**: If documents contain {{placeholders}} ,preserve exactly

### 6. Validation

After sharding:

1. Verify all sections were extracted
2. Check that no content was lost
3. Ensure heading levels were properly adjusted
4. Confirm all files were created successfully

### 7. Report Results

Provide a summary:

```text
Document sharded successfully:
- Source: [original document path]
- Destination: docs/[folder-name]/
- Files created: [count]
- Sections:
  - section-name-1.md: "Section Title 1"
  - section-name-2.md: "Section Title 2"
  ...
```

## Important Notes

- Never modify the actual content, only adjust heading levels
- Preserve ALL formatting, including whitespace where significant
- Handle edge cases like sections with code blocks containing ## symbols
- Ensure the sharding is reversible (could reconstruct the original from shards)
 