---
name: fluent-feature-explain
description: Reverse-engineer and explain an existing Fluent Commerce feature. Synthesizes workflow analysis, custom code logic, connection topology, and live runtime evidence into a comprehensive, visually rich Feature Architecture Document saved to accounts/<PROFILE>/features/<slug>/architecture.md. Triggers on "explain feature", "how does this work", "reverse engineer", "feature architecture", "document this flow", "what does this workflow do".
user-invocable: true
allowed-tools: Bash, Read, Write, Edit, Glob, Grep
argument-hint: <feature-name-or-workflow> [--depth shallow|full] [--include-runtime] [--output <path>]
cursor-tier: manual
---

# Feature Explainer

Reverse-engineer an existing feature to produce a comprehensive **Feature Architecture Document**. Orchestrates workflow analysis, code analysis, connection mapping, and live runtime evidence to explain *how* a feature is implemented end-to-end — from input trigger to terminal state, across all impacted entities.

## Pre-flight: Feedback Check

Before starting, check for past learnings from this skill:

1. Check if `accounts/<PROFILE>/feedback/fluent-feature-explain.jsonl` exists
2. If yes, read last 20 records
3. Filter to: FAILURE or USER_CORRECTED outcomes, confidence = CONFIRMED or PROMOTED
4. Extract top 3 relevant learnings — use as internal guidance during execution
5. Do NOT show raw feedback to the user — silently adjust approach based on past issues

## Ownership Boundary

This skill owns the **synthesis** of analysis artifacts into unified feature documentation.

Source analysis skills (called as needed, not duplicated):
- Workflow structure analysis -> `/fluent-workflow-analyzer`
- Code logic analysis -> `/fluent-custom-code`
- Dependency mapping -> `/fluent-connection-analysis`
- Runtime event forensics -> `/fluent-trace`
- Settings cross-reference -> `/fluent-settings`

MCP tools used directly:
- `plugin.list` — Rule descriptions, entity types, parameters
- `workflow.transitions` — Available user actions per status
- `environment.discover` — Environment context (locations, networks, catalogues)
- `event.flowInspect` — Runtime event trace (when `--include-runtime` or real entity ref provided)
- `entity.get` — Entity state and edge traversal

## When to Use

- "Explain how the Home Delivery order flow works end-to-end"
- "Reverse engineer the Click & Collect fulfilment feature"
- "Document the Return Order implementation for the team"
- "What entities, rules, and settings are involved in order allocation?"
- "How does ORDER::HD work? Show me diagrams"
- Onboarding new developers to an existing implementation
- Pre-change understanding before modifying a complex feature
- Stakeholder documentation and handover packs

## Output Location

All generated documents are saved to:

```
accounts/<PROFILE>/features/<slug>/architecture.md
```

Where `<slug>` is derived from the user's request (kebab-case):
- Workflow name: `ORDER::HD` -> `order-hd`
- Feature name: `"Home Delivery"` -> `home-delivery`
- Custom name via `--output`: saves to the specified path

## Progress

Emit this block at each phase transition to show progress:

```
▸ /fluent-feature-explain [1/6]
  ✓ Scope identification     → Structural analysis
  ○ Logic analysis           ○ Connection & dependencies
  ○ Runtime evidence         ○ Synthesis & write doc
```

Update the block as each phase completes — mark completed phases with `✓`, the active phase with `→`, and remaining phases with `○`. Replace `[1/6]` with the current phase number.

Each document includes a metadata header for traceability:

```markdown
<!-- Feature Architecture Document -->
<!-- Generated: 2026-02-23T14:30:00Z -->
<!-- Profile: MY_PROFILE -->
<!-- Retailer: MY_RETAILER (ID: 5) -->
<!-- Workflows: ORDER::HD (v1.50), FULFILMENT::HD_WH (v1.22) -->
<!-- Depth: full -->
<!-- Runtime evidence: yes (entity: HD-001) -->
```

### Feature Linkage — `basedOn` Field

When explaining an existing feature, this skill checks if a new feature is being built on top of it. The "explain then extend" pattern works as follows:

1. User runs `/fluent-feature-explain ORDER::HD` → produces `architecture.md` in `features/order-hd/`
2. User later says "Now add curbside pickup to this" → `/fluent-use-case-discover` creates `features/curbside-pickup/`
3. The new feature's `status.json` can include a `basedOn` field linking back to the architecture doc:

```json
{
  "basedOn": "features/order-hd/architecture.md"
}
```

**When this skill creates an architecture document:**
- If a `status.json` already exists in the feature directory, update `architecture: true` but do NOT overwrite other fields
- If no `status.json` exists, create one with minimal fields:
  ```json
  {
    "$schema": "feature-status-v2",
    "feature": "<slug>",
    "retailers": ["<retailer>"],
    "status": "DISCOVERY",
    "created": "<today>",
    "updated": "<today>",
    "spec": null,
    "plan": null,
    "build": null,
    "deploy": null,
    "planRevision": null,
    "architecture": true,
    "basedOn": null,
    "next": "/fluent-use-case-discover",
    "sessions": []
  }
  ```

**When downstream skills create a feature that builds on an explained feature:**
- `/fluent-use-case-discover` and `/fluent-feature-plan` should check if the user references an existing architecture document
- If so, set `basedOn: "features/<base-slug>/architecture.md"` in the new feature's `status.json`
- The architecture doc is then available as context during spec gathering and planning

## Pre-flight: Project Knowledge Check

Check for project-specific knowledge that should inform feature explanation:

1. Check if `accounts/<PROFILE>/knowledge/` exists
2. If yes, read it and find files where `relevant-skills` includes `fluent-feature-explain`
   **Account knowledge:** Read from `accounts/<PROFILE>/knowledge/` when `FLUENT_PROFILE` is set. These contain project-specific conventions.

3. Read matching knowledge files — typically:
   - `knowledge/platform/domain-model.md` — use for entity edges, cross-domain relationships, valid GraphQL connections
   - `knowledge/platform/create-order-reference.md` — createOrder input schema, fulfilmentChoice wiring, ORDER::MULTI patterns. Use when explaining order intake flows.
   - `accounts/<PROFILE>/knowledge/client/business-rules.md` — use for business context of rules and workflows
   - `accounts/<PROFILE>/knowledge/client/data-model.md` — use for entity types, subtypes, attribute schemas
4. Apply knowledge silently — do NOT show raw knowledge to user, just use it to produce better explanations

## Execution Protocol

### Phase 1: Scope Identification

1. **Parse user request** — Extract feature name, workflow names, entity types, or entry points.

2. **Discover workflows** — If the user names a feature (not a workflow), map it to candidate workflows:
   - Search workflow JSON filenames in `accounts/<PROFILE>/workflows/<RETAILER>/`
   - If workflows not downloaded, download them first:
     ```bash
     fluent workflow download -p <PROFILE> -r <RETAILER_REF> -w all -o accounts/<PROFILE>/workflows/<RETAILER_REF>/
     # If CLI returns 401 or on Windows, use MCP with outputDir:
     # workflow.list({ retailerId: "<id>", outputDir: "accounts/<PROFILE>/workflows/<RETAILER_REF>" })
     ```
   - Match by entity type, subtype, or keyword in workflow names/rulesets

3. **Determine boundaries:**
   - **Primary entity type** (e.g., ORDER)
   - **Related entity types** (e.g., FULFILMENT_CHOICE, FULFILMENT, ARTICLE)
   - **Entry events** (what triggers this feature)
   - **Terminal states** (where the feature ends)

4. **Select depth:**
   - `--depth shallow` — Primary workflow only, no cross-entity tracing
   - `--depth full` (default) — All related workflows, cross-entity flows, settings, integrations

5. **Check for feature context** — If this feature has a `status.json`, read it for context:
   ```bash
   cat accounts/<PROFILE>/features/<slug>/status.json
   ```
   If `basedOn` is set, also read the referenced architecture doc as foundational context. If `spec` is set, read the spec for business context.

### Phase 2: Structural Analysis

For each workflow in scope, invoke `/fluent-workflow-analyzer` capabilities:

**From workflow JSON (static analysis):**
- Parse all statuses, rulesets, triggers, and rules
- Classify process flows (CREATE, USER_ACTION, SCHEDULED_EVENT, CROSS_WORKFLOW, INTEGRATION_EVENT, INTERNAL)
- Build status transition graph
- Identify event chains from entry to terminal states

