# NT8 SDK — Kilocode Runbook
## Production Hardening: 5 Tasks, ~4 Hours Total

This runbook tells you exactly what to say to Kilocode for each task, in which order, and how to verify before moving on.

---

## Pre-Flight Checklist (Do This Once Before Starting)

**1. Open VS Code in the right folder**
```
File → Open Folder → C:\dev\nt8-sdk
```

**2. Verify Kilocode rules are loaded**
- Click the ⚖️ (law) icon in the Kilocode panel bottom-right
- You should see these 5 rules listed and enabled:
  - `csharp_50_syntax.md`
  - `coding_patterns.md`
  - `file_boundaries.md`
  - `verification_requirements.md`
  - `project_context.md`
- If not showing: `Ctrl+Shift+P` → "Kilocode: Reload Rules"

**3. Confirm baseline build passes**
```
Ctrl+Shift+B
```
Expected output: ✅ All checks passed! (zero errors, zero warnings)

**4. Confirm baseline tests pass**
```
Ctrl+Shift+P → Run Task → test-all
```
Expected: 240+ tests passed, 0 failed

If either fails — **do not start** — fix the baseline first.

---

## Task Order

```
TASK-01  Kill Switch + Verbose Logging   [CRITICAL, ~45 min]   no deps
TASK-02  Wire Circuit Breaker            [CRITICAL, ~45 min]   after TASK-01
TASK-03  Fix TrailingStop Math           [HIGH,     ~60 min]   no deps
TASK-04  BasicLogger Level Filter        [HIGH,     ~20 min]   no deps
TASK-05  Session Holiday Awareness       [MEDIUM,   ~30 min]   no deps
```

Tasks 03, 04, 05 can run in parallel with or after 01/02 — they touch different files.

---

## TASK-01 — Kill Switch + Verbose Logging

**File being modified:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
**Spec file:** `TASK-01-kill-switch.md`

### Kilocode Prompt

Paste this into Kilocode chat verbatim:

```
Please implement TASK-01 from TASK-01-kill-switch.md

Summary of what you need to do:
1. Add two NinjaScript properties to NT8StrategyBase: EnableKillSwitch (bool) and EnableVerboseLogging (bool)
2. Add private field: _killSwitchTriggered
3. Set defaults in OnStateChange → State.SetDefaults
4. Add kill switch check as the VERY FIRST thing in OnBarUpdate() — before all other guards
5. Wrap Print calls inside ProcessStrategyIntent() with `if (EnableVerboseLogging)`

Important constraints:
- C# 5.0 only — use string.Format(), not $""
- Do NOT use ?. null conditional operator  
- Do NOT change constructor, InitializeSdkComponents(), or SubmitOrderToNT8()
- After every file change, run verify-build.bat mentally (I will run it to verify)

When done, tell me exactly what lines you added/changed and confirm the acceptance criteria from the task file are met.
```

### After Kilocode Responds

1. **Review the diff** — confirm:
   - `EnableKillSwitch` and `EnableVerboseLogging` are `[NinjaScriptProperty]` decorated
   - Kill switch check is the FIRST thing in `OnBarUpdate()` before `_sdkInitialized` check
   - No `$""` string interpolation introduced
   - No other files were modified

2. **Run verify-build:**
   ```
   Ctrl+Shift+B
   ```
   ✅ Must pass before proceeding

3. **If verify-build fails:** Paste the error output back to Kilocode:
   ```
   verify-build.bat failed with these errors:
   [paste errors]
   Please fix them. Remember C# 5.0 only — no string interpolation, no ?. operator.
   ```

4. **Run tests:**
   ```
   Ctrl+Shift+P → Run Task → test-all
   ```
   ✅ All 240+ tests must still pass

---

## TASK-02 — Wire ExecutionCircuitBreaker

**File being modified:** `src/NT8.Adapters/Strategies/NT8StrategyBase.cs`
**Spec file:** `TASK-02-circuit-breaker.md`
**Depends on:** TASK-01 must be complete

### Kilocode Prompt

