---
name: step-00-init
description: Initialize Business Analysis - Parse flags, route use case, create feature.json
next_step: steps/step-01-cadrage.md
---

# Step 00: Initialize Business Analysis

Initialize the business analysis workflow by parsing input flags, routing to the appropriate use case handler, and creating the initial feature.json structure.

## Flow

1. Parse command flags and determine use case
2. Route to specialized handler (question, refactoring, micro, or new feature)
3. MCP health check (non-blocking)
4. Interactive mode (if enabled)
5. Validate business context
6. Determine application and module
7. Select language
8. Generate feature ID
9. Create output directory structure
10. Create initial feature.json
11. Update config
12. Display summary
13. Load next step

## Step 1: Parse Command Flags

Parse all command-line arguments to determine execution mode and routing.

### Default Values
```yaml
auto_mode: false
economy_mode: false
context: business
question_mode: false
refactor_mode: false
micro_mode: false
interactive_mode: false
application_mode: false    # Multi-module application analysis
```

### Flag Parsing Rules

| Flag | Long Form | Effect | Argument |
|------|-----------|--------|----------|
| `-a` | `--auto` | Enable auto mode | none |
| `-e` | `--economy` | Enable economy mode | none |
| `-A` | `--no-auto` | Disable auto mode | none |
| `-E` | `--no-economy` | Disable economy mode | none |
| `-q` | `--question` | Question mode | next arg = FEAT-ID, remaining = question text |
| `-r` | `--refactor` | Refactoring mode | next arg = FEAT-ID, remaining = change description |
| `-m` | `--micro` | Micro feature mode | none |
| `-i` | `--interactive` | Interactive mode | none |
| `-app` | `--application` | Application mode: multi-module analysis | none |

**Remaining arguments after flag removal = feature_description**

### Set Use Case
```
IF question_mode = true:
  use_case = "question"
ELSE IF refactor_mode = true:
  use_case = "refactoring"
ELSE IF micro_mode = true:
  use_case = "micro"
ELSE:
  use_case = "new"
```

## Step 2: Use Case Routing

Route execution based on the detected use case.

### Question Mode (-q)
```
1. Parse: question_mode = true, feat_id = first remaining arg, question_text = rest
2. Call ba-reader agent:
   - ba-reader.findFeatureByID(feat_id)
   - Retrieve existing feature.json
3. Call ba-reader.answerQuestion(feat_id, question_text)
   - Answer question from context
4. Display answer in user session
5. EXIT - no further steps
```

**Example:**
```
ba -q FEAT-001 "What are the main actors in this feature?"
```

### Refactoring Mode (-r)
```
1. Parse: refactor_mode = true, feat_id = first remaining arg, change_description = rest
2. Call ba-reader agent:
   - ba-reader.findFeatureByID(feat_id)
   - Load existing feature.json
3. Call ba-writer agent:
   - ba-writer.createVersion(feat_id, change_description)
   - Increment version (e.g., 1.0 -> 1.1)
   - Mark changeReason
4. Set use_case = "refactoring"
5. Set version = new version number
6. Set feature_id from loaded feature
7. Continue to Step 5 (context validation)
8. Continue to Step 9 (create output structure at new version)
9. Load step-01-analyse in delta mode (compare old vs new)
```

**Example:**
```
ba -r FEAT-001 "Add support for multi-language feature names"
```

### Micro Feature Mode (-m)
```
1. Set use_case = "micro"
2. Set feature_type = "micro"
3. Continue to standard init flow (Steps 5-9)
4. Load step-01-analyse in micro mode (simplified analysis)
```

**Example:**
```
ba -m "Add email notification on approval"
```

### Default Mode (New Feature)
```
1. Set use_case = "new"
2. Continue to standard init flow (Steps 5-9)
3. Load step-01-analyse in full mode
```

**Example:**
```
ba "Create order management system"
```

## Step 2B: Application Mode Detection

**IF `-app` flag is set:**
- Set `{workflow_mode}` = "application"
- Set `{use_case}` = "application"

**ELSE IF no explicit mode flag:**
- Analyze `{feature_description}` for multi-module signals:
  - Keywords: "application", "system", "platform", "suite", "complet", "ensemble"
  - Multiple module mentions (3+ distinct functional areas)
  - Scope description spanning multiple domains