**From MCP tools (live data):**
- `plugin.list` — Get rule descriptions, accepted entity types, produced events, parameters for every rule in the workflow
- `workflow.transitions` — Query available user actions at each status (validates the state machine against deployed workflow)

**Strict user-action checks (anti-hallucination):**
- Treat `userActions[].eventName` as the only valid action trigger (never infer from labels).
- Treat `userActions[].attributes` as the runtime payload contract (do not invent keys).
- If expected actions are missing, verify ALL THREE mandatory Transition API params: `module` (specific name — `"all"` returns NOTHING), `flexType`, and `flexVersion`.
- If actions still missing after verifying params, check `context[].modules` for visibility drift (module name must match manifest setting suffix: `fc.mystique.manifest.<module>` → `<module>`).
- Cross-check workflow authoring against `/fluent-workflow-builder` and diagnostics against `/fluent-transition-api`.

**Produce:**
- Status state machine per entity type
- Event chain from trigger to terminal
- Process flow classification table

### Phase 3: Logic Analysis

For rules involved in the feature, gather behavior information using a tiered approach based on available evidence:

**Tier 1: `plugin.list` MCP tool** (always available):
- Rule descriptions (what the rule does)
- Event attributes consumed (what data the rule reads)
- Parameters (configurable behavior)
- Accepted entity types

**Tier 2: Source code analysis** (when `accounts/<PROFILE>/SOURCE/backend/` exists):
Invoke `/fluent-custom-code` to analyze Java source:
- `source-map.json` — Rule class locations, test coverage
- `workflow-rule-map.json` — Rule-to-workflow mapping with confidence
- `behavior-map.md` — Human-readable behavior descriptions

**Source code validation** (automatically triggered for custom rules):
- Cross-reference rule props from workflow JSON against what the Java code actually reads
- Verify that configurable JSON paths (e.g., `sourcingLocationPath`) match fields the code navigates
- Check test coverage per custom rule — flag untested rules
- Identify any rules referenced in the workflow but missing from SOURCE (gap)

**Tier 2b: JAR decompilation** (when source code is missing for some rules but JARs exist):

After completing Tier 2 source analysis, identify any custom rules still unresolved (found in workflow JSON + plugin.list but not in SOURCE Java files). For these rules:

**How to find rules without decompiling (discovery vs decompilation are separate):**
- `plugin.list` gives you the rule's fully qualified key (e.g., `MY_PROFILE.order.ForwardEventByFulfilmentChoiceType`) — the namespace prefix (`order`) hints at the module name
- `jar tf` lists all class file paths inside a JAR by reading the ZIP index — **no decompilation needed** for discovery
- Only after confirming which JAR contains the class do you extract + decompile it

1. **Ensure CFR decompiler is available** — auto-download if missing:
   ```bash
   CFR_DIR="$HOME/.fluent-ai-skills/tools"
   CFR_JAR="$CFR_DIR/cfr.jar"
   if [ ! -f "$CFR_JAR" ]; then
     mkdir -p "$CFR_DIR"
     curl -L -o "$CFR_JAR" "https://github.com/leibnitz27/cfr/releases/download/0.152/cfr-0.152.jar"
   fi
   # Verify it works
   java -jar "$CFR_JAR" --version
   ```
   CFR is a single-JAR decompiler (~2MB), cached in `~/.fluent-ai-skills/tools/` — just `java -jar`.

2. **Search for JARs recursively** under `accounts/<PROFILE>/SOURCE/backend/`:
   ```bash
   find accounts/<PROFILE>/SOURCE/backend/ -name "*.jar" -type f
   ```
   Look in: reference modules (`referece modules/`, `reference-modules/`), `assets/rules/`, `dist/`, `target/`.

3. **Match unresolved rules to JARs** — `jar tf` reads the ZIP directory index (instant, no decompilation). For each JAR, check for matching class names:
   ```bash
   jar tf <path-to-jar> | grep -i "<RuleClassName>"
   ```
   This tells you exactly which JAR contains which rule, and the full package path.

4. **Decompile the matched JAR** with CFR using `--jarfilter` to extract only rule classes:
   ```bash
   java -jar "$CFR_JAR" "<path-to-jar>" \
     --outputdir "accounts/<PROFILE>/SOURCE/backend/.decompiled/<jar-basename>" \
     --jarfilter "com.fluentcommerce.rule"
   ```
   The `--jarfilter` flag restricts decompilation to classes matching the package prefix, keeping output focused on rule logic only. This produces clean, readable Java files organized by package path.

