diff --git a/docs/superpowers/plans/2026-11-30-application-status-model-phase1.md b/docs/superpowers/plans/2026-11-30-application-status-model-phase1.md new file mode 100644 index 00000000..4db61b86 --- /dev/null +++ b/docs/superpowers/plans/2026-11-30-application-status-model-phase1.md @@ -0,0 +1,120 @@ +# Application Status Model — Phase 1 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Stop the nightly scheduler from corrupting outcomes, add the approved stage/outcome/waitingOn model alongside the legacy `status` (expand + dual-write), and migrate every record whose mapping is deterministic, flagging the rest `NEEDS_REVIEW`. + +**Architecture:** Legacy `status` stays the write contract (API, MCP, frontend unchanged). A pure `LegacyStatusMapper` derives `stage`/`outcome`/`waitingOn`/`statusMigration` from the legacy fields; `ApplicationService` and the scheduler call it on every status change (dual-write), and a startup backfill runs it once over rows not yet mapped. One rule set, unit-tested, no SQL duplicate. + +**Tech Stack:** Spring Boot 4, JPA/Hibernate, Flyway (PostgreSQL only — `db/migration/postgresql`), JUnit 5 + Mockito. + +**Spec:** `docs/superpowers/specs/2026-11-30-application-status-model-rfc.md` + +## Global Constraints + +- Never overwrite or delete `status`, `previous_status`, interview fields or `archived` during migration; `legacy_status` is an exact copy of `status`. +- Never invent dates, activities, `waiting_since` or an outcome that the legacy data does not state. +- Ambiguous legacy values map to `statusMigration = NEEDS_REVIEW` with `stage`/`outcome`/`waitingOn` null. +- Stable keys: stages `DRAFT, APPLIED, RECRUITER_SCREEN, HIRING_MANAGER, ASSESSMENT, INTERVIEW, OFFER`; outcomes `HIRED, REJECTED, ROLE_CANCELLED, WITHDREW`; waitingOn `COMPANY, CANDIDATE`; migration `MAPPED, NEEDS_REVIEW`. +- Flyway migrations go only in `src/main/resources/db/migration/postgresql/` (prod/dev locations); next version is `V40`. + +## Review Focus + +- Case/whitespace variants of legacy values (`rejected`, ` RH `) — expected to map like the canonical value. Test in Task 2. +- `Ghosting` whose `previous_status` is itself `Ghosting` or unknown text — expected `NEEDS_REVIEW`, no loop. Test in Task 2. +- Archived rows older than a month — expected untouched by the scheduler. Test in Task 3. +- Backfill rerun on restart — expected zero writes the second time. Test in Task 4. +- API clients that ignore the new response fields — expected no breaking change (fields are additive, `NON_NULL`). Covered by Task 5 mapper test. + +--- + +### Task 1: Model enums + schema expand + +**Files:** +- Create: `src/main/java/com/jobtracker/entity/enums/ApplicationStage.java`, `ApplicationOutcome.java`, `WaitingOn.java`, `StatusMigrationState.java` +- Create: `src/main/resources/db/migration/postgresql/V40__add_application_stage_outcome.sql` +- Modify: `src/main/java/com/jobtracker/entity/JobApplication.java` (fields + getters/setters) +- Keep: `entity/enums/ApplicationStatus.java` — since #119 the assistant query repository uses it for status aliases. + +**Interfaces — Produces:** `JobApplication#get/setStage(ApplicationStage)`, `get/setOutcome(ApplicationOutcome)`, `get/setWaitingOn(WaitingOn)`, `get/setLegacyStatus(String)`, `get/setStatusMigration(StatusMigrationState)`; all `@Enumerated(STRING)`, nullable. + +- [ ] Migration adds nullable `stage VARCHAR(32)`, `outcome VARCHAR(32)`, `waiting_on VARCHAR(16)`, `legacy_status VARCHAR(100)`, `status_migration VARCHAR(16)` plus `CREATE INDEX idx_app_status_migration ON job_applications (status_migration)`. No data changes in SQL. +- [ ] `mvn -q -DskipTests compile` passes. Commit. + +### Task 2: `LegacyStatusMapper` + +**Files:** Create `src/main/java/com/jobtracker/service/status/LegacyStatusMapper.java`, `StatusMapping.java`; Test `src/test/java/com/jobtracker/unit/status/LegacyStatusMapperTest.java` + +**Interfaces — Produces:** +- `record StatusMapping(ApplicationStage stage, ApplicationOutcome outcome, WaitingOn waitingOn, StatusMigrationState state, String rule)` +- `static StatusMapping LegacyStatusMapper.map(String status, String previousStatus, boolean toSendLater, LocalDate applicationDate)` +- `static void LegacyStatusMapper.apply(JobApplication app)` — sets the five new fields (`legacyStatus = status`). + +Rules (lookup by trimmed, case-insensitive value; aliases = V29 label, enum display name, enum constant name): + +| Legacy | Result | +|---|---| +| null + `toSendLater` + no date | `DRAFT` MAPPED | +| null otherwise | NEEDS_REVIEW | +| `RH` with date | `APPLIED` | +| `RH` without date | NEEDS_REVIEW | +| `Pending HR Response`, `RH (Negociação)`/`RH_NEGOCIACAO`, `Tarde demais`/`TARDE_DEMAIS`, `Approved`, unknown | NEEDS_REVIEW | +| `Pending Hiring Manager Response`, `FIZ_A_HIRING_MANAGER_AGUARDANDO_ATUALIZACAO` + label | `HIRING_MANAGER` + `COMPANY` | +| `FIZ_A_RH_AGUARDANDO_ATUALIZACAO` + label | `RECRUITER_SCREEN` + `COMPANY` | +| `Technical Test`, `TESTE_TECNICO`, `Teste Técnico` | `ASSESSMENT` | +| `Pending Technical Test Response`, `FIZ_TESTE_TECNICO_AGUARDANDO_ATUALIZACAO` + label | `ASSESSMENT` + `COMPANY` | +| `ENTREVISTA_MARCADA`, `Entrevista marcada` | `INTERVIEW` | +| `Offer Negotiation` | `OFFER` | +| Rejected family (`Rejected`, `REJEITADO`, `Rejeitado`), no date, no previous | `DRAFT` (scheduler-expired draft signature; API forbids status without date) | +| Rejected family, previous maps to a non-terminal stage | that stage + `REJECTED` | +| Rejected family otherwise (has date) | `APPLIED` + `REJECTED` (last stage proven by the date) | +| Ghosting family, previous in Rejected family, has date | `APPLIED` + `REJECTED` | +| Ghosting family, previous maps to a non-terminal MAPPED stage | that stage + `COMPANY`, no outcome | +| Ghosting family otherwise | NEEDS_REVIEW | + +- [ ] Write parameterized tests covering every row above plus the Review Focus cases (`" rejected "`, Ghosting→Ghosting). Run `mvn -q test -Dtest=LegacyStatusMapperTest` → FAIL (class missing). +- [ ] Implement; rerun → PASS. Commit. + +### Task 3: Scheduler hotfix + dual-write there + +**Files:** Modify `tasks/StaleApplicationsScheduler.java`, `repository/ApplicationRepository.java`; Test `unit/StaleApplicationsSchedulerTest.java` + +**Interfaces — Consumes:** `LegacyStatusMapper.apply`. +**Produces:** `ApplicationRepository#findStaleActiveApplications(Collection excludedStatuses, LocalDateTime updatedBefore)` — JPQL: `status IS NOT NULL AND status NOT IN :excluded AND archived = false AND updatedAt < :before`. + +- [ ] Tests: drafts older than a week are not touched (`findByStatusIsNullAndUpdatedAtBefore` never called); terminal set passed to the query contains every Rejected/Ghosting/Approved/Tarde demais alias; a stale `Technical Test` becomes `Ghosting` with `previousStatus=Technical Test`, `stage=ASSESSMENT`, `waitingOn=COMPANY`. +- [ ] Remove the draft→Rejected branch; replace the ghosting query; call `LegacyStatusMapper.apply` after setting `Ghosting`. Drop the now-unused repository methods. Tests PASS. Commit. + +### Task 4: Startup backfill + +**Files:** Create `service/status/LegacyStatusBackfill.java`; Modify `ApplicationRepository` (`findTop500ByStatusMigrationIsNull()` + `countByStatusMigrationIsNull()`); Test `unit/status/LegacyStatusBackfillTest.java` + +- [ ] `@EventListener(ApplicationReadyEvent.class) @Transactional public int run()` loops batches of 500 from `findTop500ByStatusMigrationIsNull`, applies the mapper, `saveAll`, logs counts per state; returns rows migrated. Rows are selected by `status_migration IS NULL`, so a second run writes nothing. Must not change `updatedAt` semantics for ghosting: set `updatedAt` back to its previous value before save is not possible with `@PreUpdate`, so use a bulk JPQL `UPDATE` per row instead of entity save (`ApplicationRepository#applyStatusMapping(UUID id, stage, outcome, waitingOn, legacyStatus, migration)` with `@Modifying`), leaving `updated_at` untouched. +- [ ] Tests: two batches then empty → returns total and calls `applyStatusMapping` once per row; second invocation with empty page writes nothing. PASS. Commit. + +### Task 5: Dual-write in `ApplicationService` + API exposure + +**Files:** Modify `service/ApplicationService.java` (`applyStatusChange` end → `LegacyStatusMapper.apply(app)`; also after `mapRequestToEntity`/patch date changes since `RH` depends on the date), `dto/application/ApplicationResponse.java` (append `String stage, String outcome, String waitingOn, String statusMigration`), `mapper/ApplicationMapper.java`, positional constructors in `ApplicationServiceTest`, `McpAnalyticsToolsTest`, `McpApplicationToolsTest`. + +- [ ] Tests in `ApplicationServiceTest`: create with `RH` + date → entity `stage=APPLIED`, `statusMigration=MAPPED`, `legacyStatus=RH`; updateStatus to `Rejected` from `Technical Test` → `stage=ASSESSMENT`, `outcome=REJECTED`; patch status null → `DRAFT`. +- [ ] Implement; `mvn -q test -Dtest='ApplicationServiceTest,Mcp*Test'` PASS. Commit. + +### Task 6: Contract hygiene (MCP + Swagger) + +**Files:** `dto/application/ApplicationRequest.java`, `UpdateStatusRequest.java` (allowableValues = the nine V29 names + `TO_SEND_LATER`), `mcp/McpPromptsConfig.java`, `mcp/resources/McpApplicationCreationRulesResource.java`, `mcp/resources/McpApplicationStatusesResource.java` (bump `LAST_MODIFIED`, add one-line meaning per status). + +Single rule everywhere: *`RH` = application sent (manual or automatic), no human recruiter contact implied. Omit status only for drafts not yet sent. Never use `Pending HR Response` unless a human recruiter actually replied.* + +- [ ] Update tests asserting these strings (`McpApplicationCreationRulesResourceTest`, `McpPromptsConfigTest`); PASS. Commit. + +### Task 7: n8n workflow `Candidaturas enviadas → Applywell` + +- [ ] Replace "call List-Statuses once and use a valid status from its result" with: `status` must be exactly `"RH"`; remove `List-Statuses` from the tool list. Validate, publish, re-read to confirm. + +### Task 8: Verification + +- [ ] `mvn -B -ntp verify` locally for unit tests (integration tests need Docker → CI). Push, watch CI. + +## Out of scope (needs brainstorm) + +Frontend consumption of `stage`/`outcome`, a `NEEDS_REVIEW` review UI, new MCP tools (`Set-Application-Stage`, `Close-Application`), metrics/dashboard/gamification on the new model, activities table, computed ghosting indicator, contract phase. diff --git a/docs/superpowers/plans/2026-12-01-stage-outcome-cutover-backend.md b/docs/superpowers/plans/2026-12-01-stage-outcome-cutover-backend.md new file mode 100644 index 00000000..fc721074 --- /dev/null +++ b/docs/superpowers/plans/2026-12-01-stage-outcome-cutover-backend.md @@ -0,0 +1,115 @@ +# Stage/Outcome Cutover — Backend Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make stage/outcome/waitingOn the read and write model for every backend consumer (REST, MCP, assistant, dashboard, metrics, gamification, export), with best-effort conversion of legacy statuses and calculated ghosting. + +**Architecture:** A pure `LegacyStatusMapper` converts legacy values; a `StageResolver` decides the stage of every content write (explicit stage → convertible legacy status → keep current, failing on unconverted records); `GhostingPolicy` is the single ghosting rule used by responses, dashboard, analytics and gamification. Legacy `status` stays accepted on input during the transition so the current frontend keeps working. + +**Tech Stack:** Spring Boot 4, JPA/Hibernate, Flyway (PostgreSQL), Spring AI MCP annotations, JUnit 5 + Mockito. + +**Spec:** `docs/superpowers/specs/2026-12-01-application-status-cutover-design.md` (conversion table §3, write rules §6, ghosting §5) + +## Global Constraints + +- Keys: stages `DRAFT, APPLIED, RECRUITER_SCREEN, HIRING_MANAGER, ASSESSMENT, INTERVIEW, OFFER`; outcomes `HIRED, REJECTED, ROLE_CANCELLED, WITHDREW`; waitingOn `COMPANY, CANDIDATE`. +- "Progress" stages (interview metrics, gamification): `RECRUITER_SCREEN, HIRING_MANAGER, ASSESSMENT, INTERVIEW, OFFER`. +- Unconverted ⇔ `stage IS NULL AND legacy_status IS NOT NULL`; never attempted ⇔ `legacy_status IS NULL AND stage IS NULL`. +- Consistency: outcome requires stage; DRAFT allows only `WITHDREW`; `HIRED` requires `OFFER`; waitingOn is stored null when outcome is set or stage is DRAFT; stage ≠ DRAFT requires `applicationDate`; DRAFT clears `applicationDate` and sets `to_send_later=true`. +- Ghosting: `stage != null && stage != DRAFT && outcome == null && waitingOn != CANDIDATE && !archived && updatedAt < now - app.applications.ghosting-after-days (default 30)`. Never persisted. +- `status` column: **transition rule (deviation from spec §4, for the old frontend)** — a write that arrives as a legacy status stores that value in `status`; a write that arrives as `stage` stores `status = null`. No business logic reads `status`. +- API error messages in English, as today. MCP copy in English. +- Migrations only in `src/main/resources/db/migration/postgresql/`. V40 is unreleased: rewrite it in place. +- Local checks: `mvn -B -ntp -q test -Dtest='com.jobtracker.unit.**.*Test' -Dsurefire.failIfNoSpecifiedTests=false` (ITs need Docker → CI). + +## Review Focus + +- Archive/restore/mark-DM/reminder/delete on an **unconverted** record — must succeed without a stage. Test in Task 2. +- PATCH that only changes `applicationDate` to null on an open (non-DRAFT) record — must 400, not silently turn it into a draft. Test in Task 2. +- Legacy `status: "TO_SEND_LATER"` or blank from the current frontend — must map to DRAFT. Test in Task 2. +- Dashboard totals with unconverted records — they count in `totalApplications` and in no stage/outcome bucket. Test in Task 4. +- Ghosting boundary at exactly 30 days and on archived records. Test in Task 3. + +--- + +### Task 1: Converter rules + schema/backfill rework + +**Files:** Modify `entity/enums/ApplicationStage.java` (add `boolean isProgress()`), `service/status/LegacyStatusMapper.java`, `service/status/StatusMapping.java` → replace with `service/status/StageState.java`, `service/status/LegacyStatusBackfill.java`, `entity/JobApplication.java` (drop `statusMigration`; add `void applyStage(StageState s)`), `repository/ApplicationRepository.java`, `postgresql/V40__add_application_stage_outcome.sql` (drop `status_migration` + its index); Delete `entity/enums/StatusMigrationState.java`; Tests `unit/status/LegacyStatusMapperTest.java`, `unit/status/LegacyStatusBackfillTest.java`. + +**Interfaces — Produces:** +- `record StageState(ApplicationStage stage, ApplicationOutcome outcome, WaitingOn waitingOn)` with `StageState normalized()` (applies waitingOn-null rule) and `void validate()` (throws `BadRequestException` per Global Constraints). +- `static Optional LegacyStatusMapper.map(String status, String previousStatus, boolean toSendLater, LocalDate applicationDate)` — empty = not converted. Blank or `TO_SEND_LATER` status is treated like null. +- `JobApplication#applyStage(StageState)` sets stage/outcome/waitingOn, `toSendLater = stage == DRAFT`, clears `applicationDate` on DRAFT. +- `ApplicationRepository#findTop500ByLegacyStatusIsNullAndStageIsNullOrderByIdAsc()`; `applyStatusMapping(UUID id, ApplicationStage, ApplicationOutcome, WaitingOn, String legacyStatus)` (bulk, `WHERE legacy_status IS NULL AND stage IS NULL`). For rows that do not convert, it still writes `legacyStatus` so they are not retried. + +- [ ] Rewrite mapper tests to the spec §3 table, one case per row, including: `Pending HR Response`→RECRUITER_SCREEN+COMPANY; `RH (Negociação)`→OFFER; `Approved`→OFFER+HIRED; `Tarde demais` with date→APPLIED+WITHDREW, without→DRAFT+WITHDREW; Ghosting over `Approved`→OFFER+HIRED; Ghosting over `Tarde demais`→APPLIED+WITHDREW; Ghosting without previous + date→APPLIED+COMPANY; Ghosting without date→empty; `RH` without date→empty; `"garbage"`→empty; `" rejected "`→APPLIED+REJECTED. Backfill test: unconverted row is written with null stage and its legacy value; second run reads nothing. +- [ ] Run → FAIL. Implement. Run → PASS. Commit `refactor(status): best-effort conversion, drop NEEDS_REVIEW`. + +### Task 2: Stage resolution on writes + +**Files:** Create `service/status/StageResolver.java`, `service/status/StageInput.java`; Modify `dto/application/ApplicationRequest.java`, `ApplicationPatchRequest.java` (+ `hasStage()`, etc.), `service/ApplicationService.java`, `controller/ApplicationController.java`; Create `dto/application/UpdateStageRequest.java`; Test `unit/status/StageResolverTest.java`, `unit/ApplicationServiceTest.java`. + +**Interfaces:** +- Consumes: `StageState`, `LegacyStatusMapper.map`, `JobApplication#applyStage`. +- Produces: `record StageInput(boolean stageProvided, ApplicationStage stage, ApplicationOutcome outcome, WaitingOn waitingOn, boolean legacyProvided, String legacyStatus)`; `static StageState StageResolver.resolve(JobApplication current, StageInput input, LocalDate effectiveApplicationDate)` — rules spec §6 1-3; unconverted + nothing provided → `BadRequestException("This application still uses a legacy status; provide a stage")`; unconvertible legacy → `BadRequestException("Status '' cannot be converted; provide a stage")`. +- `ApplicationService#updateStage(UUID id, UpdateStageRequest)`; `PATCH /api/v1/applications/{id}/stage`. `updateStatus` keeps working through the resolver. +- Request fields `stage`, `outcome`, `waitingOn` (enum-typed, Jackson rejects unknown keys with 400). `status` stays, documented as legacy. +- `status` column per the transition rule in Global Constraints. + +- [ ] Tests (`StageResolverTest`): explicit stage wins over legacy; convertible legacy used; unconvertible legacy → 400; nothing provided keeps current; nothing provided on unconverted → 400; `TO_SEND_LATER` → DRAFT; HIRED with ASSESSMENT → 400; outcome on DRAFT other than WITHDREW → 400. +- [ ] Tests (`ApplicationServiceTest`): create with `stage=APPLIED` + date → `status` null, `toSendLater` false; create with legacy `RH` → stage APPLIED and `status` "RH"; patch note-only on unconverted → 400; `archive`, `markDmSent`, `updateReminder` on unconverted succeed; patch `applicationDate=null` on APPLIED → 400; `updateStage(DRAFT)` clears the date. +- [ ] Run → FAIL. Implement; delete the old `applyStatusChange`/`previous_status` bookkeeping (resolver replaces it; `previous_status` is no longer written). Run → PASS. Commit. + +### Task 3: Ghosting policy, scheduler removal, response shape + +**Files:** Create `service/status/GhostingPolicy.java`; Delete `tasks/StaleApplicationsScheduler.java` + its test; Modify `application.yml` (`app.applications.ghosting-after-days: 30`), `dto/application/ApplicationResponse.java`, `mapper/ApplicationMapper.java` (now a bean that gets `GhostingPolicy`), `repository/ApplicationRepository.java`; Test `unit/status/GhostingPolicyTest.java`. + +**Interfaces — Produces:** +- `GhostingPolicy#isGhosting(JobApplication app)`, `GhostingPolicy#cutoff(): LocalDateTime` (uses an injected `Clock`). +- `ApplicationRepository#countGhosting(UUID userId, LocalDateTime cutoff)` and a reusable `ApplicationSpecifications.ghosting(LocalDateTime cutoff)` — the same predicate as `isGhosting`, archived excluded. +- `ApplicationResponse`: replace `statusMigration` with `String legacyStatus` (non-null only when unconverted) and `boolean ghosting`; keep `stage`, `outcome`, `waitingOn`, `status`. + +- [ ] Tests: each false term flips the result (DRAFT, outcome set, CANDIDATE, archived, null stage); `updatedAt` 29 days → false, 31 → true; waitingOn null → counts. +- [ ] Implement; PASS; commit. + +### Task 4: Dashboard, interview metrics, gamification + +**Files:** Modify `service/DashboardService.java`, `service/InterviewMetricsService.java`, `service/GamificationService.java`, `repository/ApplicationRepository.java`; Tests `unit/DashboardServiceTest.java` (create if absent), `InterviewMetricsServiceTest`, `GamificationServiceTest`. + +**Interfaces:** +- `InterviewMetricsService#recordStageTransition(JobApplication app, ApplicationStage from, ApplicationStage to)` — records when `to.isProgress() && (from == null || !from.isProgress())`; `old_status/new_status` get the stage names. +- `GamificationService#onApplicationUpdated(JobApplication, ApplicationStage previousStage, boolean previousInterviewScheduled, String previousNote)` and `onApplicationStageUpdated(JobApplication, ApplicationStage previousStage)`; interview progress = entering a progress stage; OFFER_WON = entering OFFER; GHOSTBUSTER = any `GhostingPolicy#isGhosting`. +- Dashboard: `toSendLater` = stage DRAFT; `waitingResponses` = open, stage ∉ {null, DRAFT}, waitingOn ≠ CANDIDATE, not archived; `rejectedCount` = outcome REJECTED; `ghostingCount` = `countGhosting`. + +- [ ] Tests: fixture with one of each (DRAFT, APPLIED waiting, ASSESSMENT waiting CANDIDATE, REJECTED, ROLE_CANCELLED, stale APPLIED, unconverted) → expected counts (`rejectedCount` 1, ghosting 1, toSendLater 1, total 7). Entering RECRUITER_SCREEN from APPLIED records one event; ASSESSMENT→INTERVIEW records none. +- [ ] Implement; remove the legacy string sets; PASS; commit. + +### Task 5: Filters, specifications, export + +**Files:** `dto/application/ApplicationFilter.java`, `dto/export/ExportFilters.java`, `repository/ApplicationSpecifications.java`, `controller/ApplicationController.java` (query params `stage`, `outcome`, `ghosting`), `service/export/ExportColumn.java`; Tests `unit/export/*`, `ApplicationSpecifications` coverage via `ApplicationRepositoryIT` (CI). + +- [ ] Filters accept `stage`, `outcome` (lists for export), `ghosting` (Boolean); legacy `status` is converted with `LegacyStatusMapper.map(status, null, false, LocalDate.MIN)` to stage/outcome predicates; `TO_SEND_LATER` → DRAFT; unconvertible legacy filters on `legacy_status` equality. Global search also matches stage/outcome keys. +- [ ] Export columns: `STATUS` becomes the display of `outcome ?: stage ?: legacy_status`; add `STAGE`, `OUTCOME`, `WAITING_ON`, `GHOSTING`. +- [ ] Tests for legacy-filter translation and export column values; PASS; commit. + +### Task 6: Assistant queries + +**Files:** `repository/assistant/AssistantApplicationQueryRepository.java`, `service/assistant/AssistantTools.java`, `service/assistant/AssistantApplicationQueryService.java`; Tests `unit/AssistantApplicationQueryRepositoryTest.java`, `AssistantToolsTest.java`. + +- [ ] Replace `CANONICAL_STATUS` with `COALESCE(outcome, stage, legacy_status)` exposed as `phase`; filters accept stage/outcome keys or legacy names (translated by the mapper); the `GroupBy.STATUS` aggregate groups by `phase`. Tool descriptions list the new keys. `"Ghosting"` in a filter means the ghosting predicate. +- [ ] Update tests' expected SQL fragments and alias cases; PASS; commit. + +### Task 7: Catalog endpoint + MCP + +**Files:** Create `dto/application/StageCatalogResponse.java`, `service/status/StageCatalog.java`; Modify `ApplicationController` (`GET /applications/stages`), `mcp/tools/McpApplicationTools.java`, `mcp/tools/McpAnalyticsTools.java`, `mcp/resources/McpApplicationStatusesResource.java`, `McpApplicationCreationRulesResource.java`, `McpApplicationLifecycleRulesResource.java`, `mcp/McpPromptsConfig.java`; Tests `unit/mcp/*`. + +**Interfaces:** `record StageCatalogResponse(List