# Merge plan — `sprint1-2` into `release/12-09-2026-sprint-4`

**Status:** APPLIED. Merged as `87e7a04` on `release/12-09-2026-sprint-4` and pushed to origin (2026-09-12). See §8 for what changed between plan and execution — two findings below were overturned by evidence during the merge and are marked as such in place.
**Merge base:** `3f0efe7a864dd2ba80ccb3a26611430e383d7f73` ("date fixissue", 2026-09-04 04:10 -0600)
**Divergence:** sprint1-2 +96 commits · release +68 commits · 83 files in the union
**Investigated with:** `git merge-base`, `git diff --name-status` (per side), `git merge-tree --write-tree`, Python `ast` over all four versions (base / sprint1-2 / release / merged) of every hotspot.

---

## 0. Four premises in the brief are wrong — read this first

These corrections change what the merge actually costs. Each is backed by a command you can re-run.

### 0.1 There are **no deletions on either side**. Bucket C is empty.

```
git diff --diff-filter=D --name-only <base> sprint1-2                   -> (empty)
git diff --diff-filter=D --name-only <base> release/12-09-2026-sprint-4 -> (empty)
```

`bare_verb_clarify_state.py` and `bare_verb_config.py` were **added by sprint1-2** (`A`, not `D`) and have never existed on the release branch. `leave_type_clarify_state.py` already existed at the merge base. Nothing was deleted on either side, so there is no delete-vs-modify decision anywhere in this merge.

### 0.2 `attendance.py` did not shrink, and nothing moved into `ai_service.py`

`services/attendance.py` is **byte-identical** between the base and the release branch:

```
git rev-parse <base>:services/attendance.py release/...:services/attendance.py
  e5afff294e394032a7e7083779109c71d0b567c0
  e5afff294e394032a7e7083779109c71d0b567c0        # same blob
git log <base>..release/... -- services/attendance.py   -> (no commits)
```

Directional numstat (`<base> -> branch`):

| file | sprint1-2 | release |
|---|---|---|
| `services/ai_service.py` | +51 / −14 | +809 / −21 |
| `services/attendance.py` | **+142 / −46** | untouched |
| `services/attendance_explain.py` | **+128 / −2** | +42 / −7 |

The `+46 −142` and `+43 −134` in the brief come from `git diff sprint1-2 release/...`, which reads **sprint1-2 as the "before"**. Those files grew on sprint1-2; the minus numbers are sprint1-2's own additions seen backwards.

