---
name: fluent-source-onboard
description: Onboard existing Java source code into a proper Fluent Commerce extension module. Analyzes non-standard code layouts (loose files, decompiled JARs, different build systems), restructures into Maven multi-module format with module.json, validates the result, and optionally attempts a build. Triggers on "onboard source", "refactor to module", "convert to module format", "restructure module", "import source code", "migrate to fluent module".
user-invocable: true
allowed-tools: Bash, Read, Write, Edit, Glob, Grep
argument-hint: <source-path> [--module-name <name>] [--account-prefix <PREFIX>] [--dry-run] [--skip-build]
cursor-tier: manual
planning-gate: advisory
---

# Source Onboarder

Take existing Java source code — whether loose files, a non-standard project layout, a decompiled JAR, or a project using a different build system — and restructure it into a proper Fluent Commerce extension module that passes `/fluent-module-validate` and builds with `/fluent-build`.

## Pre-flight: Feedback Check

Before starting, check for past learnings from this skill:

1. Check if `accounts/<PROFILE>/feedback/fluent-source-onboard.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

## When to Use

- "I have Java rule classes but they're not in a Fluent module structure"
- "Onboard this decompiled JAR into a buildable module"
- "Convert this Gradle project to Fluent Commerce module format"
- "I have source code from another team — make it a proper module"
- "Restructure this code into the standard Maven multi-module layout"
- "Import these rule classes into a deployable module"
- Code exists in `accounts/<PROFILE>/SOURCE/backend/` but doesn't pass `/fluent-module-validate`
- Decompiled output exists in `accounts/<PROFILE>/SOURCE/backend/.decompiled/` and needs to become a buildable module
- `/fluent-scope-decompose` generated a `SOURCE_ONBOARD` task

## When NOT to Use

- Source code doesn't exist yet --> `/fluent-module-scaffold` (creates from scratch)
- Module already exists and passes validation, just need to add rules --> `/fluent-rule-scaffold`
- Only need to analyze/understand code, not restructure --> `/fluent-custom-code`
- Module structure is fine but needs version bumps --> `/fluent-version-manage`

## Ownership Boundary

This skill owns:
- Analyzing existing source layout and classifying its state
- Generating a restructuring plan (target module structure)
- Moving, renaming, and refactoring files into Fluent module format
- Generating missing infrastructure files (POMs, module.json, build scripts, .gitignore)
- Fixing common structural issues (wrong base class, missing annotations, package mismatches)
- Running post-restructure validation via `/fluent-module-validate`

This skill does **not** own:
- Building the module after restructuring --> `/fluent-build`
- Adding new rules not present in source --> `/fluent-rule-scaffold`
- Deploying the restructured module --> `/fluent-module-deploy`
- Deep behavior analysis of existing rules --> `/fluent-custom-code`
- Decompiling JARs (but uses decompiled output) --> `/fluent-custom-code` or `/fluent-connect`

### Cross-Skill Integration

**Upstream:**
- `/fluent-custom-code` — May have already analyzed the source (reuse `source-map.json`, `workflow-rule-map.json`)
- `/fluent-connect` — May have already decompiled JARs (reuse `.decompiled/` output)
- `/fluent-scope-decompose` — May have generated the `SOURCE_ONBOARD` task that triggered this skill

**Downstream:**
- `/fluent-module-validate` — Validate the restructured output
- `/fluent-build` — Attempt a Maven compile to verify buildability
- `/fluent-rule-scaffold` — Add new rules to the now-valid module
- `/fluent-module-deploy` — Deploy the restructured module

## Inputs

| Parameter | Required | Default | Description |
|-----------|----------|---------|-------------|
| `source-path` | Yes | -- | Path to existing source code. Can be a directory with Java files, a decompiled JAR output, or a non-standard project root. Relative to workspace or absolute. |
| `--module-name` | No | Auto-detect | Target module name. If not specified, derived from directory name or existing `module.json`. |
| `--account-prefix` | No | Auto-detect | Account context prefix for rule registration (e.g., `MY_PROFILE`). Same detection logic as `/fluent-module-scaffold`. |
| `--dry-run` | No | `false` | Analyze and plan only — do not move or modify any files. Produces the restructuring plan and exits. |
| `--skip-build` | No | `false` | Skip the post-restructure Maven build verification. |
| `--preserve-original` | No | `true` | Keep original files in a `.onboard-backup/` directory. Set `false` to delete originals after restructuring. |

## Execution Protocol

**Phase ordering note:** Unlike most implementation skills, source-onboard runs analysis (Phase 1) BEFORE the planning gate (Phase 2). This is intentional — you must understand what exists before you can plan the restructuring. Phase 1 is read-only analysis. Phase 2 is the mandatory approval gate before any files are modified.

### Phase 1: Source Analysis (read-only)

**Goal:** Understand what exists, classify its state, and identify all rule classes. **No files are modified in this phase.**

#### Step 1.1: Classify Source Layout

Scan the provided `source-path` and classify into one of these categories:

| Category | Detection | Example |
|----------|-----------|---------|
| `DECOMPILED_JAR` | Path contains `.decompiled/` or has `DECOMPILED.md` marker | `SOURCE/backend/.decompiled/fc-module-ext/` |
| `STANDARD_MODULE` | Has `module.json` + `pom.xml` + `src/main/java/` | Standard but may have issues |
| `PARTIAL_MODULE` | Has some but not all of: `module.json`, `pom.xml`, Maven layout | Missing pieces |
| `MAVEN_NONSTANDARD` | Has `pom.xml` but not Fluent module layout (missing `plugins/` structure) | Generic Maven project |
| `GRADLE_PROJECT` | Has `build.gradle` or `build.gradle.kts` | Needs Maven conversion |
| `LOOSE_JAVA` | Has `.java` files but no build system files | Bare source files |
| `MIXED` | Multiple of the above in subdirectories | Complex layout |

```
source-path/
├── Glob("**/*.java")      → collect all Java files
├── Glob("**/module.json")  → find Fluent module manifests
├── Glob("**/pom.xml")      → find Maven POMs
├── Glob("**/build.gradle*") → find Gradle files
├── Glob("**/DECOMPILED.md") → check for decompiled markers
└── Classify based on what's found
```

#### Step 1.2: Discover Rule Classes

For each Java file found, determine if it's a Fluent rule class:

**Detection patterns** (check in order):
1. Extends `BaseRule` or `Rule` (from Rubix SDK)
2. Has `@RuleInfo` annotation
3. Implements `run(ContextWrapper context)` or `run(Context context)` method
4. Contains `context.getProp(...)` or `context.getEvent()` calls
5. Is registered in a `module.json` (if one exists)

**For each detected rule, extract:**
- Class name (e.g., `ValidateReturnWindow`)
- Package name (e.g., `com.fluentcommerce.rule.order`)
- Base class (`BaseRule`, `Rule`, or other)
- Entity types accepted (from `@RuleInfo` or method signatures)
- Parameters read (from `context.getProp(...)` calls)
- Events produced (from `context.action().sendEvent(...)` calls)
- Has corresponding test class? (`<ClassName>Test.java`)

**For decompiled source**, also flag:
- Synthetic variable names (e.g., `var1`, `this$0`)
- Missing Javadoc/comments
- Confidence level: decompiled vs original

#### Step 1.3: Detect Existing module.json

If a `module.json` exists in the source path:
- Parse it for existing rule registrations
- Compare against discovered Java classes
- Flag mismatches:
  - Rules in `module.json` but no Java class found (orphaned registration)
  - Java rule classes not in `module.json` (unregistered rules)
  - Version information
  - Account prefix / symbolic name

#### Step 1.4: Check Against Deployed State

Query the live environment to understand what's deployed:

```
plugin.list (compact: true)
```

- Cross-reference discovered rule classes against deployed rules
- Identify rules that are deployed but have different versions or parameters
- Flag any namespace conflicts

### Phase 2: Planning Gate

#### Pre-flight Chain (Three-Level)

Before restructuring any source code, run the three-level pre-flight check:

1. **Spec check:** If `accounts/<PROFILE>/features/<slug>/status.json` exists for this work:
   - Check `spec: "APPROVED"` — If missing, BLOCK: `→ BLOCKED: PREREQ_MISSING — Run /fluent-use-case-discover first`
   - Check `plan: "APPROVED"` — If missing, BLOCK: `→ BLOCKED: PLAN_REQUIRED — Run /fluent-feature-plan first`
   - If both approved, skip to implementation referencing the plan's relevant sections
2. **Multi-artifact work** (onboarding as part of larger feature): STOP. Invoke `/fluent-feature-plan` first
3. **Standalone source-onboard work** (no feature context):
   - Check `accounts/<PROFILE>/tasks/` for a task plan with `Status: APPROVED`
   - If approved task plan found, skip to implementation
   - If no plan, continue to the Planning Gate below

**MANDATORY: Present a restructuring plan before making ANY changes.** Use the template from `PLAN_TEMPLATE.md` in the `fluent-feature-plan` skill as the base structure. Every table row must carry a Source column (NEW/EXISTING/MODIFIED/REUSED/OOTB). Extend with the source-onboard-specific sections below.

Write the plan to: `accounts/<PROFILE>/tasks/<YYYY-MM-DD>-source-onboard-<slug>.md`. Set `Status: PENDING`.

**Source-onboard specific sections** (in addition to the standard template):

#### 2.1 Source Assessment Summary

```markdown
## Source Assessment