5. **Create a `DECOMPILED.md` marker** in the output directory:
   ```markdown
   # Decompiled Source
   - **Source JAR:** `<path-to-jar>`
   - **Decompiled on:** <date>
   - **Decompiler:** CFR 0.152
   - **Rule classes:** <count>
   - **Filter:** `com.fluentcommerce.rule.*`
   - **Note:** This is decompiled bytecode, not original source. Variable names may be synthetic.
   ```

6. **Fallback if Java not available** — extract and disassemble individual classes:
   ```bash
   mkdir -p /tmp/jar-decompile && cd /tmp/jar-decompile
   jar xf <path-to-jar> <class-path>
   javap -c -p <extracted-class-file>
   ```
   `javap -c -p` provides bytecode disassembly sufficient to determine matching logic, null guards, data flow, and exception handling.

7. **Confidence level:**
   - Full decompilation (CFR/Fernflower): mark as **HIGH** — readable Java, prop names visible, logic clear
   - `javap` bytecode: mark as **HIGH** — implementation logic is unambiguous from bytecode
   - Note the JAR version, decompiler version, and source path in the document metadata

**If SOURCE directory is missing or empty (no source, no JARs):**
- Ask the user: "Custom rules were found but no source code or JARs are available under `accounts/<PROFILE>/SOURCE/backend/`. Options: (1) Clone plugin repos to `accounts/<PROFILE>/SOURCE/backend/<repo>/` (2) Place reference module ZIPs/JARs in `accounts/<PROFILE>/SOURCE/backend/` for decompilation (3) Run `/fluent-connect` for full workspace preparation including JAR provision"
- If user declines or source unavailable, proceed with Tier 1 only and add confidence caveats to the document:
  - Mark affected rules as **MEDIUM confidence** (behavior inferred from plugin.list + runtime only)
  - Add explicit "What we don't know" column for each affected rule
  - Note in Analysis Caveats: "For more accurate analysis of these rules, provide source code or module JARs"

**Tier 3: Runtime evidence** (when entities exist — see Phase 5):
- Validates static analysis against actual execution
- Confirms which rulesets actually fire vs which are theorized from workflow JSON

**Produce:**
- Per-ruleset explanation: what it does, what triggers it, what it changes, what it emits
- Decision points and conditional logic
- Custom vs OOTB rule classification
- **Confidence level per rule** (see Analysis Confidence Levels below)

### Phase 4: Connection & Dependency Analysis

Invoke `/fluent-connection-analysis` capabilities:

**Map:**
- Internal connections (rulesets within same workflow)
- Cross-entity connections (ORDER -> FULFILMENT_CHOICE -> FULFILMENT)
- Cross-workflow connections (shared events)
- Integration points (webhooks, external system calls)
- Settings dependencies (which settings each ruleset reads)

**From `/fluent-settings` cross-reference:**
- List all settings referenced by rules in scope
- Show current values (or MISSING status)
- Map setting -> ruleset -> behavior impact

### Phase 5: Runtime Evidence (Adaptive)

**Auto-discovery:** Before asking the user, automatically search for existing entities of the workflow's entity type via GraphQL. Query for entities with matching type/subtype that have reached a non-initial status (e.g., not just CREATED). If entities are found, use the most recently completed one for runtime evidence.

**When runtime exists** (entities found, or `--include-runtime` specified, or user provides entity ref):

**IMPORTANT — Staged flowInspect pattern (never call with `compact: false` upfront):**

**Step 1: Compact call (always start here, ~2-3k tokens):**
```
event.flowInspect({ rootEntityRef: "<REF>", rootEntityType: "<TYPE>" })
```
Returns: status flow, anomaly findings, failed webhooks, slowest rulesets, event counts. This is sufficient for the Runtime Evidence section in most cases.

**Step 2: Targeted drill-down (only if compact findings indicate issues):**
- If anomalies found → `event.get` on specific event IDs from the compact diagnostics
- If webhook failures → compact response already includes failed webhook details
- If rule timing needed → call `event.flowInspect` with ONLY `includeRuleDetails: true` (keep compact: true)
- If custom log messages needed → call with ONLY `includeCustomLogs: true` (keep compact: true)