```
TASK-01 is complete. Now please implement TASK-02 from TASK-02-circuit-breaker.md

Summary:
1. Add using statements: NT8.Core.Execution and Microsoft.Extensions.Logging.Abstractions
2. Add private field: _circuitBreaker (type ExecutionCircuitBreaker)
3. Instantiate in InitializeSdkComponents() after _positionSizer is created:
   _circuitBreaker = new ExecutionCircuitBreaker(NullLogger<ExecutionCircuitBreaker>.Instance, failureThreshold: 3, timeout: TimeSpan.FromSeconds(30));
4. Add circuit breaker gate at the TOP of SubmitOrderToNT8() — if ShouldAllowOrder() returns false, Print a message and return
5. After successful submission, call _circuitBreaker.OnSuccess()
6. In the catch block, call _circuitBreaker.OnFailure()
7. In OnOrderUpdate(), when orderState == OrderState.Rejected, call _circuitBreaker.RecordOrderRejection(reason)

Constraints:
- C# 5.0 only
- Do NOT modify ExecutionCircuitBreaker.cs — it is already correct
- Do NOT modify any Core layer files
- Do NOT modify any test files

When done, confirm all acceptance criteria from TASK-02-circuit-breaker.md are met.
```

### Verification

1. **Check the diff:**
   - `_circuitBreaker` field exists
   - `SubmitOrderToNT8()` has the `ShouldAllowOrder()` gate at the top
   - `OnOrderUpdate()` calls `RecordOrderRejection()` on rejected state
   - `ExecutionCircuitBreaker.cs` was NOT touched

2. ```
   Ctrl+Shift+B
   ```
   ✅ Must pass

3. ```
   Ctrl+Shift+P → Run Task → test-all
   ```
   ✅ 240+ tests must pass

---

## TASK-03 — Fix TrailingStop Placeholder Math

**File being modified:** `src/NT8.Core/Execution/TrailingStopManager.cs`
**Spec file:** `TASK-03-trailing-stop.md`
**No dependencies**

### Kilocode Prompt

```
Please implement TASK-03 from TASK-03-trailing-stop.md

Summary:
1. Open src/NT8.Core/Execution/TrailingStopManager.cs
2. Find CalculateNewStopPrice() — it currently has broken/placeholder math
3. Update the signature to add a TrailingStopConfig config parameter
4. Replace the switch body with real calculations:
   - FixedTrailing: marketPrice ± (config.TrailingAmountTicks * 0.25m)
   - ATRTrailing: marketPrice ± (config.AtrMultiplier * estimatedAtr) where estimatedAtr = position.AverageFillPrice * 0.005m
   - Chandelier: same formula as ATRTrailing but default multiplier 3.0
   - Use position.Side to determine + vs - (Buy = subtract from price, Sell = add to price)
5. Fix the ONE call site inside UpdateTrailingStop() to pass trailingStop.Config
6. Create tests/NT8.Core.Tests/Execution/TrailingStopManagerFixedTests.cs with unit tests verifying:
   - Long FixedTrailing 8 ticks at price 5100 → stop = 5098.0
   - Short FixedTrailing 8 ticks at price 5100 → stop = 5102.0

Constraints:
- C# 5.0 only
- Check the actual field names in TrailingStopConfig before using them — do not assume
- Do NOT change the class structure, just the CalculateNewStopPrice() method and its call site

When done, confirm acceptance criteria from TASK-03-trailing-stop.md are met.
```

### Verification

1. **Check the diff:**
   - `CalculateNewStopPrice` has new `config` parameter
   - `UpdateTrailingStop()` call site is updated
   - No other methods were changed
   - New test file exists

2. ```
   Ctrl+Shift+B
   ```
   ✅ Must pass

3. ```
   Ctrl+Shift+P → Run Task → test-core
   ```
   ✅ New tests + all existing tests must pass

---

## TASK-04 — BasicLogger Log Level Filter

**File being modified:** `src/NT8.Core/Logging/BasicLogger.cs`
**Spec file:** `TASK-04-log-level.md`
**No dependencies**

### Kilocode Prompt

```
Please implement TASK-04 from TASK-04-log-level.md

Summary:
1. First, check if a LogLevel enum already exists in the project (search for "enum LogLevel")
2. If not, add LogLevel enum: Debug=0, Information=1, Warning=2, Error=3, Critical=4
3. Add MinimumLevel property (type LogLevel, default Information) to BasicLogger
4. Update the private WriteLog() helper to accept a LogLevel and return early if below MinimumLevel
5. Update each public log method (LogDebug, LogInformation, etc.) to pass its level to WriteLog()

Constraints:
- C# 5.0 only
- Default must be Information (backward compatible — existing behavior unchanged at default)
- Do NOT change the ILogger interface signature
- Do NOT break any existing tests that depend on specific log output

When done, confirm acceptance criteria from TASK-04-log-level.md are met.
```

### Verification

1. **Check the diff:**
   - `MinimumLevel` property is public
   - `WriteLog()` has early return when `level < MinimumLevel`
   - No interface changes

2. ```
   Ctrl+Shift+B
   ```
   ✅ Must pass