| Property | Value |
|----------|-------|
| Source path | `accounts/MY_PROFILE/SOURCE/backend/.decompiled/fc-module-ext/` |
| Layout category | DECOMPILED_JAR |
| Java files found | 12 |
| Rule classes detected | 8 |
| Test classes found | 3 |
| Existing module.json | No |
| Existing pom.xml | No |
| Decompiled source | Yes (confidence: MEDIUM) |
```

#### 2.2 Discovered Rules Table

```markdown
## Discovered Rules

| # | Class Name | Package | Base Class | Entity Types | Has Test | Deployed? | Status |
|---|-----------|---------|------------|-------------|----------|-----------|--------|
| 1 | ValidateOrder | com.fc.rule.order | BaseRule | ORDER | Yes | Yes (v2.1) | OK |
| 2 | CreateFulfilment | com.fc.rule.ful | Rule | ORDER | No | Yes (v2.1) | WARN: extends Rule, not BaseRule |
| 3 | NotifyWarehouse | com.fc.rule.webhook | BaseRule | FULFILMENT | No | No | NEW |
```

#### 2.3 Target Module Structure

```markdown
## Target Structure

accounts/<PROFILE>/SOURCE/backend/fluentcommerce-fc-module-<module-name>/
+-- plugins/
|   +-- pom.xml                    # NEW: parent POM
|   +-- types/
|   |   +-- <alias>/
|   |       +-- pom.xml            # NEW: types POM
|   |       +-- src/main/java/     # MOVED: DTO/type classes
|   +-- util/
|   |   +-- <alias>/
|   |       +-- pom.xml            # NEW: util POM
|   |       +-- src/main/java/     # MOVED: utility classes
|   +-- rules/
|       +-- <alias>/
|           +-- pom.xml            # NEW: rules POM
|           +-- src/main/java/     # MOVED: rule classes (repackaged)
|           +-- src/test/java/     # MOVED or GENERATED: test classes
+-- resources/
|   +-- module.json                # NEW or MERGED: rule registrations
+-- scripts/
|   +-- build.sh                   # NEW: build script
|   +-- build.ps1                  # NEW: PowerShell build script
+-- .gitignore                     # NEW
```

#### 2.4 File Operations Plan

```markdown
## File Operations