**NEVER do this** (wastes ~30k tokens of context):
```
event.flowInspect({ ..., compact: false, includeAudit: true, includeRuleDetails: true, ... })
```

**From `entity.get`:**
- Current entity state with edge traversal
- Related entities (fulfilments, items, articles)
- Attribute values at current state

This grounds the static analysis in real execution evidence.

**When NO runtime exists** (no entities found for this workflow type):
- Skip the Runtime Evidence section
- Automatically escalate source code analysis depth (Phase 3 Tier 2) if SOURCE is available
- Add the "Analysis Confidence" caveat section to the document (see below)
- Note in the document: "No entities of type {entityType}::{subtype} found in the environment. Runtime evidence unavailable. Deploy and process a test entity for validated analysis."

### Phase 6: Synthesis — Feature Architecture Document

Combine all findings into the output document with the following sections:

---

## Document Structure

### Section 1: Feature Overview

```markdown
# Feature Architecture: <Feature Name>

## Overview

**Purpose:** <1-2 sentence description of what the feature does>
**Primary Entity:** <entity type and subtype> (e.g., ORDER::HD)
**Related Entities:** <list> (e.g., FULFILMENT_CHOICE, FULFILMENT::HD_WH, ARTICLE)
**Workflows:** <list with versions>
**Entry Point:** <triggering event or API call>
**Terminal States:** <list of end states>
```

### Section 2: Entity Lifecycle — State Machine

> **Mandatory validation:** Before writing any Mermaid diagram to the feature architecture document, validate syntax via `knowledge/mermaid-syntax-rules.md`.

One `stateDiagram-v2` per entity type showing ALL statuses and transitions:

````markdown
## Entity Lifecycle

### ORDER::HD

```mermaid
stateDiagram-v2
    [*] --> CREATED : CreateOrder
    CREATED --> BOOKED : BookOrder
    BOOKED --> FULFILLED : AllFulfilmentsComplete
    FULFILLED --> COMPLETE : CompleteOrder
    CREATED --> CANCELLED : CancelOrder
    BOOKED --> CANCELLED : CancelOrder

    note right of CREATED : Entry point — order submitted
    note right of BOOKED : Inventory allocated, fulfilments created
    note right of FULFILLED : All items shipped/collected
```

### FULFILMENT::HD_WH

```mermaid
stateDiagram-v2
    [*] --> CREATED : CreateFulfilment
    CREATED --> ASSIGNED : AssignToLocation
    ASSIGNED --> PICKED : ConfirmPick
    PICKED --> PACKED : ConfirmPack
    PACKED --> SHIPPED : ConfirmShipment
    SHIPPED --> DELIVERED : ConfirmDelivery
    SHIPPED --> COMPLETE : CompleteWithoutDelivery
```
````

### Section 3: Cross-Entity Flow — Sequence Diagram

Show the full lifecycle across entity types with event names and key data:

````markdown
## Cross-Entity Flow

```mermaid
sequenceDiagram
    participant EXT as External System
    participant ORD as ORDER
    participant FC as FULFILMENT_CHOICE
    participant FUL as FULFILMENT
    participant LOC as Location / WMS

    EXT->>ORD: CreateOrder (ref, items, customer)
    ORD->>ORD: CREATED → Validate & Book
    ORD->>FC: SendEvent: CreateFulfilmentChoice
    FC->>FC: CREATED → Evaluate sourcing
    FC->>FUL: SendEvent: CreateFulfilment (locationRef, items)
    FC->>ORD: SendEvent: OrderBooked
    ORD->>ORD: CREATED → BOOKED

    FUL->>LOC: Webhook: NotifyWarehouse (endpoint, payload)
    LOC-->>FUL: ConfirmPick (pickedItems)
    FUL->>FUL: ASSIGNED → PICKED
    FUL->>FUL: PICKED → PACKED → SHIPPED

    FUL->>ORD: SendEvent: FulfilmentComplete
    ORD->>ORD: BOOKED → FULFILLED → COMPLETE
```
````

### Section 4: Event Chain

Flowchart showing the event propagation tree:

````markdown
## Event Chain

