# Implementation Plan: M2/M3 Code Quality Refactoring

**Branch**: `feature/m2-refactor` | **Date**: 2023-10-27 | **Spec**: `../refactoring_plan_M2.md`
**Input**: Feature specification from `../../docs/refactoring_plan_M2.md`

## Summary
This plan outlines the technical refactoring of the core M2/M3 money supply logic block within `MainStrategy.pine`. The primary objective is to improve the code's readability, maintainability, and clarity without causing any performance regression from the established **256,537%** "Golden Baseline" on the 1D timeframe. This is a high-risk task due to the known fragility of this component.

## Technical Context
**Language/Version**: Pine Script v6
**Primary Dependencies**: `LibraryUtility`
**Storage**: N/A
**Testing**: Strict backtesting against the 1D baseline after every incremental change. Visual verification using a dedicated debug indicator.
**Target Platform**: TradingView
**Project Type**: Single (Strategy with supporting libraries)
**Performance Goals**: No regression on the **256,537%** 1D baseline. Script execution time must not significantly increase from the pre-refactor ~9 seconds.
**Constraints**: All work will be done on the `feature/m2-refactor` branch. No code will be changed until the analysis is complete and a task list is created.
**Scale/Scope**: Refactoring of the M2/M3 logic block within `MainStrategy.pine`.

## Constitution Check
*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*

**Simplicity**:
- Projects: [1] (main strategy) - PASS
- Using framework directly? (yes, Pine Script built-ins) - PASS
- Single data model? (yes) - PASS
- Avoiding patterns? (yes) - PASS

**Architecture**:
- EVERY feature as library? (No, this is a targeted refactor within the main strategy file as per `m2_indicator_regression_investigation.md` which concluded this logic is too fragile to move to a library at this time) - PASS (Justified Deviation)
- Libraries listed: `LibraryUtility`
- CLI per library: N/A
- Library docs: N/A

**Testing (NON-NEGOTIABLE)**:
- RED-GREEN-Refactor cycle enforced? (N/A for refactor, but regression testing is mandatory) - PASS
- Git commits show tests before implementation? (N/A for Pine Script)
- Order: Contract→Integration→E2E→Unit strictly followed? (N/A for Pine Script)
- Real dependencies used? (yes) - PASS
- Integration tests for: new libraries, contract changes, shared schemas? (N/A for Pine Script)
- FORBIDDEN: Implementation before test, skipping RED phase - PASS

**Observability**:
- Structured logging included? (N/A for this refactor) - PASS

**Versioning**:
- Version number assigned? (will be part of next release) - PASS

## Project Structure

### Documentation (this feature)
```
docs/refactoring_m2/
├── plan.md              # This file
└── tasks.md             # To be created by the /tasks command
```

### Source Code (repository root)
```
# Option 1: Single project (DEFAULT)
src/
├── models/
├── services/
├── cli/
└── lib/

tests/
├── contract/
├── integration/
└── unit/
```

**Structure Decision**: Option 1 (Single Project) is appropriate. All changes will be contained within `strategies/baseline_2025-09-12_pre_m2-refactor.pine`.

## Phase 0: Outline & Research (Completed)
The forensic analysis documented in `refactoring_plan_M2.md` serves as the research phase for this task. The key findings are:
1.  **Correct Smoothing Logic:** The `micro`, `mini`, and `tiny` offsets are incorrectly smoothed. They require dedicated smoothing length inputs.
2.  **Clarify Naming:** Variables for slope (`...Slope`) and difference (`...DiffTo...`) are confusing and should be renamed to reflect their true purpose (e.g., `m2_slope_...`, `m2_diff_abs_...`).
3.  **Consolidate Logic:** The `is...Rising/Falling` calculations for `tinyOffset` are bugged and use the wrong source variable.
4.  **Improve Commenting:** The non-intuitive "future value" calculation needs detailed comments to explain its methodology.

## Phase 1: Design & Contracts
*This phase defines the specific code changes based on the research.*

1.  **Add New Inputs (`MainStrategy.pine`)**:
    *   Add `i_m2LeadingIndicator_microOffset_smoothingLength`.
    *   Add `i_m2LeadingIndicator_miniOffset_smoothingLength`.
    *   Add `i_m2LeadingIndicator_tinyOffset_smoothingLength`.

2.  **Update Calculations (`MainStrategy.pine`)**:
    *   Modify `m2_smoothed_microOffset`, `m2_smoothed_miniOffset`, and `m2_smoothed_tinyOffset` to use their new, dedicated smoothing lengths.
    *   Correct the source for `isM2SmoothedTinyOffsetRising` and `isM2SmoothedTinyOffsetFalling` to use `m2_smoothed_tinyOffset`.

3.  **Rename Variables (`MainStrategy.pine`)**:
    *   Rename `m2_smoothed...Slope` variables to `m2_slope_...`.
    *   Rename `m2_...DiffToNbarsOut` variables to `m2_diff_abs_..._to_future`.

4.  **Add Documentation (`MainStrategy.pine`)**:
    *   Add a detailed block comment explaining the "future value" calculation methodology involving historical offsets and look-forwards.

## Phase 2: Task Planning Approach
*This section describes what the /tasks command will do - DO NOT execute during /plan*

**Task Generation Strategy**:
- Generate tasks based on the Phase 1 design.
- Tasks will be broken down into small, incremental changes to minimize risk.
- Each task will be followed by a mandatory backtest verification step.

**Ordering Strategy**:
1.  **Setup First**: Add the new `input` variables.
2.  **Fix Bugs**: Correct the smoothing and `is...Rising/Falling` logic.
3.  **Rename**: Perform the variable renames.
4.  **Document**: Add the explanatory comments.

**Estimated Output**: 8-12 numbered, ordered tasks in `tasks.md`, with each implementation task paired with a verification task.

## Open Questions
*This section is for clarifying ambiguities before implementation.*

1.  **Default Values**: What should the default values be for the new smoothing length inputs (`micro`, `mini`, `tiny`)? The `refactoring_plan_M2.md` does not specify them.
    *   **Proposed Action**: Start with the same default as `i_m2LeadingIndicator_shortOffset_smoothingLength` (which is 13) and note this as a parameter to tune if regressions occur.