| # | Operation | Source | Target | Notes |
|---|-----------|--------|--------|-------|
| 1 | MOVE | .decompiled/fc-ext/com/fc/rule/order/ValidateOrder.java | plugins/rules/<alias>/src/main/java/com/fluentcommerce/rule/order/ValidateOrder.java | Repackage from com.fc to com.fluentcommerce |
| 2 | MOVE | .decompiled/fc-ext/com/fc/rule/ful/CreateFulfilment.java | plugins/rules/<alias>/src/main/java/com/fluentcommerce/rule/fulfilment/CreateFulfilment.java | Repackage + fix base class |
| 3 | GENERATE | -- | plugins/rules/<alias>/src/test/java/.../CreateFulfilmentTest.java | Test skeleton (no existing test) |
| 4 | GENERATE | -- | resources/module.json | 8 rule registrations |
| 5 | GENERATE | -- | plugins/pom.xml | Parent POM with SDK dependencies |
```

#### 2.5 Code Modifications Plan

```markdown
## Code Modifications

| # | File | Change | Reason |
|---|------|--------|--------|
| 1 | CreateFulfilment.java | `extends Rule` -> `extends BaseRule` | Standard base class |
| 2 | All rule classes | Package `com.fc.rule.*` -> `com.fluentcommerce.rule.*` | Standard package convention |
| 3 | All rule classes | Add missing `@RuleInfo` annotation | Required for module.json wiring |
| 4 | NotifyWarehouse.java | Add `@Override` to `run()` method | Compiler warning fix |
```

#### 2.6 Risk Assessment

```markdown
## Risk Assessment

