---
name: remuneration-orchestrator
description: "Coordinates the Variable Remuneration, Compensation, and Commissions multi-agent team (Planner, Calculator, QA Auditor). Use this when executing or verifying commission calculations, setting up goals/quotas, validating plans, running delta check clawbacks, testing RLS security, or updating results. Use to re-run, modify, update, correct, check, or audit existing calculations and plan versions."
---

# Remuneration Orchestrator

Wires the multi-agent pipeline: Planner Agent -> Calculator Agent -> QA Auditor Agent to manage plans, execute settlements, and audit outputs.

## Execution Mode: Sequential Subagent Mode

## Subagent Team Configuration

| Agent TypeName | Core Role | Assigned Skills | Intermediate Outputs |
|:---|:---|:---|:---|
| `planner-agent` | Plan & Goal Architect | `plan-management` | `_workspace/02_planner_plans.json` |
| `calculator-agent` | Calculation Engine | `settlement-calculation`, `integration-validation` | `_workspace/03_calculator_settlements.json` |
| `qa-auditor-agent` | Compliance & QA Auditor | `reconciliation-auditing` | `_workspace/04_qa_audit_report.json` |

## Workflow Phases

### Phase 0: Context Check (Incremental & Follow-up Support)
1. Verify if the `_workspace/` directory exists under the project root.
2. Determine execution mode:
   - **No `_workspace/` folder**: Initial run. Proceed to Phase 1.
   - **`_workspace/` exists + User requests partial edit/fix**: Partial re-run. Identify the failing or target agent, call it using `invoke_subagent` with the existing input/output files in the prompt, and overwrite only the target outputs.
   - **`_workspace/` exists + User provides new raw data/plan**: Fresh run. Backup the current workspace to `_workspace_backup_<timestamp>/` and create a clean `_workspace/` folder.
3. For partial re-runs, ensure the subagent receives paths to previous outputs to merge changes correctly.

### Phase 1: Setup & Initialization
1. Parse the user's input request, target collaborators, plans, and period.
2. Ensure `_workspace/` is created and initialize `_workspace/00_input/`.
3. Save raw input parameters or JSON configurations to `_workspace/00_input/parameters.json`.

### Phase 2: Plan Validation & Goals Mapping
1. Invoke the `planner-agent` to check goals and plan statuses.
   - **TypeName**: `planner-agent`
   - **Role**: Plan Manager
   - **Prompt**: "Read the inputs from `_workspace/00_input/parameters.json`. Verify the compensation plans, quotas, and goals. Ensure active plans are version-controlled and not modified in place. Write the validated configuration to `_workspace/02_planner_plans.json`."
2. Read the output of `planner-agent` to ensure no validation flags or unresolved conflicts remain.

### Phase 3: Settlement Execution & Retroactive Clawbacks
1. Invoke the `calculator-agent` to process formulas, run delta checks, and trigger n8n workflows.
   - **TypeName**: `calculator-agent`
   - **Role**: Commission Calculator
   - **Prompt**: "Using the validated plans in `_workspace/02_planner_plans.json`, perform the settlement calculation. Verify historical sales for retroactive clawbacks (delta checks). Route tests through `/webhook-test` endpoints on the internal hostnames. Ensure all `aiAuditNotes` and `flaggedReason` strings are stored as bilingual `{ en, es }` JSON objects. Write outputs to `_workspace/03_calculator_settlements.json`."
2. Verify that settlements were successfully generated.

### Phase 4: QA Auditing & Compliance Checks
1. Invoke the `qa-auditor-agent` to run assertion checks and RLS validations.
   - **TypeName**: `qa-auditor-agent`
   - **Role**: QA Auditor
   - **Prompt**: "Audit the calculation outputs in `_workspace/03_calculator_settlements.json`. Verify row-level security (RLS) constraints for the collaborators, ensure log immutability is respected, and assert that `aiAuditNotes` and `flaggedReason` are correctly formatted as bilingual `{ en, es }` JSON objects. Write your report to `_workspace/04_qa_audit_report.json`."
2. Read the audit report. If critical violations (e.g. invalid bilingual JSON, RLS failures) are found, request corrections from the respective agent.

### Phase 5: final Integration & Output Generation
1. Read the final QA audit report and the calculation outputs.
2. Compile and save the final settlement run summary to `docs/settlement_run_latest.md`.
3. Keep the `_workspace/` directory preserved for history/auditing.
4. Report the summary of the run to the user, highlighting calculations, adjusted clawbacks, and validation status.

## Data Flow Diagram

```mermaid
graph TD
    User([User Request]) --> P1[Phase 1: Setup]
    P1 -->|Save input| RawFile[_workspace/00_input/parameters.json]
    RawFile --> P2[Phase 2: planner-agent]
    P2 -->|Validate plans| PlanFile[_workspace/02_planner_plans.json]
    PlanFile --> P3[Phase 3: calculator-agent]
    P3 -->|Run settlement & n8n| CalcFile[_workspace/03_calculator_settlements.json]
    CalcFile --> P4[Phase 4: qa-auditor-agent]
    P4 -->|Verify RLS & i18n JSON| QAFile[_workspace/04_qa_audit_report.json]
    QAFile --> P5[Phase 5: Orchestrator Integration]
    P5 -->|Write summary| FinalOut[docs/settlement_run_latest.md]
```

## Error Handling Matrix

| Failure Mode | Resolution Strategy |
|:---|:---|
| Subagent execution error | Retry once. If failure persists, record the traceback, fallback to a safe null output, and flag the failure in the final report. |
| Non-bilingual `{ en, es }` notes | Re-invoke the calculator-agent to apply the translation chain and rewrite the fields as valid `{ en, es }` JSON. |
| RLS constraint breach | Immediately halt the pipeline, mark the run as FAILED, and notify the user with the trace details. |
| n8n webhook connection failure | Verify shared Docker network routing between Caddy and n8n, check internal hostnames, and retry with the correct endpoint. |

## Verification Test Scenarios

### Scenario 1: Standard Commission Run (Success)
1. **Input**: Quota/goals for collaborator "Juan Perez" with monthly sales data.
2. **Execution**: Planner validates goal, Calculator computes commission and translates notes to Spanish/English, QA Auditor verifies RLS rules and bilingual JSON.
3. **Expected Outcome**: `docs/settlement_run_latest.md` created, all tests pass, and database stores bilingual notes.

### Scenario 2: RLS Validation Failure (Error Fallback)
1. **Input**: Sales imports trying to cross-read records of another hotel site without appropriate permissions.
2. **Execution**: Planner passes layout, Calculator executes, but QA Auditor detects RLS violation during boundary checking.
3. **Expected Outcome**: Run halted. No settlements approved. Error logged in `_workspace/04_qa_audit_report.json`.