- IF multi-module signals detected:
  ```
  AskUserQuestion:
    question: "Votre description semble couvrir plusieurs modules. Voulez-vous une analyse multi-module (application complète) ?"
    header: "Mode"
    options:
      - label: "Oui, analyse application"
        description: "Identifier les modules, les analyser un par un avec validation client"
      - label: "Non, module unique"
        description: "Traiter comme un seul module"
  ```
- IF user confirms multi-module: Set `{workflow_mode}` = "application"
- ELSE: Set `{workflow_mode}` = "module"

## Step 3: MCP Prerequisite Check (BLOCKING)

Verify MCP availability. **This check is BLOCKING** - the skill cannot proceed without MCP.

> See `_shared.md` → "MCP Prerequisite Guard (BLOCKING)" for the full pattern.

**Detection:** Call MCP with minimal parameters:

```
mcp__smartstack__validate_conventions({ checks: ["tables"] })
```

**Decision matrix:**

| Result | Action |
|--------|--------|
| Success response | Set `mcp_available = true`, continue to Step 4 |
| Connection error / tool not found | **STOP EXECUTION** - display error below |

**On success:**
- Set `mcp_available = true`
- Update `.claude/mcp-status.json` cache
- Continue workflow

**On failure (STOP):**

```
═══════════════════════════════════════════════════════════════
  MCP SMARTSTACK NOT AVAILABLE - SKILL BLOCKED
═══════════════════════════════════════════════════════════════

  The SmartStack MCP server is required for business-analyse
  but could not be reached.

  To install:
    claude mcp add smartstack -- npx --package @atlashub/smartstack-cli smartstack-mcp

  To verify:
    /mcp:healthcheck

  After installation, restart Claude Code and retry.

═══════════════════════════════════════════════════════════════
```

**DO NOT** offer fallback modes, economy mode workarounds, or degraded execution.
**DO NOT** continue to Step 4 or any subsequent step.
**STOP the skill immediately.**

## Step 4: Interactive Mode

If `-i` or `--interactive` flag is set, prompt for confirmation.

**Prompt:**
```
Confirm initialization with:
- Use Case: {use_case}
- Application: {application_name}
- Module: {module_name}
- Auto Mode: {auto_mode}
- Economy Mode: {economy_mode}

Continue? (y/n)
```

If 'n', EXIT.

## Step 5: Validate Business Context

Verify that the business context is properly configured.

**Check:**
1. Does `.business-analyse/config.json` exist?
2. Does it contain `businessContext` section?
3. Are required fields present?

**If missing:**
1. Create fresh config with defaults
2. Prompt for business context (only in interactive mode)
3. Save to `.business-analyse/config.json`

**Required config structure:**
```json
{
  "businessContext": {
    "organization": "string",
    "domain": "string",
    "language": "string"
  }
}
```

## Step 6: Determine Application and Module

Scan for existing applications and modules.

**Scan order:**
1. Primary: `docs/business/` (modern structure)
   - List subdirectories = applications
   - Inside each app, list subdirectories = modules
2. Fallback: `.business-analyse/business/` (legacy)
   - Same structure as above

**Logic:**
```
IF auto_mode = true:
  application_name = first found app OR "default"
  module_name = first found module OR "default"
ELSE (interactive):
  Prompt: "Select application: [list]"
  Prompt: "Select module: [list]"
  OR: "Create new application: {name}"
  OR: "Create new module: {name}"
```

**Store:**
```yaml
application_name: string
module_name: string
```

## Step 7: Select Language

Determine the language for analysis and code generation.

**Check config:**
- Retrieve `businessContext.language` from config
- Default: "en" (English)

**If interactive:**
```
Select language:
[ ] English (en)
[ ] French (fr)
[ ] Spanish (es)
[ ] Custom: {input}
```

**Store:**
```yaml
language: string (code, e.g., "en", "fr")
```

## Step 8: Generate Feature ID

Create a unique feature identifier.