The `+823 −72` for `ai_service.py` is the same artifact. The real release-side `+809` is **entirely new sprint-4 LLM extractors** — `extract_shift_target_fields`, `classify_shift_intent`, `extract_individual_report_fields`, `classify_individual_report_sub_intent`, `classify_individual_report_intent`, `extract_leave_approval_fields` and their DeepSeek/OpenAI call pairs. No attendance logic moved in (grep for `attendance_explain|_resolve_date_expression|_normalize_attendance_dates` over release's `ai_service.py` additions returns nothing). **There is no dead-duplicate risk here.** sprint1-2's own `ai_service.py` change is prompt *text* only — no code.

### 0.3 Alembic has a single linear head. No merge revision is needed.

**sprint1-2 added zero migrations.** The release branch added two, chained correctly:

```
368e866132a6 -> 46e80b665382 -> c8508289bb9b -> a1b2c3d4e5f6
             -> a4670b4556a8 -> b7f2c9d1a3e4 -> d3a7f1c05b28   (single head)
```

`b7f2c9d1a3e4` (ai_action_audit_logs) has `down_revision='a4670b4556a8'`; `d3a7f1c05b28` (erp payload columns) has `down_revision='b7f2c9d1a3e4'`. The merge cannot create a second head because only one side has migrations at all. See §5 — it is a verification step, not a repair step.

### 0.4 bare-verb was **not replaced** by leave-type-clarify — they are disjoint, and both live on sprint1-2

* `bare_verb_config.py` fires on a **lone verb with no object**: `apply`, `cancel`, `regularise`, `check` (all four are in `_ACTIVE_BARE_VERBS`). It answers "What would you like to apply for?" with choices `["Leave", "Attendance regularisation"]`.
* `leave_type_clarify_state` fires on a **bare leave-type noun** ("sick leave") and asks balance / eligibility / apply / status.

Different inputs, different prompts. Neither covers the other, so "does the replacement cover every case" does not arise — but **both mechanisms must survive**, and today they live in two *different files* on the *same* branch. That is §1.2, and it is the real problem in this merge.

---

## 1. Divergence summary — what each branch was actually building

### 1.1 The branches already merged once, and the release branch then reverted much of it

`ff6768b "Merge pull request #33 from adminofgit590/sprint1-2"` is a **true merge commit whose second parent is `3f0efe7` — our merge base**. On 2026-09-04 the release branch absorbed all of sprint1-2 as it then stood. Everything since is one week of parallel work.

What happened next on the release branch is the thing to understand before resolving anything:

| commit | date | `classify_node.py` | `hr_graph.py` | what it did |
|---|---|---|---|---|
| `ff6768b` | 09-04 | — | — | real merge of sprint1-2 @ base |
| `add92ee` "fixes on merged code" | 09-04 | +205 / −0 | **+57 / −956** | stripped ~950 lines of merged-in hr_graph |
| `9995fb4` "hr graph changes from sprint 1-2-3" | 09-08 | — | **+664 / −1** | **single-parent** manual re-paste — not a merge |
| `301f96b` | 09-08 | — | — | PR #37 `review/sprint1-2-merge` |
| `bcd2fb4` **"Fix classify node"** | 09-09 | **+34 / −436** | **+1 / −348** | stripped it out again |

So sprint1-2 content has been merged in, hand-deleted, hand-re-pasted, and hand-deleted again. This is why the textual conflict count is low (4 files) while the *semantic* risk is high: the two sides are not independent features, they are **two divergent copies of the same code**.

### 1.2 The actual architectural split: two `classify_node` implementations

There are two functions named `classify_node` in this repo, and **the branches disagree about which one runs**.

```
              defines hr_graph.classify_node?   graph.add_node("classify_node", ...)   LIVE implementation
base          yes (line 576, dead)              classify_node_impl                     services/classify_node.py
sprint1-2     yes (line 776)                    classify_node   <-- local def wins     hr_graph.py  (719 lines)
release       no  (deleted)                     classify_node   <-- import             services/classify_node.py (563 lines)
```

Verified by AST (last module-level binding of the name wins in Python):

```
hr_graph.base : line 576 def classify_node          (but graph wires classify_node_impl -> module)
hr_graph.s12  : line 776 def classify_node          (graph wires classify_node -> THIS local def)
hr_graph.rel  : line 17  from services.classify_node import classify_node
```

At the base, `hr_graph`'s local copy was **dead code** — the graph wired `classify_node_impl`. sprint1-2 changed the wiring line to bare `classify_node`, which silently promoted its local fork to being the live classifier. The release branch deleted the local fork and kept the module version live.

**Consequence: `services/classify_node.py` on sprint1-2 — including its Fast-paths 0.2/0.3/0.35/0.4/0.6/0.7 — is dead code on that branch today.** Whether that was intended is Open Question Q1.

**What each side was building:**

* **sprint1-2** — conversational robustness for the *employee* flows, inside `hr_graph.classify_node`: bare-verb clarification, `last_intent` follow-up memory, `last_resolved_date_state` date carry-over, regularisation mid-flow interruption handling, a unified apply-discard predicate, deterministic date resolution across leave/attendance/punch. Plus a large amount of work in `services/classify_node.py` that is not currently reachable.
* **release/sprint-4** — *manager* surfaces, inside `services/classify_node.py` and new modules: `manager_gate_node`, shift queries, individual reports, leave approval, regularisation approval, complex-manager routing, team attendance/leave, ERP payload audit logging.

The two feature sets are **complementary, not contradictory** — but they were written into two different copies of the same function.

### 1.3 The divergence the brief asked about, located correctly

`intent="unclear", error="unclear"` vs `intent="unknown", error="flagged"` is **not two branches of one function**. It is the two *different functions*:

* `hr_graph.classify_node` (live on sprint1-2) — has an `"unclear"` low-confidence branch:
  ```python
  return {"moderation": moderation_result, "intent": "unclear", "is_hr": False, "error": "unclear",
  ```
* `services/classify_node.py::classify_node` (live on release) — **every** version of this file, on both branches and at base, uses `"unknown"/"flagged"` only. It has no `"unclear"` branch at all.

So the downstream ambiguity the brief describes is real, but it appears **only if you keep sprint1-2's local fork live**. Full enumeration of the divergence between the two live implementations (AST-extracted):

| dimension | only on sprint1-2's live `hr_graph.classify_node` | only on release's live module `classify_node` |
|---|---|---|
| intents returned | `clarify_needed`, `unclear` | `HRMS_TEAM_MEMBERS_QUERY`, `leave_policy`, `leave_type_clarify`, `manager_leave_approval`, `shift_query` |
| `error` values | `"unclear"` | — |
| state keys read | `last_intent` | `is_manager` |
| redis state modules | `bare_verb_clarify_state`, `last_resolved_date_state` | `leave_type_clarify_state` |
| Fast-path blocks | `0.5` only | `0.2, 0.3, 0.35, 0.4, 0.5, 0.6, 0.7, 1, 2` |
| size | 719 lines | 563 lines |

### 1.4 The release branch has committed, unresolved conflict markers

```
release/...:tests/test_hr_leave_query_cases.py   12 marker lines  -> SyntaxError at line 308
release/...:tests/test_leave_action.py           11 marker lines  -> SyntaxError at line 192
sprint1-2:  (none)
```

These markers came **from the merge base** (base has 12 in each file) and reference commit `9e3d35c2e9b5...`. **sprint1-2 resolved them; the release branch never did.** Both files fail `ast.parse` on base and on release — the test suite cannot collect them there today. Merging sprint1-2 *repairs* this, provided the `test_leave_action.py` conflict is resolved toward sprint1-2's marker-free text.

---

## 2. File table

83 files. Actual buckets: **A = 69, B = 4, C = 0, D = 10.**

### Bucket B — textual conflict (4 files, 11 hunks)

| path | side | hunks | resolution | risk |
|---|---|---|---|---|
| `services/hr_graph.py` | BOTH | 5 | §4.1 — **decides the whole merge** | 🔴 critical |
| `services/classify_node.py` | BOTH | 3 | §4.2 — keep both; 2 of 3 are whitespace-vs-code | 🟠 high |
| `tests/test_leave_action.py` | BOTH | 2 | §4.3 — take sprint1-2 (removes committed markers), append release's classes | 🟡 medium |
| `tests/test_nlp_service.py` | BOTH | 1 | §4.4 — keep both test classes, purely additive | 🟢 low |

### Bucket D — auto-merges but changes behaviour (10 files)

| path | side | what each side did | resolution | risk |
|---|---|---|---|---|
| `schema/agent.py` | BOTH | s12 `+regularisation_blocked`; rel `+is_manager`, `+is_manager_jwt` | keep both, **plus add `last_intent`** — §4.5 | 🔴 critical |
| `services/ai_service.py` | BOTH | s12 prompt-text only; rel +809 new extractors | keep both — §4.6 | 🟢 low |
| `services/date_resolver.py` | BOTH | s12 week-of-month / last-day / bare-weekday; rel explicit-calendar / past-weekday | keep both, **audit precedence** — §4.7 | 🟠 high |
| `services/leave_action_service.py` | BOTH | s12 +746 (cancel cards, typo tolerance, weekday anchors); rel +55 (`_names_request_artifact`) | keep both — §4.8 | 🟡 medium |
| `services/attendance_explain.py` | BOTH | s12 date carry-over + a **dead** `COMING_SOON` constant; rel LLM status reason | keep both — §4.9 | 🟡 medium |
| `services/nlp_service.py` | BOTH | s12 `is_explicit_leave_action_instruction`; rel `_RECORDED_DAY_MENTION` + team patterns | keep both — §4.10 | 🟡 medium |
| `main.py` | BOTH | s12 `last_intent` plumbing; rel cache-exclusion set + comment trim | keep both — §4.11 | 🟠 high |
| `.env.example` | BOTH | s12 `QUERY_CACHE_ENABLED`; rel `ERP_LOG_PAYLOADS`, `ERP_LOG_PAYLOAD_MAX_CHARS` | keep both — §4.12 | 🟢 low |
| `tests/test_attendance_explain.py` | BOTH | both added cases | keep both | 🟢 low |
| `tests/test_punch_details.py` | BOTH | both added cases | keep both | 🟢 low |

### Bucket C — deleted one side / modified other

**None.** See §0.1.

### Bucket A — clean auto-merge, low risk (69 files, list only)

*sprint1-2 only (30):* `dump.rdb`, `services/attendance.py`, `services/bare_verb_clarify_state.py`, `services/bare_verb_config.py`, `services/cache_service.py`, `services/chat_service.py`, `services/date_query_resolver.py`, `services/get_date_promt.py`, `services/last_resolved_date_state.py`, `services/leave_cancel_state.py`, `services/leave_disambiguation_state.py`, `services/leave_eligibility_clarify_state.py`, `services/leave_eligibility_service.py`, `services/leave_history_clarify_state.py`, `services/leave_type_clarify_state.py`, `services/punch_details.py`, `services/regularisation_node.py`, `services/regularisation_store.py`, `services/slot_flow.py`, `services/slot_store.py`, `tests/conftest.py`, `tests/test_attendance_numeric_date_regex.py`, `tests/test_bare_date_followup_routing.py`, `tests/test_date_query_resolver.py`, `tests/test_hr_leave_query_cases.py`, `tests/test_leave_eligibility.py`, `tests/test_regularisation_mid_flow_routing.py`, `tests/test_regularisation_new_request_reset.py`, `tests/test_regularisation_other_topic_interruption.py`, `tests/test_slot_flow_entry_corrections.py`

*release only (39):* `.gitignore`, `alembic/versions/b7f2c9d1a3e4_add_ai_action_audit_logs_table.py`, `alembic/versions/d3a7f1c05b28_add_payload_columns_to_erp_api_call_logs.py`, `dependencies.py`, `docs/complex-manager-task-routing-test-cases.md`, `models/ai_action_audit_log.py`, `models/erp_api_call_log.py`, `services/audit_log_service.py`, `services/complex_manager_router.py`, `services/erp_client.py`, `services/individual_report.py`, `services/leave_approval.py`, `services/leave_slot_service.py`, `services/ownership_guard.py`, `services/regularisation_approval.py`, `services/shift_query.py`, `services/team_leave_filter.py`, `tests/fixtures/intent_eval_dataset.py`, `tests/generate_full_qa_report.py`, `tests/generate_leave_approval_xlsx_report.py`, `tests/generate_qa_team_attendance_tc1_tc4_report.py`, `tests/generate_team_attendance_summary_xlsx_report.py`, `tests/test_ai_service.py`, `tests/test_complex_manager_router.py`, `tests/test_complex_manager_task.py`, `tests/test_date_resolver.py`, `tests/test_erp_call_log_payloads.py`, `tests/test_individual_report.py`, `tests/test_individual_report_named_employee.py`, `tests/test_leave_approval.py`, `tests/test_leave_approval_qa_scenarios.py`, `tests/test_ownership_guard.py`, `tests/test_regularisation_approval.py`, `tests/test_shift_query.py`, `tests/test_shift_query_self_and_code.py`, `tests/test_team_attendance_summary.py`, `tests/test_team_leave_status_filter.py`, `tests/test_team_pending_leave_acceptance.py`, `tests/verify_attendance_hierarchy_scope.py`

> `dump.rdb` is a committed Redis snapshot and a binary. It will conflict-or-clobber meaninglessly. Take either side; it is not program state you need. Consider untracking it separately (not as part of this merge).

---

## 3. Ordered merge sequence

Resolve in this order. The order matters: step 1 determines what steps 2–4 even mean.

1. **Decide the `classify_node` question first (§4.1 / Q1).** *(Settled from the repo — see §7.)* Do not touch another file until this is settled. Every other resolution in `hr_graph.py` and `classify_node.py` follows from it.
2. **`schema/agent.py` (§4.5).** State shape is upstream of every node; LangGraph filters node input by the annotated TypedDict, so a missing key silently disables a guard rather than erroring. Get the key set right before you test anything.
3. **`services/hr_graph.py` hunks 1–4** (imports, local `HRState`). Mechanical once step 1 is decided.
4. **`services/hr_graph.py` hunk 5 + `services/classify_node.py`** (the classifier bodies). The substantive work.
5. **`main.py` (§4.11)** — `last_intent` plumbing must match what the live classifier reads.
6. **Bucket-D leaf modules** — `date_resolver.py`, `nlp_service.py`, `leave_action_service.py`, `attendance_explain.py`, `ai_service.py`, `.env.example`.
7. **Test files** — `test_leave_action.py`, `test_nlp_service.py`, and the two auto-merged test files.
8. **Import-time smoke check**, then Alembic (§5), then the flow checklist (§6).

Work on a scratch branch:

```bash
git switch -c merge/sprint1-2-into-sprint-4 release/12-09-2026-sprint-4
git merge --no-commit --no-ff sprint1-2
```

`--no-commit` keeps the index open so you can inspect each stage. The pre-merge state is already preserved on `backup/release-before-sprint1-2-merge`.

---

## 4. Bucket-C and bucket-D resolutions

Bucket C is empty (§0.1). Bucket B and D follow.

### 4.1 `services/hr_graph.py` — the decisive conflict 🔴

**Hunk 5** is the whole merge in one place. The release side is **empty**; the sprint1-2 side is the entire 719-line local `classify_node`:

```
<<<<<<< release/12-09-2026-sprint-4
=======

async def classify_node(state: HRState, writer: StreamWriter) -> dict:
    query = state["query"].strip()
    ...
>>>>>>> sprint1-2
```

**The trap:** the brief's standing rule — *"where both sides added a distinct guard or branch, the default is to KEEP BOTH"* — produces a broken build here. Keeping sprint1-2's local def yields this module:

```python
line   31:  from services.classify_node import classify_node , _VALID_INTENT_LABELS   # release
line   34:  from services.classify_node import classify_node as classify_node_impl    # sprint1-2
line  900:  async def classify_node(state: HRState, writer: StreamWriter) -> dict:     # sprint1-2 — REBINDS
line 4198:  graph.add_node("classify_node", classify_node)                             # resolves to line 900
```

The local `def` at 900 shadows the import at 31. The graph then runs sprint1-2's 719-line fork, and **every sprint-4 manager feature becomes unreachable** — the fork returns none of `shift_query`, `manager_leave_approval`, `leave_type_clarify`, `leave_policy`, `HRMS_TEAM_MEMBERS_QUERY`, and never reads `is_manager`. The 10 release-only graph nodes stay wired but nothing routes to them.

**This produces no error.** `build_hr_graph` auto-merges to the correct 22-node union (verified — the merged node set is exactly `sprint1-2 ∪ release`), and the wiring line `graph.add_node("classify_node", classify_node)` does not conflict because *both* sides changed it to the same text. Only the shadowing is wrong, and Python does not complain.

**Resolution — do not pick a side. Consolidate:**

1. **Delete the local `def classify_node` from `hr_graph.py`** (drop the sprint1-2 half of hunk 5). Keep exactly one import: `from services.classify_node import classify_node, _VALID_INTENT_LABELS`.
2. **Port sprint1-2's fork-only behaviour into `services/classify_node.py`**, which becomes the single classifier. Specifically, port:
   * the bare-verb fast-path (`bare_verb_clarify_state` + `detect_bare_verb_query` / `get_clarify_prompt` / `get_clarify_choices` / `resolve_bare_verb_clarification`) and the `clarify_needed` intent that feeds `clarify_node`;
   * the `last_resolved_date_state` side-effect write at the top of the function (date carry-over for dateless follow-ups);
   * the `last_intent` follow-up override;
   * the regularisation mid-flow block and `pending_regularisation_hint`;
   * the `is_explicit_leave_action_instruction` guard at the cancel `awaiting_reason` step.
3. **Decide the `unclear` branch explicitly (Q2).** It exists only in the fork. Either port it *and* give `"unclear"` a distinct downstream rendering, or drop it and let low confidence fall through to `"unknown"`. Do not port it silently — with `error="flagged"` already meaning "guardrail blocked", a shared value makes a low-confidence query indistinguishable from a blocked one, which is the failure mode the brief describes.

**What the discarded side did:** dropping the local `def` discards *nothing functional* **provided step 2 is completed**, because the fork's behaviour is what step 2 ports. It is a code-motion decision, not a feature decision. If step 2 is skipped, you lose bare-verb clarification, `last_intent` memory, date carry-over, and the regularisation interruption guards — the whole of sprint1-2's conversational-robustness work.

**Hunks 1–4** are mechanical:

* **Hunk 1** — release commented out `# from schema.agent import HRState` and imports fewer nlp helpers. **Take sprint1-2's import list** (it adds `is_explicit_leave_action_instruction`, needed by the ported guard). Restore the real `from schema.agent import HRState` import — see §4.5.
* **Hunk 2** — take **both** import groups, minus the now-removed `classify_node_impl` alias: keep release's `from services.classify_node import classify_node, _VALID_INTENT_LABELS` **and** sprint1-2's `bare_verb_clarify_state`, `last_resolved_date_state`, `bare_verb_config` imports.
* **Hunk 3** — pure addition on both sides. **Keep both**: release's `shift_query` / `individual_report` / `leave_approval` / `regularisation_approval` / `complex_manager_router` imports **and** sprint1-2's `import services.date_query_resolver as date_query_resolver`.
* **Hunk 4** — local `HRState` keys. **Keep both**: release's `is_manager_jwt` + `is_manager`, sprint1-2's `last_intent`. See §4.5.

### 4.2 `services/classify_node.py` 🟠

Three hunks. **Two of them are whitespace-versus-code** — the release side is a stray indented blank line left behind by `bcd2fb4`'s deletion:

* **Hunk 1** — release side is `  ` (two spaces). sprint1-2 side is **Fast-path 0.35** (leave-type reply to a pending eligibility clarify) plus the header comment for Fast-path 0.4. **Take sprint1-2 entirely.**
* **Hunk 3** — release side is `      ` (six spaces). sprint1-2 side is the `awaiting_reason` / `is_explicit_leave_action_instruction` guard. **Take sprint1-2 entirely.**
* **Hunk 2** — a genuine refactor. Release keeps two narrower predicates; sprint1-2 replaces them with one:

  ```python
  # release
  is_ambiguous_cancel_during_apply = (
      interrupt_intent == "cancel_leave" and not _extract_request_id(query)
  )
  is_confirmation_decline = (
      existing_leave_slots.get("step") == "awaiting_confirmation"
      and _is_declining_or_cancelling(query)
  ```
  ```python
  # sprint1-2
  is_apply_discard_reply = (
      _is_declining_or_cancelling(query)
      and not _is_cancel_card_button(query)
      and not cancel_phrase_targets_submitted_request(query)
  ```

  **Take sprint1-2's unified predicate.** Its own comment states the case: the two release predicates disagreed at the edges — the first kept *every* `cancel_leave` hit without a reference number during apply (including "cancel my leaves", which can only mean submitted ones), while the second caught only a bare "cancel" at `awaiting_confirmation`, letting one typed mid-collection reach the LLM fallback. **This is the one place in the merge where "keep both" is wrong on the merits** — the two predicates are alternative implementations of one rule, and keeping both reintroduces the disagreement. sprint1-2's version also stays consistent with `leave_action_service.cancel_phrase_targets_submitted_request`, which is what the discard check downstream uses.

  **What release's side did that must not be lost:** `_extract_request_id` gating. Confirm `cancel_phrase_targets_submitted_request` subsumes it — i.e. that a message naming `LR-2041` still routes to `cancel_leave` and is not swallowed as a draft discard. Cover it with a test (§6).

> **CORRECTED DURING EXECUTION — the paragraph that stood here was wrong.** The plan claimed Fast-paths 0.2/0.3/0.5/0.6/0.7 were stripped by `bcd2fb4` and lost by the merge. That inference used the `# ── Fast-path N` comment banners as a proxy for the code. Stripping comments and diffing the executable lines of `services/classify_node.py` before and after `bcd2fb4` shows it removed **one line of code** (a keyword-argument change) and 436 lines of comments; net executable lines went *up* by 4. The state-module references that implement each fast-path (`leave_disambiguation_state`, `leave_history_clarify_state`, `leave_type_clarify_state`, `leave_cancel_state`, `leave_slot_service`) are present at the same counts on release as at the base. **Nothing was lost and nothing needed restoring.** The banners were simply gone. Lesson recorded: presence of a comment is not presence of a feature — verify at the AST/token level.

### 4.3 `tests/test_leave_action.py` 🟡

Hunk 2's `<<<<<<< HEAD` is **not** a merge artifact — it is a conflict marker committed at the merge base and still present on release (§1.4). **Resolve toward sprint1-2**, which removed the markers and makes the file parse, then append release's added classes (`TestLeaveActionNodePendingRequestCards`, the HEL-281 block and its `_pending_leave` / `_build_test_card` helpers). Verify with `python -m compileall` or `pytest --collect-only` that the file parses — it does not on release today.

### 4.4 `tests/test_nlp_service.py` 🟢

Purely additive on both sides: release added `TestTeamLeaveQueryDetection` (FR-07.1 team-scoped phrasing), sprint1-2 added `TestGenuineQueryMarkerRecognizesExplain`. **Keep both classes.** No shared fixtures.

### 4.5 `schema/agent.py` 🔴 — auto-merges, but incompletely

The auto-merge is correct as far as it goes: sprint1-2 adds `regularisation_blocked`, release adds `is_manager` / `is_manager_jwt`, different regions, both survive.

The risk is what the release branch documented in this very file:

> `These MUST be declared here, not only on hr_graph.HRState. LangGraph takes a node's input schema from its type annotation, and classify_node is annotated with THIS TypedDict — so the state it receives is filtered to these keys. While is_manager was missing, state.get("is_manager") is True was false on every request no matter what manager_gate_node had resolved (...) The nodes still re-check the role themselves, so nothing was ever wrongly ALLOWED by this — it silently cost the shortcuts.`

That is exactly the failure mode to avoid, and there is **one key still missing**. Current declarations:

```
schema/agent.py HRState : ... route_to blocked regularisation_blocked is_manager is_manager_jwt   (after merge)
hr_graph.py     HRState : ... route_to blocked last_intent clarify_message clarify_options is_manager is_manager_jwt
```

`last_intent`, `clarify_message` and `clarify_options` are declared **only on `hr_graph`'s local `HRState`**. That was self-consistent on sprint1-2 (its classifier lived in `hr_graph.py`, annotated with the local class). Once §4.1 moves the classifier into `services/classify_node.py` — annotated with `schema.agent.HRState` — **`state.get("last_intent")` silently returns `None` on every request** and the follow-up override dies with no error.

**Resolution:** add `last_intent: Optional[str]` to `schema/agent.py`'s `HRState`, and add `clarify_message` / `clarify_options` if the ported `clarify_needed` path reads them from state. Keep both sides' additions. Also decide Q3: whether `hr_graph.py` should keep a second local `HRState` at all, or re-import the schema one (release commented that import out — `# from schema.agent import HRState`). Two TypedDicts named `HRState` that must be kept in sync by hand is how the `is_manager` bug happened in the first place.

`StateGraph(HRState)` resolves to the *local* class in every version, so the local one is the graph's channel schema — but node input filtering uses each node's own annotation. Both must carry the union.

### 4.6 `services/ai_service.py` 🟢

Auto-merges cleanly; sides touch disjoint regions. **Keep both.** sprint1-2 contributes prompt-text rules only:

* the 3-step "reason" extraction rule (STEP 1 "is there a reason at all" → `null` for `"i want to apply leave for first week of october"`; STEP 2 strip the request wrapper; STEP 3 keep every detail of the cause);
* "a day name is a DATE, never a leave type" — `"cancel my sunday leave"` → `leave_type` `null`.

Release contributes the 6 new extractor/classifier function groups (§0.2). No interaction. The only thing to check is that sprint1-2's prompt edits landed in the *apply-leave* and *cancel-leave* prompt constants and were not accidentally duplicated into release's new prompt builders.

### 4.7 `services/date_resolver.py` 🟠

Both sides added substantial, **independent** resolvers into the same module:

* sprint1-2: `_THIS_MONTH_WEEK_PATTERN` / `resolve_week_of_this_month_phrase`, `_LAST_DAY_OF_MONTH_PATTERN` / `resolve_last_day_of_month_phrase`, `_BARE_WEEKDAY_ENDPOINT`, `_BARE_WEEKDAY_ONLY`
* release: `_MONTH_DAY_PATTERN` / `_DAY_MONTH_PATTERN` / `_ISO_DATE_PATTERN` / `resolve_explicit_calendar_date`, `_PAST_WEEKDAY_PATTERN` / `resolve_past_weekday_phrase` / `most_recent_weekday` / `_start_of_week`, `_year_for_past_tolerant`

**Keep both** — they are different phrase families. **But the composition is not automatic.** sprint1-2's `_BARE_WEEKDAY_ONLY` ("monday") and release's `resolve_past_weekday_phrase` ("last monday") overlap on weekday tokens, and `_year_for_past_tolerant` changes year inference for bare dates. Whichever resolver the dispatcher calls first wins. **Read the call order in the resolver entry point and assert it explicitly with tests** for: `"monday"`, `"last monday"`, `"next monday"`, `"last week of October"`, `"last day of this month"`, `"15th"`, `"05-03-2026"` (must be 5 March, per the prompt rule). This is the most likely place for a quiet wrong-date regression.

### 4.8 `services/leave_action_service.py` 🟡

sprint1-2 +746 / release +55, disjoint regions, auto-merges. **Keep both.** sprint1-2 adds the cancel-card button handling (`_CANCEL_CARD_BUTTON_TEXTS`, `_is_cancel_card_button`), balance-retry slots, `_next_date_on_day_of_month`, `_spoken_date`, decision-reason extraction, `_single_date_anchor` / `_bare_weekday_anchor`, status-word typo tolerance, bare-leave-type reply handling. Release adds `_REQUEST_ARTIFACT_RE` / `_names_request_artifact`. Check that `_names_request_artifact` and `cancel_phrase_targets_submitted_request` (§4.2) agree on what counts as naming a submitted request — they are two answers to the same question and are the pair most likely to drift.

### 4.9 `services/attendance_explain.py` 🟡

**Not disabled — verified.** sprint1-2 added

```python
_ATTENDANCE_EXPLAIN_COMING_SOON = "Attendance explain functionality will be available soon."
```

with a comment claiming the real implementation was renamed to `attendance_explain_node1`. **No such function exists**, and the constant is **never referenced** on sprint1-2 or in the merge result — the stub was already reverted and only the constant and a stale comment remain. `attendance_explain_node` is the real implementation on both branches.

**Keep both** sides' changes (they auto-merge: release's `_generate_status_reason_via_llm` and `_resolve_attendance_date` work, sprint1-2's `last_resolved_date_state` carry-over and `NoSuchOrdinalWeekday` handling all survive). **Delete the dead constant and the stale comment** as cleanup, and confirm release's `individual_report.attendance_explanation_node` (the manager-facing sibling) is unaffected — it is a separate node.

### 4.10 `services/nlp_service.py` 🟡

**Keep both.** sprint1-2 adds `is_explicit_leave_action_instruction` (required by §4.1 step 2 and §4.2 hunk 3); release adds `_RECORDED_DAY_MENTION` and the `_TEAM_QUERY_PATTERNS` used by `fast_classify` for team-scoped phrasing. The ordering constraint release documents — `_TEAM_QUERY_PATTERNS` must be checked **before** `_LEAVE_STATUS_PATTERNS`, or team queries get swallowed by that list's `\b(pending|...)\b...\bleaves?\b` — must survive the merge. `tests/test_nlp_service.py::TestTeamLeaveQueryDetection` guards it; run it.

### 4.11 `main.py` 🟠

**Keep both.** Two independent changes:

* **sprint1-2** adds `last_intent` plumbing: the `get_last_intent` import, `last_intent = await run_in_threadpool(get_last_intent, db, conversation_id, company_id)`, and `"last_intent": last_intent` in the initial state. **This is load-bearing for §4.1/§4.5** — without it the ported follow-up override has nothing to read.
* **release** is net-negative mostly through trimming a long comment block above the cache-exclusion set, while *adding* members to the set itself: `leave_type_clarify`, `HRMS_TEAM_LEAVE_QUERY`, `shift_query`, `manager_leave_request_lookup`, `manager_attendance_explanation`, `manager_leave_approval`, `regularisation`, `manager_regularisation_view`, `manager_regularisation_approval`, `large_team_review`, `bulk_approvals`, `shift_planning`, `comparative_reporting`.

**The cache-exclusion set is a privacy control, not a performance tuning knob** — the cache key is `company_id` + normalized query text with **no caller identity**, so an intent wrongly absent from the set can serve one employee's or manager's data to another. After merging, enumerate the final set and confirm every intent the *merged* classifier can return that is caller-scoped or state-mutating is present — including any intent sprint1-2 adds (`clarify_needed`, and `unclear` if Q2 keeps it). Do not let the comment-block deletion obscure a set-membership change; diff the set contents, not the block.

### 4.12 `.env.example` 🟢

Disjoint additions. **Keep both**: sprint1-2's `QUERY_CACHE_ENABLED=true`, release's `ERP_LOG_PAYLOADS=true` and `ERP_LOG_PAYLOAD_MAX_CHARS=32000`. Mirror all three into the deployed `.env` files — `ERP_LOG_PAYLOADS` gates PII capture and `QUERY_CACHE_ENABLED` gates the answer cache; both default meaningfully.

---

## 5. Alembic steps

There is **no head merge to perform** (§0.3). This is verification only.

```bash
alembic heads          # expect exactly ONE: d3a7f1c05b28
alembic history | head -20
alembic upgrade head   # applies b7f2c9d1a3e4 then d3a7f1c05b28 on an env at a4670b4556a8
```

* If `alembic heads` prints **one** revision — done. No merge revision, no `down_revision` edits.
* If it prints **two**, something outside this merge introduced a migration (e.g. a later cherry-pick). Only then:
  ```bash
  alembic merge -m "merge sprint1-2 into sprint-4" <head1> <head2>
  ```
  and hand-verify the generated `down_revision` tuple.

Also confirm the two release-only migrations' models come across, since they are bucket A and easy to overlook: `models/ai_action_audit_log.py` (new), `models/erp_api_call_log.py` (modified — payload columns), plus `services/audit_log_service.py`. `tests/test_erp_call_log_payloads.py` covers the payload columns; run it against a migrated DB.

---

## 6. Verification checklist

### 6.1 Gate 0 — does it even load (run before anything else)

```bash
python -c "import services.hr_graph"
python -c "from services.hr_graph import build_hr_graph; g=build_hr_graph(); print(g)"
```

Then assert the classifier identity explicitly — **this is the check that catches §4.1**:

```python
import services.hr_graph as hg, services.classify_node as cn
assert hg.classify_node is cn.classify_node, "hr_graph is shadowing the module classifier"
```

Expect **22 graph nodes** (the verified union). Confirm all present:
`attendance_explain_node, attendance_explanation_node, attendance_node, clarify_node, classify_node, complex_manager_task_node, hr_response_node, leave_action_node, leave_approval_node, leave_eligibility_node, leave_request_node, manager_gate_node, non_hr_node, ownership_guard_node, punch_details_node, regularisation_approval_node, regularisation_eligibility_node, regularisation_node, shift_query_node, team_attendance_summary_node, team_leave_query_node, team_members_node`

Two of these (`clarify_node`, `regularisation_eligibility_node`) come only from sprint1-2; ten come only from release. If any is missing, `build_hr_graph` was mis-resolved.

Then parse-check the two previously broken files:

```bash
python -m compileall -q tests/test_leave_action.py tests/test_hr_leave_query_cases.py
grep -rn '^<<<<<<<\|^>>>>>>>' --include='*.py' .    # must be empty
```

### 6.2 Gate 1 — state-shape assertions

```python
from schema.agent import HRState
from services.hr_graph import HRState as GraphState
required = {"is_manager","is_manager_jwt","regularisation_blocked","last_intent","route_to","blocked"}
assert required <= set(HRState.__annotations__), required - set(HRState.__annotations__)
assert set(HRState.__annotations__) <= set(GraphState.__annotations__)
```

### 6.3 Gate 2 — existing tests

Run the full suite, but these are the ones that actually discriminate:

| area | tests that exist | what they guard |
|---|---|---|
| apply-leave slot filling | `tests/test_leave_action.py`, `tests/test_slot_flow_entry_corrections.py` (s12) | Fast-path 0.5, slot state |
| regularisation | `tests/test_regularisation_mid_flow_routing.py`, `test_regularisation_new_request_reset.py`, `test_regularisation_other_topic_interruption.py` (s12) | mid-flow interruption; **these fail loudly if the §4.1 port is incomplete** |
| regularisation approval | `tests/test_regularisation_approval.py` (rel) | manager approve path |
| leave-type clarify | `tests/test_leave_eligibility.py` (s12), `tests/test_hr_leave_query_cases.py` (s12) | Fast-paths 0.35 / 0.4 / 0.7 |
| manager routing | `tests/test_complex_manager_router.py`, `test_complex_manager_task.py`, `test_ownership_guard.py`, `test_team_leave_status_filter.py`, `test_team_pending_leave_acceptance.py` (rel) | `is_manager` gating |
| approval | `tests/test_leave_approval.py`, `test_leave_approval_qa_scenarios.py` (rel) | approve/reject |
| attendance / punch | `tests/test_attendance_explain.py`, `test_punch_details.py` (both), `test_attendance_numeric_date_regex.py`, `test_bare_date_followup_routing.py` (s12) | date carry-over |
| dates | `tests/test_date_resolver.py` (rel), `test_date_query_resolver.py` (s12) | §4.7 precedence |
| intent routing | `tests/fixtures/intent_eval_dataset.py` (rel) | regression corpus |
| shift / report | `test_shift_query*.py`, `test_individual_report*.py` (rel) | sprint-4 surfaces |

**Note the asymmetry:** sprint1-2's regularisation/date tests and release's manager/approval tests are each the *only* guard on their side's work. Both sets must pass together — that is the merge's actual acceptance criterion.

### 6.4 Gate 3 — manual flows (the brief's list)

1. **Apply-leave slot filling** — "apply leave" → type → dates → reason → confirm. Check the reason is stored verbatim (§4.6 STEP 3), and that `"i want to apply leave for first week of october"` yields `reason=null`, not an echoed reason.
2. **Mid-flow interruption** — start apply-leave, then ask "what is the salary range for AI engineer" mid-flow. Must answer the question and resume, not swallow it as slot input (Fast-path 0.5).
3. **Regularisation** — start it, interrupt with another topic, return. Then a new request mid-flow (reset). Then a non-regularisable date → `regularisation_blocked` must end the turn, not fall into `regularisation_node`.
4. **Cancel-leave** — "cancel" during an open draft must discard the draft; "cancel my leaves" and "cancel LR-2041" must target submitted requests (§4.2 hunk 2). At `awaiting_reason`, "hi" must be accepted as a reason, while "apply new leave" must abandon the cancel (§4.2 hunk 3).
5. **Leave-type clarify** — bare "sick leave" → the clarify card, then "balance" resolves. Bare "apply" → bare-verb card with Leave / Attendance regularisation. **Both must work** (§0.4).
6. **Manager approval routing** — as a manager: pending list, approve, reject. As a non-manager: refusal. Then with erp-api unreachable (`MANAGER_UNKNOWN`) — must not wrongly allow.
7. **Attendance / punch** — "explain my attendance for 5th"; a bare date query followed by "yes, give me punch details" (date carry-over must work, not default to today); `"5th Wednesday"` in a month with four.
8. **Cross-cutting** — a low-confidence query must be visibly distinguishable from a guardrail block (Q2).

### 6.5 Gaps needing new tests

* **No test asserts which `classify_node` is live.** Add the `hg.classify_node is cn.classify_node` assertion from §6.1 as a permanent test — this merge's single highest-risk failure has no guard today. *(Still open after the merge — checked manually at Gate 0 only.)*
* **No test asserts the Fast-path set is present.** Add one that reads `services/classify_node.py` source and asserts markers `0.2, 0.3, 0.35, 0.4, 0.5, 0.6, 0.7` all appear (crude, but it would have caught `bcd2fb4`).
* **No test asserts the graph node set.** Add an assertion on the 22-node union.
* **No test covers date-resolver precedence** between sprint1-2's and release's overlapping weekday resolvers (§4.7).
* **No test covers cache-exclusion set membership** (§4.11) — add one asserting every caller-scoped/state-mutating intent the classifier can return is in the set.
* **`bare_verb_config.py` and `bare_verb_clarify_state.py` arrive with no tests at all** — all four verbs (`apply`, `cancel`, `regularise`, `check`) are in `_ACTIVE_BARE_VERBS` and untested.

---

## 7. Open questions — resolved

Five of the seven were answered from the repository itself during execution (recorded below so the reasoning is auditable); Q2 was decided by the owner; Q7 remains a deployment action.

**Q1 — Which `classify_node` is canonical?** → **`services/classify_node.py`. Answered by the repo.** Two independent pieces of evidence: (a) `review/sprint1-2-merge` (= `9995fb4`, an ancestor of release) had the fork **live** at its line 3521, and `bcd2fb4 "Fix classify node"` is its direct child and deleted it — that commit *is* the deliberate repair of the shadowing; (b) release's own QA report (`tests/generate_full_qa_report.py`, finding D-04, High, FIXED) documents wiring Fast-path 0.8 into `services/classify_node.py` — the team was actively developing the module as the live classifier. Consolidated on the module as §4.1 recommended; the four fork-only behaviours were ported.

**Q2 — Keep the `"unclear"` intent?** → **Yes, decided by the owner.** The `classification_failed` path now returns `intent="unclear", error="unclear"`; the two guardrail paths keep `"unknown"/"flagged"`. Verified safe before changing: `_route_after_classify` ends the turn on *any* truthy `error`, so routing is identical; nothing branches on `intent == "unknown"`; the `intent` column is an unconstrained `String`; `unclear` is in neither `_DATE_REFINABLE_INTENTS` nor `_STATEFUL_QUERY_INTENTS`. The SSE stream already distinguished the two (`guardrail` vs `error` event) — this closes the gap on the *recorded* side (`hr_query_log`, `get_last_intent`, logs). One pinned test (`test_unrecognized_llm_label_falls_back_safely`) updated; `TestRefusalIsDistinguishableFromIncomprehension` added as the regression guard.

**Q3 — One `HRState` or two?** → **Two, kept in sync — consolidation deferred.** Collapsing them touches every node annotation and is out of merge scope. Both now carry the full 22-key union, and Gate 1 (§6.2) asserts `schema ⊆ graph`. Recommended follow-up: a single source of truth, precisely because this hand-sync is how the `is_manager` bug happened and how `regularisation_blocked` was found missing from the graph class during this merge (§8).

**Q4 — `bcd2fb4` deliberate or a mis-resolution?** → **Deliberate and correct.** It removed the shadowing fork from `hr_graph.py` (−348) and *comments only* from `services/classify_node.py` (see the correction in §4.2). It did not remove fast-path logic, so there was nothing to restore and no rollback to worry about reintroducing.

**Q5 — Is `review/sprint1-2-merge` the reference resolution?** → **No — it is the broken intermediate state.** It equals `9995fb4`, the single-parent manual paste that made the fork live, and `bcd2fb4` was the fix for it. Useful as evidence for Q1, not as a template.

**Q6 — `dump.rdb`.** Auto-merged without conflict this time (only sprint1-2 changed it). Still recommend untracking it separately; left as-is in this merge.

**Q7 — Deployment ordering.** *Still open — operational, not code.* `alembic upgrade head` (to `d3a7f1c05b28`) must run before the merged code serves traffic, and `ERP_LOG_PAYLOADS` / `ERP_LOG_PAYLOAD_MAX_CHARS` / `QUERY_CACHE_ENABLED` must be set in each target environment.

---

## 8. As applied — what changed between plan and execution

**Merge:** `87e7a04`, parents `62b9777` (release) and `dcfd47a` (sprint1-2), on `release/12-09-2026-sprint-4`, pushed to origin.

**Conflicts (4 files, 11 hunks) — resolved as planned:**
- `hr_graph.py` — fork dropped (hunk 5, 723 lines); imports/HRState keys kept from both sides. Confirmed by AST that the only remaining binding of `classify_node` is the import.
- `classify_node.py` — sprint1-2 taken in all three hunks. Hunk 2 was confirmed mechanically: the merged surrounding code already referenced `is_apply_discard_reply`, so release's two predicates would have been undefined names.
- `test_leave_action.py` — the three "release-only" tests were the *discarded half* of the base's committed conflict; sprint1-2's resolution (`test_manager_gets_the_same_flow_as_an_employee`, `test_manager_sees_own_pending_requests_not_blocked`) was already present. Nothing lost.
- `test_nlp_service.py` — both classes kept.

**Ported from the fork into `services/classify_node.py`:** bare-verb clarification (resolve as Fast-path 0.45, detect as 0.9 immediately before the LLM call), `last_intent` override plus `_is_bare_date_fragment` and `_DATE_REFINABLE_INTENTS` (spelled literally to avoid an import cycle), `last_resolved_date_state` carry-over, and a local `_today_in_app_timezone` (fourth copy in `services/` — flagged, not consolidated).

**Bugs found and fixed beyond the plan:**
1. `regularisation_blocked` was declared on `schema.agent.HRState` but **not** on `hr_graph.HRState` — the class `StateGraph()` is built with — so it was never a channel and `_route_after_regularisation_eligibility` could never see it. Same silent failure as `is_manager`. Added.
2. `clarify_needed` writes `bare_verb_clarify_state` before answering but was absent from `main.py`'s `_STATEFUL_QUERY_INTENTS`; a cache replay would have shown the card while recording nothing. Added (set is now 24 entries).

**Also:** removed the dead `_ATTENDANCE_EXPLAIN_COMING_SOON` constant and its comment describing a nonexistent `attendance_explain_node1` (§4.9).

**Verification actually performed:** all 142 tracked `.py` files parse (the two that were broken on release now parse); `hr_graph.classify_node is services.classify_node.classify_node` → True; 22 graph nodes = exact union; `schema ⊆ graph` state keys; Alembic single head `d3a7f1c05b28`; `test_nlp_service.py` 151 passed; `test_regularisation_mid_flow_routing.py` 9 passed; `test_regularisation_other_topic_interruption.py` 5 passed; `test_moderation_override.py` 9 passed (6 existing + 3 new).

**Verification NOT performed:** the full suite. Many tests make live LLM/erp-api calls (`ACTIVE_LLM_PROVIDER=openai`, 10s read timeouts) and the execution environment had no egress. `test_slot_flow_entry_corrections.py` fails 4 tests here — but fails **identically** (same lines, same 100.75s) in a clean `sprint1-2` worktree, so it is environmental and pre-existing. **A networked `pytest tests/` run is still owed before this is treated as fully verified.**

**§6.5 gaps — status:** distinguishability guard added (`TestRefusalIsDistinguishableFromIncomprehension`). Still unwritten: the classifier-identity assertion as a permanent test, the 22-node graph assertion, date-resolver precedence tests, cache-set membership test, and any tests for `bare_verb_config.py` / `bare_verb_clarify_state.py`.

---

## Appendix — commands used

```bash
git merge-base sprint1-2 release/12-09-2026-sprint-4
git rev-list --left-right --count sprint1-2...release/12-09-2026-sprint-4
git log --oneline <base>..sprint1-2
git log --oneline <base>..release/12-09-2026-sprint-4
git diff --name-status <base> sprint1-2
git diff --name-status <base> release/12-09-2026-sprint-4
git diff --diff-filter=D --name-only <base> <each side>
git merge-tree --write-tree --name-only release/12-09-2026-sprint-4 sprint1-2
git log --oneline --numstat <base>..release/... -- services/classify_node.py services/hr_graph.py
git grep -n -E '^(<<<<<<<|>>>>>>>)' <each ref> -- '*.py'
# plus Python `ast` over base/sprint1-2/release/merged copies of hr_graph.py and classify_node.py
# to enumerate module-level bindings, HRState keys, graph node sets, and def-level gains/losses
```

The plan phase ran no merge and modified no file other than this document. The execution phase is recorded in §8.