```mermaid
flowchart TD
    A[CreateOrder] --> B[ORDER: CREATED]
    B --> C{Validate}
    C -->|pass| D[BookOrder]
    C -->|fail| E[ORDER: CANCELLED]
    D --> F[FULFILMENT_CHOICE: CREATED]
    F --> G[FULFILMENT: CREATED]
    G --> H[AssignToLocation]
    H --> I[ConfirmPick]
    I --> J[ConfirmPack]
    J --> K[ConfirmShipment]
    K --> L[FULFILMENT: SHIPPED]
    L --> M[ORDER: FULFILLED]
    M --> N[ORDER: COMPLETE]

    style E fill:#f99
    style N fill:#9f9
```
````

### Section 5: Input → Output Data Flow

Table mapping what data enters, transforms, and exits at each step:

```markdown
## Input → Output Data Flow

| Step | Event / Action | Input Data | Logic / Transformation | Output / Side Effect |
|------|---------------|------------|----------------------|---------------------|
| 1 | CreateOrder | items[], customer, deliveryAddress | Validate structure | ORDER entity CREATED |
| 2 | BookOrder | ORDER attributes | Inventory allocation | FULFILMENT_CHOICE created |
| 3 | CreateFulfilment | locationRef, items | Assign to warehouse | FULFILMENT entity CREATED |
| 4 | ConfirmPick | pickedItems[], picker | Verify quantities | FULFILMENT → PICKED |
| 5 | ConfirmShipment | carrierRef, trackingNum | Link carrier | FULFILMENT → SHIPPED, webhook sent |
| 6 | FulfilmentComplete | fulfilmentRef | Check all complete | ORDER → FULFILLED |
```

### Section 6: Rules & Logic

Per-ruleset explanation with source:

```markdown
## Rules & Logic

### Ruleset: BookOrder (ORDER::HD)

| Rule | Type | Description | Reads | Produces |
|------|------|-------------|-------|----------|
| ValidateOrderAttributes | OOTB | Validates required order attributes | event.attributes | - |
| CreateFulfilmentChoice | Custom | Creates FC entity with sourcing logic | ORDER items, locations | FULFILMENT_CHOICE entity |
| SetOrderStatus | OOTB | Sets ORDER status to BOOKED | - | status: BOOKED |
| SendOrderBookedEvent | OOTB | Emits event for downstream | orderRef | Event: OrderBooked |

**Decision Points:**
- If validation fails → ORDER transitions to CANCELLED (CancelOrder ruleset)
- If no sourcing location found → ORDER stays BOOKED, manual intervention required

**Custom Rule Detail: CreateFulfilmentChoice**
- Source: `accounts/MY_PROFILE/SOURCE/backend/fc-module-my-extensions/src/main/java/.../CreateFulfilmentChoiceRule.java`
- Reads: `order.items`, `order.deliveryAddress`, location capabilities
- Logic: Evaluates location proximity, stock availability, delivery SLAs
- Produces: FULFILMENT_CHOICE entity with selected location
```

### Section 7: Settings Dependencies

```markdown
## Settings Dependencies

| Setting Key | Context | Current Value | Used By | Purpose |
|------------|---------|---------------|---------|---------|
| WEBHOOK_ENDPOINT_ORDER_BOOK | RETAILER | https://api.example.com/orders | BookOrder ruleset | Notify external OMS |
| INVENTORY_ALLOCATION_STRATEGY | RETAILER | CLOSEST_LOCATION | CreateFulfilmentChoice | Sourcing algorithm |
| ORDER_VALIDATION_ENABLED | RETAILER | true | ValidateOrder | Feature flag |
| MAX_FULFILMENT_RETRIES | RETAILER | MISSING | RetryFulfilment | **Gap: setting not created** |
```

### Section 8: Integration Points

```markdown
## Learning Capture

This is an analysis skill — follow the **Learning Capture Protocol** (see CLAUDE.md Cross-Skill Conventions). After producing the architecture document, when the user confirms or corrects findings about feature behavior, workflow decisions, or integration patterns, write the confirmed learning to the `implementation-learnings.md` auto-memory file under the relevant account heading.

## Integration Points

### Webhooks

| Ruleset | Endpoint Setting | HTTP Method | Payload Shape | Direction |
|---------|-----------------|-------------|---------------|-----------|
| NotifyWarehouse | WEBHOOK_WMS_FULFILMENT | POST | { fulfilmentRef, items, locationRef } | Outbound |
| ReceiveShipment | N/A (inbound event) | POST /event | { trackingNumber, carrier } | Inbound |

### Scheduled Events

| Ruleset | Event Name | Delay | Purpose |
|---------|-----------|-------|---------|
| RetryAllocation | RetryFulfilmentAllocation | 30min | Retry failed sourcing |
| EscalateStuck | EscalateStuckOrder | 24h | Alert ops team |
```

