# Complex Manager Task Routing — Implementation Summary & Test Cases

Story: **HA-214**, FR-07.5 — *"Manager requests that require large-team review, bulk
approvals, shift planning, or comparative reporting shall be routed to the relevant
traditional page rather than attempted in chat."*

Format and methodology follow the convention established in
`docs/leave-module-test-cases.md` (branch `leaves_kumargirinath`): separate what was
verified by the automated (mocked) suite from what was verified live, and only mark a
row "Pass" for something this document's author actually ran, not for what a screenshot
or a prior report claimed.

## ⚠️ A note on the reference image provided for this story

The scenario-table screenshot supplied alongside this story (44 rows: "Simple Relative
Date," "Weekday Phrase," "Named-Month Anchored Date," "Explicit Duration," "Leave Type
Validation," etc., all marked "Pass") is **not new material for this story** — it is the
same image already investigated in `docs/leave-module-test-cases.md` §2.1 on
`leaves_kumargirinath`, where it's described as *"a differently-formatted test-case
reference (screenshotted, not sourced from this repo)"* provided as a template for the
**apply-leave date/duration parsing** feature. That investigation ran the actual
extraction call for equivalent queries and found **most of the image's specific "Pass"
claims did not hold** (12 outright failures, 3 partial, out of 25 tested) — see that
document's §2.1–§2.2 for the full breakdown, and its §6.5 for a second, separate incident
where an external "HA-163 Unit Test Report" described a test class that never existed in
this repository's history.

Two things follow from that:

1. **The image's content doesn't apply here.** It documents date-parsing behavior for
   `apply_leave`, an entirely different flow from complex-manager-task routing — none of
   its rows describe `large_team_review`, `bulk_approvals`, `shift_planning`, or
   `comparative_reporting`.
2. **Its format is worth reusing, its claims are not.** This document borrows the
   table shape (category / type / query / expected / result / notes) but every "Pass" in
   the tables below reflects a test or a live API call actually run for this story —
   consistent with the standard the other document already established for this
   codebase.

---

## 1. What was built

Backend-only (this repo has no frontend code in its history — the Navigation Card UI
itself lives in a separate frontend repository).

| Component | File | Responsibility |
|---|---|---|
| Route config | [`services/complex_manager_router.py`](../services/complex_manager_router.py) | Single source of truth: `COMPLEX_MANAGER_INTENTS`, `COMPLEX_MANAGER_ROUTE_CONFIG`, `route_complex_manager_task()`, `log_task_routed()` |
| Intent classification | [`services/hr_graph.py`](../services/hr_graph.py) `_build_intent_prompt` | Added the 4 categories as LLM-classified labels with disambiguation rules |
| Graph node | [`services/hr_graph.py`](../services/hr_graph.py) `complex_manager_task_node` | Role guard (reuses `erp_client.get_leave_context`) → Navigation Card emission → audit log |
| Routing | [`services/hr_graph.py`](../services/hr_graph.py) `_route_after_classify` | Routes the 4 intents to `complex_manager_task_node` |
| SSE passthrough | [`main.py`](../main.py) | `"navigation_card"` added to the streamed-event whitelist |

### Deep-link mapping (AC5)

| Category | Intent | Path |
|---|---|---|
| Large-Team Review | `large_team_review` | `/team/review` |
| Bulk Approvals | `bulk_approvals` | `/payroll/approvals/bulk` |
| Shift Planning | `shift_planning` | `/shifts/planner` |
| Comparative Reporting | `comparative_reporting` | `/reports/comparative` |

### Response contract

```json
{"type": "navigation_card", "data": {
  "category": "bulk_approvals",
  "title": "Bulk Approvals",
  "message": "Bulk approvals are best handled on the full web dashboard. Click below to open the Bulk Approvals page.",
  "button": {"label": "Open Bulk Approvals Page", "path": "/payroll/approvals/bulk"}
}}
```
followed by the standard terminal `"done"` event carrying the same object under `data.navigation`.

---

## 2. Methodology

- **Automated (mocked) tests** — [`tests/test_complex_manager_router.py`](../tests/test_complex_manager_router.py)
  and [`tests/test_complex_manager_task.py`](../tests/test_complex_manager_task.py). Deterministic,
  run via `pytest`, exercise every branch of the router config and the graph node (role
  gate, card emission, no-execution guarantee, routing) with a fake erp-api and a fake
  StreamWriter — the same pattern `tests/test_leave_action.py` already uses for
  `leave_action_node`.
- **Live verification** — the one genuinely non-deterministic piece of this feature is
  the LLM intent-classification step (`_build_intent_prompt` + a real model call), so
  that's what was run live below: the actual prompt, a real API call, no mocking.
  Everything downstream of classification (role gate, card content, deep-link path,
  no-execution guarantee) is deterministic Python and is covered by the mocked suite
  instead — running it live would need a real bearer token, a reachable erp-api, and a
  running server, none of which are available in this environment (see [§5](#5-known-gaps--not-covered-here),
  same category of gap `leave-module-test-cases.md` documents for its own §1.3/§2.4/§6.7).
- Live calls in this document were made **2026-08-31**, directly against this repo's
  actual configured LLM provider — which turned out to be **OpenAI (`gpt-4o-mini`)**,
  not DeepSeek (`ACTIVE_LLM_PROVIDER` in the local `.env` is currently set to `openai`).
  This is the same call `classify_node` makes once it decides an LLM classification is
  needed, invoked directly (`services.hr_graph._build_intent_prompt` →
  `services.ai_service._call_llm`) — no HTTP server, database, Redis, or erp-api
  involved, so nothing here reads or writes real data.

---

## 3. Automated test case matrix

**21/21 passing** (`pytest tests/test_complex_manager_router.py tests/test_complex_manager_task.py -v`, run 2026-08-31).

| # | File | Test | Verifies | AC | Result |
|---|---|---|---|---|---|
| 1 | test_complex_manager_router.py | `test_all_four_categories_are_configured` | Config has exactly the 4 categories | — | Pass |
| 2 | test_complex_manager_router.py | `test_each_intent_maps_to_the_correct_deep_link_target` | Every intent → its correct path | AC5 | Pass |
| 3 | test_complex_manager_router.py | `test_navigation_card_shape` | Card shape + exact wording | AC2 | Pass |
| 4 | test_complex_manager_router.py | `test_unknown_intent_returns_none_instead_of_inventing_a_destination` | Never substitutes/invents a destination | AC5 | Pass |
| 5 | test_complex_manager_router.py | `test_unknown_intent_logs_route_not_configured` | `COMPLEX_MANAGER_ROUTE_NOT_CONFIGURED` gets logged | LLD §17 | Pass |
| 6 | test_complex_manager_task.py | `test_non_manager_gets_no_navigation_card` | Non-manager never receives a card | LLD §4 | Pass |
| 7 | test_complex_manager_task.py | `test_erp_api_timeout_returns_graceful_message_no_card` | erp-api timeout → clean message, no card | LLD §17 | Pass |
| 8 | test_complex_manager_task.py | `test_erp_api_unavailable_returns_graceful_message_no_card` | erp-api down → clean message, no card | LLD §17 | Pass |
| 9–12 | test_complex_manager_task.py | `test_manager_gets_correct_navigation_card[large_team_review\|bulk_approvals\|shift_planning\|comparative_reporting]` | Not attempted in chat; correct title/message/label/path per category; `done` carries the same navigation object | AC1–AC4 | Pass ×4 |
| 13 | test_complex_manager_task.py | `test_deep_link_targets_are_never_substituted` | All 4 paths distinct, none duplicated | AC5 | Pass |
| 14 | test_complex_manager_task.py | `test_no_underlying_operation_is_ever_called` | `get_leave_balance`/`apply_leave`/`get_leave_status` never called by this node | AC6 | Pass |
| 15–18 | test_complex_manager_task.py | `test_complex_manager_intents_route_to_the_new_node[*]` | Each of the 4 intents routes to `complex_manager_task_node` | AC1–AC4 | Pass ×4 |
| 19 | test_complex_manager_task.py | `test_ordinary_hr_intent_still_routes_to_hr_response_node` | No regression to existing routing | — | Pass |
| 20 | test_complex_manager_task.py | `test_error_state_still_short_circuits_to_end` | Existing error short-circuit still wins | — | Pass |
| 21 | test_complex_manager_task.py | `test_prompt_names_every_complex_manager_intent_label` | LLM prompt still names all 4 labels (regression guard) | — | Pass |

Full repo suite (`pytest tests/`): 187 passed, 1 pre-existing unrelated failure
(`test_admin_quota_routes.py::test_create_duplicate_active_scope_is_rejected`, confirmed
present on `HA-214` before this feature too — not introduced by this work).

---

## 4. Live verification — intent classification (2026-08-31, real OpenAI `gpt-4o-mini` call)

Script used: a standalone probe that neutralizes the DB import side-effect the same way
`tests/conftest.py` does (mocks `sqlalchemy.create_engine` before import — no real
database is touched), then calls the real `_build_intent_prompt` + `_call_llm` for each
query below. Kept in the session scratchpad rather than committed, per the same
convention `leave-module-test-cases.md`'s Appendix uses for its own probe scripts.

| # | Category | Type | User Query | Expected Intent | Actual Intent | Result | Notes |
|---|---|---|---|---|---|---|---|
| 1 | Large-Team Review | Positive | I need to review attendance for all 40 people in my org before the quarterly audit | large_team_review | large_team_review | Pass | Story's own AC1 example query |
| 2 | Large-Team Review | Positive | Show me all team members that need approval | large_team_review | large_team_review | Pass | LLD §5 mapping example |
| 3 | Large-Team Review | Positive | Can you review my entire team's records? | large_team_review | large_team_review | Pass | |
| 4 | Large-Team Review | Positive | Review my team | large_team_review | large_team_review | Pass | Short/terse phrasing edge case |
| 5 | Large-Team Review | Negative | What is Sarah's leave status? | ~~leave_status~~ → **general_hr** | general_hr | Pass* | *Test-design correction: this repo's `leave_status` intent is explicitly self-service only ("checking THEIR OWN leave request") — a third party's name correctly falls outside it, so `general_hr` is the right answer, not a bug. What this row actually needed to prove — that it does **not** get pulled into `large_team_review` just because "team"-adjacent words are nearby — held. |
| 6 | Large-Team Review | Negative | What's my own attendance record this month? | attendance | attendance | Pass | Self-only query, correctly not team-wide |
| 7 | Bulk Approvals | Positive | Approve all pending leave requests for my team this week | bulk_approvals | bulk_approvals | Pass | Story's own AC2 example query |
| 8 | Bulk Approvals | Positive | Approve these leaves in bulk | bulk_approvals | bulk_approvals | Pass | LLD §5 mapping example |
| 9 | Bulk Approvals | Positive | Can you clear my entire approval queue? | bulk_approvals | bulk_approvals | Pass | |
| 10 | Bulk Approvals | Positive | Approve all my team's pending requests | bulk_approvals | bulk_approvals | Pass | LLD's own "Final Expected Flow" example |
| 11 | Bulk Approvals | Negative | Approve John's leave request | general_hr | general_hr | Pass | Single named request — hard rule requires "all/these/in bulk" language |
| 12 | Bulk Approvals | Negative | What is my leave status? | leave_status | leave_status | Pass | Not swallowed by the new label |
| 13 | Shift Planning | Positive | Help me plan next month's shift roster for the support team | shift_planning | shift_planning | Pass | Story's own AC3 example query |
| 14 | Shift Planning | Positive | Create next week's shift schedule | shift_planning | shift_planning | Pass | LLD §5 mapping example |
| 15 | Shift Planning | Positive | I need to build a shift roster for December | shift_planning | shift_planning | Pass | |
| 16 | Shift Planning | Positive | Plan shifts for my team | shift_planning | shift_planning | Pass | LLD §5 mapping example |
| 17 | Shift Planning | Negative | What's my team's shift timing policy? | attendance | attendance | Pass | Nothing being planned/created — correctly not shift_planning |
| 18 | Shift Planning | Negative | What time does my shift start today? | attendance | attendance | Pass | Self-only, not a planning request |
| 19 | Comparative Reporting | Positive | Compare my team's attendance this quarter against last quarter, broken down by department | comparative_reporting | comparative_reporting | Pass | Story's own AC4 example query |
| 20 | Comparative Reporting | Positive | Give me a department-level comparison report | comparative_reporting | comparative_reporting | Pass | LLD §5 mapping example |
| 21 | Comparative Reporting | Positive | How does this month's team performance compare to last month? | comparative_reporting | comparative_reporting | Pass | |
| 22 | Comparative Reporting | Negative | What is my attendance record this month? | attendance | attendance | Pass | Single-period, self-only — no comparison requested |
| 23 | Comparative Reporting | Negative | What are the latest HR hiring trends? | general_hr | general_hr | Pass | Market/industry language, not a team-metric comparison |
| 24 | Regression | N/A | Hi there | greeting | greeting | Pass | Conversational intents unaffected |
| 25 | Regression | N/A | What is my leave balance | leave_balance | leave_balance | Pass | Pre-existing HR flow unaffected |
| 26 | Regression | N/A | What's the weather today | non_hr | non_hr | Pass | Pre-existing non_hr classification unaffected |
| 27 | Regression | N/A | I want to apply for leave | apply_leave | apply_leave | Pass | Pre-existing HR flow unaffected |
| 28 | Regression | N/A | What is the sick leave policy | leave_policy | leave_policy | Pass | Pre-existing HR flow unaffected |

**28/28 passed** (27 matched the original expectation exactly; #5's expectation was
corrected in-place above with the reasoning shown, and the corrected expectation
matched). All 4 new categories classified correctly on every positive example given —
including the story's own AC1–AC4 example queries verbatim — and none of the negative/
regression queries were misrouted into a manager-task category.

---

## 5. Known gaps — not covered here

- **Role-gate and Navigation Card emission were not live-tested end-to-end.** That path
  needs a real bearer token against a reachable erp-api (`get_leave_context`) plus a
  running server — none available in this environment. It is fully covered by the
  mocked suite (§3, rows 6–14) instead, the same tradeoff `leave-module-test-cases.md`
  makes for its own untestable-live gaps (§1.3, §2.4, §6.7).
- **Frontend Navigation Card component** — out of scope for this repo (no frontend code
  exists here); needs to be implemented against the `"navigation_card"` / `data.navigation`
  contract documented in §1 wherever the chat UI actually lives.
- **LLM non-determinism** — like the apply-leave date-parsing note in
  `leave-module-test-cases.md` §2.1, a live LLM classification call is not guaranteed to
  reproduce identically on a future run even at the same settings. The prompt includes
  explicit hard rules specifically to narrow this (see `_build_intent_prompt`'s "HARD
  RULES" section), and the regression guard in §3 row 21 catches the labels being
  accidentally removed from the prompt — but a full behavioral guarantee would need a
  scheduled live sweep, not a one-time check.