| Risk | Severity | Mitigation |
|------|----------|------------|
| Package rename breaks imports in downstream code | MEDIUM | Grep for old package refs after restructure |
| Decompiled source may have subtle bytecode artifacts | LOW | Build verification will catch compile errors |
| Module.json registration keys may not match deployed names | HIGH | Cross-reference with plugin.list before deploy |
| Test classes may not compile due to missing test dependencies | LOW | POMs include standard test deps |
```

**Wait for user approval.** On `--dry-run`, output the plan and exit without making changes.

## Handoff Protocol

### Signals emitted by this skill

| Signal | Condition | Example |
|--------|-----------|---------|
| `-> READY: <path>` | Module restructured | `-> READY: accounts/MY_PROFILE/SOURCE/backend/fc-module-restructured/` |
| `-> NEXT: /fluent-<skill>` | Ready for build + validation | `-> NEXT: /fluent-build` |
| `-> BLOCKED: <reason>` | Cannot proceed | `-> BLOCKED: PREREQ_MISSING — No source code found at specified path` |

### Error codes

| Code | Condition | Recovery |
|------|-----------|----------|
| `PREREQ_MISSING` | No source code found at the specified path | Provide correct path or clone repo |
| `VALIDATION_FAILED` | Source cannot be restructured (incompatible format) | Manual intervention required |

### Phase 3: Execute Restructuring

After approval, execute the plan in this order:

#### Step 3.1: Create Target Directory Structure

Generate the full Maven multi-module directory tree using the same structure as `/fluent-module-scaffold`:

```
fluentcommerce-fc-module-<module-name>/
  plugins/
    pom.xml (parent, packaging=pom)
    types/<alias>/pom.xml + src/main/java/
    util/<alias>/pom.xml + src/main/java/
    rules/<alias>/pom.xml + src/main/java/ + src/test/java/
  resources/module.json
  scripts/build.sh + build.ps1
  .gitignore
```

Use the **exact same POM templates, SDK versions, and build scripts** as `/fluent-module-scaffold` generates. Do not reinvent — reuse the same patterns.

#### Step 3.2: Move and Repackage Rule Classes

For each discovered rule class:

1. **Copy** (not move initially) to target location under `plugins/rules/<alias>/src/main/java/`
2. **Repackage** if the original package doesn't follow `com.fluentcommerce.*` convention:
   - Update `package` declaration in the Java file
   - Update all internal `import` statements that reference sibling classes
   - Track old-to-new package mapping for cross-reference
3. **Classify** non-rule classes:
   - Classes that are DTOs/POJOs/types --> `plugins/types/<alias>/src/main/java/`
   - Classes that are utilities/helpers --> `plugins/util/<alias>/src/main/java/`
   - Classes that are rule implementations --> `plugins/rules/<alias>/src/main/java/`

**Classification heuristics:**
- Extends `BaseRule`/`Rule` or has `@RuleInfo` --> rule
- Is an `enum`, has only getters/setters, or has `@Data`/`@Builder` --> type
- Is a helper/utility (static methods, service patterns, no rule inheritance) --> util
- Unclear --> ask user, default to rules

#### Step 3.3: Fix Common Structural Issues

Apply these fixes automatically (all tracked in the plan):

| Issue | Fix | Auto-apply? |
|-------|-----|-------------|
| `extends Rule` instead of `extends BaseRule` | Change to `extends BaseRule` | Yes |
| Missing `@RuleInfo` annotation | Add with class name as description | Yes (warn: description is generic) |
| Missing `@Override` on `run()` method | Add `@Override` | Yes |
| Wrong import for `BaseRule`/`Rule` | Fix to `com.fluentretail.rubix.rule.meta.BaseRule` | Yes |
| Synthetic variable names (decompiled) | Leave as-is, add `// decompiled` comment at top | Yes |
| Missing `@ParamString` annotations on rule parameters | Add based on `context.getProp()` calls detected in Phase 1 | Yes |
| Non-standard `run()` signature | Fix to `run(ContextWrapper context)` | Ask user |

