---
name: step-00-init
description: Initialize Business Analysis - Auto-detect new/update, create feature.json
model: sonnet
next_step: steps/step-01-cadrage.md
---

> **Context files:** `_shared.md`

# Step 00: Initialize Business Analysis

**Before anything else**, display the version banner:

```
═══════════════════════════════════════════════════════════════
  SmartStack Business Analyse — v{{SMARTSTACK_VERSION}}
═══════════════════════════════════════════════════════════════
```

Initialize the business analysis workflow by auto-detecting whether this is a new application or an update to an existing one, then creating the initial feature.json structure.

## Flow

1. MCP health check (blocking)
2. Scan existing applications in `docs/business/`
3. Auto-detect: new application or update
4. Determine application name
5. Select language
6. Generate feature ID
7. Create output directory structure
8. Deploy JSON schemas
9. Create master feature.json
10. Update config
11. Display summary
12. Load next step

## Step 1: 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 2 |
| Connection error / tool not found | **STOP EXECUTION** - display error below |

**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** continue to any subsequent step.
**STOP the skill immediately.**

## Step 2-3: Workflow Detection (Review / New / Update)

**Objective:** Detect workflow type and match against existing applications.

**Process:**

Execute workflow detection algorithm:
1. **Review Mode Detection:** Check if `{feature_description}` starts with `-review`
2. **Existing Projects Scanner:** Glob `docs/business-analyse/*/feature.json` (project-level)
2b. **Existing Applications Scanner:** Glob `docs/business/*/business-analyse/*/feature.json` + `docs/platform/*/business-analyse/*/feature.json` + `docs/personal/*/business-analyse/*/feature.json`
3. **Similarity Analysis:** Score user intent against existing apps (>= 80 = strong match)
4. **Decision Tree:** Prompt user with relevant options

```javascript
const detectionResult = detectWorkflowType(feature_description, existingApps);

IF detectionResult.error OR detectionResult.ambiguous:
  // CONDITIONAL LOAD: Only load detection strategies on error or ambiguity
  Read references/detection-strategies.md
  Display:
    - Detailed similarity scoring algorithm
    - Decision tree with thresholds
    - Error handling procedures
    - Review mode troubleshooting (if review mode failed)

  → Resolve ambiguity with user clarification

ELSE:
  Workflow detected: {detectionResult.workflow_type} ✓
  → Continue to application name determination
```

**Key decision points:**
1. IF review mode → load ba-review.json, skip to step-06-review.md
2. IF no existing apps → workflow_type = "new"
3. IF existing apps → analyze similarity → prompt user

**Optimization:** The detailed 400-line detection-strategies.md is loaded **only when detection fails or is ambiguous** (saves ~15,000 tokens on clear detection path).

**Store:**
```yaml
workflow_type: "new" | "update" | "review"
existing_feature_id: string | null
existing_project_id: string | null  # PROJ-NNN if resuming a project
version: "1.0" (new) | "1.1"+ (update)
review_json_path: string | null (review only)
existing_apps: array of { app, featureId, description, version }
existing_projects: array of { projectName, projectId, applications[], version }
```

> **Project Resume Detection:** If a project-level feature.json is found at `docs/business-analyse/*/feature.json`, check its `metadata.workflow` to determine resume point. The project may have partially completed applications.

## Step 4: Determine Application Name

```
IF workflow_type = "update":
  application_name = existing app name (from step 3)
ELSE:
  Analyze {feature_description} to extract application name
  Ask via AskUserQuestion:
    question: "Quel nom pour cette application ?"
    header: "Application"
    options:
      - label: "{detected_name}"
        description: "Nom détecté depuis votre description"
      - label: "Autre"
        description: "Saisir un nom personnalisé"
```

**Validate business context:**
```
validate_business_context("business")
→ BA restricted to 'business' context only
```

**Store:**
```yaml
application_name: string
context: "business"
```

## Step 5: Select Language

Determine the language for analysis and code generation.

**Check config:**
- Retrieve `language` from `.business-analyse/config.json`
- Default: "fr" (Francais)

**If not in config:**
```
Ask via AskUserQuestion:
  question: "Quelle langue pour l'analyse ?"
  header: "Langue"
  options:
    - label: "Francais (fr)"
    - label: "English (en)"
    - label: "Italiano (it)"
    - label: "Deutsch (de)"
```

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

## Step 5b: Analysis Mode

> The analysis phase is ALWAYS interactive — the AI listens, reformulates,
> challenges, and validates with the user. This is non-negotiable regardless
> of development mode. Vibe coding applies to code execution (step-03+), NOT to analysis.

**Set directly (no question):**

```yaml
analysisMode: "interactive"  # Always interactive for cadrage
```

## Step 6: Generate Feature ID

Create a unique feature identifier.

```
IF workflow_type = "update":
  feature_id = existing_feature_id (from step 3)
ELSE:
  feature_id = generate_feature_id()
  → Read .business-analyse/config.json → lastFeatureId
  → Increment and format as FEAT-NNN
```

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

## Step 7: Create Output Directory Structure

```
IF workflow_type = "new":
  mkdir -p docs/business/{application_name}/business-analyse/v1.0
ELSE:
  Directory already exists from ba-writer.createVersion()
```

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

## Step 8: 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.

See [references/init-schema-deployment.md](../references/init-schema-deployment.md) for cache-based deployment logic (9 schema files, version-checked via `.schema-cache.json`).

## Step 8b: Cache Warming (PERFORMANCE OPTIMIZATION)

> **Objective:** Pre-load frequently-used templates and context files to reduce redundant reads.
> **Expected token savings:** 15-20% across entire BA session

**Implementation:**