### Section 9: Runtime Evidence (when available)

```markdown
## Runtime Evidence

**Entity:** ORDER HD-001
**Trace period:** 2026-02-23T10:00:00Z to 2026-02-23T10:15:00Z

### Execution Timeline

| Time | Event | Entity | Status Change | Duration |
|------|-------|--------|--------------|----------|
| 10:00:01 | CreateOrder | ORDER | → CREATED | - |
| 10:00:02 | BookOrder | ORDER | CREATED → BOOKED | 1.2s |
| 10:00:03 | CreateFC | FC | → CREATED | 0.8s |
| 10:00:04 | CreateFulfilment | FUL | → CREATED | 0.5s |
| 10:05:30 | ConfirmPick | FUL | ASSIGNED → PICKED | 0.3s |

### Anomalies

- No anomalies detected (all events SUCCESS)
- OR: `RetryAllocation` fired 3 times before success (check inventory levels)
```

### Section 10: Analysis Confidence (always included)

This section is **always** included in the document and communicates the depth and reliability of the analysis based on what evidence was available.

```markdown
## Analysis Confidence

### Evidence Availability

| Source | Available | Impact |
|--------|-----------|--------|
| Workflow JSON | Yes | State machine, rulesets, triggers, props — **structural analysis complete** |
| plugin.list (deployed rules) | Yes | Rule descriptions, parameters, entity types — **rule behavior inferred** |
| workflow.transitions (live) | Yes | User actions validated against deployed workflow |
| Source code (Java) | No | Custom rule internals unknown — prop-to-code validation not possible |
| Runtime evidence | No | No executed entities found — theoretical flow only, not validated |

### Confidence Levels

| Aspect | Confidence | Reason |
|--------|------------|--------|
| State machine (statuses, transitions) | HIGH | Derived from workflow JSON — definitive |
| Event chain (happy path) | HIGH | Traced through rulesets + triggers — deterministic |
| Event chain (error/edge paths) | MEDIUM | Inferred from trigger coverage — not runtime-validated |
| Custom rule behavior | LOW | Only plugin.list description available — actual Java logic not inspected |
| Webhook payload shapes | LOW | Setting keys identified but payload templates not inspected |
| Integration timing / performance | N/A | No runtime evidence |
| Settings values | MEDIUM | Keys identified from rule props — current values need `/fluent-settings` audit |

### Recommendations for Higher Confidence

1. **Clone plugin source code** to `accounts/<PROFILE>/SOURCE/backend/` and re-run with source analysis:
   - Enables prop-to-code validation for custom rules
   - Reveals actual logic, edge cases, and error handling
   - Shows test coverage per rule
2. **If source repos unavailable, provide module JARs** in `accounts/<PROFILE>/SOURCE/backend/`:
   - Run `/fluent-custom-code` to decompile JARs into `.decompiled/` (CFR or Fernflower)
   - Decompiled source gives MEDIUM confidence (synthetic variable names, no comments)
   - Still enables cross-referencing workflow props against actual `context.getProp()` calls
3. **Process a test entity** through the workflow and re-run with `--include-runtime`:
   - Validates which rulesets actually fire
   - Reveals timing, webhook responses, and NO_MATCH events
   - Confirms the theoretical flow matches reality
3. **Run `/fluent-settings` audit** to verify all referenced settings exist with correct values
```

**Confidence level rules:**

| Evidence combination | Custom rule confidence | Flow confidence |
|---------------------|----------------------|-----------------|
| Workflow JSON + plugin.list only | LOW | HIGH (structure) / MEDIUM (behavior) |
| + Decompiled JAR (no original source) | MEDIUM | HIGH |
| + Original source code | HIGH | HIGH |
| + Runtime evidence | HIGH (validated) | HIGH (validated) |
| All three (original source + runtime) | HIGHEST — fully validated | HIGHEST — fully validated |

---

## Arguments