#### Step 3.4: Move or Generate Test Classes

For each rule class:

1. If a test class exists in the source: **copy** it to `plugins/rules/<alias>/src/test/java/` with matching package
2. If no test class exists: **generate** a skeleton test using the same template as `/fluent-rule-scaffold`:
   - Class name: `<RuleName>Test.java`
   - Imports: JUnit 5, Mockito, Fluent test utilities
   - One `@Test` method: `test<RuleName>_shouldRun()` with setup/execute/verify structure
   - Comment: `// TODO: implement test logic`

#### Step 3.5: Generate or Merge module.json

If no `module.json` exists in the source:
- **Generate** a new one following the same format as `/fluent-module-scaffold`
- Register all discovered rule classes with:
  - Key: `<ACCOUNT_PREFIX>.<context>.<ClassName>` (e.g., `MY_PROFILE.order.ValidateOrder`)
  - Context derived from entity type or package name
  - Class path: `com.fluentcommerce.rule.<domain>.<ClassName>`

If a `module.json` already exists:
- **Merge**: keep existing entries, add missing rules, flag conflicts
- Fix any rule keys that don't match the account prefix
- Preserve metadata fields (`_schema`, `title`, `description`, `authors`, etc.)
- Add missing metadata fields with sensible defaults

#### Step 3.6: Generate Build Infrastructure

**Files to generate** (same templates as `/fluent-module-scaffold`):

- `plugins/pom.xml` — Parent POM (packaging=pom, modules: types, util, rules)
- `plugins/types/<alias>/pom.xml` — Types submodule
- `plugins/util/<alias>/pom.xml` — Util submodule
- `plugins/rules/<alias>/pom.xml` — Rules submodule (depends on types + util, includes test deps)
- `scripts/build.sh` — Bash build script
- `scripts/build.ps1` — PowerShell build script
- `.gitignore` — Standard ignores (target/, *.class, .idea/, etc.)

**SDK version detection:**
- If existing POMs reference Fluent SDK versions, preserve them
- Otherwise use the latest versions from `/fluent-module-scaffold` defaults
- Always include: `rubix-plugin-sdk`, `fluent-api-client`, JUnit 5, Mockito

#### Step 3.7: Backup Original Files

If `--preserve-original` is true (default):
- Create `<module-root>/.onboard-backup/` directory
- Copy all original source files there (preserving directory structure)
- Write `BACKUP.md` with timestamp, source path, and file count

### Phase 4: Validation

After restructuring, run validation checks to verify the result.

#### Step 4.1: Structure Validation

Run the same checks as `/fluent-module-validate`:

| Check | Expected | Severity |
|-------|----------|----------|
| `resources/module.json` exists | Yes | FAIL |
| `module.json` has valid JSON | Yes | FAIL |
| `module.json` has `name` field | Yes | FAIL |
| `module.json.rules[]` is non-empty | Yes | FAIL |
| Each rule in `module.json` has matching Java class | Yes | FAIL |
| Each Java rule class is in `module.json` | Yes | WARN |
| `plugins/pom.xml` exists | Yes | FAIL |
| Parent POM has `<packaging>pom</packaging>` | Yes | WARN |
| Rules POM references parent | Yes | WARN |
| Each rule extends `BaseRule` or `Rule` | Yes | WARN |
| Each rule has `@RuleInfo` annotation | Yes | WARN |
| Each rule has a corresponding test class | Yes | WARN |
| No orphaned Java files outside the standard layout | Yes | WARN |
| No leftover files from original layout | Yes | INFO |

Report results as a table with PASS/WARN/FAIL per check.

#### Step 4.2: Compilation Check (unless --skip-build)

Attempt a Maven build to verify the restructured module compiles:

```bash
cd accounts/<PROFILE>/SOURCE/backend/fluentcommerce-fc-module-<module-name>/plugins
mvn clean compile -q 2>&1
```

**If build succeeds:** Report success with artifact coordinates.

**If build fails:**
- Parse Maven error output
- Classify errors:
  - Missing imports (suggest adding dependencies to POM)
  - Unresolved symbols (suggest checking package renames)
  - Type mismatches (suggest reviewing decompiled artifacts)
- Present errors to user with suggested fixes
- Do NOT automatically retry — the user should review

#### Step 4.3: Deployed Rule Reconciliation

Cross-reference the restructured module against deployed rules:

```
plugin.list (name filter: <ACCOUNT_PREFIX>)
```

| Check | Result |
|-------|--------|
| Rules in module.json that are already deployed | LIST (version comparison) |
| Deployed rules NOT in this module | LIST (belong to other modules?) |
| Rule key format matches deployed format | PASS/FAIL per rule |
| Account prefix is consistent | PASS/FAIL |

#### Step 4.4: Functional Checklist

Present a manual verification checklist to the user:

```markdown
## Post-Onboard Checklist

- [ ] Review repackaged rule classes — verify business logic is preserved
- [ ] Review generated test skeletons — add meaningful test assertions
- [ ] Verify module.json rule keys match expected deployment names
- [ ] If source was decompiled: review for synthetic artifacts, add meaningful variable names
- [ ] Run full test suite: `cd plugins && mvn test`
- [ ] Deploy to sandbox: `/fluent-module-deploy`
- [ ] Run E2E test: `/fluent-e2e-test` to verify runtime behavior
```

### Phase 5: Summary Report

Output a structured summary:

```markdown
## Source Onboard Summary

| Metric | Value |
|--------|-------|
| Source category | DECOMPILED_JAR |
| Rule classes onboarded | 8 |
| Test classes moved | 3 |
| Test skeletons generated | 5 |
| Type/DTO classes moved | 2 |
| Utility classes moved | 1 |
| module.json rules registered | 8 |
| Code modifications applied | 12 |
| Validation: PASS | 14 |
| Validation: WARN | 3 |
| Validation: FAIL | 0 |
| Build status | SUCCESS |
| Original files backed up | Yes (.onboard-backup/) |

### Files Created
- `plugins/pom.xml` (parent)
- `plugins/types/<alias>/pom.xml`
- `plugins/util/<alias>/pom.xml`
- `plugins/rules/<alias>/pom.xml`
- `resources/module.json` (8 rules)
- `scripts/build.sh`
- `scripts/build.ps1`
- `.gitignore`
- 5 test skeleton files

### Code Changes Applied
- 8 classes repackaged: com.fc.rule.* -> com.fluentcommerce.rule.*
- 1 class fixed: CreateFulfilment extends Rule -> extends BaseRule
- 2 classes: added missing @RuleInfo annotation
- 3 classes: added missing @Override on run()

### Next Steps
1. Review generated tests and add assertions
2. Run `/fluent-module-validate` for detailed structural report
3. Build: `/fluent-build`
4. Deploy: `/fluent-module-deploy`
```

---

## Input Scenarios — Detailed Handling

### Scenario A: Decompiled JAR (`.decompiled/` directory)

```
accounts/MY_PROFILE/SOURCE/backend/.decompiled/fc-module-ext/
  com/fluentcommerce/rule/order/ValidateOrder.class → .java (decompiled)
  com/fluentcommerce/rule/fulfilment/CreateFulfilment.class → .java
  DECOMPILED.md
```

**Handling:**
1. Read `DECOMPILED.md` for source JAR name, date, decompiler used
2. All classes are rule candidates — classify by detection patterns
3. Package structure may already be correct (decompiled from original)
4. Add `// Decompiled source — variable names may be synthetic` header to each file
5. Mark confidence as MEDIUM in module.json comments
6. Generate all infrastructure files (POMs, module.json, build scripts)
7. **Do not modify decompiled business logic** — only structural fixes (base class, annotations)

### Scenario B: Loose Java Files

```
some-directory/
  ValidateOrder.java
  CreateFulfilment.java
  OrderHelper.java
  OrderType.java
```

