# Leave Module — Test Case Reference

Scenario matrix and verification status for the four conversational leave flows in `services/hr_graph.py` / `services/leave_action_service.py`:

1. [Leave Eligibility](#1-leave-eligibility-hel-280) (`leave_eligibility` intent)
2. [Apply Leave — Date & Duration Parsing](#2-apply-leave--date--duration-parsing) (`apply_leave` intent)
3. [Cancel Leave](#3-cancel-leave) (`cancel_leave` intent)
4. [View Pending Leaves](#4-view-pending-leaves) and [View Any Type of Leaves](#5-view-any-type-of-leaves-leave-status--history) (`leave_status` intent — one node handles both)
5. [Leave Failure Messaging](#6-leave-failure-messaging-hel-283) (HEL-283 — cross-cutting: apply, cancel, eligibility)

Each section lists the scenario categories, where they're pinned down in the automated suite, and — where the call is read-only and safe to run for real — actual results from a live run against production erp-api (`https://erp-api14.studyineurope.xyz`), not just mocked fixtures.

## Methodology

- **Automated (mocked) tests** — `tests/test_leave_eligibility.py` and `tests/test_leave_action.py`. Deterministic, run in CI, exercise every branch including ones that can't be reached live (auth failures, timeouts, an employee still on probation).
- **Live verification** — a real bearer JWT (decoded: `user_id=3735`, "B Geo", company "Mehar by Rhysley") driven directly through the production node functions (`leave_eligibility_node`, `leave_action_node`), bypassing only the HTTP server layer (no DATABASE_URL/Redis dependency in that path) and the LLM intent classifier. Real erp-api calls, real data, real answers.
- **Read-only vs. mutating** — Eligibility and view-leaves are GET-only end to end; a live run of either carries no risk. Cancel-leave's *match → select → preview* steps are also GET-only (`get_applied_leaves`, `get_leave_balance`); only the final **confirm** step calls the mutating `/leave/cancel` endpoint. Live verification below stops at the preview step deliberately — see [§3.4](#34-live-verification).
- Everything under "Live verification" was run on 2026-08-21 against real account data; leave references (`LR-*`) are that account's real submitted requests, not fixtures.

---

## 1. Leave Eligibility (HEL-280)

Node: `leave_eligibility_node` · Tests: `tests/test_leave_eligibility.py` (**89 passing**)

### 1.1 Detailed test case matrix

Verified 2026-08-25 against the actual implementation (`services/leave_eligibility_service.py`) — "Test Query" wording is illustrative (many phrasings reach the same branch); "Expected Behavior" quotes the real generated text where it's static, or describes the construction where it's data-dependent. "Expected Date Resolution" mostly doesn't apply here (eligibility is a policy question, not a date one) — used only where DOJ/probation date arithmetic is involved.

| # | Category | Expected Result | Test Query | Expected Behavior | Expected Date Resolution | Status | Notes |
|---|---|---|---|---|---|---|---|
| 1 | Single Configured Type | Positive | Am I eligible for casual leave? | "Casual Leave is available from your date of joining, so you are eligible for it." + policy summary sentence (quota/month-max/per-application-max/carry-forward/notice/settlement, whichever fields erp-api actually returned). | N/A | Pass | `benefit_start: "joining"` → always eligible, day one. |
| 2 | Single Configured Type | Positive | Do I qualify for earned leave? (probation complete) | "Earned Leave becomes available after your probation ends. Your probation is complete, so you are eligible for it." | N/A | Pass | `benefit_start: "confirmation"` + `is_confirmed: true`. |
| 3 | Single Configured Type | Negative | Am I eligible for earned leave? (still on probation) | "Earned Leave becomes available only after your probation ends. Your probation ends on 14 Sep 2026." (or "You are still on probation." if no end date given) | Probation end date shown as `DD Mon YYYY` | Pass | `is_confirmed: false` — reason names the actual end date, not a guess. |
| 4 | Single Configured Type | Negative | Am I eligible for earned leave? (confirmation status unknown) | "Earned Leave becomes available after your probation ends, but your probation status is unavailable right now." — `eligible: null`, no verdict rendered, no `leave_eligibility` SSE card emitted at all. | N/A | Pass | `is_confirmed: null` fails CLOSED, never silently denies or approves. |
| 5 | Single Configured Type | Negative | Am I eligible for casual leave? (`benefit_start` unrecognised/garbled) | "I couldn't work out the eligibility rule for Casual Leave — it doesn't look right on your company's side." — `eligible: null`. | N/A | Pass | `RULE_NOT_UNDERSTOOD` — fails closed rather than guessing yes/no on a rule it doesn't recognise. |
| 6 | Phrasing Variety | Positive | "do I qualify for earned leave" / "am I entitled to sick leave" / "can I take casual leave" / "is my leave eligibility ok for short leave" / "am I allowed short leave" | All route to the same single-type verdict as #1/#2 — phrasing never changes the answer, only intent classification has to recognise it as `leave_eligibility`. | N/A | Pass | Modal-verb / synonym coverage, not a separate code path. |
| 7 | Typo Tolerance | Negative (not in policy) | show my meternity leave eligibility | Exact-word match first (no typo needed here) — "Maternity leave is not part of your company's leave policy, so there is no eligibility to check. The leave types available to you are: Casual Leave, Sick Leave, Earned Leave, Short Leave." | N/A | Pass | `_mentions_unconfigured_leave` checks the exact word list before fuzzy matching. |
| 8 | Typo Tolerance | Negative (not in policy) | am I eligible for metrenity leave | Same as #7 — "Maternity" recovered via fuzzy match (`metrenity` vs `maternity` scores 0.778, above the 0.75 cutoff). | N/A | Pass | Verified live: `_mentions_unconfigured_leave("metrenity")` → `"maternity"`. |
| 9 | Typo Tolerance | Negative control | what material do I need for this / is my maternal leave eligible | Falls through to the ambiguous "no leave type named" clarification (#16) — NOT misread as "maternity". | N/A | Pass | Verified live: both return `None` from the fuzzy matcher. "material" (0.667) and "maternal" (~0.7) both sit below the 0.75 cutoff. |
| 10 | Quota-Only Unconfigured Type | Negative (not in policy) | am I eligible for comp off | "Comp Off is not part of your company's leave policy, so there is no eligibility to check. The leave types available to you are: ..." | N/A | Pass | `comp_off` has a `leave_quota` entry but no `leave_settings.leave_type[]` policy entry — same outcome as a named-but-unconfigured type (#7), different code path (`requested`, not `_mentions_unconfigured_leave`). |
| 11 | Quota-Only Unconfigured Type | Negative (not in policy) | am I eligible for leave without pay | Same shape as #10, for `leave_without_pay`. | N/A | Pass | |
| 12 | Ambiguous — No Type Named | Negative (clarification, not a rejection) | check my leave eligibility / show my leave eligibility / am I eligible for leave? | "Sure — your company offers 4 leave types: Casual Leave, Sick Leave, Earned Leave, and Short Leave. From these, you can ask me about any leave eligibility you'd like to check." | N/A | Pass | Humanized 2026-08-25 — previously a bare "Could you let me know which type..." with no acknowledgment. `reason_code: LEAVE_TYPE_NOT_SPECIFIED`. |
| 13 | General Eligibility Question | Positive (brief) | what kind of leaves am I eligible for? / what am I eligible for? | "You're eligible for CL, SL, ShL. Not yet eligible for EL — Earned Leave becomes available only after your probation ends. You are still on probation." | N/A | Pass | Codes only for the eligible group; each not-yet-eligible type gets its own reason inline. Only fires when NO specific type (real or unconfigured) was already named. |
| 14 | Explicit All-Types Request | Positive (detailed) | show me all leave types eligibility / eligibility for all leaves | Full per-type breakdown: `"Casual Leave (CL): <verdict sentence> <policy summary>. Sick Leave (SL): ... Earned Leave (EL): ... Short Leave (ShL): ..."` — same depth as a single-type answer, repeated per type. | N/A | Pass | Distinct from #13 — explicit "all/every leave types" phrasing gets the full rundown, not just codes. |
| 15 | Named Type Takes Priority | Positive | am I eligible for casual leave and what am I eligible for | Answers ONLY casual leave (the single-type path) — the "what am I eligible for" phrase is ignored once a real type is already named. | N/A | Pass | Guards against the all-types patterns hijacking a query that already named a specific type. |
| 16 | Multi-Type Query | Positive | casual and sick leave? | Terse per-type line: `"Casual Leave: eligible. Sick Leave: eligible."` (not the brief-mode code list — this is the "≥2 explicitly named types" path, not the general-eligibility-question path). | N/A | Pass | `len(results) > 1` and not `all_types_mode` → the terse per-type join, distinct from #13's code-only format. |
| 17 | Multi-Type Query (mixed) | Positive + Negative (not in policy) | casual and comp off leave? | Casual Leave gets a real verdict; message appended: "Comp Off is not part of your company's leave policy, so there is no eligibility to check for it." | N/A | Pass | The configured half is never silently dropped because the other half is unconfigured. |
| 18 | Multi-Type Query (mixed) | Positive + Negative (not in policy) | casual and maternity leave? | Same shape as #17, for the named-word case: "... Maternity Leave is not part of your company's leave policy ..." | N/A | Pass | |
| 19 | Multi-Type Query (mixed, 3+ unconfigured) | Positive + Negative (not in policy) | casual, maternity, and comp off leave? | Casual gets a verdict; both unconfigured names listed together: "Comp Off, Maternity Leave are not part of your company's leave policy, so there is no eligibility to check for them." | N/A | Pass | Plural "are"/"them" grammar when 2+ unconfigured names are combined. |
| 20 | Employee Card — DOJ Formatting | N/A (display fact) | am I eligible for casual leave (doj = 2025-06-14) | `employee.doj` on the `leave_eligibility` card renders as `"14th June 2025"`. | DOJ formatted, not resolved — `14th June 2025` | Pass | Verified live: `_display_doj("2025-06-14")` → `"14th June 2025"`. Ordinal suffix handles 11th–13th correctly (never "11th"→"11st"). |
| 21 | Employee Card — Tenure Label | N/A (display fact) | am I eligible for casual leave (doj = 2025-06-14, today = 2026-08-25) | `employee.tenure_label` on the card renders as `"1 year 2 months"`. | Computed from DOJ, independent of the display-formatted `doj` field | Pass | Verified live. Computed from erp-api's raw `doj`, not the formatted display string — no coupling bug between the two fields. |
| 22 | Employee Card — Employee Code | N/A (display fact) | am I eligible for casual leave (emp_no = "geo3") | `employee.emp_code` on the card renders as `"EMP-geo3"`; `null` if erp-api didn't return `emp_no`. | N/A | Pass | Same field shape as cancel-leave's employee-identity block. |
| 23 | Leave Code Field | N/A (display fact) | am I eligible for casual leave / sick leave / earned leave / short leave | Each result's `leave_type.leave_code` is `CL` / `SL` / `EL` / `ShL` respectively; `null` for any slug not in the shared `_LEAVE_TYPE_CODES` map (e.g. `comp_off`, `leave_without_pay` if they ever reached this far). | N/A | Pass | Same code map cancel-leave already uses — one source of truth. |
| 24 | Policy Summary — Full Fields | N/A (display fact) | am I eligible for casual leave (quota=12, max_apply_in_month=2, oneTypeMax=1) | "You're entitled to 12 Casual Leaves a year; up to 2 Casual Leaves a month; and a maximum of 1 Casual Leave per application." | N/A | Pass | Verified live. Names the actual leave type in each clause ("12 Casual Leaves") rather than generic "days". |
| 25 | Policy Summary — Partial Fields | N/A (display fact) | am I eligible for sick leave (only `quota` present, everything else null/false) | "You're entitled to 12 Sick Leaves a year." — single clause, no trailing semicolons for fields erp-api didn't return or that are simply `false`. | N/A | Pass | `is_carry_forward`/`notice_period_applicable`/`salary_settlement` are omitted entirely when `False` — not stated as "does not carry forward" (unremarkable default, not worth saying). |
| 26 | Policy Summary — No Fields At All | N/A (display fact) | am I eligible for casual leave (erp-api returns no policy-detail fields at all) | Verdict sentence only, no trailing policy summary appended — never an empty "." or a sentence fragment. | N/A | Pass | `_policy_summary_sentence` returns `""` when nothing is parseable; caller only appends it when non-empty. |
| 27 | Erp-api Failure — Unauthorized | Negative | am I eligible for casual leave (bearer token expired, 401) | "Sorry, your session has expired — please log in again to continue." | N/A | Pass | Humanized 2026-08-25 — previously the bare imperative "Your session has expired. Please log in again to continue." |
| 28 | Erp-api Failure — Timeout | Negative | am I eligible for casual leave (erp-api exceeds the 3s eligibility SLA) | "I couldn't reach the HR system in time to check your eligibility — please try again in a moment." | N/A | Pass | Humanized 2026-08-25, and restored the timeout/unavailable wording split that had briefly collapsed into one generic message. |
| 29 | Erp-api Failure — Unavailable | Negative | am I eligible for casual leave (erp-api 5xx / unreachable) | "I'm unable to reach the HR system right now to check your eligibility — please try again shortly." | N/A | Pass | Distinct wording from #28 (timeout vs. genuinely down), matching the pattern already used in cancel-leave/attendance/punch-details. |
| 30 | Erp-api Failure — No Policy Configured | Negative | am I eligible for casual leave (`leave_settings.leave_type` is empty/missing entirely) | "I couldn't check your eligibility — your company's leave policy information isn't available right now." | N/A | Pass | Humanized 2026-08-25 — previously "Unable to determine your eligibility because required leave policy information is unavailable." |
| 31 | Erp-api Failure — Employee Data Unavailable (all types) | Negative | am I eligible for casual leave (every requested type resolves `eligible: null`) | "I couldn't check your eligibility — some of your employee information isn't available right now." No `leave_eligibility` SSE card emitted — an all-undetermined result is never rendered as if it were a verdict. | N/A | Pass | Humanized 2026-08-25 — previously "Unable to determine your eligibility because required employee information is unavailable." |
| 32 | Case Sensitivity | Positive | AM I ELIGIBLE FOR CASUAL LEAVE? / Am I Eligible For Casual Leave? | Identical result to #1 regardless of casing. | N/A | Pass | Type-word matching and typo/fuzzy matching both lower-case the query first. |
| 33 | Not-a-Balance-Question Guard | Positive | am I eligible for casual leave | Never reads `leave_quota` (remaining balance) at all when computing the verdict — an employee with 0 days remaining is still shown as policy-eligible. | N/A | Pass | AC#5 — `evaluate_eligibility` is pure policy logic; balance is fetched only for `_policy_details`' entitlement facts (annual quota), never the remaining-days figure. |
| 34 | Compound Type Names | Negative (not in policy) | am I eligible for leave without pay and comp off (both quota-only, no policy) | "Comp Off, Leave Without Pay are not part of your company's leave policy, so there is no eligibility to check. The leave types available to you are: ..." — both names joined in ONE message. | N/A | Pass | Verified live (`_extract_leave_type_filters` returns both slugs). Since `known` stays completely empty (neither is configured), this hits the same early "not in policy" branch as #10/#11, not the mixed-query branch (#17/#18) which needs at least one KNOWN type — confirms multiple simultaneous unconfigured names are joined correctly even with zero configured types in the query. |
| 35 | Unconfigured Type — Every Documented Word | Negative (not in policy) | paternity / sabbatical / bereavement / compassionate / marriage / adoption / menstrual / study leave | Each names itself back correctly: "Paternity leave is not part of your company's leave policy...", etc. | N/A | Pass | Full `_UNCONFIGURED_LEAVE_WORDS` set, not just the maternity example. |

### 1.2 Scenario categories (summary)

| Cat | Scenario | Example queries |
|---|---|---|
| A | Single configured type, phrasing variety | "Am I eligible for casual leave?", "do I qualify for earned leave", "am I entitled to sick leave", "can I take casual leave" (modal), "is my leave eligibility ok for short leave", "am I allowed short leave" |
| B | Unconfigured / not-in-policy type | Named-word not in policy: "maternity", "sabbatical", "paternity", "bereavement", etc. (typo-tolerant, cutoff 0.75). Quota-only slug with no policy entry: "comp off", "leave without pay" |
| C | Ambiguous — no leave type named | "can I take some time off?", "am I eligible for leave?" — humanized clarification, lists the real configured types |
| D | Multi-type queries | All configured: "casual and sick leave?" · Mixed configured + quota-only: "casual and comp off leave?" · Mixed configured + named-unconfigured: "casual and maternity leave?" |
| D2 | All-types queries | Brief code list: "what kind of leaves am I eligible for?" · Full per-type breakdown: "show me all leave types eligibility" |
| E | Employee data state | Confirmed (`is_confirmed=true`) → eligible for confirmation-gated types. On probation (`is_confirmed=false`) → not eligible, reason states probation end date. `is_confirmed=null` → fails closed, no verdict rendered, no card. |
| F | Erp-api failure modes | 401 → "your session has expired." Timeout (>3s SLA) → "couldn't reach the HR system in time." Unavailable → "unable to reach the HR system right now." Missing `leave_settings` entirely → "your company's leave policy information isn't available right now." |

### 1.3 Known untestable-live gap

Category E's `REQUIRES_CONFIRMATION` and `EMPLOYEE_DATA_UNAVAILABLE` paths need an employee still on probation (`is_confirmed=false` or `null`). No such test account exists in this environment — the original HEL-280 dependency doc raised this as an open item. These paths are pinned down by mocked tests only (`TestEvaluateEligibility`, `TestUnknownAndAmbiguous` in `test_leave_eligibility.py`) until such an account is provisioned. Category F is likewise intentionally not fired live (would mean deliberately corrupting a real credential or blocking network access for no additional signal beyond what the mocked `ErpApiUnauthorized`/`ErpApiTimeout`/`ErpApiUnavailable` tests already prove).

### 1.4 Live verification (2026-08-21, real account, real erp-api)

Raw contract check confirmed `/ai/leave/context` returns `is_confirmed`, `probation_end_date`, `doj` in production (not just in the dependency doc's example), and `/ai/leave/balance`'s `leave_settings.leave_type[]` carries `quota`, `max_apply_in_month`, `oneTypeMax`, `is_carry_forward`, `notice_period_applicable`, `salary_settlement` on every type.

| # | Query | Result |
|---|---|---|
| A1 | casual leave | Eligible, `AVAILABLE_FROM_JOINING`, 24 days/yr, 10 applications/mo, max 2 days/application |
| A2 | earned leave | Eligible, `CONFIRMED` (probation complete), 6 days/yr, carries forward, notice period applies, settled on exit |
| A3 | sick leave | Eligible, 12 days/yr |
| A4 | "can I take casual leave" | Correctly classified as eligibility, not apply |
| A5/A6 | short leave (2 phrasings) | Eligible, 24 days/yr, max 3 applications/mo |
| B1/B2 | maternity / sabbatical | `LEAVE_TYPE_NOT_IN_POLICY`, lists the 4 real configured types |
| B3/B4 | comp off / leave without pay | Same not-in-policy answer via the quota-only-slug path (distinct code path from B1/B2, same correct outcome) |
| C1/C2 | "some time off" / "leave" | Clarification question, does not guess |
| D1 | casual + sick | Both evaluated, both eligible |
| D2 | casual + comp off | Casual gets a verdict; comp off explicitly flagged not-in-policy |
| D3 | casual + maternity | Same, for the named-word case |

All 11 live cases matched the mocked-suite predictions exactly, including the mixed-query (D2/D3) and policy-detail-enrichment behavior.

---

## 2. Apply Leave — Date & Duration Parsing

Node: `leave_action_node` (branch: `state["intent"] == "apply_leave"`) · Date/duration resolution: `services/ai_service.py::_build_leave_slot_extraction_prompt`, one LLM extraction call — **not deterministic code**. Automated tests: `tests/test_leave_action.py`'s `TestLeaveActionNodeApplyBranch` cover the conversational slot-filling/confirmation/submission state machine using *mocked* extraction results — they pin down the conversation logic, not real date-parsing accuracy, since that's inherently non-deterministic model behavior.

### 2.1 Important caveat — read before trusting any row below

Unlike Eligibility, Cancel, and View-Pending (all backed by inspectable Python logic you can read line-by-line), **date/duration resolution here has no deterministic code at all.** "next Monday," "a week," "20 days" are resolved entirely by asking the LLM to interpret them in one JSON-extraction call — there is no post-processing, no weekday/duration math, no validation of what comes back. The table below is a real, live run against the actual `_call_llm` extraction call (OpenAI, 2026-08-25, a Tuesday) — not a static test suite, and **not guaranteed to reproduce identically on a future run**, since LLM output for the same prompt is not perfectly deterministic even at temperature 0.

This distinction matters because a differently-formatted test-case reference (screenshotted, not sourced from this repo) was provided as a template for this section, claiming specific "Pass" results for weekday/month/duration phrasing (e.g. "next to next Monday = next Monday + 7 days," "two weeks = 14 days," "20 days = a full 20-day span"). Running the actual extraction call against equivalent queries today shows **most of those specific claims do not hold** — see §2.2. This section documents what was actually verified just now, not what the reference image asserted. (§6.4 of this same document already records a prior incident where an external "test report" made unverifiable/false claims about this codebase — the standard here is the same: only what's actually been run gets marked Pass.)

### 2.2 Live verification (2026-08-25, real OpenAI call via `_call_llm` + `_build_leave_slot_extraction_prompt`, today = Tuesday)

| # | Category | Test Query | Actual Result (from_date → to_date) | Correct? | Notes |
|---|---|---|---|---|---|
| 1 | Simple Relative Date | Apply casual leave today | 2026-08-25 → 2026-08-25 | Pass | Matches today exactly. |
| 2 | Simple Relative Date | Apply casual leave tomorrow | 2026-08-26 → 2026-08-26 | Pass | |
| 3 | Simple Relative Date | Apply casual leave day after tomorrow | 2026-08-27 → 2026-08-27 | Pass | |
| 4 | Simple Relative Date | Apply casual leave yesterday | 2026-08-24 → 2026-08-24 | Partial | Extraction resolves the literal date correctly — but this call has no past-date rejection logic at all. "N/A — request denied" (as the reference image claims) would require a *separate* back-date validation step against real company settings (`back_date_leave_allow`), not exercised by this isolated extraction call. Not tested here — needs a full apply-flow run with a bearer token. |
| 5 | Weekday Phrase | Apply casual leave this Monday | 2026-08-29 | **Fail** | 2026-08-29 is a **Saturday**, not a Monday. Correct answer is 2026-08-31. |
| 6 | Weekday Phrase | Apply casual leave this coming Monday | 2026-08-29 | **Fail** | Same wrong date as #5. |
| 7 | Weekday Phrase | Apply casual leave next Monday | 2026-08-29 | **Fail** | Same wrong date — also fails the reference image's own claimed rule that "this Monday" and "next Monday" should coincide when today isn't Monday (both should be 2026-08-31; instead both wrongly land on a Saturday). |
| 8 | Weekday Phrase | Apply casual leave next week Monday | 2026-08-31 | Pass | Correctly a Monday — this specific phrasing worked where the bare "next Monday" (#7) didn't. |
| 9 | Weekday Phrase | Apply casual leave next to next Monday | 2026-09-05 | **Fail** | 2026-09-05 is a Saturday. Expected 2026-09-07 (next Monday + 7 days, per the claimed rule). |
| 10 | Weekday Phrase | Apply casual leave next to next Friday | 2026-09-08 | **Fail** | 2026-09-08 is a Tuesday, not a Friday at all. Expected 2026-09-04. |
| 11 | Month-Relative Phrase | Apply casual leave week after next | 2026-09-05 | **Fail** | Saturday, not the Monday of (current week + 2) — expected 2026-09-07. |
| 12 | Month-Relative Phrase | Apply casual leave next month | 2026-09-01 | Pass | Correctly the 1st of next calendar month. |
| 13 | Month-Relative Phrase | Apply casual leave first Monday of next month | 2026-09-04 | **Fail** | 2026-09-04 is a Friday. Expected 2026-09-07 (the actual first Monday in September 2026). |
| 14 | Named-Month Anchored Date | Apply sick leave first Wednesday of October | 2026-10-05 | **Fail** | 2026-10-05 is a Monday. Expected 2026-10-07. |
| 15 | Named-Month Anchored Date | I want to apply sick leave first wednesday of october to october next saturday | 2026-10-04 → 2026-10-10 | **Fail** (start) | Start date is a Sunday, not the named Wednesday (expected 2026-10-07). End date (Saturday) happens to be correct in isolation, but the pair doesn't form the named Wed→Sat range. |
| 16 | Week-of-Month Range | I want to apply leave from november first week to end of the first week | 2026-11-01 → 2026-11-07 | Pass | Full first-week span of November, exactly as claimed. |
| 17 | Week-of-Month Range | Apply leave for the last week of October | 2026-10-25 → 2026-10-31 | Pass | Final 7 days of October, exactly as claimed. |
| 18 | Weekday-to-Weekday Range | I want to apply casual leave for upcoming wednesday to next sunday for full day due to health issue | 2026-08-30 → 2026-09-04 (`full_day`) | **Fail** (dates) | Expected upcoming Wednesday (2026-08-26) → the following Sunday (2026-08-30). Got a range shifted several days later on both ends. Session type (`full_day`) was extracted correctly. |
| 19 | Weekday-to-Weekday Range | Apply leave this Monday to this Friday | 2026-08-29 → 2026-09-02 | **Fail** | Neither end is the named weekday (expected 2026-08-31 → 2026-09-04, i.e. within the actual current calendar week). |
| 20 | Explicit Duration | I want to apply 20 days leaves from 12th november | 2026-11-12 → 2026-11-12 | **Fail** | The stated "20 days" was dropped entirely — resolved as a single day, not a 20-day span (expected 2026-11-12 → 2026-12-01). |
| 21 | Explicit Duration | Apply casual leave for a week starting next Monday | 2026-08-29 → 2026-09-04 | Partial | The *span length* is correctly 7 days — but anchored to the same wrong "Monday" as #5/#7 (2026-08-29 is a Saturday). |
| 22 | Explicit Duration | Apply casual leave for two weeks | 2026-08-25 → 2026-09-08 | **Fail** | 15 days inclusive, not 14. |
| 23 | Explicit Duration | Apply casual leave for a month | 2026-08-25 → 2026-09-25 | Different from claimed | 32 days inclusive (resolved as "the same date next calendar month," not the reference's claimed fixed 30-day approximation). Arguably more defensible than a flat 30-day rule, but doesn't match what was claimed. |
| 24 | Explicit Duration | Apply half day tomorrow | 2026-08-26 → 2026-08-26 (`half_day`) | Pass | Correctly a single day, not misread as a duration count — matches the claimed regression guard. |
| 25 | Explicit Duration | Apply from 5th to 10th november for a week | 2026-11-05 → 2026-11-10 | Pass | The explicit date range correctly wins over the conflicting spoken "a week" — matches the claimed precedence rule. |

**9 of 25 fully correct, 3 partial, 1 differs from the claimed rule without necessarily being wrong, 12 fail outright** — nearly all of them in named-weekday and month-relative-weekday resolution. The pattern that reliably works: bare relative dates (today/tomorrow/day-after-tomorrow), the literal "next month," "next week Monday" specifically, week-of-month ranges ("first/last week of [month]"), half-day-not-duration, and explicit-date-range-wins-over-spoken-duration. The pattern that's currently unreliable: almost any bare named-weekday phrase ("this/next/next-to-next Monday/Friday"), "first [weekday] of [month]," and multi-word explicit day-counts ("20 days," "two weeks").

### 2.3 Recommendation

Every other flow in this document (Eligibility, Cancel, View-Pending) computes its logic in inspectable Python and only leans on an LLM for free-text generation or intent classification — never for the underlying arithmetic. Apply Leave is the one flow where core business logic (which literal calendar date a leave request is for) is delegated entirely to an LLM's interpretation with no verification step, and today's run shows that's currently unreliable for a large fraction of realistic phrasing. Given a wrong date here silently submits a real leave application for the wrong day, this is worth a deterministic date-resolution layer (parse "next Monday" / "first Wednesday of October" / "two weeks" in actual code, the same way eligibility parses probation dates) rather than continuing to trust free-form LLM date arithmetic for something this consequential.

### 2.4 Known gap — not covered by this run

Leave Type Validation, Balance Validation, Back-Date Validation, and Conflict Check (all data-dependent on a real account's actual leave settings/balance/existing applications) need a live bearer token against real erp-api, the same as this doc's other "Live verification" subsections — not tested here since none was available for this run. The reference image's claims for those categories are unverified either way.

---

## 3. Cancel Leave

Node: `leave_action_node` (branch: `state["intent"] == "cancel_leave"`) · State machine: `services/leave_cancel_state.py` (Redis-backed, survives across turns) · Tests: `tests/test_leave_action.py` (**38 passing** — `TestLeaveActionNodeCancelBranch` + `TestClassifyNodeCancelMidFlow`)

### 3.1 Flow

Match → Select (only if ambiguous) → Preview (balance impact) → Confirm → Execute (`erp_client.cancel_leave`, the only mutating call in this whole flow).

### 3.2 Scenario categories

| Cat | Scenario | Example queries |
|---|---|---|
| A | Starting a cancellation | "Cancel my leave request for Friday" (date match) · "Cancel my leave" (vague — straight to preview if exactly one pending request, else a selection list) · "Cancel LR-2041" / "cancel #2041" (reference ID — skips selection even with multiple pending) · "Cancel my sick leave" (type match) · "Cancel my casual leave for next Monday" (type + date) · "I want to withdraw my leave request" / "I don't want my leave anymore" (phrasing variants) · "Cancel my leave, my plans changed" (reason inline, forwarded to erp-api's `cancel_reason`) |
| B | Selection replies (only after an ambiguous list) | "2" / "the second one" / "the first one" · "LR-2043" · "the casual leave one" / "the one on the 21st" |
| C | Confirmation replies (after the balance-impact preview) | "Confirm Cancellation" (actual frontend button label) · "yes" / "go ahead" / "proceed" / "confirm" · "Keep Request" (actual frontend decline label) · "no" / "don't cancel it" / "never mind" · "hmm not sure" (off-topic — re-asks without dropping state) |
| D | Interruptions | "what's my leave balance?" mid-selection/confirmation — answered directly, cancel flow resumable after · "cancel my leave" mid-apply-flow — interrupts the apply draft, which stays resumable |
| E | Edge cases | Zero pending requests · Confirming after the request was already approved/rejected elsewhere (revalidation catches it) · A request erp-api itself refuses (e.g. payroll-locked, already-cancelled, attendance-locked, a policy notice-period rule) — routed through the shared HEL-283 failure-card layer as of 2026-08-21, see [§6](#6-leave-failure-messaging-hel-283) |

### 3.3 Employee identity on the card

`leave_cancellation_preview` and `leave_cancel_success` both carry an `employee: {user_id, name}` block. Neither costs an extra erp-api call: `user_id` is `company_id` in this codebase's graph state (already the JWT's `user_id` — see `main.py`'s `verify_jwt_token`), and `name` comes from the role-gate `/ai/leave/context` call every leave intent already makes at the top of `leave_action_node`, reused rather than re-fetched.

### 3.4 Live verification

**Deliberately stops before Confirm.** Cancel-leave's execute step calls the real, mutating `/leave/cancel` endpoint — this is the same class of action that caused the LR-69 incident during a previous live test session (see project memory). Match and Preview are both GET-only and carry no such risk, so live verification covers those two steps and stops.

Live run, 2026-08-21, query `"cancel my leave for today"`, matched against this account's real pending request:

```json
{
  "id": 78,
  "leave_type": "Casual Leave",
  "from_date": "2026-08-21",
  "to_date": "2026-08-21",
  "status_name": "pending",
  "reference": "LR-78",
  "current_balance": "16",
  "days_to_restore": "1",
  "projected_balance": 17.0,
  "employee": { "user_id": 3735, "name": "B Geo" }
}
```

Answer: *"Here's your Casual Leave request (2026-08-21 to 2026-08-21 (1 day(s)), ref LR-78). Current balance: 16 day(s) -> after cancellation: 17.0 day(s). Please review the details above. Would you like to cancel this request? Reply to confirm and the reason for cancelling."*

Match, balance lookup, and the employee-identity fix all confirmed against real data. **No confirmation reply was sent; LR-78 was not cancelled.** The Confirm → Execute step (categories B/C's resolution and the actual `/leave/cancel` call) remains verified by the mocked suite only, pending an explicit go-ahead and a specific request you're fine with actually cancelling.

---

## 4. View Pending Leaves

## 5. View Any Type of Leaves (Leave Status & History)

Both are the same `leave_status` intent and the same code path in `leave_action_node` — "pending" is simply the default filter when no status word is given. Tests: `tests/test_leave_action.py` (**33 passing** — `TestLeaveActionNodeStatusBranch`).

### 4/5.1 Detailed test case matrix

Verified against the actual implementation (`services/leave_action_service.py`'s `leave_status` branch, `services/hr_graph.py`'s `classify_node` fast-paths, `services/intent_classification_service.py`'s intent prompt). "Test Query" wording is illustrative — many phrasings reach the same branch. "Expected Date Resolution" mostly doesn't apply here (this is a viewing/filtering flow, not a date-parsing one).

| # | Category | Expected Result | Test Query | Expected Behavior | Expected Date Resolution | Status | Notes |
|---|---|---|---|---|---|---|---|
| 1 | Default Pending List | Positive | show me my pending leaves | Returns only `status_name == "pending"` records, structured card list + prose summary. | N/A | Pass | Default filter — no status word required. |
| 2 | Default Pending List | Positive | do I have any pending leave requests | Same as #1. | N/A | Pass | |
| 3 | Default Pending List | Positive | view pending leave request | Same as #1. | N/A | Pass | LIVE BUG FIXED: this is exactly 4 words — with prior HR context in the conversation, it was being stolen by classify_node's "≤4-word short follow-up" heuristic and downgraded to generic `follow_up` before ever reaching real classification, even though `fast_classify` already confidently said `leave_status`. |
| 4 | Default Pending List | Positive | give my pending leaves | Same as #1. | N/A | Pass | Same bug class as #3. |
| 5 | Default Pending List | Positive | whats my pending leaves | Same as #1. | N/A | Pass | Same bug class as #3. |
| 6 | Default Pending List | Positive | show me my pending leaves (5 words — doesn't hit the ≤4-word fast-path at all) | Reaches the real LLM classifier and correctly returns `leave_status`. | N/A | Pass | LIVE BUG FIXED: previously reached the LLM and was misclassified as `leave_balance` — the intent prompt's `leave_status` description never mentioned "pending," giving the model nothing to anchor that phrasing to. Fixed by adding explicit pending-leave examples and a hard rule distinguishing it from balance. |
| 7 | Zero Pending | Negative | show me my pending leaves (no pending records exist) | "You currently have no pending leave requests." | N/A | Pass | Exact wording matches the story's AC3 example. |
| 8 | Status Question — Single Match | Positive | is my leave approved (1 pending record) | Answers directly: "Your Casual Leave request (2026-07-30 to 2026-07-30) (1 day(s)) is pending with Manager." | N/A | Pass | |
| 9 | Status Question — Single Match | Positive | was my leave rejected (1 pending record) | Same direct answer as #8 — correctly NOT filtered to "rejected". | N/A | Pass | LIVE BUG FIXED: "rejected" is also a recognized status-filter keyword, so this previously hit the same blanket refusal built for an explicit "show me my rejected leaves" request — even though the person never asked to see a list, just whether theirs was decided. |
| 10 | Status Question — Single Match | Positive | did HR approve my leave / has my leave been accepted yet | Same as #8/#9. | N/A | Pass | Covers reversed word order and the "accepted"/"yet" phrasing variants. |
| 11 | Status Question — Zero Match | Negative | is my leave approved (0 pending records) | "You don't have any pending leave requests right now, so if you're asking about one you already applied for, it's most likely already been decided — I can only see pending requests from here, not the final outcome. Check the Leave module for the result." | N/A | Pass | Deliberately NOT the generic pending zero-state (#7) — `/leave/pending` genuinely can't distinguish approved/rejected/never-submitted, so this says so honestly instead of reading like the question was ignored. |
| 12 | Status Question — Multiple Matches | Positive (asks, doesn't guess) | is my leave approved (2+ pending records) | "You have multiple pending leave requests — which one are you asking about? Casual Leave (2026-07-30 to 2026-07-30) or Sick Leave (2026-08-14 to 2026-08-15)?" | N/A | Pass | A singular status question with 2+ candidates is genuinely ambiguous — asks instead of picking one or dumping every status into one sentence. |
| 13 | Disambiguation Reply | Positive | the casual leave one (reply to #12) | Resolves to that one card's status directly, no re-fetch (candidates were stored fully built). | N/A | Pass | Matched by leave-type keyword. |
| 14 | Disambiguation Reply | Positive | 2026-07-30 (reply to #12) | Same resolution as #13. | N/A | Pass | Matched by exact ISO date substring. |
| 15 | Disambiguation Reply | Positive | the 14th (reply to #12) | Same resolution, resolves to the Sick Leave candidate. | N/A | Pass | Matched by day-of-month, only trusted when unique among the candidates. |
| 16 | Disambiguation Reply | Negative (unresolvable) | never mind, something else (reply to #12) | Clears the pending disambiguation state and falls back to showing the full list, rather than guessing which one was meant. | N/A | Pass | |
| 17 | List Request (not a question) | Positive | show me my pending leaves (2+ pending records) | Lists all of them with inline statuses in one summary — NOT a disambiguation ask. | N/A | Pass | Confirms the question-vs-list distinction: #12 asks because it's singular ("my leave"); this doesn't, because it's an explicit list request. |
| 18 | Explicit Non-Pending Filter | Negative (refused) | show me my approved leaves | "I can only show your pending leave requests here — approved, rejected, or cancelled history isn't available through this view." erp-api is not even called. | N/A | Pass | `/leave/pending` (renamed from `/leave/status` 2026-08-18) genuinely cannot answer this — it only ever returns pending records now. Checked before the erp-api call, not after, to avoid a wasted round-trip. |
| 19 | Explicit Non-Pending Filter | Negative (refused) | my rejected leaves / show me cancelled leaves | Same refusal as #18. | N/A | Pass | |
| 20 | Balance/Status Ambiguity | Positive (asks) | my pending leave situation (fast_classify and the LLM disagree specifically between leave_balance and leave_status) | "Just to make sure I get you the right info — are you asking about your leave balance (days remaining) or your pending leave requests (status of what you've already applied for)?" | N/A | Pass | Narrow, confidence-gated safety net — only this exact disagreement pair triggers it; every other disagreement keeps trusting the LLM silently. |
| 21 | Balance/Status Clarification Reply | Positive | the pending one (reply to #20) | Resolves directly to `leave_status`, no re-classification. | N/A | Pass | |
| 22 | Balance/Status Clarification Reply | Positive | my balance please (reply to #20) | Resolves directly to `leave_balance`. | N/A | Pass | |
| 23 | Pagination | Positive | show me my pending leaves (6+ pending records, default display limit 5) | Shows the first 5, "... (showing 5 of 6 — ask to see more)". | N/A | Pass | `PENDING_LEAVE_DISPLAY_LIMIT` env var, default 5. |
| 24 | View More | Positive | show me more (reply to #23) | Resumes from the stored offset, shows the remaining 1. | N/A | Pass | Recognized by classify_node's own fast-path — "show me more" has no leave/pending keyword in it at all. |
| 25 | View More — Exhausted | Negative | show me more (asked again after the list was already fully shown) | "You've already seen all 6 of your pending leave requests." | N/A | Pass | Not a false zero-state — there ARE requests, they've just all been shown already. |
| 26 | Mandatory Fields | N/A (display fact) | any non-empty pending result | Card carries all 7 mandatory fields: Leave Type, Start/End Date, Total Days, Current Status, Current Approver Name, Request Submission Date, plus a synthesized `LR-<id>` reference and a chip-ready `status_label` ("Pending with Manager" / "Pending with HR"). | N/A | Pass | Approver name/role/submission date read from erp-api's real fields when present, degrade gracefully (computed or omitted, never faked) when absent. |
| 27 | Manager Access | Positive | do I have any pending leave requests (manager role) | Full self-service, identical to an employee — sees only their own submitted requests. | N/A | Pass | No team-approval view is ever reachable through this path; every call is scoped to the caller's own token regardless of role. |
| 28 | Mid-Flow Interruption | Positive | is my leave approved (asked while an apply-leave draft is in progress) | Interrupts and answers directly; the apply draft is preserved and resumable afterward. | N/A | Pass | |
| 29 | Follow-up Suggestions | N/A (display fact) | any non-empty pending result | "Would you like to check your leave balance?" / "Would you like to apply for leave?" / "You can also ask me to cancel a pending request." attached to the response. | N/A | Pass | Cancel suggestion is copy-only pending the real cancel-leave integration (see [§3](#3-cancel-leave), which has since landed). |
| 30 | Erp-api Failure — Timeout | Negative | any query, erp-api exceeds its SLA | "I couldn't reach the HR system in time — please try again in a moment." | N/A | Pass | |
| 31 | Erp-api Failure — Unavailable | Negative | any query, erp-api 5xx / unreachable | "I'm unable to reach the HR system right now — please try again shortly." | N/A | Pass | |

### 4/5.2 Scenario categories

| Cat | Scenario | Example queries |
|---|---|---|
| Default (pending) | No status word given | "show me my pending leaves" · "what's the status of my leave" · "show my casual leave status" — all default to `pending` |
| Explicit status | Named status, matched by prefix (verb/noun/adjective forms) | "show my approved leaves" · "show my rejected leaves" · "show me cancelled leaves" · "show my approve leave" / "show my cancel leave" (missing suffix — still matches) |
| All / history | Every status at once | "show me all my leave requests" · "show my applied leaves" |
| Status question | Yes/no question about a specific request, not a list request | "is my leave approved" · "was my leave rejected" · "why was my leave rejected" (narrows to the named status among several candidates) |
| Type filter | Combined with a leave type | "show my casual leave status" · "how many of my sick leaves were rejected" |
| Date range | Combined with a date range | "show me my leave requests from 2026-08-19 to 2026-08-20" |
| Ambiguous | No status signal, no "all", not a question, doesn't say "status" | "show me my leave requests" — asks whether they mean balance / all / approved / cancelled / rejected, even if a date range was already given |
| Disambiguation | Status question matches multiple candidates | Asks "which one?", resolves a follow-up reply ("the casual leave one", "the one on the 21st") without re-classifying |
| Zero results | No leaves matching the filter | Honest "you don't have any {filter} leave requests on record" — never a false zero |

### 4/5.3 Live verification (2026-08-21, real account — 12 real leave records: 1 pending, 1 approved, 1 rejected, 9 cancelled)

| # | Query | Result |
|---|---|---|
| S1 | "show me my pending leaves" | 1 result — Casual Leave, 2026-08-21, pending |
| S2 | "show me all my leave requests" | 12 results, full mixed-status list |
| S3 | "what leaves have been approved" | 1 result — Sick Leave, 2026-08-14, approved |
| S4 | "show my rejected leaves" | 1 result — Casual Leave, 2026-08-20, rejected, with the real rejection reason |
| S5 | "show me cancelled leaves" | 9 results |
| S6 | "is my leave approved" | Status question — precise answer, the one approved Sick Leave |
| S7 | "why was my leave rejected" | Status question — narrows correctly to the one rejected record among 12, with reason |
| S8 | "show my casual leave status" | Type filter, no status word — defaults to pending, correct single match |
| S9 | "what's the status of my leave" | Defaults to pending, correct single match |
| S10 | "show me my leave requests ... from 2026-08-19 to 2026-08-20" | Correctly asks for clarification — a date range alone does not resolve category ambiguity when no status/all/question signal is present; this is intended behavior, not a bug |

All 10 live cases matched expected behavior against real, mixed-status data, including the deliberately-ambiguous S10 case.

---

## 6. Leave Failure Messaging (HEL-283)

Shared module: `services/leave_failure.py` · Wired into: the `apply_leave` and `cancel_leave` branches of `leave_action_node` (`services/leave_action_service.py`), and the eligibility failure path in `services/leave_eligibility_service.py` · Tests: `tests/test_leave_failure.py` (**54 passing**, shared layer) + `tests/test_leave_action.py` (**15** apply-side + **13** cancel-side, across `TestCancelFailureCards` + `TestCancelFailureIsBackendOnly`) + `tests/test_leave_eligibility.py` (**3** eligibility-side) — **85 passing total**

Cross-cutting rather than its own conversational flow: this is the layer all three flows above route their *failures* through, so a rejection is explained the same way regardless of which one hit it.

### 6.1 What it does

- Turns any erp-api rejection — or a finding Helix determined itself (a pre-submission balance/holiday/duplicate check, an unconfigured leave type) — into one `leave_failure` SSE card plus a spoken sentence, per the story's AC1–AC6.
- Never rewords, invents, or interprets a backend reason (AC1–AC3): erp-api's sentence is shown character for character, or not at all.
- Strips technical leakage (stack traces, SQL errors, HTML error pages) and replaces bare/unknown error codes with one controlled fallback message, never displayed as if it explained anything (AC5).
- Every failure gets a `reason_code` — unrecognised wording defaults to `POLICY_RULE` rather than `null` (product decision, 2026-08-24, superseding the original no-badge default) — but the badge/heading is the only thing ever guessed; `display_message` itself is always either erp-api's exact words or the controlled fallback, never invented.
- Lists every applicable reason, not just the first (AC4) — apply enriches erp-api's own rejection (or a local pre-check) with anything else Helix's own checks find wrong with the same request (a blocked holiday, insufficient balance, a duplicate application). Cancel deliberately does **not** do this — see §6.4's "Cancel — Backend-Only Rejection" row.
- Offers a next step only where one is safely knowable from *which slot* was invalidated (apply) or that a real, understood rejection occurred (cancel), never guessed from reading the rejection text, and never offered on a fallback (AC6).

### 6.2 Detailed test case matrix

Verified 2026-08-25 directly against the current `services/leave_failure.py` (calling `interpret_failure`/`build_card` live, not just reading test comments) and the current call sites in `services/leave_action_service.py` / `services/leave_eligibility_service.py`. "Test Query" describes the triggering condition rather than literal chat text where the scenario is a backend/local-check response rather than a phrasing variant. "Expected Date Resolution" doesn't apply to this flow (failure messaging, not date parsing).

| # | Category | Expected Result | Test Query | Expected Behavior | Expected Date Resolution | Status | Notes |
|---|---|---|---|---|---|---|---|
| 1 | Verbatim Passthrough | Positive | Apply rejected: "You have already applied Casual Leave from 2026-08-20 to 2026-08-20." | Shown character-for-character as `display_message[0]` — never reworded or summarised. | N/A | Pass | `TestVerbatimPassthrough`; live payload captured 2026-08-19. |
| 2 | Verbatim Passthrough | Positive | Cancel rejected: "This leave request has already been cancelled." | Same — verbatim. | N/A | Pass | Same test class, live payload captured 2026-08-19. |
| 3 | Reason-Code Classification | Positive | "This leave request has already been cancelled." | `reason_code = ALREADY_CANCELLED`; `badge = null` (unmapped, pending BA sign-off). | N/A | Pass | `TestCancelFailureCards::test_already_cancelled_maps_to_its_reason_code`. |
| 4 | Reason-Code Classification | Positive | "You cannot cancel this leave because attendance has already been calculated." (cancel) / "Attendance is locked for date 2026-09-01" (apply — different wording) | Both map to `ATTENDANCE_LOCKED` — one pattern covers both observed phrasings. | N/A | Pass | `TestReasonCodes::test_attendance_locked_wording_from_apply_is_also_matched` + `test_apply_failure_from_erp_api_surfaces_its_message`. |
| 5 | Reason-Code Classification | Positive | "Monthly sick leave limit reached. Monthly limit: 2, already applied: 2, requested: 1." | `MONTHLY_LIMIT_REACHED` — NOT filed as `INSUFFICIENT_BALANCE` (a cap ≠ balance exhaustion) or `DUPLICATE_APPLICATION` (regression guard: the sentence itself contains "already applied: 2"). | N/A | Pass | `TestMonthlyLimit` (5 tests). |
| 6 | Reason-Code Classification | Positive | "Your manager is currently unavailable to approve this." (unrecognised wording) | Defaults to `reason_code = POLICY_RULE` (product decision, 2026-08-24) rather than `null` — the message itself is still shown exactly as written either way. | N/A | Pass | `TestReasonCodes::test_unrecognised_message_defaults_to_policy_rule`. |
| 7 | Reason-Code Classification | Negative (guard) | "Your leave balance summary could not be loaded." | Does NOT get filed as `INSUFFICIENT_BALANCE` just because the word "balance" appears — gets the generic `POLICY_RULE` default instead. | N/A | Pass | `TestReasonCodes::test_ticket_categories_are_not_invented` — the ticket's own `INSUFFICIENT_BALANCE`/`BLOCKED_DATE`/`POLICY_RESTRICTION` taxonomy has never appeared in a real erp-api response. |
| 8 | Verbatim + Classification (mockup match) | Positive | Cancel rejected: "Policy LP-14: approved leave can only be cancelled at least 48 hours before the start date. Your leave starts on 06 Aug 2026." | `reason_code=POLICY_RULE`, `badge=policy_rule`, `badge_label="Policy rule"`, `sub_title="Blocked by leave policy"`, message shown verbatim — reproduces the approved mockup card exactly. | N/A | Pass | `TestCardShape::test_cancel_policy_rule_card_matches_the_approved_mockup` + `TestCancelFailureCards::test_backend_reason_is_never_reworded`. |
| 9 | Local Pre-Check (Apply) | Negative | Apply casual leave for a date the employee already has a pending Sick Leave request on | Blocked BEFORE `apply()` is ever called — `DUPLICATE_APPLICATION`, `badge=null`, `sub_title="Requested date is a duplicate"`. | N/A | Pass | `test_proactive_duplicate_date_check_emits_a_leave_failure_card` — live UX fix 2026-08-24 (previously a bare chat message with no card at all). |
| 10 | Local Pre-Check (Apply) | Negative | Apply for 20 Dec, a configured company holiday (Quarter-End Freeze) | Blocked before `apply()` — `BLOCKED_DATE`, `badge=blocked_date`, `sub_title="Requested date is blocked"`. | N/A | Pass | `test_proactive_holiday_check_emits_a_leave_failure_card` — live bug fix 2026-08-24 (previously only checked AFTER an erp-api rejection, so a fully-holiday request erp-api itself didn't reject went through uncaught). |
| 11 | Local Pre-Check (Apply) | Negative | Apply for 5 days Sick Leave, 3 remaining | Blocked before `apply()` — `INSUFFICIENT_BALANCE`, `badge=balance`, `sub_title="Not enough Sick Leave balance"` (built dynamically per the actual leave type, not a static table). | N/A | Pass | `test_insufficient_balance_gets_a_dynamic_sub_title` — matches the confirmed mockup wording exactly. |
| 12 | Erp-api Rejection (Apply) | Negative | Apply confirmed, erp-api rejects: "Attendance is locked for date 2026-09-01" | Shown verbatim, `ATTENDANCE_LOCKED`; slots reset to `collecting`, dates cleared so a bare "yes" can't resubmit the identical rejected request. | N/A | Pass | `test_apply_failure_from_erp_api_surfaces_its_message`. |
| 13 | Erp-api Rejection (Apply) | Negative | Apply confirmed, erp-api rejects as duplicate; user replies "yes" again | Second "yes" is NOT re-read as re-confirming the same rejected request — does not loop forever. | N/A | Pass | `test_apply_failure_reply_does_not_loop_forever` — live bug fix. |
| 14 | No Card on Success | Positive | Apply succeeds | `done` event's `is_failure` is `false`; no `leave_failure` event at all. | N/A | Pass | `test_is_failure_defaults_false_on_an_ordinary_apply_response`. |
| 15 | No Card on Success | Positive | Cancel succeeds | Same — no `leave_failure` card; success/balance card shown instead. | N/A | Pass | `TestCancelFailureCards::test_successful_cancellation_emits_no_failure_card`. |
| 16 | No Card on Success | Positive | Eligibility — a genuine verdict ("am I eligible for casual leave?") | No failure card — a real answer is never rendered as a failure. | N/A | Pass | `TestFailureCardForUnconfiguredType::test_a_real_verdict_emits_no_failure_card`. |
| 17 | Cancel — Backend-Only Rejection | Negative | Cancel rejected: "This leave request is locked due to payroll processing." | Exactly ONE reason shown — nothing derived locally added beside it (unlike apply, which enriches with holiday/balance/conflict findings). erp-api's `/leave/cancel` is the sole authority on cancellability, by design. | N/A | Pass | `TestCancelFailureIsBackendOnly::test_only_the_backend_reason_is_shown` — deliberate design choice, not a gap. |
| 18 | Cancel — Status Never Gates | Positive | Confirming a cancel after the request's status changed to "approved" between preview and confirm | Still cancelled if erp-api accepts it — a future approved leave is a normal thing to withdraw; no client-side pending/approved pre-check re-added. | N/A | Pass | `TestCancelFailureIsBackendOnly::test_a_status_change_never_gates_a_cancellation`. |
| 19 | AC6 — Next Action (Cancel) | Positive | Cancel rejected with a real, understood reason | `next_action = "Would you like to see your other leave requests?"` — appended to both the card and the spoken reply. | N/A | Pass | `TestCancelFailureIsBackendOnly::test_next_action_is_offered_on_a_real_rejection`. |
| 20 | AC6 — Next Action Suppressed | Negative | Cancel rejected with only a bare code ("ERR_9001") | `next_action` is `null` — nothing sensible to suggest when the backend explained nothing. | N/A | Pass | `TestCancelFailureIsBackendOnly::test_no_next_action_when_the_backend_explained_nothing`. |
| 21 | Technical-Leak Guard | Negative | erp-api leaks a SQL error / a stack frame / an HTML 500 page / an `Undefined index` / an `Exception:` string | All five replaced wholesale by the controlled fallback — never shown, in either apply or cancel. | N/A | Pass | `TestTechnicalLeakGuard` (parametrized ×5) + `TestCancelFailureCards::test_technical_detail_never_reaches_the_employee`. |
| 22 | Technical-Leak Guard | Negative | A leaking message ALSO carries a clean `data.error` | Falls through to the clean `data.error` rather than straight to the generic fallback. | N/A | Pass | `TestTechnicalLeakGuard::test_leaky_message_falls_through_to_clean_data_error`. |
| 23 | Unknown/Bare Error Code | Negative | `"ERR_5521"`, `"E1042"`, `"500"`, `"LEAVE_APPLY_FAILED"`, `"Failed."`, `"ERR 5521"`, `"LEAVE ERROR 42"` | All replaced by the controlled fallback — clean-looking but meaningless, treated the same as a leak. | N/A | Pass | `TestUnknownErrorCodes` (parametrized ×7) + `TestCancelFailureCards::test_unknown_error_code_gets_the_controlled_fallback`. |
| 24 | Fallback Triggers | Negative | `message` missing entirely / empty string / whitespace-only / non-string (nested object) | All four fall back to the controlled `FALLBACK_MESSAGE`, `is_fallback=true`. | N/A | Pass | `TestFallback` (4 tests). |
| 25 | Fallback Backstop | Positive | `message` missing but `data.error` present and clean | Uses `data.error` as the reason — NOT the fallback, since the two fields are always identical when both are present. | N/A | Pass | `TestFallback::test_data_error_used_only_when_message_absent`. |
| 26 | Badge Mapping | N/A (display fact) | Every known reason code | `INSUFFICIENT_BALANCE`→`balance`, `BLOCKED_DATE`→`blocked_date`, `LEAVE_TYPE_NOT_IN_POLICY`/`REQUIRES_CONFIRMATION`/`POLICY_RULE`→`policy_rule`; `DUPLICATE_APPLICATION`/`ALREADY_CANCELLED`/`ATTENDANCE_LOCKED`/`MONTHLY_LIMIT_REACHED`→ no badge (pending BA sign-off); `null` code → no badge. | N/A | Pass | `TestBadgeMapping` (5 tests). |
| 27 | Card Shape — Title | N/A (display fact) | Same rejection, three different `action` values | `apply_leave`→"Leave Request Not Completed", `cancel_leave`→"Cancellation Not Completed", `leave_eligibility`→"Eligibility Check Not Completed", an unrecognised action → "Request Not Completed" (never errors). | N/A | Pass | `TestCardShape::test_title_comes_from_the_action_not_the_message` + `test_unknown_action_still_produces_a_usable_card`. |
| 28 | Card Shape — Multiple Reasons | Positive | Apply: erp-api's monthly-limit rejection + two Helix-found local reasons (a blocked holiday, insufficient balance) on the SAME card | `reason_code[]`/`badge[]`/`display_message[]` stay index-aligned across all three entries; erp-api's own reason leads. | N/A | Pass | `TestCardShape::test_several_reasons_stay_index_aligned`. |
| 29 | Card Shape — Full Contract | N/A (display fact) | Any card | Carries exactly: `is_failure`, `status`, `action`, `title`, `reason_code[]`, `badge[]`, `badge_label[]`, `display_message[]`, `sub_title` (scalar, primary reason only), `is_fallback`, `next_action`. | N/A | Pass | `TestCardShape::test_card_carries_the_full_contract`. |
| 30 | Sub-title — Per-Reason-Code | N/A (display fact) | A duplicate-application rejection / a blocked-date local failure | `sub_title` = "Requested date is a duplicate" / "Requested date is blocked" — applies to `apply_leave` too, not just `cancel_leave`. | N/A | Pass | `TestCardShape::test_duplicate_application_and_blocked_date_get_their_own_subtitles`. |
| 31 | Eligibility — Unconfigured Type | Negative (not in policy) | "am I eligible for maternity leave?" | `LEAVE_TYPE_NOT_IN_POLICY`, `badge=policy_rule`, title "Eligibility Check Not Completed", `next_action` lists the real configured alternatives ("Casual Leave, ..."). | N/A | Pass | `TestFailureCardForUnconfiguredType::test_unconfigured_type_emits_a_policy_failure_card`. |
| 32 | Done-Event Parity | N/A (display fact) | Any failure, across all three flows | Terminal `done` event's `data.failure` == the `leave_failure` event's `data.failure`, so a client rendering from `done` alone still gets the full card. | N/A | Pass | One test per flow: `TestCancelFailureCards::test_done_event_carries_the_same_card`, `TestFailureCardForUnconfiguredType::test_done_event_carries_the_card_too`, `test_proactive_duplicate_date_check_emits_a_leave_failure_card` (asserts `done["is_failure"]`). |
| 33 | Fallback + Badge Interaction | Negative (observed gap, not a test failure) | erp-api returns a bare code / leaks a stack trace / omits `message` entirely | `interpret_failure()` still defaults `reason_code` to `POLICY_RULE` for the FALLBACK case too, so the resulting card carries `badge="policy_rule"`, `badge_label="Policy rule"`, `sub_title="Blocked by leave policy"` sitting next to the generic "try again later" text. | N/A | **Flagged** | Verified live by calling `interpret_failure()` directly, 2026-08-25 — not asserted by any test in `TestFallback`/`TestUnknownErrorCodes`/`TestTechnicalLeakGuard`. Worth a product call: a "Policy rule" chip next to a message that explicitly says the cause is unknown risks misleading the employee into thinking this was a known policy issue rather than an unrecognised failure. |

### 6.3 Scenario categories (summary)

| Cat | Scenario | Example |
|---|---|---|
| Verbatim passthrough | erp-api's own sentence reaches the employee unchanged | "You have already applied Casual Leave from 2026-08-20 to 2026-08-20." shown as-is |
| Reason-code classification | Message → code by exact pattern, derived from responses actually observed — not the ticket's assumed `INSUFFICIENT_BALANCE`/`BLOCKED_DATE`/`POLICY_RESTRICTION` taxonomy, since none of those three has ever appeared in a real erp-api response. Unrecognised wording defaults to `POLICY_RULE`, not `null` (2026-08-24 product decision) | "already been cancelled" → `ALREADY_CANCELLED`; "attendance has already been calculated" → `ATTENDANCE_LOCKED`; "monthly...limit reached" → `MONTHLY_LIMIT_REACHED`; anything else → `POLICY_RULE` |
| Badge / sub-title grouping | Coarse display layers, separate from the precise code, so several codes can share one box or none, and a rejection can carry a short heading above the backend's sentence | `LEAVE_TYPE_NOT_IN_POLICY` + `REQUIRES_CONFIRMATION` + `POLICY_RULE` → badge `policy_rule`, label "Policy rule"; `INSUFFICIENT_BALANCE`'s `sub_title` is built dynamically per leave type ("Not enough Sick Leave balance"); 4 state-conflict codes → intentionally no badge pending BA sign-off |
| Local pre-checks (not a backend rejection) | Helix's own advisory check reports a real finding before erp-api is even called | Apply: balance/holiday/duplicate-date pre-checks all block before `apply()` is ever called · Eligibility: an unconfigured leave type names itself and lists the real configured alternatives |
| Multiple simultaneous reasons (apply only) | erp-api's own rejection plus anything else Helix's own checks (holiday calendar, balance, existing applications) find wrong with the same request, so one fix-resubmit-fail cycle doesn't repeat. Cancel deliberately does NOT do this — erp-api's `/leave/cancel` already owns all cancel-eligibility validation | erp-api rejects for one reason; Helix's holiday check independently finds every requested day is a company holiday — both shown, in one array, never the same finding twice |
| Technical-leak guard | Stack traces, SQL errors, HTML error pages, internal identifiers are replaced wholesale, never shown | `"SQLSTATE[23000]: Integrity constraint violation..."` → controlled fallback |
| Unknown/bare error code | A clean-looking but meaningless string is treated the same as a leak, not shown as a reason | `"ERR_5521"`, `"500"`, `"Failed."` → controlled fallback |
| Per-action card identity | Title comes from which action failed, never from reading the message | `apply_leave` → "Leave Request Not Completed"; `cancel_leave` → "Cancellation Not Completed"; `leave_eligibility` → "Eligibility Check Not Completed" |
| Done-event parity | The terminal `done` SSE event repeats the same card, so a client rendering from it alone still gets the full structure | Card in `leave_failure` event == `data.failure` in `done` event, for all three flows |
| No card on success | A successful apply/cancel, or a genuine eligibility verdict, never emits a failure card | — |

### 6.4 Per-flow coverage

| Flow | Covered | Tests |
|---|---|---|
| Apply Leave | Local pre-checks (balance/holiday/duplicate-date, each with a dynamic or static sub_title), erp-api rejection + reason code, multi-reason index-alignment, no-loop-on-retry, no-card-on-success | 15 (inline in `TestLeaveActionNodeApplyBranch`, `tests/test_leave_action.py`) |
| Cancel Leave | erp-api rejection + reason code (`ALREADY_CANCELLED`, `ATTENDANCE_LOCKED`, `POLICY_RULE` default), technical-leak guard, unknown-code fallback, backend-only (no local enrichment), status-change-never-gates, AC6 next-action offered/suppressed, no-card-on-success, done-event parity | 13 (`TestCancelFailureCards` (7) + `TestCancelFailureIsBackendOnly` (6), `tests/test_leave_action.py`) |
| Eligibility Check | Unconfigured leave type → policy failure card naming real alternatives; no card on a genuine verdict; done-event parity | 3 (`TestFailureCardForUnconfiguredType`, `tests/test_leave_eligibility.py`) |
| Shared layer | Failure detection, verbatim passthrough, reason-code classification + `POLICY_RULE` default, monthly-limit-vs-duplicate/balance disambiguation, fallback triggers, technical-leak denylist, badge/badge-label/sub-title mapping, card shape/index-alignment, local-failure contract, immutability | 54 (`tests/test_leave_failure.py`) |

### 6.5 Gap found and fixed (2026-08-21 → 2026-08-25)

Cancel Leave was **not** wired to the shared layer as of 2026-08-21, despite the module and the apply/eligibility integrations already existing — `_execute_cancel` was doing a raw `cancel_body.get("message") or "This request couldn't be cancelled."`, with no `leave_failure` card, no technical-leak guard, and no bare-code guard. Fixed the same day by routing it through `leave_failure.interpret_failure()` + `build_card("cancel_leave", ...)`, and substantially extended since (badge labels, per-code sub-titles, the `POLICY_RULE` default, an AC6 next-action, backend-only enrichment semantics) — see the row-by-row matrix in [§6.2](#62-detailed-test-case-matrix).

Worth noting: an existing "HA-163 Unit Test Report" document describes a `TestCancelFailureCards` class with 8 passing tests covering this exact behavior, attributed to commit `be40ec1`. That class does not exist anywhere in this repository's history — not at that commit, not on `feature_arsh/HA-160`, not anywhere. The report's claims for Apply Leave and Eligibility Check do match what's actually in the repo; its cancel-flow claim does not.

**Second gap found and fixed (2026-08-25):** `tests/test_leave_action.py` briefly contained two classes both named `TestCancelFailureCards` (one stale, referencing a helper method — `_build_leave_card` — that no longer exists after a rename to `_build_applied_leave_card`, and asserting outdated behavior — `reason_code: null` — from before the `POLICY_RULE` default landed). Python class redefinition silently discarded the first one; pytest only ever collected the second, so this was never a visible test failure, just 8 dead test methods sitting in the file. Removed the stale class (and its now-unused `leave_failure_mod` import) — the assertions it duplicated already have equivalent, up-to-date coverage in `TestCancelFailureIsBackendOnly`. Full suite re-verified at 708 passing after the removal.

### 6.6 Known limitations

- Four reason codes have no approved badge yet, pending a BA decision: `DUPLICATE_APPLICATION`, `ALREADY_CANCELLED`, `ATTENDANCE_LOCKED`, `MONTHLY_LIMIT_REACHED`. Each renders its exact reason with no category chip — a correct outcome, not a degraded one.
- The `POLICY_RULE` default (row 6/7/33 above) means every unrecognised or fallback message now gets a "Policy rule" chip — a deliberate 2026-08-24 product decision for the *recognised-but-uncategorised* case, but its interaction with the *fallback* case (row 33) isn't covered by any test and is worth a second look.
- `BLOCKED_DATE` (apply-side enrichment) is backed only by the company holiday calendar; a year-end freeze or blackout window is a different concept with no equivalent field in any erp-api response today.
- The probation path (`REQUIRES_CONFIRMATION`) has no reachable test account (`is_confirmed=false`) in this environment — mocked-only, same gap noted in [§1.3](#13-known-untestable-live-gap).
- Multi-reason enrichment exists only for apply, by design — see the "Cancel — Backend-Only Rejection" row in §6.2.
- System errors (timeout, erp-api unreachable) are out of scope by design and emit no failure card — they're not a verdict on the leave request, and are handled by the Sprint-1 foundation behavior instead.

### 6.7 Live verification

Not run live end-to-end (no bearer token was available for this pass), but every row in [§6.2](#62-detailed-test-case-matrix) was verified directly against the running `services/leave_failure.py` code (calling `interpret_failure`/`build_card`/`classify` live, 2026-08-25) rather than taken from test comments alone — that's how row 33's untested fallback/badge interaction was actually found. A true end-to-end live run would still require either provoking a genuine erp-api rejection against a real account or constructing malformed backend data (bare codes, stack traces) a real erp-api wouldn't produce on demand — creating junk leave records or depending on erp-api misbehaving on cue, for no signal beyond what 85 mocked tests plus a direct code check already pin down. Consistent with this doc's stance on Cancel Leave's mutating `/leave/cancel` call in [§3.4](#34-live-verification).

### 6.8 HA-163 Sprint 2 product spec compliance (2026-08-25)

A follow-up product/UX spec (Sprint 2 wrap-up email) added requirements beyond what §6.1–§6.7 covered: exact message wording for three named scenarios, a mandatory quick-reply-chips UI element, and per-reason next actions. Gaps found against the running code, and what changed:

| Gap | Before | After |
|---|---|---|
| No structured chips field | `next_action` was a single free-text sentence — no way to express the mockup's multiple discrete buttons (e.g. `[Check Available Balance]` + `[Apply for 3 Days]`) | Added `leave_failure.chip(label, action)` and a `next_actions: [{label, action}]` array on the card, independent of the existing spoken `next_action` sentence — see `TestCardShape`-equivalent coverage in `tests/test_leave_failure.py::test_next_actions_chips_are_carried_alongside_the_spoken_sentence` |
| Balance message wording | *"You only have 3 day(s) of sick leave remaining, but this request needs 4."* — no leave code, no suggestion, unresolved `"day(s)"` | *"You have 3 days of Sick Leave (SL) available, but this request needs 4 days. Reduce the duration or use another type."* — exact spec match via `_insufficient_balance_message()`, reusing the existing `_LEAVE_TYPE_CODES` map and `_pluralize_leave_type` helper |
| Balance chips | None | `[Check Available Balance]` always; `[Apply for N Days]` (N = actual remaining balance) when `remaining > 0`, else `[Use Another Leave Type]` — never a nonsensical "Apply for 0 Days" |
| Blocked-date message wording | *"2026-08-15 is a company holiday (Quarter-End Freeze)."* — ISO date, "holiday" not "blackout period", no range | *"15 Aug 2026 falls in a company blackout period (Quarter-End Freeze, 10 Aug - 18 Aug 2026). Leave cannot be applied for blocked dates."* when the calendar lists a contiguous run of days under the same name (`_named_holiday_span()` walks outward from the requested day through real, consecutive same-named calendar entries — never fabricates a range it wasn't given); falls back to the original single-day wording when the calendar has no such run |
| Blocked-date chip | None | `[Select Another Date]` |
| Cancel next action | Always the fixed sentence *"Would you like to see your other leave requests?"*, regardless of why the cancellation failed | Now varies by `reason_code`: a `POLICY_RULE` rejection (Scenario C — e.g. LP-14's 48-hour notice rule) gets `[Contact HR Help Desk]`; any other real, understood rejection keeps the original `[View My Leave Requests]` |
| "Always attach chips" vs. the fallback's suppressed next_action | A fallback failure (bare code, leaked stack trace, missing message) got no next-step suggestion at all, on either apply or cancel | Now attaches `[Contact HR Help Desk]` even on a fallback — safe specifically because it echoes what `FALLBACK_MESSAGE` already says ("...or contact HR support if the issue persists"), unlike a "try different dates" suggestion, which would have contradicted "we don't know what went wrong" |
| Done-event parity gap (found in passing, unrelated to the spec) | The apply balance pre-check fired the `leave_failure` SSE event but never passed the card as `extra_data` to `_finish` — the terminal `done` event was missing the card entirely for this one path, unlike every other failure path in this file | Fixed — `extra_data=card` now passed, matching the pattern everywhere else; covered by `test_insufficient_balance_message_and_chips_match_ha163_scenario_a`'s `done["failure"] == card["failure"]` assertion |

**Still not fully achievable:** the blackout-period range wording (Scenario B) only renders correctly when erp-api's holiday calendar actually lists every day of the freeze as an individual entry under the same name — confirmed to work that way in the tests above, but not verified against a real erp-api response. If erp-api's calendar instead only lists isolated named days with no per-day entries for a range, no code change here can recover a range that was never in the data — that would need erp-api to expose a genuine start/end "blocked period" concept, which still doesn't exist as of this writing.

New/updated tests: `TestCardShape` (shared layer, +1), and in `TestLeaveActionNodeApplyBranch`: `test_insufficient_balance_message_and_chips_match_ha163_scenario_a`, `test_insufficient_balance_with_zero_remaining_suggests_another_type`, `test_blocked_date_message_expands_to_the_full_named_range`, `test_blocked_date_message_stays_single_day_when_calendar_has_no_range`, `test_erp_rejection_chips_vary_by_which_slot_was_invalidated`; in `TestCancelFailureIsBackendOnly`: updated `test_next_action_is_offered_on_a_real_rejection` plus new `test_next_action_offers_to_view_requests_for_a_non_policy_rejection` and an updated `test_no_next_action_when_the_backend_explained_nothing`. Full suite re-verified at 738 passing.

---

## Appendix — running these live checks again

The probe scripts used above live outside the repo (session scratchpad, not committed) since they take a raw bearer token as a shell env var rather than persisting it anywhere on disk. To reproduce:

1. Get a real bearer token for a `role_id=5` employee account (decode-check it matches this `.env`'s `ERP_API_URL`).
2. Call `services.hr_graph.leave_eligibility_node` / `services.hr_graph.leave_action_node` directly with `{"query": ..., "bearer_token": ..., "company_id": <the token's user_id>, "conversation_id": ..., "usage_events": []}` and a simple event-collecting writer — no server, DB, or Redis required for eligibility or view-leaves; cancel-leave's preview step also needs none, but do **not** send a follow-up confirmation turn unless you intend to actually cancel that request.
3. For a true end-to-end run (real LLM intent classification, real Postgres/Redis persistence), use the existing `tests/live_intent_sweep.py` pattern instead, with `LIVE_TEST_USER_EMAIL` / `LIVE_TEST_USER_PASSWORD` set and both `helixta-api` and `erp-api` reachable.
