---
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/`
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-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 3b: Early Multi-Application Detection from Prompt (NEW)

> **Detect multi-app structure BEFORE asking for a single application name.**
> When the user's prompt explicitly describes multiple applications, we must recognize this immediately
> and set `workflow.mode = "project"` to avoid doing cadrage for a single app.

**Detection patterns (ANY match = multi-app detected):**

```javascript
const multiAppPatterns = [
  // French patterns
  /une\s+application\s+\w+.*une\s+application\s+\w+/is,
  /application\s*\d?\s*[:]\s*\w+.*application\s*\d?\s*[:]\s*\w+/is,
  /premier[e]?\s+application.*deuxième\s+application/is,
  /app\s*1\s*[:.].*app\s*2\s*[:.]*/is,
  // English patterns
  /an?\s+application\s+(for\s+)?\w+.*an?\s+application\s+(for\s+)?\w+/is,
  /application\s*#?\d\s*[:.].*application\s*#?\d\s*[:.]*/is,
  /first\s+app.*second\s+app/is,
];

const isMultiApp = multiAppPatterns.some(p => p.test(feature_description));
```

**IF multi-app detected:**

1. Extract candidate applications from the prompt:

```javascript
// Parse the prompt to identify application boundaries
// Each "une application X" / "an application X" block = one candidate
const candidates = extractApplicationCandidates(feature_description);
// Result example:
// [
//   { name: "RH", description: "gestion des employes, conges, temps", modules: ["Employes", "Conges", "Temps"] },
//   { name: "Projet", description: "gestion des projets, saisie du temps", modules: ["Projets", "Temps"] }
// ]
```

2. Detect shared modules across candidates:

```javascript
const allModules = candidates.flatMap(c => c.modules);
const sharedModules = allModules.filter((m, i) => allModules.indexOf(m) !== i);
// Example: sharedModules = ["Temps"] → appears in both RH and Projet
```

3. Display detection result and confirm:

```
{language == "fr"
  ? "### Détection multi-application\n\nJ'ai détecté **{candidates.length} applications** dans votre description :"
  : "### Multi-application detection\n\nI detected **{candidates.length} applications** in your description:"}

| # | Application | Modules identifiés |
|---|-------------|-------------------|
{for each candidate: index | name | modules.join(", ")}

{sharedModules.length > 0
  ? "⚠️ **Modules partagés détectés :** {sharedModules.join(', ')} — ces modules apparaissent dans plusieurs applications. Ils pourraient constituer une application transversale dédiée."
  : ""}
```

Ask via AskUserQuestion:
```
question: "{language == 'fr' ? 'Confirmez-vous cette structure multi-application ?' : 'Do you confirm this multi-application structure?'}"
header: "Architecture"
options:
  - label: "{language == 'fr' ? 'Oui, {candidates.length} applications' : 'Yes, {candidates.length} applications'}"
    description: "{language == 'fr' ? 'Créer un projet avec les applications identifiées' : 'Create a project with the identified applications'}"
  - label: "{language == 'fr' ? 'Extraire les modules partagés' : 'Extract shared modules'}" (only if sharedModules.length > 0)
    description: "{language == 'fr' ? 'Créer une application dédiée pour {sharedModules.join(', ')} ({candidates.length + 1} applications au total)' : 'Create a dedicated app for {sharedModules.join(', ')} ({candidates.length + 1} total)'}"
  - label: "{language == 'fr' ? 'Application unique' : 'Single application'}"
    description: "{language == 'fr' ? 'Tout regrouper en une seule application avec plusieurs modules' : 'Group everything into one application with multiple modules'}"
```

**IF "Oui, N applications" or "Extraire les modules partagés":**

```yaml
workflow_mode: "project"
project_name: derived from feature_description
candidate_applications: [{ name, description, modules, context }]
shared_modules_extracted: boolean  # true if user chose extraction
```

→ Skip step 4 (application name) — applications will be confirmed in step-01b
→ Continue to step 5 (language selection)

**IF "Application unique":**

```yaml
workflow_mode: "application"
```

→ Continue to step 4 normally

**IF no multi-app patterns detected:**
→ Continue to step 4 normally

## Step 4: Determine Application Name

> **This step is SKIPPED if `workflow_mode = "project"` (multi-app detected in step 3b).**

```
IF workflow_mode = "project":
  application_name = project_name  // Project-level name, not a single app name
  → Skip to step 5

ELSE 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é"
```

**Store:**
```yaml
application_name: string  # or project_name if project mode
```

## 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_mode = "project":
  // Project mode: create project-level directory + per-app directories later (in step-01b)
  mkdir -p docs/business-analyse/v1.0
  docs_dir = "docs/business-analyse/v{version}"

ELSE IF workflow_type = "new":
  mkdir -p docs/{application_name}/business-analyse/v1.0
  docs_dir = "docs/{app}/business-analyse/v{version}"

ELSE:
  Directory already exists from ba-writer.createVersion()
```

**Store:**
```yaml
docs_dir: string
```

## 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/{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.

```
IF workflow_mode = "project":
  // PROJECT MODE: Create project-level feature.json
  ba-writer.createProjectFeature({
    id: generate_project_id(),  // PROJ-NNN
    version: {version},
    scope: "project",
    status: "draft",
    metadata: {
      projectName: {project_name},
      language: {language},
      featureDescription: {feature_description},
      workflowType: {workflow_type},
      analysisMode: "interactive",
      mcpAvailable: true,
      candidateApplications: {candidate_applications},  // From step 3b detection
      sharedModulesExtracted: {shared_modules_extracted},
      workflow: {
        mode: "project",
        applicationOrder: [],
        currentApplicationIndex: 0,
        completedApplications: []
      }
    }
  })

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

  Store:
    project_id: string  // PROJ-NNN
    feature_id: project_id  // In project mode, feature_id = project_id for step-01

ELSE:
  // SINGLE-APP MODE: Create application-level feature.json
  ba-writer.createApplicationFeature({
    id: {feature_id},
    version: {version},
    scope: "application",
    status: "draft",
    metadata: {
      application: {application_name},
      language: {language},
      featureDescription: {feature_description},
      workflowType: {workflow_type},
      analysisMode: "interactive",
      mcpAvailable: true,
      workflow: {
        mode: "application",
        moduleOrder: [],
        currentModuleIndex: 0,
        completedModules: [],
        currentModule: null
      }
    }
  })

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

> **Note:** In project mode, per-application feature.json files are created later in step-01b.
> In single-app mode, 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}                               |
| Mode               | {workflow_mode === "project" ? "Multi-application project" : "Single application"} |
| Application/Project| {workflow_mode === "project" ? project_name + " (" + candidate_applications.length + " apps)" : application_name} |
| Output Path        | {docs_dir}/feature.json                      |
| Language           | {language}                                   |
| Version            | {version}                                    |
| MCP Available      | true                                         |
| Analysis Mode      | Interactive (always)                         |

{workflow_mode === "project"
  ? "Candidate applications: " + candidate_applications.map(a => a.name).join(", ")
  : ""}

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               # FEAT-NNN (single-app) or PROJ-NNN (project)
feature_description: string
workflow_type: "new" | "update"
workflow_mode: "application" | "project"
application_name: string         # Single-app: app name. Project: project name.
applicationCode: string          # PascalCase derived from application_name (preliminary, confirmed in step-01b)
project_id: string | null        # PROJ-NNN if project mode, null if single-app
candidate_applications: array | null  # Pre-identified apps from prompt (project mode only)
shared_modules_extracted: boolean     # True if user chose to extract shared modules as new app
language: string
docs_dir: string
mcp_available: boolean
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/`
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.