**Logic:**
```
IF use_case = "question" OR "refactoring":
  feature_id = use provided feat_id (already parsed)
ELSE:
  feature_id = generate using pattern: FEAT-{timestamp-based}-{random}
  OR: FEAT-{app-short}-{seq-number}
  Example: FEAT-001, FEAT-002, ...
```

**Store:**
```yaml
feature_id: string
```

## Step 9: Create Output Directory Structure

Create the directory hierarchy for feature documentation.

**For new features / micro / refactoring:**
```
docs/business/{application_name}/{module_name}/business-analyse/v{version}/
```

**Where version:**
- New feature: "1.0"
- Refactoring: from ba-writer (e.g., "1.1", "1.2")
- Micro: "1.0"

**Create directories:**
```bash
mkdir -p docs/business/{app}/{module}/business-analyse/v{version}
```

**Store:**
```yaml
docs_dir: "docs/business/{app}/{module}/business-analyse/v{version}"
output_dir: same as docs_dir
```

## Step 9-bis: Deploy JSON Schemas to Project (MANDATORY)

> **The JSON Schemas MUST be present in the project alongside the generated feature.json files.**
> Without schemas, feature.json files cannot be validated and have no structural reference.

**Check if schemas already deployed:**
```
IF EXISTS docs/business/{app}/business-analyse/schemas/feature-schema.json:
  Skip deployment (schemas already present)
ELSE:
  Deploy schemas
```

**Deploy all schema files from skill directory to project:**

Source: `schemas/` (relative to skill root = `~/.claude/skills/business-analyse/schemas/`)
Destination: `docs/business/{app}/business-analyse/schemas/`

```
Read and Write each file (preserving directory structure):

docs/business/{app}/business-analyse/schemas/
├── feature-schema.json              ← from schemas/feature-schema.json
├── application-schema.json          ← from schemas/application-schema.json
├── sections/
│   ├── metadata-schema.json         ← from schemas/sections/metadata-schema.json
│   ├── discovery-schema.json        ← from schemas/sections/discovery-schema.json
│   ├── analysis-schema.json         ← from schemas/sections/analysis-schema.json
│   ├── specification-schema.json    ← from schemas/sections/specification-schema.json
│   ├── validation-schema.json       ← from schemas/sections/validation-schema.json
│   └── handoff-schema.json          ← from schemas/sections/handoff-schema.json
└── shared/
    └── common-defs.json             ← from schemas/shared/common-defs.json
```

**Total: 9 files to deploy.**

**Implementation:**
1. Use Glob to find all `.json` files in `schemas/` directory (skill-relative)
2. For each file, Read from skill directory and Write to project directory
3. Preserve the subdirectory structure (sections/, shared/)

**Store:**
```yaml
schemas_dir: "docs/business/{app}/business-analyse/schemas"
```

## Step 10: Create Master feature.json

Create the master feature document using ba-writer agent.

**Use ba-writer agent:**

```
ba-writer.createApplicationFeature({
  id: {feature_id},
  version: "1.0",
  scope: "application",
  status: "draft",
  metadata: {
    application: {application_name},
    context: "business",
    language: {language},
    featureDescription: {feature_description},
    useCase: {use_case},
    mcpAvailable: {mcp_available},
    economyMode: {economy_mode},
    workflow: {
      mode: {workflow_mode},
      moduleOrder: [],
      currentModuleIndex: 0,
      completedModules: [],
      currentModule: null
    }
  }
})
```

**Output path:**
- Application mode: `docs/business/{app}/business-analyse/v1.0/feature.json`
- Module mode: `docs/business/{app}/business-analyse/v1.0/feature.json` (same - always create master first)

> **Note:** Even in single-module mode, we create the master feature.json. The decomposition step will trivially identify one module.