**Handling:**
1. No existing package structure — derive from class content or ask user
2. Default package: `com.fluentcommerce.rule.<entity-type-lowercase>`
3. Add `package` declarations to files that don't have them
4. Classify: rules vs types vs utils
5. Generate complete module infrastructure from scratch

### Scenario C: Non-Standard Maven Project

```
my-rules/
  pom.xml (exists but not Fluent multi-module layout)
  src/main/java/com/mycompany/rules/
    ValidateOrder.java
    CreateFulfilment.java
  src/test/java/com/mycompany/rules/
    ValidateOrderTest.java
```

**Handling:**
1. Existing POM — parse for dependency versions, group ID
2. Existing package `com.mycompany` — repackage to `com.fluentcommerce`
3. Existing tests — move alongside repackaged classes
4. Restructure to multi-module layout (flat `src/` -> `plugins/rules/<alias>/src/`)
5. Generate missing types/util submodules (empty initially)
6. Preserve dependency versions from original POM where possible

### Scenario D: Gradle Project

```
my-gradle-module/
  build.gradle
  src/main/java/...
  src/test/java/...
```

**Handling:**
1. Parse `build.gradle` for dependencies and versions
2. Convert dependency declarations to Maven POM format
3. Same restructuring as Scenario C but with Gradle-to-Maven conversion
4. Warn about any Gradle plugins that don't have Maven equivalents

### Scenario E: Existing Module with Structural Issues

```
fc-module-ext/
  resources/module.json (exists, possibly outdated)
  plugins/
    pom.xml (exists but may be wrong)
    rules/<alias>/
      src/main/java/... (exists)
```

**Handling:**
1. This is a "repair" mode — module exists but has issues
2. Run `/fluent-module-validate` to identify specific problems
3. Generate a targeted fix plan (don't rebuild from scratch)
4. Fix only what's broken:
   - Missing submodules → generate them
   - Orphaned rules → add to module.json
   - Wrong base class → fix
   - Missing tests → generate skeletons
5. Preserve everything that's already correct

---

## Error Recovery

| Error | Handling |
|-------|---------|
| Java file doesn't compile after repackaging | List errors, suggest fixes, don't auto-retry |
| module.json rule key conflicts with existing deployed rule | Warn, ask user to choose: keep existing key or use new |
| Circular package dependencies after restructuring | Flag in validation, suggest manual reorganization |
| Decompiled source has unresolvable artifacts | Mark as `// MANUAL_REVIEW_NEEDED`, add to checklist |
| Maven build fails on SDK version mismatch | Suggest updating SDK versions, show what deployed modules use |
| Source path doesn't contain any Java files | Abort: "No Java files found in <path>. Verify the source path." |
| Source path contains only non-rule Java files | Abort: "No Fluent rule classes detected. Found N Java files but none extend BaseRule/Rule or have @RuleInfo." |
| `--module-name` conflicts with existing module | Warn and ask user: rename or merge? |

---

## Cross-References

- Module structure reference: `/fluent-module-scaffold`
- Source code analysis: `/fluent-custom-code`
- Structure validation: `/fluent-module-validate`
- Build execution: `/fluent-build`
- Rule addition: `/fluent-rule-scaffold`
- Deployment: `/fluent-module-deploy`
- Version management: `/fluent-version-manage`
- Pre-deploy checks: `/fluent-pre-deploy-check`
- JAR decompilation: `/fluent-custom-code` (Step 1A) or `/fluent-connect` (workspace setup)

## Example Usage

```bash
# Onboard decompiled JAR output into a module
/fluent-source-onboard accounts/MY_PROFILE/SOURCE/backend/.decompiled/fc-module-ext/

# Onboard loose Java files with explicit module name
/fluent-source-onboard ./my-rules/ --module-name my-returns

# Dry run — analyze and plan only, don't modify anything
/fluent-source-onboard accounts/MY_PROFILE/SOURCE/backend/legacy-project/ --dry-run

# Onboard without attempting build (e.g., missing SDK locally)
/fluent-source-onboard accounts/MY_PROFILE/SOURCE/backend/old-module/ --skip-build

# Repair an existing module with structural issues
/fluent-source-onboard accounts/MY_PROFILE/SOURCE/backend/fluentcommerce-fc-module-ext/
```

## 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-source-onboard"`
   - `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-source-onboard.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 -->