```javascript
// Pre-load CRITICAL (schemas) and HIGH (questionnaires) priority buckets
const schemaFiles = glob("docs/business/{app}/business-analyse/schemas/**/*.json");
for (const file of schemaFiles) {
  read(file);  // Triggers cache
}

const questionnaireFiles = glob("~/.claude/skills/business-analyse/questionnaire/*.md");
for (const file of questionnaireFiles) {
  read(file);  // Triggers cache
}

read("~/.claude/skills/business-analyse/patterns/suggestion-catalog.md");

// Display status
console.log(`
✓ Cache warmed: 9 schemas + 16 questionnaires + 1 catalog
  Expected savings: 15-20% session tokens
  Retention: schemas (session-wide), questionnaires (until step-02)
`);
```

**Bucket Strategy:**

See [references/cache-warming-strategy.md](../references/cache-warming-strategy.md) for complete documentation on:
- 5 cache buckets (schemas, questionnaires, moduleSpec, handoff, etc.)
- Retention policies and clearing rules
- Token savings calculations (baseline vs optimized)
- Monitoring cache efficiency
- When to pre-load vs lazy-load

## Step 9: Create Master feature.json

Create the master feature document using ba-writer agent.

```
ba-writer.createApplicationFeature({
  id: {feature_id},
  version: {version},
  scope: "application",
  status: "draft",
  metadata: {
    application: {application_name},
    context: "business",
    language: {language},
    featureDescription: {feature_description},
    workflowType: {workflow_type},
    analysisMode: "interactive",
    mcpAvailable: true,
    workflow: {
      mode: "application",
      moduleOrder: [],
      currentModuleIndex: 0,
      completedModules: [],
      currentModule: null
    }
  }
})
```

**Output path:**
`docs/business/{app}/business-analyse/v{version}/feature.json`

> **Note:** Always create the master feature.json first. Step-02 (decomposition) determines if it's single or multi-module.

## Step 10: Update Config

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

```json
{
  "currentFeature": {
    "id": "{feature_id}",
    "version": "{version}",
    "docsDir": "{docs_dir}",
    "workflowType": "{workflow_type}",
    "application": "{application_name}"
  },
  "lastInitialized": "{ISO timestamp}"
}
```

## Step 11: Display Summary

```
═══════════════════════════════════════════════════════════════
  BUSINESS ANALYSIS INITIALIZATION COMPLETE
  SmartStack CLI v{{SMARTSTACK_VERSION}}
═══════════════════════════════════════════════════════════════

| Field              | Value                                        |
|--------------------|----------------------------------------------|
| Feature ID         | {feature_id}                                 |
| Workflow           | {workflow_type}                               |
| Application        | business/{application_name}                  |
| Output Path        | {docs_dir}/feature.json                      |
| Language           | {language}                                   |
| Version            | {version}                                    |
| MCP Available      | true                                         |
| Analysis Mode      | Interactive (always)                         |

NEXT STEP: step-01-cadrage
═══════════════════════════════════════════════════════════════
```

## Step 12: Load Next Step

After showing initialization summary, proceed to `./step-01-cadrage.md`

**Pass context variables:**
```yaml
feature_id: string
feature_description: string
workflow_type: "new" | "update"
application_name: string
language: string
docs_dir: string
mcp_available: boolean
workflow_mode: "application"
analysisMode: "interactive"
version: string
```

## Error Handling

| 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 |
| Feature ID not unique | Generate new ID, retry |

### Resume After Interruption

If initialization was interrupted:

1. Check `.business-analyse/config.json` for currentFeature or currentProject
2. If project ID exists, search for project feature.json in `docs/business-analyse/`
   - If found with scope = "project": resume project mode (see Project Resume below)
3. If feature ID exists, search for feature.json in `docs/business/`, `docs/platform/`, `docs/personal/`
4. If found, check status and `metadata.workflow.lastCompletedStep`:

   **Status-based resume routing (check in this order):**

   - If status = `"handed-off"` AND `ba-interactive.html` missing:
     → Resume at `step-05b-deploy.md` (deploy artifacts + HTML)
     → Display: "Handoff complete but HTML/artifacts missing — deploying..."

   - If status = `"handed-off"` AND `.ralph/prd-*.json` files missing:
     → Resume at `step-05b-deploy.md` (only deploy artifacts needed)
     → Display: "Handoff complete but PRD files missing — deploying..."

   - If status = `"consolidated"` OR lastCompletedStep = `"step-04-consolidation"`:
     → Resume directly at `step-05a-handoff.md` (skip steps 00-04)
     → Display: "Resuming from consolidation — proceeding to handoff..."

   - If status = `"specified"` AND `metadata.workflow.allModulesSpecified === true`:
     → Resume at `step-04a-collect.md` (consolidation phase)
     → Display: "All modules specified — resuming at consolidation..."

   - If status = `"specified"` AND `metadata.workflow.completedModules.length > 0` AND `metadata.workflow.completedModules.length < metadata.workflow.moduleOrder.length`:
     → Resume at `step-03a1-setup.md` (continue specifying remaining modules)
     → Display: "Resuming module specification ({completedCount}/{totalCount})..."

   - Otherwise: offer to resume from last completed step

4. If not found, create fresh feature.json

**Project Resume (project mode):**

If a project-level feature.json is found (scope = "project"):

   - If status = `"draft"` or `"framed"`:
     → Resume at `step-01-cadrage.md` or `step-01b-applications.md`

   - If status = `"decomposed"`:
     → Check `metadata.workflow.currentApplicationIndex` and `completedApplications[]`
     → Resume module specification for current application (step-02 or step-03)

   - If status = `"specified"`:
     → All applications specified → Resume at `step-04a-collect.md`

   - If status = `"consolidated"`:
     → Resume at `step-05a-handoff.md`

   Follow `_module-loop.md` "Project Mode (multi app)" resume logic for detailed routing.