**Result structure:**
```json
{
  "$schema": "../schemas/application-schema.json",
  "id": "{feature_id}",
  "version": "1.0",
  "status": "draft",
  "metadata": {
    "createdAt": "{ISO timestamp}",
    "updatedAt": "{ISO timestamp}",
    "application": "{application_name}",
    "module": "{module_name}",
    "context": "business",
    "language": "{language}",
    "featureDescription": "{feature_description}",
    "featureType": null,
    "useCase": "{use_case}",
    "permissionBase": "business.{app}.{module}",
    "previousVersion": null,
    "changeReason": null,
    "mcpAvailable": {mcp_available},
    "economyMode": {economy_mode},
    "steps": {
      "init": {
        "status": "completed",
        "startedAt": "{ISO timestamp}",
        "completedAt": "{ISO timestamp}"
      },
      "analyse": {
        "status": "pending",
        "startedAt": null,
        "completedAt": null
      },
      "specify": {
        "status": "pending",
        "startedAt": null,
        "completedAt": null
      },
      "validate": {
        "status": "pending",
        "startedAt": null,
        "completedAt": null
      },
      "handoff": {
        "status": "pending",
        "startedAt": null,
        "completedAt": null
      }
    }
  },
  "discovery": {},
  "analysis": {},
  "specification": {},
  "validation": {},
  "handoff": {},
  "suggestions": [],
  "changelog": [
    {
      "version": "1.0",
      "timestamp": "{ISO timestamp}",
      "author": "BA Skill",
      "changes": ["Initial feature.json created"]
    }
  ]
}
```

**Write to:**
```
{docs_dir}/feature.json
```

## Step 11: Update Config

Update `.business-analyse/config.json` with new feature information.

**Update fields:**
```json
{
  "currentFeature": {
    "id": "{feature_id}",
    "version": "1.0",
    "docsDir": "{docs_dir}",
    "useCase": "{use_case}",
    "application": "{application_name}",
    "module": "{module_name}"
  },
  "lastInitialized": "{ISO timestamp}",
  "autoMode": {auto_mode},
  "economyMode": {economy_mode},
  "interactiveMode": {interactive_mode}
}
```

## Step 12: Display Summary

Show initialization results in a clear table format.

**Output:**
```
═══════════════════════════════════════════════════════════════
  BUSINESS ANALYSIS INITIALIZATION COMPLETE
═══════════════════════════════════════════════════════════════

| Field              | Value                                        |
|--------------------|----------------------------------------------|
| Step               | INIT (00)                                    |
| Feature ID         | {feature_id}                                 |
| Use Case           | {use_case}                                   |
| Application        | business/{application_name}                  |
| Module             | {module_name}                                |
| Output Path        | {docs_dir}/feature.json                      |
| Language           | {language}                                   |
| Auto Mode          | {auto_mode}                                  |
| Economy Mode       | {economy_mode}                               |
| MCP Available      | {mcp_available}                              |
| Timestamp          | {ISO timestamp}                              |

NEXT STEP: step-01-analyse ({use_case} mode)
═══════════════════════════════════════════════════════════════
```

## Step 13: Load Next Step

**All modes except question (-q) and micro (-m):**
After showing initialization summary, proceed to `./step-01-cadrage.md`

**Question mode (-q):** EXIT after ba-reader answers the question.
**Micro mode (-m):** Load `./step-05-handoff.md` directly.

**Pass context variables:**
```yaml
feature_id: string
feature_description: string
use_case: "new" | "question" | "refactoring" | "micro" | "application"
application_name: string
module_name: string
language: string
docs_dir: string
auto_mode: boolean
economy_mode: boolean
interactive_mode: boolean
mcp_available: boolean
workflow_mode: string
```

## Error Handling

Handle common initialization failures gracefully.

| Error | Action |
|-------|--------|
| Config missing | Create fresh with defaults, continue |
| Directory creation fails | Check permissions, display error, EXIT |
| feature.json creation fails | Validate ba-writer, retry or fallback |
| Legacy structure detected | Offer migration to new docs/business/ structure |
| Feature ID not unique | Generate new ID, retry |
| Invalid language | Default to "en", warn user |

### Resume After Interruption

If initialization was interrupted:

1. Check `.business-analyse/config.json` for currentFeature
2. If feature ID exists, search for feature.json:
   - Primary: `docs/business/{app}/{module}/business-analyse/v{version}/`
   - Fallback: `.business-analyse/{app}/{module}/`
3. If found, offer to resume from last completed step
4. If not found, create fresh feature.json

### Clean Fallbacks

If modern paths unavailable:
1. Search `.business-analyse/business/` (legacy)
2. Create new structure under `docs/business/` regardless
3. Log migration notice (automated, non-blocking)