3. ```
   Ctrl+Shift+P → Run Task → test-all
   ```
   ✅ All tests must pass

---

## TASK-05 — Session Holiday Awareness

**File being modified:** `src/NT8.Core/MarketData/SessionManager.cs`
**Spec file:** `TASK-05-session-holidays.md`
**No dependencies**

### Kilocode Prompt

```
Please implement TASK-05 from TASK-05-session-holidays.md

Summary:
1. Add a static readonly HashSet<DateTime> _cmeHolidays field to SessionManager
   Include 2025 and 2026 CME US Futures holidays (New Year's, MLK Day, Presidents' Day, Good Friday, Memorial Day, Juneteenth, Independence Day, Labor Day, Thanksgiving, Christmas)
2. Add private static bool IsCmeHoliday(DateTime utcTime) helper that converts to Eastern time and checks the set
3. Update IsRegularTradingHours() to call IsCmeHoliday(time) first — return false if it is a holiday

Constraints:
- C# 5.0 — use new HashSet<DateTime> { ... } initializer syntax (this works in C# 5)
- Wrap the TimeZoneInfo.ConvertTimeFromUtc() call in try/catch — return false on exception
- Do NOT change any other session detection logic

When done, confirm:
- IsRegularTradingHours("ES", DateTime(2025, 12, 25, 14, 0, 0, Utc)) returns false
- IsRegularTradingHours("ES", DateTime(2025, 12, 26, 14, 0, 0, Utc)) returns true
- verify-build.bat passes
```

### Verification

1. **Check the diff:**
   - `_cmeHolidays` contains dates for 2025 and 2026
   - `IsRegularTradingHours()` checks holiday before session time logic
   - No other session logic was changed

2. ```
   Ctrl+Shift+B
   ```
   ✅ Must pass

3. ```
   Ctrl+Shift+P → Run Task → test-all
   ```
   ✅ All tests must pass

---

## Final Verification — All 5 Tasks Complete

Run this sequence once all tasks are done:

**1. Full build:**
```
Ctrl+Shift+B
```
Expected: ✅ All checks passed!

**2. Full test suite:**
```
Ctrl+Shift+P → Run Task → test-all
```
Expected: 245+ tests passed (240 existing + new TrailingStop tests), 0 failed

**3. Git commit:**
```
git add -A
git commit -m "Production hardening: kill switch, circuit breaker, trailing stops, log level, holiday calendar"
git push
```

---

## Troubleshooting Kilocode

### If Kilocode introduces C# 6+ syntax

Paste this correction:
```
Build failed with C# syntax errors. You used C# 6+ features which are not allowed.
This project targets C# 5.0 / .NET Framework 4.8.

Please fix:
- Replace any $"..." with string.Format("...", ...)
- Replace ?. with explicit null checks: if (x != null) x.Method()
- Replace => on properties/methods with standard { get { return ...; } } syntax
- Replace nameof() with string literals
- Replace out var with two-step: declare variable, then call with out

Then re-run verify-build.bat to confirm.
```

### If Kilocode modifies the wrong file

```
You modified [filename] which is in the "Do NOT Change" list.
Please revert those changes and only modify the files listed in the task spec.
The Core layer is complete and tested — changes there break 240+ tests.
```

### If tests fail after a task

```
Tests failed after your changes. Please:
1. Run: dotnet test NT8-SDK.sln --verbosity normal 2>&1 | head -50
2. Show me the first failing test and its error message
3. Fix only the failing tests without introducing new changes to passing test files
```

### If Kilocode is unsure about a field name or method signature

```
Before assuming a field name, please read the actual file first:
[specify file path]
Confirm the exact field/method names before writing code.
```

---

## Quick Reference — Files Being Modified

| Task | File | What Changes |
|---|---|---|
| 01 | `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` | +2 properties, +1 field, kill switch in OnBarUpdate |
| 02 | `src/NT8.Adapters/Strategies/NT8StrategyBase.cs` | +circuit breaker field, gate in SubmitOrderToNT8, wire in OnOrderUpdate |
| 03 | `src/NT8.Core/Execution/TrailingStopManager.cs` | Fix CalculateNewStopPrice, update call site |
| 03 | `tests/NT8.Core.Tests/Execution/TrailingStopManagerFixedTests.cs` | NEW — unit tests |
| 04 | `src/NT8.Core/Logging/BasicLogger.cs` | +MinimumLevel property, level filter in WriteLog |
| 05 | `src/NT8.Core/MarketData/SessionManager.cs` | +holiday set, holiday check in IsRegularTradingHours |

**Nothing else should be modified. If Kilocode touches other files, ask it to revert them.**