| Argument | Description | Default |
|----------|-------------|---------|
| `<feature>` | Feature name, workflow name (e.g., `ORDER::HD`), or entity ref | Required |
| `--depth shallow` | Primary workflow only, no cross-entity tracing | `full` |
| `--depth full` | All related workflows, cross-entity flows, settings, integrations | Default |
| `--include-runtime` | Collect live event trace via `event.flowInspect` | Off unless entity ref provided |
| `--output <path>` | Custom output path instead of default `accounts/<PROFILE>/features/<slug>/architecture.md` | Auto-generated |

## Quality Checklist

Before saving the document, verify:

- [ ] State diagram shows ALL statuses in the workflow, not just the happy path
- [ ] Cross-entity sequence diagram includes event names AND key data flowing between entities
- [ ] Every ruleset in scope has an explanation row in the Rules & Logic table
- [ ] Settings table shows current values with MISSING flagged for any gaps
- [ ] Integration points table includes endpoint, HTTP method, and payload shape
- [ ] Input → Output data flow table covers every step from entry to terminal
- [ ] Custom rules have source file paths (or "source unavailable" noted)
- [ ] Terminal states are clearly identified (success AND failure paths)
- [ ] Mermaid diagrams render correctly — validate against `knowledge/mermaid-syntax-rules.md` rules (no colons in free text, no unicode arrows, quoted special-char labels)
- [ ] Metadata header includes profile, retailer, workflow versions, generation timestamp
- [ ] **Analysis Confidence section is present** with evidence availability table and per-aspect confidence levels
- [ ] **Missing evidence is called out** — if no source code or runtime, recommendations section explains how to get higher confidence
- [ ] **User action contract validated** (if applicable) — explicit `eventName`, valid `context[].modules`, no invented user-action keys
- [ ] **status.json updated** — `architecture: true` set in the feature's status.json
- [ ] **Extends linkage noted** — if this architecture doc will be the basis for a new feature, note this in the Overview section

## Cross-References

- Workflow structure details: `/fluent-workflow-analyzer`
- Custom code behavior: `/fluent-custom-code`
- Connection topology: `/fluent-connection-analysis`
- Runtime debugging: `/fluent-trace`
- Settings audit: `/fluent-settings`
- Environment discovery: `/fluent-mcp-tools` → `environment.discover`
- Rule descriptions: `/fluent-mcp-tools` → `plugin.list`
- User actions per status: `/fluent-mcp-tools` → `workflow.transitions`
- User action authoring contract: `/fluent-workflow-builder`
- User action diagnostics: `/fluent-transition-api`

## Example Usage

```bash
# Explain a workflow by name
/fluent-feature-explain ORDER::HD

# Explain a named feature (maps to workflows automatically)
/fluent-feature-explain "Home Delivery"

# Shallow analysis — single workflow only
/fluent-feature-explain FULFILMENT::HD_WH --depth shallow

# Include runtime evidence from a real entity
/fluent-feature-explain ORDER::HD --include-runtime HD-001

# Custom output path
/fluent-feature-explain "Click & Collect" --output ./docs/cc-feature.md
```

## Post-Execution: Feedback Capture

After completing this skill (whether success or failure), write a feedback record:

1. **Classify outcome:** `SUCCESS` (completed cleanly), `PARTIAL_SUCCESS` (completed after fixing issues), `FAILURE` (could not complete), `BLOCKED` (prereq missing), `USER_CORRECTED` (user overrode approach)
2. **Build record:** Create a `feedback-record-v1` JSON object with:
   - `skill`: `"fluent-feature-explain"`
   - `feature`: feature slug if applicable, null otherwise
   - `phases`: trace of each phase with PASS/FAIL/SKIP
   - `learnings`: any gotchas discovered during execution
   - `userCorrections`: any corrections the user provided
3. **Redact secrets:** Strip tokens, passwords, API keys. Keep business identifiers.
4. **Append** one JSON line to `accounts/<PROFILE>/feedback/fluent-feature-explain.jsonl`
5. **Update** `accounts/<PROFILE>/feedback/index.json` counters (create with `mkdir -p` if missing)

**Skip capture if:** The execution was trivially simple (e.g., user asked a question, no actual write operation happened).

## Known Pitfalls
<!-- feedback-promoted: managed section, updated by feedback loop -->

_(No promoted learnings yet.)_

<!-- end feedback-promoted -->
