diff --git a/.env.example b/.env.example index 3723f2b..81b3e1b 100644 --- a/.env.example +++ b/.env.example @@ -24,6 +24,7 @@ SPRING_MAIL_PROPERTIES_MAIL_SMTP_STARTTLS_ENABLE=true SPRING_MAIL_PROPERTIES_MAIL_SMTP_SSL_ENABLE=false ALERTOPS_EMAIL_FROM= ALERTOPS_UI_BASE_URL=http://localhost:5173 +ALERTOPS_EMAIL_VERIFICATION_TTL=30m ALERTOPS_ACKNOWLEDGEMENT_TTL=72h ALERTOPS_WEBHOOK_MAX_BODY_BYTES=65536 ALERTOPS_WEBHOOK_RATE_LIMIT=120 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9a17109..ce35856 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,4 +1,4 @@ -name: AlertOps CI +name: ReplyTrail CI on: push: diff --git a/AGENTS.md b/AGENTS.md index c094617..7c0a802 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,4 +1,4 @@ -# Agent instructions for AlertOps +# Agent instructions for ReplyTrail These rules apply to all work in this repository: backend, frontend, database, configuration, and documentation. @@ -8,10 +8,16 @@ Act as a software engineer collaborating with the project owner. Read the releva ## Project goal -Build AlertOps into a production-ready alerting and escalation product for real users. Treat the backend, UI, security, reliability, and operations as parts of the same product. Use [the product launch checklist](docs/product-launch-readiness.md) for current release priorities. +Build ReplyTrail into a production-ready alerting and escalation product for real users. Treat the backend, UI, security, reliability, and operations as parts of the same product. Use [the product launch checklist](docs/product-launch-readiness.md) for current release priorities. Existing `alertops` technical identifiers remain compatible during the public rebrand. ## Changes +- Write user-facing copy as natural, complete sentences across the UI, emails, + notifications, templates, and user-facing documentation. Avoid comma-separated + slogan or headline fragments. Prefer a sentence such as “Review every handoff + in one timeline.” Normal grammatical commas in full prose are fine; this rule + targets copy that reads like a list of fragments or generic AI-generated + marketing text. - Use clear, descriptive names for variables, methods, and classes. - Name types and methods for the business responsibility or user-visible outcome first, not for the internal mechanism. Prefer names such as @@ -93,8 +99,6 @@ Build AlertOps into a production-ready alerting and escalation product for real - Add or update a focused test for each meaningful behavior or failure path, especially races, retries, restart recovery, idempotency, and null repository results. - When a Spring component's constructor dependencies change, update every affected test context before handoff. Provide new dependencies with `@MockitoBean` or explicit test configuration in `@WebMvcTest` and other slice tests, update direct constructor tests, and run the focused slice test. If a context failure threshold appears, inspect the first underlying `UnsatisfiedDependencyException` rather than treating the threshold as the root cause. - Run the narrowest relevant tests plus the normal project build before handoff. Clearly distinguish passed local checks from integration or deployed checks that were skipped because required services or environment variables were unavailable. -- Before handoff for every repository task, run an independent, read-only verification subagent using the original request, acceptance criteria, changed-file list, and intended verification commands as its inputs. Ask it to inspect the current worktree and relevant code, tests, and documentation; run the narrowest relevant checks it can run; and return an evidence-based verdict of `Achieved`, `Not achieved`, or `Inconclusive`, with each acceptance criterion mapped to evidence, command results, gaps, regressions, and recommended follow-up. -- Keep the verifier independent: do not seed it with the desired conclusion, and do not allow it to modify files, stage changes, commit, or otherwise change repository state. The primary agent remains responsible for the result, must reconcile any disagreement or `Inconclusive` finding before claiming completion, and must record the verifier verdict, evidence, and material limitations in the current plan and final handoff. If the environment has no usable subagent mechanism, explicitly record that verification was skipped and why; do not present the task as independently verified. ## Transactions diff --git a/CHANGELOG.md b/CHANGELOG.md index 851f500..5ece39d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,457 @@ Completed repository changes, newest first. Tracking begins on 2026-10-05; earlier work has not been reconstructed. Planning and archive rules are in [AGENTS.md](AGENTS.md#task-plans-and-documentation). +## 2026-10-11 — Implement minimum recurring escalation runs + +- Implement daily/weekly repeat support on the existing escalation row with + independent child IDs, atomic next-repeat advancement, restart recovery, + stop-repeat, existing-screen controls, and source-run links. Defer advanced + recurrence options and preserve one-time scheduling behavior. +- Verification: calendar unit test, backend test compilation/package, UI build, + UI lint, and diff checks pass. Mockito service tests are blocked by local + Byte Buddy self-attachment; PostgreSQL and deployed checks remain pending. + +## 2026-10-10 — Move response steps to a numbered position + +- Make drag targets select the final numbered position and add direct position + selection to each card. Dragging, keyboard arrows, and selection share the + same placement rule and refresh numbers from the saved order. +- Verification: four UI ordering tests, two backend reorder tests, UI build, + and diff checks pass. Lint retains two existing flow-page warnings; browser + interaction checks remain pending. + +## 2026-10-10 — Use available space for escalation steps + +- Replace the horizontal response-step strip with a responsive grid that fills + the workspace width and scrolls vertically for long paths. Show numbered + order across rows and retain step actions and reordering controls. +- Verification: UI build and diff checks pass; lint retains two existing + flow-page warnings. Browser visual and interaction checks remain pending. + +## 2026-10-10 — Keep growing workspace lists scrollable + +- Bound growing workspace collections with responsive scrolling, themed + scrollbars, and keyboard-accessible regions. Keep table headers visible and + leave headings, filters, and actions above the scrolling content. +- Verification: UI build and `git diff --check` pass; lint retains the two + existing flow-page warnings. Browser visual and interaction checks remain + pending because browser access was unavailable. + +## 2026-10-10 — Label task details in escalation emails + +- Add a dedicated `Task details` section after the task metadata so the + description is clearly separated in both plain-text and HTML email formats. +- Verification: `NotificationTest`, the backend package, and `git diff --check` + pass. Visual SMTP-client inspection remains pending. + +## 2026-10-10 — Send the first escalation alert immediately + +- Send the first response-step email immediately for every start mode, include + the escalation name, ID, and response window, and keep later-step timing and + retry behavior unchanged. +- Restyle the HTML email as a compact dark responsive card with wrapped long + values while preserving the plain-text fallback and safe action links. +- Verification: focused unit tests, seven PostgreSQL scheduling tests, the + backend package, and `git diff --check` pass. SMTP delivery and multi-client + visual inspection remain pending. + +## 2026-10-10 — Register timers after escalation starts + +- Publish scheduling events normally and let a Spring transaction event listener + register them after commit, with immediate fallback for transactionless + callers. Read committed state in a separate read-only transaction so cached + pre-start statuses cannot silently prevent timer registration. +- Verification: seven focused PostgreSQL cases cover all start modes and due + publication, zero delay, rollback, fallback, and recovery; the backend package + passes with a test agent, and `git diff --check` passes. The local app needs a + restart; real broker/email verification remains pending. See the + [timer handoff guidance](docs/in-memory-timer-implementation-plan.md#durable-scheduling-state). + +## 2026-10-10 — Style escalation notification email + +- Refresh the escalation email with the ReplyTrail navy, mint, and blue + palette, a branded header, a structured task panel, and clearer actions while + preserving the plain-text fallback and recipient-scoped links. +- Verification: focused mail test and `./mvnw -q package` pass with 240 tests, + 0 failures/errors, and 17 environment-gated skips; `git diff --check` passes. + Visual email-client inspection was unavailable. + +## 2026-10-10 — Fix home-page theme toggle contrast + +- Give the light-mode Dark button in the public home-page header readable + foreground and border contrast without changing the persisted theme behavior. +- Verification: UI build and `git diff --check` pass; lint retains the two + existing `FlowDetailPage.tsx` warnings, and browser visual inspection was not + available in this session. + +## 2026-10-09 — Simplify response-route scanning + +- Keep the route card focused on the step count, Add response step, and a + compact horizontal card rail with a visible next-card cue; move rail controls + out of the header. +- Add a page-header Resolution timeout shortcut with an ON/OFF status that + opens and scrolls to the existing path settings disclosure. +- Verification: UI build, lint, and `git diff --check` pass; protected route + browser inspection was unavailable because the local browser session was at + the login screen. Lint retains the two existing `FlowDetailPage.tsx` + warnings. + +## 2026-10-09 — Refine response-route navigation + +- Restore the established compact response-step card size and add a partial + next-card cue with accessible previous/next controls for longer routes. +- Verification: UI build, lint, `git diff --check`, and Chrome inspection of + compact cards, overflow cues, and rail navigation pass; lint retains the two + existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Expand the response-route workspace + +- Move Add response step into the route card and change the ordered steps to a + spacious single-row rail that uses the available width and scrolls + horizontally for longer paths. +- Verification: UI build, lint, `git diff --check`, and Chrome inspection of + the route header and 11-card horizontal overflow pass; lint retains the two + existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Keep active escalation activity live + +- Poll the escalation detail activity timeline every three seconds alongside + status and step progress while a run is `OPEN` or `ACKNOWLEDGED`, then stop + polling for terminal and scheduled states. +- Verification: UI build, lint, `git diff --check`, and Chrome detail-page + inspection pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Clarify response-step action icons + +- Replace ambiguous Unicode glyphs with visible duplicate, edit, and delete + icons, and add native guidance to the three-dot step action trigger. +- Verification: UI build, lint, `git diff --check`, and Chrome dark-theme menu + inspection pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Add response-step duplication + +- Add a Duplicate step action to each response-step menu; it copies the + recipient, wait time, and enabled timeout, then places the new step after + its source without requiring a trip back to the page header. +- Verification: UI build, lint, `git diff --check`, and Chrome menu and ordered + duplicate inspection pass; lint retains the two existing + `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Focus escalation paths on response steps + +- Make the ordered response route the primary path-detail view, move resolution + timeout into a separate collapsed Path settings disclosure, and remove the + repeated timeout field from step cards and the step editor. +- Verification: UI build, lint, `git diff --check`, and Chrome route, settings, + and step-editor inspection pass; lint retains the two existing + `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Label collapsed sidebar icons on hover + +- Add native hover titles and accessible names to sidebar navigation icons, + workspace switching, the escalation engine, sign-out, and the sidebar + toggle so the collapsed rail remains understandable. +- Verification: UI build, lint, `git diff --check`, and Chrome collapsed and + expanded inspection pass; lint retains the two existing `FlowDetailPage.tsx` + warnings. + +## 2026-10-09 — Place the sidebar toggle inside the navigation rail + +- Move the desktop expand/collapse control beside the ReplyTrail mark and keep + it inside the collapsed rail beneath the mark, making the control feel owned + by the navigation while preserving mobile drawer access. +- Verification: UI build, lint, `git diff --check`, and Chrome expanded, + collapsed, reopened, and light/dark inspection pass; lint retains the two + existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Restore dark-mode task detail contrast + +- Add dark-theme colors for the saved task description, field labels, values, + links, and metadata separators so task context remains readable against the + dark card surface. +- Verification: UI build, lint, `git diff --check`, and Chrome light/dark task + detail inspection pass; lint retains the two existing `FlowDetailPage.tsx` + warnings. + +## 2026-10-09 — Modernize the sidebar toggle + +- Replace the text-heavy navigation control with a persistent icon-only + panel-and-arrow toggle whose icon and accessible label follow the sidebar + state; the same control expands and collapses navigation. +- Verification: UI build, lint, `git diff --check`, and Chrome expanded, + collapsed, and reopened inspection pass; lint retains the two existing + `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Improve collapsed sidebar identity spacing + +- Add breathing room between the ReplyTrail mark and workspace avatar when the + sidebar is collapsed, making the two identity cues easier to distinguish. +- Verification: UI build, lint, `git diff --check`, and Chrome expanded/collapsed + inspection pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Use one persistent sidebar toggle + +- Remove the duplicate close button from the sidebar and make the top-bar + toggle the single control for opening, collapsing, and closing navigation; + keep it visible as the workspace scrolls. +- Verification: UI build, lint, `git diff --check`, and Chrome expanded, + collapsed, reopened, and scrolled inspection pass; lint retains the two + existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Polish team-selection theme spacing + +- Give the team-selection theme toggle more breathing room and anchor the page + to the viewport theme so dark mode no longer exposes a light strip at the top + after switching. +- Verification: UI build, lint, `git diff --check`, and Chrome light/dark + inspection pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Make sidebar reopening discoverable + +- Add visible Menu and Open menu labels to the workspace navigation toggle so + the collapsed sidebar has an obvious reopen action; keep the expanded sidebar + branding clean and retain the accessible close control. +- Verification: UI build, lint, `git diff --check`, and Chrome expanded, + collapsed, and reopened inspection pass; lint retains the two existing + `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Keep workspace navigation open and reachable + +- Open the desktop sidebar by default on each page load while retaining the + collapse/reopen control, and make the full navigation independently scrollable + so the escalation engine and Sign out controls remain reachable. +- The existing landing and workspace copy already explains the product clearly + on first view and remains unchanged. Verification: UI build, lint, + `git diff --check`, and Chrome fresh-load, collapse/reopen, and sidebar-scroll + inspection pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Refine workspace navigation spacing + +- Replace one-off sidebar margins with consistent navigation groups, link + heights, section gaps, workspace spacing, and a separated bottom system area + so the expanded and collapsed menu states share the same visual rhythm. +- Verification: UI build, lint, `git diff --check`, and Chrome expanded/collapsed + inspection pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Reorganize and dismiss the workspace navigation + +- Group the signed-in menu into Monitor, Configure, and Team sections, then add + desktop collapse behavior plus a closeable mobile navigation drawer with + backdrop and reopen controls. +- Verification: UI build, lint, `git diff --check`, and Chrome interaction + checks pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Add date filters to the Audit trail + +- Add inclusive From date and To date filters to the frontend Audit trail, + resolved against the user's local calendar, with clear dates and invalid-range + feedback; the existing backend audit contract remains unchanged. +- Verification: UI build, lint, `git diff --check`, and Chrome interaction + checks pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Standardize natural user-facing copy + +- Add repository guidance to avoid comma-separated slogan fragments in UI, + emails, notifications, templates, and user-facing documentation; replace the + Audit page heading with “Review every handoff in one timeline.” +- Verification: targeted phrase search, UI build, lint, and `git diff --check` + pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Add a frontend-only audit trail page + +- Add a signed-in Audit trail page that aggregates all available escalation + history through the existing APIs, with escalation links, actor/time/state + context, search, event filtering, refresh, empty/error/loading states, and + light/dark responsive styling; no backend changes were required. +- Verification: UI build, lint, `git diff --check`, and Chrome inspection pass; + lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Refine the automatic recovery badge + +- Turn the reliability card's recovery label into a compact icon badge that + stays aligned with the heading on desktop and stacks cleanly on mobile. +- Verification: UI build, lint, and whitespace checks pass; lint retains the + two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Modernize overview workflow cards + +- Add meaningful task, path, response, saved-state, handoff, and recovery icons + to the setup/reliability cards, with accent rails, connected step styling, + badges, softer surfaces, and clearer hover hierarchy. +- Verification: UI build, lint, and whitespace checks pass; lint retains the + two existing `FlowDetailPage.tsx` warnings. Live workspace visual inspection + was limited because the browser had no authenticated session. + +## 2026-10-09 — Add clickable workspace breadcrumbs + +- Add route-aware breadcrumbs to the signed-in shell so collection and detail + pages expose clickable parent levels such as Team → Tasks → Task details. +- Verification: UI build, lint, and whitespace checks pass; live route-click + inspection was limited because the browser had no authenticated workspace. + +## 2026-10-09 — Add icons to overview metrics + +- Replace placeholder metric letters/arrows with the existing task, flow, + escalation, and overview SVG icons while preserving clickable destinations. +- Verification: UI build, lint, and whitespace checks pass; lint retains the + two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Make overview metrics clickable + +- Turn the four overview metric cards into semantic links to Tasks, Escalation + paths, and Escalations, with full-card hover, focus, and arrow affordances. +- Verification: UI build, lint, and whitespace checks pass; live click testing + was unavailable because the browser had no authenticated workspace session. + +## 2026-10-09 — Unify the response tagline + +- Replace the comma-based “Your response, in order.” overview title with the + natural existing ReplyTrail tagline, “Keep every response on track.” +- Verification: UI build, lint, phrase search, and whitespace checks pass; the + old phrase is absent from the product UI. + +## 2026-10-09 — Improve email footer wording + +- Replace the awkward comma-based footer slogan in invitation and escalation + notification emails with the existing natural ReplyTrail tagline, + “Keep every response on track.” +- Verification: backend package, wording search, and whitespace checks pass. + +## 2026-10-09 — Add password visibility controls + +- Add a reusable eye-icon show/hide control to sign-in and registration + password fields, keeping passwords masked by default with accessible state + labels. +- Verification: UI build, lint, whitespace checks, and Chrome interaction + checks pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Silence development SQL statement output + +- Disable Hibernate SQL rendering and formatting in the local `dev` profile so + debugger terminals keep normal application logs without printing every query. +- Verification: `mvn -DskipTests package`, property inspection, and whitespace + checks pass; production SQL logging settings remain unchanged. + +## 2026-10-09 — Clarify the escalation overview description + +- Replace the technical-sounding overview description with clearer copy that + emphasizes reliable ownership from the first alert to the final handoff. +- Verification: UI build, lint, and whitespace checks pass; lint retains the + two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Soften the light UI palette + +- Replace stark white light-mode canvases, cards, controls, public sections, + product previews, and dialogs with muted blue-gray/off-white surfaces while + preserving text contrast and semantic status colors. +- Verification: UI build, lint, whitespace checks, and Chrome light/dark theme + inspection pass; lint retains the two existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Turn the home page into an interactive product tour + +- Replace static use-case tiles with thirteen clickable workflow stories that + open accessible details for the scenario, owner handoff, timing, and finish + condition; add a responsive signed-in workspace preview of an active run. +- Add theme-aware product-window, card, dialog, and mobile styling with + reduced-motion-safe interactions, keeping the existing registration and sign-in + paths unchanged. +- Verification: UI build and whitespace checks pass; Chrome inspection confirmed + the preview, all cards, dialog content, and close behavior. Lint retains the + two pre-existing `FlowDetailPage.tsx` warnings. + +## 2026-10-09 — Load local env from the VS Code Java launch profile + +- Configure the `AlertOpsApplication` debug profile to load the ignored root + `.env` and send Spring logs to the integrated terminal. +- Verification: launch JSONC parsing and whitespace checks pass; the existing + backend remains healthy on port 8096 with the same local env. The VS Code GUI + launch itself remains a user-side F5 action. + +## 2026-10-09 — Prepare the local full-stack environment + +- Reconcile the ignored root `.env` with Docker Compose's PostgreSQL, RabbitMQ, + Redis, UI URL, and application defaults; add ignored `ui/.env` with the local + Vite proxy configuration and add the missing email-verification example key. +- Install Docker CLI/Compose and native PostgreSQL 16/RabbitMQ dependencies; + start the native services and initialize the local `alert_ops` database using + the existing ignored credentials without exposing secret values. +- Verification: Compose config, backend compile, UI build, Vite proxy, backend + liveness, Flyway migrations, and native service checks pass. Docker/Colima VM + image downloads stalled, so the app was verified with native services instead. + +## 2026-10-09 — Improve light-mode contrast and home-page engagement + +- Strengthen light-mode text, border, control, card, and secondary-surface + contrast for easier reading across the UI. +- Add workflow-benefit cues, a ready-to-run workflow count, richer public-section + surfaces, hover feedback, and subtle reduced-motion-safe status animation. +- Verification: UI build, lint, diff checks, desktop/mobile Chrome inspection, + and light/dark theme checks pass; lint retains two pre-existing warnings. + +## 2026-10-08 — Add persisted dark mode to the UI + +- Add a local-storage-backed light/dark theme with pre-paint restoration and + accessible toggles across public, auth, workspace, team, invitation, and + email-action surfaces. +- Add dark styling for shared navigation, forms, cards, notices, statuses, path + builders, and public use-case sections without changing product behavior. +- Verification: UI build, lint, diff checks, public switching/reload, and sign-in + screen inspection pass; lint retains two pre-existing FlowDetailPage warnings. + +## 2026-10-08 — Bring ReplyTrail use cases to the home page + +- Add a scannable public landing-page section for all thirteen README use cases, + with plain-language descriptions, responsive cards, a hero anchor link, and + the existing SVG favicon linked for a clean browser preview. +- Verification: UI build, `git diff --check`, and Chrome desktop/400px responsive + inspection pass; the hero anchor and existing signup links work. UI lint retains + two pre-existing FlowDetailPage warnings; live email and deployed journeys were + not tested. + +## 2026-10-08 — Explain ReplyTrail and its use cases + +- Rewrite the [README](README.md) introduction for new visitors with thirteen use + cases in plain language and definitions of the core concepts. Simplify setup + and ten personal reminders, keeping timing and acknowledgement behavior clear; + remove the extended customer onboarding walkthrough. +- Document current scheduling, resolution, manual actions, and history; correct + the first-use walkthrough and Spring Boot version while retaining setup/API examples. +- Verification: UI build, Maven verification outside the sandbox (240 tests, + 17 environment-gated skips), link/example checks, and whitespace checks pass. UI lint retains two + existing warnings; live email, Docker startup, and deployed journeys were not tested. + +## 2026-10-08 — Remove mandatory secondary review instructions + +- Remove the repository-level requirement and maintained-plan references that + caused an extra review process to run for every task. +- Preserve historical changelog evidence while keeping current instructions + focused on direct local verification. +- Verification: targeted instruction search and `git diff --check` pass; no + product build was needed for this documentation-only change. + +## 2026-10-08 — Implement the ReplyTrail public rebrand + +- Rename visible product surfaces, metadata, current documentation, CI display + labels, verification/invitation mail, and escalation notifications to ReplyTrail. +- Keep `com.alertops`, `alertops.*`, `ALERTOPS_*`, webhook headers, session keys, + queues, caches, and deployment identifiers unchanged for compatibility; domain, + sender, and deployed rollout work remain pending. +- Verification: UI build and 14 focused branding/email tests pass; full Maven clean + verification passes (240 tests, 17 environment-gated skips); lint retains two + existing FlowDetailPage warnings. Independent read-only review: **Achieved**; + residual references, compatibility paths, and 132 documentation links/anchors + were checked. Browser/deployed, domain, sender, and real-delivery checks remain pending. + +## 2026-10-08 — Plan the product rebrand + +- Add a [phased product rebranding plan](docs/product-rebranding-plan.md) covering + identity selection, UI and emails, compatibility, verification, rollout, and rollback. +- Link the pending initiative from launch readiness; final name/domain selection + and implementation remain open. This task changes documentation only. +- Verification: document links, diff checks, UI build, and full Maven verification + pass (238 tests, 17 environment-gated skips); lint retains two existing warnings. + Independent read-only review: Achieved; runtime/deployed checks await implementation. + ## 2026-10-08 — Fix CI container image build - Remove brittle exact Jammy OpenSSL package pins while continuing to install diff --git a/README.md b/README.md index a29a400..1a02e03 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,83 @@ -# AlertOps +# ReplyTrail -AlertOps helps teams turn tasks or incoming webhook events into ordered email response paths. A task can represent an operational alert, an onboarding request, or any other item that needs a response. A team member can start an escalation manually, or a webhook can create the task and start it automatically. Email recipients can acknowledge a run to stop later steps. +**Keep every response on track.** -The product is being prepared for release. See the [product launch checklist](docs/product-launch-readiness.md) for remaining work. +ReplyTrail is a self-hosted web application for team response coordination. Turn an alert or request into a task, choose an ordered path of people to notify, and track the response from the first email to acknowledgement or resolution. If nobody responds within the configured wait, the run advances to the next person. + +It helps teams answer three questions: **Who should respond? When should the next person be notified? What happened to this request?** A team member can start a run in the UI, schedule it for later, or let an external system trigger it through a webhook. This repository contains the React UI, Spring Boot API and workers, database migrations, and deployment configuration. + +## Use cases + +Use ReplyTrail when you want someone to follow up on a problem, a request, or a +reminder. It sends an email and, if nobody responds in time, can email the next +person or remind the same person again. + +- Website or app problems: Email the person who looks after the service. If they do not respond, notify their team lead. +- Helping new customers: Ask someone to help a customer finish setting up their account. Notify another team member if no one responds. +- IT help: Follow up on requests such as a login problem or access to a work tool. +- Failed jobs: Ask the person responsible to check a failed data import or other background job. +- Unanswered support requests: Remind the support team about a customer who is still waiting for help. +- Failed backups: Ask someone to check why a backup failed or could not be restored. +- Security problems: Notify the person who should review a reported security issue. +- Payment or invoice problems: Ask the billing team to follow up on a failed payment or an incorrect invoice. +- Upcoming renewals: Schedule a reminder before a certificate expires or a contract needs renewing. +- Late deliveries: Ask the purchasing team to follow up when a supplier misses a delivery date. +- Office repairs: Follow up on a broken printer, an office repair, or another maintenance request. +- Future follow-ups: Schedule a reminder to check a task at a later date. +- Personal reminders: Send yourself a reminder about the same task roughly once a day for ten days. + +Add a task describing what needs attention, choose who should receive the +emails and how long to wait, then start it now or choose a future start time. +Everyone receiving emails must be a member of your ReplyTrail team. + +You can also connect another tool through a webhook to send tasks to ReplyTrail. +That tool detects the problem and sends the details; ReplyTrail emails the +people you choose. They carry out the work in the relevant app or system. + +### Example: daily reminders for ten days + +Create a flow with ten steps and put your own team-member email on every step. +Set each wait to **1,440 minutes (24 hours)** and leave **resolution timeout** +disabled. Start it with the task you want to be reminded about. + +The first reminder is scheduled for 24 hours after you start. Each later +reminder is scheduled for 24 hours after the previous email is sent. If you +click **Acknowledge** and confirm, the remaining reminders stop. + +If you do not acknowledge, the ten-step sequence continues and then ends; +it does not repeat automatically. Delivery delays or downtime can change when +emails arrive, so they may not reach you at the same clock time every day. + +## Core concepts + +| Concept | Meaning | +| --- | --- | +| Team | A workspace containing its members, tasks, paths, webhooks, and runs. | +| Task | The work that needs a response: title, description, source, and optional context. | +| Response path | A reusable, ordered sequence of team-member recipients and configured timing. Called a flow in the API and code. | +| Escalation run | One execution of a task through a path, with saved progress and history. | +| Acknowledgement | A recipient accepts responsibility; it completes the run or starts a resolution window, depending on the path settings. | +| Resolution | Completion of the issue after acknowledgement when resolution timeout is enabled. | ## Features - **Accounts and teams:** Registration requires email verification before login. Users can belong to multiple teams. Owners and admins can invite members; admins can invite users only. Acceptance requires the invited, verified email address. - **Tasks:** Name, description, and source, plus optional priority, category, and HTTP(S) reference URL. Priority is a user-defined label. Manually created tasks default to source `Manual`. -- **Response paths:** Ordered steps with a team-member recipient and wait time. Add, edit, delete, and drag steps to reorder them. Runs already started retain their saved step details when a path changes. -- **Escalations:** Create a run from a task and response path, then start it. The UI shows the run and saved state of each step. +- **Response paths:** Ordered steps with a team-member recipient and wait time, plus optional resolution timeouts. Add, edit, delete, and drag steps to reorder them. Started runs retain their saved task context, step details, and timing when a task or path changes. +- **Immediate or scheduled runs:** Start a run from a task and path immediately, or schedule a one-time start using a date, time, and IANA timezone. Reschedule, cancel, or start a scheduled run early before it begins. The first step keeps its configured wait. - **Webhooks:** Owners and admins can create a webhook with a default path, rotate its secret, and enable or disable it. An incoming event creates a task and starts a run. The complete JSON event is stored with links to both records. -- **Email acknowledgement:** Each escalation email links to a preview page. The recipient confirms there to acknowledge the run and stop later steps. +- **Acknowledgement and resolution:** Recipient-scoped email links open a preview before confirmation. Acknowledgement either completes the run or pauses later steps for a configured resolution window. Unresolved timeouts resume escalation; resolution stops remaining steps. +- **Manual escalation:** Escalate now makes the next eligible response step due immediately from the signed-in UI or an eligible email action link. +- **Activity history:** Run details show saved step progress and chronological milestones, including notification attempts, acknowledgement, resolution, and manual actions. Repeated delivery retries are grouped for readability. +- **Recovery:** PostgreSQL-backed schedules and pending publications recover after restart. Scheduled-start failures create durable email-notification obligations for the scheduler owner and team administrators. + +## Current scope + +- Notifications use **SMTP email**. SMS, phone calls, push notifications, and native Slack/Teams delivery are not implemented. +- Scheduling supports **one-time starts**, not recurring or cron schedules. A finite reminder sequence can use multiple steps assigned to the same person, as in the ten-day example above. +- A response path names individual team-member recipients; rotating on-call calendars are not implemented. +- Opening an email link does not accept responsibility automatically; the recipient must confirm the action. +- Local checks do not establish production readiness. Database/broker integration checks and deployed response journeys are tracked in the launch checklist. ## How an escalation runs @@ -36,16 +102,30 @@ PostgreSQL stores tasks, paths, events, runs, step states, and due times. The ba `SENT` means the SMTP server accepted the email, not that it reached an inbox. If SMTP accepts a message and the app stops before saving `SENT`, a retry can send it again. +## Technology stack + +| Component | Technology and responsibility | +| --- | --- | +| Web UI | React 19, TypeScript, Vite, React Router, TanStack Query, and Tailwind CSS | +| API and workers | Java 17 target, Spring Boot 4.0.8, Spring Security, and JWT authentication | +| Durable storage | PostgreSQL with Spring Data JPA and Flyway schema migrations | +| Ready-work delivery | RabbitMQ; database-backed timers determine when work becomes ready | +| Short-lived shared state | Redis for workflow intents and webhook rate limiting | +| Email | Spring Mail with an SMTP provider | +| Packaging and deployment | Docker Compose for local services; Kubernetes manifests and GitHub Actions for backend build, verification, and image scanning | + +The UI can be deployed as static files separately from the backend. Existing `com.alertops` packages, `ALERTOPS_*` settings, container/resource names, and the `X-AlertOps-Webhook-Secret` header are retained compatibility identifiers from the earlier product name. Use these exact identifiers in configuration and integrations. + ## Run locally ### Prerequisites - Docker and Docker Compose v2 for PostgreSQL, RabbitMQ, and Redis -- Java 17 to run the backend from source +- Java 17 or later to run the backend from source - Node.js 22 and npm for the UI - An SMTP account and verified sender for registration, invitation, and escalation emails -Copy the example configuration, replace the password and JWT placeholders, and keep `.env` out of source control. Generate a JWT key with `openssl rand -base64 32`. +Copy the example configuration, replace the password and JWT placeholders, configure SMTP for the account-verification flow, and keep `.env` out of source control. Generate a JWT key with `openssl rand -base64 32`. ```bash cp .env.example .env @@ -121,8 +201,8 @@ The terminal startup loads all `.env` values. The current Compose file forwards 2. Create or select a team. Invite team members from **Members** if they should receive response steps. 3. Create a task with a meaningful source and description. 4. Create a response path with at least one step assigned to a team member. -5. Create a run from the task and path, open its details, and start it. -6. Follow the step state and email. The recipient can open the acknowledgement link and confirm to stop remaining steps. +5. On **Escalations**, choose the task and path, then select **Start immediately** or **Schedule for later**. Creation starts or schedules the run according to that choice. +6. Open the run details to follow saved step progress and activity history. In the email, confirm acknowledgement; if the path requires resolution, resolve before the displayed deadline to stop later notifications. ## Trigger a task through a webhook @@ -164,18 +244,33 @@ The event route does not require a login JWT, but it checks `X-AlertOps-Webhook- The backend also reads `SPRING_DATASOURCE_*`, `SPRING_RABBITMQ_*`, `SPRING_DATA_REDIS_*`, and `SPRING_MAIL_*` settings. See [`application.properties`](src/main/resources/application.properties) and [`application-prod.properties`](src/main/resources/application-prod.properties) for other scheduler, consumer, timeout, and port settings. Compose forwards only the variables listed in its `app.environment`; add entries for other overrides when running in Docker. -The backend exposes Actuator health at `http://localhost:8096/actuator/health` and scheduling status at `/actuator/scheduling`. The production profile runs Flyway migrations and checks entity mappings against the schema. +The backend exposes Actuator health at `http://localhost:8096/actuator/health` and scheduling status at `/actuator/scheduling`. Health is public; scheduling status requires authentication. The production profile runs Flyway migrations and checks entity mappings against the schema. Stop Compose services with `docker compose down`. `docker compose down -v` also deletes their PostgreSQL, RabbitMQ, and Redis volumes and stored data. +## Development checks + +From the repository root: + +```bash +./mvnw --batch-mode --no-transfer-progress verify +npm --prefix ui ci +npm --prefix ui run build +npm --prefix ui run lint +``` + +The backend command runs tests and packages the application; the UI build checks TypeScript and produces static assets in `ui/dist/`. Integration suites for PostgreSQL, RabbitMQ, and Redis are opt-in and need running services. A passing default build can include skipped integration tests; see the suite setup in [`src/test/java/com/alertops/`](src/test/java/com/alertops/) and the [launch checklist](docs/product-launch-readiness.md) before interpreting it as a release result. + ## Repository and release status -- `src/main/java/com/alertops/`: Spring Boot API and workers (Java 17, Spring Boot 3.5). +- [`src/main/java/com/alertops/`](src/main/java/com/alertops/): Spring Boot API and workers. +- [`src/test/java/com/alertops/`](src/test/java/com/alertops/): backend unit, API, and opt-in integration tests. - `src/main/resources/db/migration/`: Flyway database migrations. - `ui/`: React 19, TypeScript, and Vite client. - `docker-compose.yml`: local backend and dependency stack. - `.github/workflows/ci.yml`: Maven verification, container build, and Trivy image scan on pull requests and configured branch pushes. - [`docs/product-launch-readiness.md`](docs/product-launch-readiness.md): release checklist and remaining end-to-end checks. - [`docs/deployment/README.md`](docs/deployment/README.md): staged deployment learning plan. +- [`CHANGELOG.md`](CHANGELOG.md): completed repository changes and verification notes. -The core manual and webhook response flows are implemented. The release checklist still calls for a deployed end-to-end run, including restart and duplicate-delivery scenarios. +Manual and webhook response flows, one-time scheduling, resolution timeouts, manual actions, and activity history are implemented locally. The release checklist still calls for deployed end-to-end runs, including restart and duplicate-delivery scenarios. Domain ownership, sender verification, and rebrand rollout are tracked in the [product rebranding plan](docs/product-rebranding-plan.md). diff --git a/docs/current-plan.md b/docs/current-plan.md index 429534b..cd18a92 100644 --- a/docs/current-plan.md +++ b/docs/current-plan.md @@ -1,48 +1,50 @@ # Current task plan -## Task: Fix CI container image build +## Task: Implement minimum recurring escalation schedules -Started: 2026-10-08 -Status: Complete +Started: 2026-10-11 +Status: Complete — local implementation finished; deployment remains pending ### Goal and scope -Restore the full CI pipeline after Maven verification succeeds but the Docker -image build fails. Keep the pinned base image and install the current patched -Jammy OpenSSL packages without depending on an unavailable repository version. - -Previous task: webhook event history navigation is complete in commits -`1b56267` and `be4c40b`. Spring Boot 4 test-import fixes are in `2e8f807`, -`c44ce71`, `63e8c7d`, and `6bc0f06`. CI run `37684605184` passed Maven but -failed during `Build commit image`; diagnostic logging in `c1f81ea` made the -successful rerun `37686152716` observable. +Implement the minimum recurring schedule scope from the [feature plan](recurring-escalation-implementation-plan.md) +while preserving one-time escalation behavior. This task includes backend, +frontend, migrations, focused tests, and documentation updates; deployment remains +excluded and is the final release step. ### Decision-compliance note -- Keep the existing pinned container base; change only the package installation - that currently prevents the image from building. -- Install named patched packages from the current Jammy repository and retain - the image vulnerability scan as the release gate. +- Preserve the existing one-time schedule and escalation lifecycle. +- Each occurrence has a new escalation ID; overlapping runs are allowed. +- The existing escalation table owns repeatType, nextRepeatAt, and repeatSourceId. + The original row owns repetition; children never own a repeating chain. +- PostgreSQL owns calendar progress and run state; timers only provide wake-ups. +- Reuse each run's scheduledStartAt and existing start/retry/publication path. +- Exclude a new schedule entity/table, duplicate repeat boolean, separate schedule + lifecycle, and custom intervals unless separately agreed. +- Minimum defaults are daily/weekly, scheduled first start, latest missed repeat + only, and stop without editing. Do not introduce repeat-after-completion, + monthly/yearly, custom intervals, or a separate schedule table. ### Acceptance criteria -- The Docker image builds successfully in CI. -- Trivy reports no unfixed HIGH or CRITICAL vulnerabilities. -- Maven verification remains green and the complete CI workflow passes. -- The changelog records the compatibility fix. +- [x] Add the three recurrence fields and daily/weekly calendar calculation. +- [x] Create independent child runs atomically and recover repeat timers safely. +- [x] Add stop-repeat and the existing-screen scheduling controls. +- [x] Run focused backend/frontend checks and update readiness documentation. -### Steps +### Steps and verification -- [x] Update the Dockerfile package installation. -- [x] Run the local diff checks and push the fix. -- [x] Inspect the diagnostic Docker build result and apply the smallest fix. -- [x] Monitor CI through Maven, image build, and Trivy completion. -- [x] Correct the changelog with the final CI result. +- [x] Inspect existing scheduling, execution, timer guidance, and launch tracking. +- [x] Confirm the canonical fields, minimum defaults, and excluded improvements. +- [x] Implement backend persistence, occurrence creation, timer recovery, and API. +- [x] Implement the existing UI controls and source-run context. +- [x] Run focused tests, normal builds, and diff checks; record limitations. -### Verification and limitations +### Verification results -Local Docker is unavailable. GitHub Actions run `37686152716` passed Maven -verification, the container image build, and the Trivy scan; the run shows five -non-blocking deprecation warnings. Maven ran 238 tests with 0 failures/errors -and 17 environment-gated skips. Independent read-only verification was skipped -because no usable subagent mechanism was available. +`EscalationRepeatCalculatorTest` passes. Backend test compilation and packaging, +UI build, UI lint, and `git diff --check` pass; UI lint retains two existing +warnings in `FlowDetailPage.tsx`. The full Mockito-backed service suite could not +start because Byte Buddy cannot self-attach on this local JDK/process environment. +PostgreSQL, broker, SMTP, restart, and deployed checks remain intentionally last. diff --git a/docs/deployment/README.md b/docs/deployment/README.md index d9fad03..d777208 100644 --- a/docs/deployment/README.md +++ b/docs/deployment/README.md @@ -1,16 +1,19 @@ -# AlertOps cloud deployment learning path +# ReplyTrail cloud deployment learning path -This guide takes AlertOps from a local Spring Boot application to a GitOps-managed +This guide takes ReplyTrail from a local Spring Boot application to a GitOps-managed Kubernetes workload. OCI is the implementation target; AWS equivalents are included so the same design can be explained in interviews. +The public product name is ReplyTrail. Existing `alertops` image, service, namespace, +cache, and resource names in the commands below remain compatibility identifiers. + ## Target architecture ```text Developer -> GitHub -> GitHub Actions -> GHCR \-> manifests repository -> Argo CD | -Internet -> load balancer -> Kubernetes Service -> AlertOps pods +Internet -> load balancer -> Kubernetes Service -> ReplyTrail pods |-- PostgreSQL |-- RabbitMQ `-- Redis @@ -22,7 +25,7 @@ AWS: VPC + EKS/EC2 + ECR + S3 PostgreSQL, RabbitMQ, and Redis can run inside Kubernetes for learning. For a production design, prefer managed services where the chosen cloud provides them. Stateful systems require backups, persistent volumes, disruption planning, and -different scaling rules from the stateless AlertOps application. +different scaling rules from the stateless ReplyTrail application. ## Course roadmap diff --git a/docs/deployment/phase-0-readiness.md b/docs/deployment/phase-0-readiness.md index 5379c5a..3d414c7 100644 --- a/docs/deployment/phase-0-readiness.md +++ b/docs/deployment/phase-0-readiness.md @@ -1,5 +1,9 @@ # Phase 0: production readiness +> **ReplyTrail rebrand note:** This readiness record uses older AlertOps wording in +> historical observations. It refers to the current ReplyTrail product; executable +> `alertops` resource and configuration identifiers remain unchanged. + Phase 0 makes failures visible before deployment automation is introduced. Kubernetes cannot repair an application that starts with invalid configuration, silently changes its database schema, or shares a signing key committed to Git. diff --git a/docs/deployment/phase-1-docker-foundations.md b/docs/deployment/phase-1-docker-foundations.md index ccbfb67..cc8f889 100644 --- a/docs/deployment/phase-1-docker-foundations.md +++ b/docs/deployment/phase-1-docker-foundations.md @@ -1,5 +1,9 @@ # Phase 1: Docker and Compose foundations +> **ReplyTrail rebrand note:** This Docker and Compose learning record uses older +> AlertOps wording in historical observations. It refers to the current ReplyTrail +> product; executable `alertops` resource and configuration identifiers remain unchanged. + This note explains what Docker Compose creates for AlertOps, why each resource exists, and which commands are safe to use. It is intended as a reference to revisit while learning; memorizing every command is not required. diff --git a/docs/deployment/phase-2-kubernetes.md b/docs/deployment/phase-2-kubernetes.md index cb66cb7..9afd009 100644 --- a/docs/deployment/phase-2-kubernetes.md +++ b/docs/deployment/phase-2-kubernetes.md @@ -1,5 +1,9 @@ # Phase 2: Local Kubernetes +> **ReplyTrail rebrand note:** This Kubernetes learning record uses older AlertOps +> wording in historical observations. It refers to the current ReplyTrail product; +> executable `alertops` resource and configuration identifiers remain unchanged. + ## Objective Run the verified AlertOps container stack on a local Kubernetes cluster and understand diff --git a/docs/deployment/phase-3-github-actions.md b/docs/deployment/phase-3-github-actions.md index db3ab0e..9e6e8bb 100644 --- a/docs/deployment/phase-3-github-actions.md +++ b/docs/deployment/phase-3-github-actions.md @@ -1,5 +1,9 @@ # Phase 3: Continuous Integration with GitHub Actions +> **ReplyTrail rebrand note:** This CI learning record uses older AlertOps wording in +> historical observations. It refers to the current ReplyTrail product; executable +> `alertops` artifact and resource identifiers remain unchanged. + ## Objective Turn the verified local build into a repeatable CI pipeline. Every relevant push and diff --git a/docs/feature-backlog.md b/docs/feature-backlog.md index 13abca7..8f9d866 100644 --- a/docs/feature-backlog.md +++ b/docs/feature-backlog.md @@ -5,7 +5,7 @@ release requirements remain in the [product launch checklist](product-launch-rea ## Send test escalation -- **Status:** Deferred — revisit after real users start using AlertOps. +- **Status:** Deferred — revisit after real users start using ReplyTrail. - **Decision date:** 2026-10-06. - **Goal:** Let a team check its escalation configuration before using it for a real incident. - **Next review:** Use feedback from initial users to decide priority and expected behavior. diff --git a/docs/in-memory-timer-implementation-plan.md b/docs/in-memory-timer-implementation-plan.md index 6ac9824..27a3c15 100644 --- a/docs/in-memory-timer-implementation-plan.md +++ b/docs/in-memory-timer-implementation-plan.md @@ -77,6 +77,13 @@ Reuse the existing fields: 4. Confirmed acceptance clears `publicationPending`, conditional on the matching attempt and due time. 5. The consumer atomically claims the attempt and clears obsolete pending state. +The step listener uses `@TransactionalEventListener(AFTER_COMMIT)` with +`fallbackExecution=true` for events published without a transaction. Its +publication eligibility check runs in a new read-only transaction: Hibernate +can retain a cached `IDLE` or `SCHEDULED` escalation after a bulk start update +has committed `OPEN`, so reusing the committing persistence context can skip +an otherwise valid timer. + If the process stops after commit but before registration, startup recovery reconstructs the timer from PostgreSQL. If local registration fails while the process stays alive, a tracked retry must repair it. No scheduling-request queue or additional request flag is needed for this single-process handoff. Late confirmations must never clear the flag of a newer attempt. Broker acceptance is not email delivery, and `SENT` continues to mean SMTP acceptance. diff --git a/docs/product-launch-readiness.md b/docs/product-launch-readiness.md index ef71ad6..c3fef5e 100644 --- a/docs/product-launch-readiness.md +++ b/docs/product-launch-readiness.md @@ -1,4 +1,4 @@ -# AlertOps: critical path to product release +# ReplyTrail: critical path to product release Reassessed: 2026-10-08. This list contains critical bugs to fix first, the two product features selected for this release, and the in-progress review of the Alert Escalation v1 requirements. Scheduling has focused PostgreSQL integration coverage with a simulated broker; the deployed end-to-end release journey remains unverified. @@ -28,6 +28,29 @@ Review these requirements in order. A checked **Requirements agreed** box means - **Evidence:** [schedule migration](../src/main/resources/db/migration/V6__add_escalation_scheduling.sql), [failure-notification migration](../src/main/resources/db/migration/V10__add_scheduled_start_failure_notifications.sql), [scheduled-start scheduler](../src/main/java/com/alertops/flow_execution_engine/service/EscalationStartScheduler.java), [failure-notification service](../src/main/java/com/alertops/flow_execution_engine/service/EscalationStartFailureNotificationService.java), [start claims](../src/main/java/com/alertops/flow_execution_engine/repository/EscalationRepository.java), [creation UI](../ui/src/features/escalations/EscalationsPage.tsx), [schedule controls and failure state](../ui/src/features/escalations/EscalationDetailPage.tsx), [notification tests](../src/test/java/com/alertops/flow_execution_engine/service/EscalationStartFailureNotificationServiceTest.java). - **Local verification:** Focused scheduling/retry/notification tests, early-start/controller tests, backend packaging, and `npm run build` pass. PostgreSQL/Testcontainers integration coverage is currently skipped in this environment, so the final readiness box stays open. +#### Recurring schedules — planned extension + +- [x] **Minimum scope defined; defaults selected** +- [x] **Minimum implementation complete locally** +- [ ] **Locally and deployed verified** +- **Agreed direction:** One recurring schedule creates independent escalation + runs with different IDs. Runs may overlap; an unresolved previous run does not + block the next calendar occurrence. Preserve the existing one-time behavior. +- **Storage agreed:** Keep recurrence on the original escalation in the existing + table with repeatType, nextRepeatAt, and repeatSourceId. Generated runs do not + repeat themselves. Do not add a separate recurring-schedule table or lifecycle. +- **Plan:** [Recurring escalation implementation plan](recurring-escalation-implementation-plan.md). + Start with daily/weekly repeats on scheduled starts, stop-repeat, and only the + latest missed repeat after downtime. Fixed timezone/DST defaults are recorded; + monthly/yearly repeats, editing, custom intervals, previews, and extra history + views are deferred. This planned extension does not change one-time readiness + or claim deployed verification. +- **Local state:** Daily/weekly recurrence, independent child runs, stop-repeat, + durable next-repeat recovery, and existing-screen controls are implemented. + Calendar unit coverage, backend compilation/package, UI build/lint, and diff + checks pass. Mockito service tests are environment-blocked by Byte Buddy + self-attachment; PostgreSQL and deployed verification remain pending. + ### 2. Incident lifecycle - [x] **Requirements agreed** @@ -81,7 +104,7 @@ Review these requirements in order. A checked **Requirements agreed** box means - **Core decisions agreed:** The flow owns an optional resolution-timeout toggle. Disabled flows have no node resolution timeouts and retain today's terminal acknowledgement behavior. Enabled flows require a positive resolution timeout on every node, copied with the toggle into runtime state at escalation start. Use one notification-step enum with terminal `SENT`, `FAILED`, and `SKIPPED` outcomes. - **Enabled behavior:** Acknowledgement of an exact sent step changes the run from `OPEN` to `ACKNOWLEDGED`, pauses the next scheduled step if present, and saves a UTC resolution deadline using that step's timeout. Resolution ends the run as `RESOLVED` and skips later unsent steps. If timeout wins first and a next step exists, resume `OPEN` and make it due immediately, even when its original due time is later. Do not restart the step delay or wait for the later of the two deadlines. With no next step, exhaust as described below. - **Uniform final-node behavior agreed:** All nodes use the same node-owned acknowledgement/resolution waits, without a separate final-node setting. A successful final send stays open for acknowledgement. If its acknowledgement wait expires, or its enabled resolution wait expires unresolved, finish as `COMPLETED` / `EXHAUSTED`; do not resend or restart. Timely enabled resolution ends `RESOLVED`; disabled acknowledgement retains terminal `ACKNOWLEDGED` behavior. See [uniform node rules](resolution-timeout-implementation-plan.md#agreed-uniform-node-waits-and-final-step-outcome). -- **Two node durations agreed:** The existing delivery delay is the acknowledgement wait, not a separate additional setting. If nobody acknowledges, that same wait expires and the next step becomes due. Timely acknowledgement with resolution enabled starts the resolution duration from acknowledgement and pauses progression. Unresolved resolution expiry makes the next step due immediately, without adding the original wait again. No third duration, separate send-delay control, or final-node exception is needed; retain the initial first-step delay. +- **Two node durations agreed:** The existing delivery delay is the acknowledgement wait, not a separate additional setting. The first response email is sent immediately when an escalation starts, and its configured duration begins after delivery. If nobody acknowledges, that same wait expires and the next step becomes due. Timely acknowledgement with resolution enabled starts the resolution duration from acknowledgement and pauses progression. Unresolved resolution expiry makes the next step due immediately, without adding the original wait again. No third duration, separate send-delay control, or final-node exception is needed. - **Links and action deadlines agreed:** Links remain viewable with safe read-only recipient context after a response deadline; new acknowledgement/resolution actions require current ownership and time strictly before their own saved deadline. Recheck on POST under the run lock, even after restart or when expiry callbacks are delayed. Timely acknowledgement keeps its separate resolution window. Repeat accepted actions show the saved result without restarting timers or reclaiming ownership. Invalid tokens still grant no access. See [link/action rules](resolution-timeout-implementation-plan.md#agreed-viewable-links-and-action-deadlines). - **Resolution access settled:** Reuse existing same-team access in the UI and the current acknowledging recipient's scoped email link, enforcing the current resolution deadline and recording the actual actor. Node recipients already belong to the team; no extra role or state is needed. - **Final lifecycle storage decision:** `RESOLVED` is self-describing and has no separate completion reason. `COMPLETED` requires `ACKNOWLEDGED` or `EXHAUSTED`; active acknowledgement owner/step/deadline fields are cleared when the run leaves `ACKNOWLEDGED`, while audit events retain the historical facts. Timing is settled: delivery delay and acknowledgement duration are the same wait. Node response durations, late-action rejection, resolution access, and email Escalate now source eligibility are settled; do not reopen those states or permissions. @@ -99,7 +122,7 @@ Review these requirements in order. A checked **Requirements agreed** box means - **Email action:** Add an **Escalate now** button opening a read-only preview/confirmation page that shows the current next recipient. Allow explicit POST confirmation without login using a hashed recipient token bound to the source step and validated against the expected target/current state. Before acknowledgement, only the current recipient within their acknowledgement window may act; after acknowledgement, only the current acknowledging recipient within their resolution window may act. At expiry or advancement, new actions are unavailable but the scoped link stays viewable. Opening/scanning never changes state. Reject invalid/foreign tokens, terminal runs, and no-next-step actions. Recheck ownership, deadline, and target under the run lock; repeated Step 1 confirmation cannot advance Step 3 after advancing Step 2. Audit the recipient email and affected steps; reuse the UI lifecycle operation. See [email source rules](resolution-timeout-implementation-plan.md#escalate-now-from-email). - **State and reliability rules:** Reuse the step-status enum from Requirement 3. Bind manual requests to the expected step so duplicate/stale clicks cannot advance another step. Save the state change, due time, publication obligation, and actor audit together; change timers/publish only after commit. Manual escalation, timeout, and resolution must have one winner for the same acknowledgement/step. Reuse durable immediate-delivery scheduling with resolution timeout expiry. - **Plan:** [Shared lifecycle plan and manual-action tasks](resolution-timeout-implementation-plan.md). Manual-action implementation is complete locally; PostgreSQL/deployed verification remains pending. -- **Verification needed:** Both OPEN/ACKNOWLEDGED paths from UI/email; early scheduled start with normal first-step delay; no-next-step and terminal restrictions; authorization/team isolation and recipient-token scope; read-only viewable links and email action eligibility before/at/after the relevant deadline; invalid/foreign/stale tokens and changed preview targets; duplicate confirmation before/after target delivery and actor audit; manual start versus automatic start/cancel/reschedule; manual escalation versus send/acknowledgement/resolution/timeout; delayed/stale callbacks; rollback and durable publication/restart recovery. +- **Verification needed:** Both OPEN/ACKNOWLEDGED paths from UI/email; immediate first email for idle, due scheduled, and early scheduled starts; first response window and later-step delay; no-next-step and terminal restrictions; authorization/team isolation and recipient-token scope; read-only viewable links and email action eligibility before/at/after the relevant deadline; invalid/foreign/stale tokens and changed preview targets; duplicate confirmation before/after target delivery and actor audit; manual start versus automatic start/cancel/reschedule; manual escalation versus send/acknowledgement/resolution/timeout; delayed/stale callbacks; rollback and durable publication/restart recovery. ### 5. Incident activity timeline @@ -111,7 +134,7 @@ Review these requirements in order. A checked **Requirements agreed** box means - **Agreed usability:** Show important milestones by default with plain wording. Group repeated failures/retries for the same step into a short summary with expandable attempt details and accurate retry counts; retain the full individual event history underneath. Keep timer housekeeping, stack traces, secrets, and raw tokens out of the timeline. Distinguish historical activity from the current step-progress display. - **Audit/API plan:** Reuse the generic audit service; save each event with its owning domain change. Preserve event context despite later flow edits, avoid duplicate successful events from repeated requests/callbacks, and expose a safe, paginated, same-team history API. Email action tokens do not grant access to full team history. - **Current state:** The audit service stores creation, scheduling, start, cancellation, notification acceptance/failure/retry, acknowledgement/deadline, manual escalation, resolution/timeout, start failure, and final exhaustion events. The same-team paginated history API exposes safe saved activity rows, and the escalation detail page now shows readable milestone history separately from current step progress, with grouped expandable retries and load-more support. PostgreSQL/deployed verification remains pending. -- **Local verification:** Focused audit/history coverage, UI build/lint, full Maven packaging, and diff checks pass. UI lint retains two pre-existing warnings in the flow detail page; browser/deployed verification and independent read-only verification remain unavailable. +- **Local verification:** Focused audit/history coverage, UI build/lint, full Maven packaging, and diff checks pass. UI lint retains two pre-existing warnings in the flow detail page; browser/deployed verification remains unavailable. - **Plan:** [Shared activity timeline design and tasks](resolution-timeout-implementation-plan.md#agreed-incident-activity-timeline). - **Verification needed:** Event coverage and rollback atomicity, email/system actors, repeated/stale operation safety, stable chronology, grouping/counts across pages, readable messages, safe metadata, flow-edit history preservation, authorization/team isolation, loading/empty/error/refresh states, and terminal history. Deployed verification stays deferred. @@ -183,6 +206,7 @@ The scheduling integration tests cover publication after commit, no publication ## Release check +- [x] Select and implement the public product identity using the [product rebranding plan](product-rebranding-plan.md). ReplyTrail is implemented locally; domain ownership, sender verification, and deployed rollout remain pending. Retain existing integration and storage identifiers during the initial rebrand. - [x] All four critical fixes above are complete locally. - [ ] A scheduled escalation that exhausts its start retries notifies the responsible user and team administrators. The pending notification survives an application crash and is recovered after restart. - [ ] Both product features work together in a deployed end-to-end run: webhook event → one task and run → email → recipient acknowledgement → no later step sent. diff --git a/docs/product-rebranding-plan.md b/docs/product-rebranding-plan.md new file mode 100644 index 0000000..20634d1 --- /dev/null +++ b/docs/product-rebranding-plan.md @@ -0,0 +1,165 @@ +# Product rebranding plan + +Created: 2026-10-08 +Status: In progress — ReplyTrail selected for the local public rebrand +Owner: Project owner +Release priorities: [Product launch checklist](product-launch-readiness.md) + +## Goal and product positioning + +Replace the AlertOps public identity with one consistent, easy-to-pronounce brand. +Describe the existing product as team response coordination: tasks and incoming +webhook events follow ordered email response paths with clear ownership, timing, +acknowledgement, resolution, and history. This includes operational alerts and +onboarding requests without promising unimplemented features. + +This initiative covers the product identity, UI, emails, maintained docs, and +release configuration. New notification channels, workflow features, a full UI +redesign, and internal infrastructure migrations are separate work. + +## Name and identity decisions + +Record these decisions here before implementing name-dependent changes: + +| Decision | Current state | Completion condition | +| --- | --- | --- | +| Product name and capitalization | **ReplyTrail** | Use this exact spelling in public UI, email, metadata, and current guidance | +| Primary domain and budget | Pending | Confirm registrar availability, first-year and renewal price, and control of the chosen domain | +| Repository slug and technical prefix | Pending; retain existing identifiers initially | Decide whether a later repository/artifact rename is needed | +| Positioning and tagline | Team response coordination; “Keep every response on track.” | Keep copy accurate to shipped behavior | +| Wordmark and favicon | Pending | Approve readable desktop/mobile/email variants using the existing visual style | +| Sender identity and public origins | Pending | Record verified email sender and UI/API URLs for each deployed environment | + +The name screen on 2026-10-08 found little indexed use of ReplyTrail, but +[`replytrail.com`](https://rdap.verisign.com/com/v1/domain/replytrail.com) and +[`replytrail.app`](https://pubapi.registry.google/rdap/domain/replytrail.app) were +already registered. Website content could not be verified. Do not treat the name +as unused or those domains as available. Recheck any chosen name before purchase +or public rollout, including relevant product, repository, package, and trademark +conflicts. ReplyTrail is approved for this local implementation. Domain ownership and +trademark clearance remain open before any public launch. + +## Decision compliance and canonical sources + +- Preserve the agreed lifecycle, manual actions, exact-step email tokens, shared + `FlowExecutionState.dueAt` wait boundary, and resolution window documented in + [the lifecycle plan](resolution-timeout-implementation-plan.md). PostgreSQL + remains authoritative; branding does not change saved statuses or timestamps. +- Preserve the task/run snapshot, webhook authentication and idempotency behavior + in [the webhook plan](webhook-escalation-implementation-plan.md) and the launch + checklist. Keep task, path, escalation, and response-step domain terminology. +- Preserve the separate frontend/backend deployment boundary in + [the UI plan](ui-implementation-plan.md#stack-and-deployment-boundary). +- Existing integration names remain canonical until a separately planned migration. + Do not introduce parallel headers, queues, databases, caches, or storage keys. +- Preserve historical changelog entries, archived plans, and applied Flyway files. + Update current guidance and code links rather than rewriting historical evidence. + +## Repository inventory and proposed treatment + +| Surface | Current source | Treatment | +| --- | --- | --- | +| Public identity and metadata | [Landing page](../ui/src/pages/PublicPage.tsx), [HTML entry](../ui/index.html), [favicon](../ui/public/favicon.svg) | Update wordmark, title, description, footer, and favicon; keep claims accurate | +| Signed-in and email-action pages | [App shell](../ui/src/components/AppShell.tsx), [auth pages](../ui/src/features/auth/AuthPages.tsx), [join page](../ui/src/features/teams/JoinTeamPage.tsx), [acknowledgement page](../ui/src/features/escalations/AcknowledgeEscalationPage.tsx), [Escalate now page](../ui/src/features/escalations/EscalateNowPage.tsx), [run detail](../ui/src/features/escalations/EscalationDetailPage.tsx), [404 page](../ui/src/App.tsx) | Update repeated branding, fallback labels, captions, system actor text, and safe errors | +| UI authentication coordination | [Session provider](../ui/src/app/Session.tsx), [API client](../ui/src/api/client.ts), auth/join pages above | Retain `alertops.token`, `alertops.team`, pending-invite/verification keys, and `alertops:unauthorized` | +| Outgoing email | [Notification](../src/main/java/com/alertops/messaging/Notification.java), [verification mailer](../src/main/java/com/alertops/messaging/EmailVerificationMailer.java), [invitation mailer](../src/main/java/com/alertops/messaging/TeamInvitationMailer.java) | Update subjects, HTML/plain text, headers/footers, and sender display name; preserve action behavior | +| External webhook contract | [Event controller](../src/main/java/com/alertops/webhook/controller/WebhookEventController.java), [CORS](../src/main/java/com/alertops/security/SecurityConfig.java), [API examples](../README.md) | Keep `X-AlertOps-Webhook-Secret`, routes, payloads, and secret handling compatible | +| Configuration and durable runtime identity | [Properties](../src/main/resources/application.properties), [environment example](../.env.example), [RabbitMQ configuration](../src/main/java/com/alertops/messaging/RabbitMqConfig.java), [intent cache](../src/main/java/com/alertops/caching/IntentCache.java), [webhook service](../src/main/java/com/alertops/webhook/service/WebhookService.java) | Retain `ALERTOPS_*`, `alertops.*`, queue/exchange/routing names, and Redis prefixes | +| Build and deployment identity | [Maven](../pom.xml), [Dockerfile](../Dockerfile), [Compose](../docker-compose.yml), [Kubernetes base](../k8s/base/), [CI](../.github/workflows/ci.yml) | Update human-readable descriptions; retain coordinates, `com.alertops` packages, resource names/selectors, volumes, and image paths initially | +| Current documentation | [README](../README.md), [UI README](../ui/README.md), [launch checklist](product-launch-readiness.md), [deployment guide](deployment/README.md), [agent instructions](../AGENTS.md) | Update current product references and explain retained compatibility identifiers | + +Several pages repeat the split wordmark markup. The initial implementation updates +those visible surfaces directly to `REPLY`/`TRAIL` and avoids introducing a new +abstraction for a fixed display name. Backend templates use their existing literal +copy, while technical configuration remains unchanged. HTML metadata and maintained +docs match the agreed spelling where the public identity is shown. + +## Ordered implementation tasks + +### 1. Settle the identity + +- [x] Select the public name, exact capitalization, and working tagline: ReplyTrail; + “Keep every response on track.” +- [ ] Select the domain, sender, and public URLs before deployment. +- [ ] Confirm domain ownership and record the compatibility identifiers to retain. +- [ ] Review a wordmark/favicon preview and representative page/email copy. +- **Done when:** the decision table is complete enough to implement without guessing. + +### 2. Rebrand the frontend + +- [x] Update the repeated wordmark and all visible surfaces listed above, including + the HTML title and description; the existing favicon has no old-name text. +- [x] Update landing-page footer/tagline copy to the team-response positioning while + preserving navigation, form labels, domain terminology, accessibility, and style. +- [x] Keep session storage and internal event identifiers unchanged. +- **Done when:** all relevant pages use the selected identity, including public action + pages and loading/error states, with no clipped wordmark on mobile or desktop. + +### 3. Rebrand notifications and maintained guidance + +- [x] Update verification, invitation, escalation, and scheduled-start-failure emails + in both HTML and available plain-text bodies; update their focused coverage. +- [x] Preserve recipient scopes, expiry, deliberate POST confirmation, and SMTP + acceptance semantics. Sender address changes require provider verification first. +- [x] Update maintained docs, project descriptions, and CI display labels. Document + old configuration/header names explicitly so examples remain executable. +- **Done when:** users see one brand across the UI and emails; existing integrations, + configured deployments, and current documentation examples still work. + +### 4. Verify and roll out + +- [x] Run focused rendering/notification and affected API tests, full builds, and a + search that classifies every remaining old-name reference as intended compatibility, + historical evidence, or an omission to fix. +- [ ] Verify the deployed UI → webhook → task/run → email → acknowledgement journey, + resolution/Escalate now links, invite/verification links, and restart recovery. +- [ ] Deploy through the existing release process, monitor, and record evidence in + the launch checklist and changelog. Keep local and deployed results separate. +- **Done when:** the acceptance criteria below are supported by evidence. + +## Domain cutover and rollback + +If an existing deployment changes domain, prepare DNS/TLS, approved CORS origins, +`VITE_API_BASE_URL`, `ALERTOPS_UI_BASE_URL`, and verified email sending before launch. +Record the actual old/new endpoints and immutable UI/backend release artifacts. +Keep the old API/webhook endpoint working; do not rely on redirects for webhook +POSTs. Preserve old UI deep links and query tokens through at least the longest +configured lifetime of already-issued verification, invitation, acknowledgement, +and manual-action links. Record a retirement date only after clients have moved. + +Browser session storage is origin-scoped: a domain change requires signing in and +selecting the team again; do not transfer authentication tokens through URLs. +Retaining existing storage keys avoids a forced session reset on the same origin. + +Rollback restores the previous UI/backend artifacts, origins, sender configuration, +and traffic routing. Keep old and new deep-link endpoints reachable for emails +sent by either release. Because the initial rebrand retains database, broker, +cache, resource, and package identifiers, rollback needs no data migration. Any +later technical rename must have its own dependency inventory and migration plan; +renaming namespaces or PVCs is not a cosmetic operation. + +## Acceptance criteria and intended verification + +- [ ] Exact name, capitalization, domain choice, copy, and assets are agreed and used + consistently in UI, emails, and current guidance; no unsupported feature claims. +- [ ] Brand changes preserve authentication, team isolation, navigation, webhook + compatibility, email token safety, lifecycle behavior, and saved execution state. +- [ ] Existing config/storage/queue/deployment identifiers are retained and documented; + old public endpoints and issued links survive any domain cutover. +- [ ] All residual AlertOps references are reviewed and classified; historical records + and applied migrations are preserved. +- [ ] Local UI build/lint, focused backend tests, and full Maven verification pass; + deployed smoke checks and rollback are proven + before release readiness is marked complete. + +Implementation commands: `npm --prefix ui run build`, `npm --prefix ui run lint`, +`./mvnw -Dtest=NotificationTest,EmailVerificationServiceTest,TeamInvitationServiceTest test`, +and `./mvnw --batch-mode --no-transfer-progress clean verify`. Add focused email +rendering coverage where current service tests do not exercise the changed content. +Run `git diff --check`; search tracked sources with +`git grep -n -i -E 'alertops|alert_ops|alert-ops'` and separately inspect split wordmarks. + +Current outcome: ReplyTrail is implemented across the local public identity surfaces, +email templates, metadata, and current guidance. Application/API/storage/deployment +identifiers remain unchanged; domain ownership, sender verification, deployed smoke +checks, and rollback evidence are still pending. diff --git a/docs/recurring-escalation-implementation-plan.md b/docs/recurring-escalation-implementation-plan.md new file mode 100644 index 0000000..de90e13 --- /dev/null +++ b/docs/recurring-escalation-implementation-plan.md @@ -0,0 +1,163 @@ +# Recurring escalation implementation plan + +Created: 2026-10-11 +Updated: 2026-10-11 — minimum first version. +Status: Implemented locally; deployment verification remains pending. + +## Minimum scope + +Add repetition to an escalation without a new table or scheduling subsystem. +The original escalation is the first run and owns repetition. Every later +occurrence has a new ID and independent steps, emails, acknowledgement, and +resolution. Runs may overlap; completion of an earlier run does not block repeats. + +Use these defaults instead of another requirements-agreement phase: + +- Support NONE, DAILY, and WEEKLY. Repeat every calendar day or week, not after + the previous run completes. +- Enable recurrence only with Schedule for later. Use its future local date/time + and IANA timezone. Existing immediate and one-time starts remain unchanged. +- Repeat until stopped. Stopping prevents future creation; existing runs, + including the original, continue independently. +- After downtime or a delayed callback, create only the latest missed repeat, + then advance to the next future occurrence. Do not replay a backlog. Saved + SCHEDULED runs still recover through the existing start scheduler. +- Future runs reuse the original task/path references and current start behavior. + Started response steps keep their existing execution snapshots. +- Failed occurrences use existing scheduled-start retries and START_FAILED + notifications. Repetition continues; do not add automatic series-pausing logic. +- Start now and cancel affect one run only. Do not allow rescheduling a recurring + original or generated run in this version; preserve the calendar anchor and + occurrence identity. Ordinary one-time rescheduling remains available. + +The [launch checklist](product-launch-readiness.md#1-scheduled-escalation-start) +tracks this extension separately from the existing one-time baseline. Defining +this scope does not claim implementation or release readiness. Deployment is last. + +## Storage and ownership + +Add only three fields to the existing Escalation table: + +| Field | Meaning | +| --- | --- | +| repeatType | String-persisted enum: NONE, DAILY, WEEKLY. No separate repeat boolean. | +| nextRepeatAt | Nullable UTC Instant on the original. Non-null means enabled; null means no future repeats. | +| repeatSourceId | Nullable self-reference to the original. Set only on generated runs. | + +The original has no repeatSourceId. Generated runs have repeatType = NONE and +nextRepeatAt = null, so they cannot create their own repeating chains. +Stopping clears nextRepeatAt but retains the rule and historical links. +EscalationStatus describes only the run; do not add a separate repeat status. + +Reuse the original scheduledStartAt and scheduleTimezone as the calendar anchor. +Never overwrite that start time with nextRepeatAt, or add another anchor field. +Each generated run's scheduledStartAt is its own intended occurrence instant. +Calculate from the original local wall time, not callback completion or fixed +24-hour UTC additions. Use injected Clock and UTC Instants for actual moments. + +For daylight saving, reject a nonexistent initial local time so the saved anchor +is unambiguous; choose the earlier offset for an ambiguous time. For later +occurrences in a gap, shift forward by the gap without changing the original +anchor. These are fixed defaults, not additional configurable options. + +Default existing rows to NONE. Add enum/field-combination constraints, a +non-cascading self-reference, indexes for repeat recovery/source lookup, and +uniqueness on (repeatSourceId, scheduledStartAt) for generated rows. +Generated rows must link directly to the same-team original and cannot repeat. + +## Execution and recovery + +1. Extend existing scheduling to save the original's first-start schedule, + repeatType, nextRepeatAt, and audit atomically. Register first-start and + repeat timers only after commit. +2. A repeat callback reloads and locks the original. Check that repetition is + enabled and the expected nextRepeatAt is current and due. Ignore stale or + duplicate callbacks. The original need not still be SCHEDULED or OPEN. +3. In one transaction, create a fresh SCHEDULED child for the selected occurrence, + set its source and non-repeating fields, advance the original's nextRepeatAt, + and audit creation. The row lock and uniqueness guard duplicate creation. +4. After commit, register the child's start with the existing start scheduler + and the original's next repeat timer. Reuse existing execution and immediate + first-email behavior; do not add another start or notification engine. +5. Stop repetition under the same original-row lock, clear nextRepeatAt, and audit + it. Cancel only the repeat timer after commit. If child creation already + committed, that child continues. Repeated stop is idempotent. + +Internal child creation accepts already-due timestamps; do not call the public +future-only scheduling API. Background work uses the saved team/scheduling actor, +not request-thread authentication. + +Startup recovers original rows with a non-NONE rule and non-null nextRepeatAt +regardless of their run status, including COMPLETED, RESOLVED, CANCELLED, and +START_FAILED. Recover saved SCHEDULED children through the existing scheduler. +A crash after commit but before registration must lose neither obligation. + +Keep only cancellable timer handles in memory. Use bounded failure-triggered +retry and startup recovery; no healthy periodic scan, extra outbox, dependency, +or duplicate database-owned state. The existing [single-process timer baseline](in-memory-timer-implementation-plan.md) +still applies. Stop-repeat may update metadata on a terminal original, never its +run outcome or response history. + +## Minimal API and UI + +- Add repeatType to the existing Schedule for later request. Return repeat fields + through existing escalation list/detail responses. +- Add one same-team stop-repeat action on the original. Recipient email tokens + cannot control repetition. Reuse existing validation and audit conventions. +- Add a repeat selector to the existing scheduling form. Show repeat type, + next repeat time, and Stop future repeats on the original's detail screen. + Explain that cancelling one run does not stop repeats, and stopping repeats + does not cancel saved runs. +- Generated runs remain in the existing paginated escalation list, with a link + to the original. Keep growing lists scrollable. No separate history API/view, + preview endpoint, schedule-management screen, or email redesign. + +## Implementation tasks + +1. [x] Add the three fields, migration/constraints, enum, and calendar calculation. +2. [x] Extend existing scheduling/read APIs; add atomic child creation and stop-repeat. +3. [x] Connect repeat timers, after-commit registration, failure retry, and recovery. +4. [x] Add the selector, repeat context, source link, and stop action to existing UI. +5. [x] Run focused tests, normal backend build, UI tests/build/lint, and retain + the existing one-time behavior. +6. [ ] Run PostgreSQL integration checks, then validate database/broker/SMTP + behavior and restarts in deployment last; + update launch readiness only with evidence. + +Local verification includes the calendar unit test, backend test compilation and +packaging, UI build, UI lint, and diff checks. Mockito-backed service tests could +not execute because Byte Buddy self-attachment is unavailable in this local +environment. PostgreSQL integration and deployed checks remain pending. + +## Required verification + +- Daily/weekly timezone calculations and DST defaults are deterministic. +- Duplicate/stale callbacks create one child; generated rows never repeat. +- Runs overlap safely; acknowledgement/resolution of one cannot affect another. +- Child creation and calendar advancement roll back together; restart after + commit recovers both the child start and next repeat. +- Recovery includes terminal originals, handles only the latest missed repeat, + and ignores stopped repetition. Saved child starts/retries still recover. +- Stop/create races have one winner; repeated stop adds no duplicate audit. +- Timer/database failure retries do not lose repeats or change the anchor. +- Team isolation, missing references, invalid inputs, and source-link null paths + are covered. Missing/deleted references use existing START_FAILED handling. +- First email, start-now/cancel isolation, and ordinary one-time scheduling, + rescheduling, cancellation, retries, and lifecycle behavior remain correct. + +## Deferred improvements + +Monthly/yearly repeats; custom intervals; immediate recurring starts; editing, +pause/resume; end dates/counts; backlog replay; automatic stop on persistent +failure; frozen task/path definitions; independently rescheduling recurring runs; +occurrence previews; grouped history/filtering and a dedicated recurrence screen. + +Implement these only when needed, as separate tasks. No additional approval +matrix or placeholder fields are required for the minimum version. + +## Existing implementation references + +- [Escalation model](../src/main/java/com/alertops/flow_execution_engine/model/Escalation.java) +- [Existing schedule operations](../src/main/java/com/alertops/flow_execution_engine/service/EscalationService.java) +- [Start scheduler and recovery](../src/main/java/com/alertops/flow_execution_engine/service/EscalationStartScheduler.java) +- [Shared start use case](../src/main/java/com/alertops/flow_execution_engine/application/StartFlowExecutionUseCase.java) diff --git a/docs/resolution-timeout-implementation-plan.md b/docs/resolution-timeout-implementation-plan.md index ee49de3..39d2ff6 100644 --- a/docs/resolution-timeout-implementation-plan.md +++ b/docs/resolution-timeout-implementation-plan.md @@ -9,7 +9,7 @@ Release priorities: [scheduled starts](product-launch-readiness.md#1-scheduled-e ## Agreed manual actions -**Start now begins the workflow.** It starts an `IDLE` run as today and also lets a team member start a `SCHEDULED` run before its saved start time. The first step keeps its configured delay. Reuse the existing start API and start use case; no extra public early-start endpoint is needed. +**Start now begins the workflow.** It starts an `IDLE` run as today and also lets a team member start a `SCHEDULED` run before its saved start time. The first response email is sent immediately; its configured duration becomes the response window after delivery. Reuse the existing start API and start use case; no extra public early-start endpoint is needed. **Escalate now removes the next notification's wait.** In `OPEN`, make the next eligible unsent step due immediately, whether it is scheduled or still pending. In `ACKNOWLEDGED`, end the resolution waiting period, return to `OPEN`, and make the next eligible paused step due immediately. Ask for confirmation in the acknowledged case because someone is already working on the issue. Advance in saved step order, without jumping over unfinished steps or resending a sent notification. If there is no next eligible step, the action is unavailable and makes no state change. @@ -17,8 +17,8 @@ Start now and the signed-in Escalate now action remain restricted to authenticat | Starting situation | Action | Result | | --- | --- | --- | -| Run is `IDLE` | Start now | `OPEN`; schedule first step with its usual delay | -| Run is `SCHEDULED` | Start now | `OPEN` early; schedule first step with its usual delay; cancel start timer after commit | +| Run is `IDLE` | Start now | `OPEN`; send the first response email immediately | +| Run is `SCHEDULED` | Start now | `OPEN` early; send the first response email immediately; cancel start timer after commit | | Run is `OPEN`, next step is waiting | Escalate now | Run stays `OPEN`; next eligible step becomes due immediately | | Run is `ACKNOWLEDGED`, next step is paused | Escalate now | Run becomes `OPEN`; end active resolution wait; next step becomes due immediately | | Run is terminal or no next step exists | Escalate now | Unavailable; no state change | @@ -139,7 +139,8 @@ with resolution enabled pauses progression and starts the resolution duration from the acknowledgement time. Unresolved resolution expiry makes the next step due immediately; do not restart the acknowledgement/delivery wait. Do not stack two ordinary waits, compare independent acknowledgement/send delays, add a third -duration, or introduce a special final-node timeout. Retain the existing first-step +duration, or introduce a special final-node timeout. Send the first response email +immediately and use its configured duration as the first response window. delay; align runtime ownership/deadline storage with this shared wait during implementation. ## Agreed viewable links and action deadlines @@ -210,7 +211,7 @@ Keep the disabled-flow path unchanged apart from explicit step-state representat ## Timer and concurrency contract -1. Ordinary progression uses one shared acknowledgement/delivery wait. After SMTP acceptance, persist the sent step and the canonical shared wait boundary atomically, aligning the next eligible delivery's `dueAt` with that same wait rather than adding another delay. Do not exhaust solely because this was the final send; persist its normal acknowledgement wait too. Keep the initial first-step delay unchanged. +1. Ordinary progression uses one shared acknowledgement/delivery wait. After SMTP acceptance, persist the sent step and the canonical shared wait boundary atomically, aligning the next eligible delivery's `dueAt` with that same wait rather than adding another delay. Do not exhaust solely because this was the final send; persist its normal acknowledgement wait too. The first response email is sent immediately; its configured duration starts the first response window after SMTP acceptance. 2. Acknowledgement locks the run and validates the exact sent step/token. With timeout enabled, atomically save `ACKNOWLEDGED`, the owning step, the deadline, and the paused next step. 3. After commit, cancel its delivery wake-up where available and register the resolution timer. A delivery callback/message already in flight must reload state and ignore paused or obsolete attempts. 4. Resolution, timeout, and manual escalation use the same run-lock/conditional-transition boundary. Only one valid transition wins for the same acknowledgement/step. Publish timer changes or delivery work after commit, never on rollback. @@ -242,7 +243,7 @@ This prerequisite is complete. Manual-action and activity-timeline behavior rema ### 2. Support Start now for scheduled runs - [x] Extend the existing manual start API/use case and conditional claim; reuse step creation and add after-commit start-timer cancellation, actor audit, and the scheduled-run UI action. -- Acceptance: early start produces one execution-state set, retains the first-step delay, and rolls back without losing the original schedule on failure. Automatic due-time gating remains enforced. Test manual/automatic starts, cancellation/reschedule races, duplicate starts, stale timer callbacks, and team isolation. +- Acceptance: early start produces one execution-state set, sends the first response email immediately, and rolls back without losing the original schedule on failure. Automatic due-time gating remains enforced. Test manual/automatic starts, cancellation/reschedule races, duplicate starts, stale timer callbacks, and team isolation. - This focused task can proceed independently of the remaining resolution decisions when selected by the user. - **Local implementation evidence:** The existing `POST /{escalationId}/start` accepts same-team `SCHEDULED` runs, uses a conditional early-start claim, records the authenticated actor, and cancels the scheduler handle after the transactional start returns. The UI exposes **Start now** for scheduled runs. Focused start/controller/scheduling tests, backend packaging, and the UI build pass. PostgreSQL/deployed verification remains pending. @@ -254,7 +255,7 @@ This prerequisite is complete. Manual-action and activity-timeline behavior rema ### 4. Add agreed flow/node timing configuration -- [x] Implement the flow toggle and the agreed two node response durations, API validation, consistent configuration updates, and flow-editor controls. Reuse the existing duration for the shared acknowledgement/delivery wait; add no separate send-delay control. Use the same response controls/rules for first, middle, and last nodes, retaining the initial first-step delay. +- [x] Implement the flow toggle and the agreed two node response durations, API validation, consistent configuration updates, and flow-editor controls. Reuse the existing duration for the shared acknowledgement/delivery wait; add no separate send-delay control. Use the same response controls/rules for first, middle, and last nodes, with the first response email sent immediately. - Acceptance: disabled flows have null resolution timeouts; enabled flows have positive resolution timeouts on every node; the configuration update is all-or-nothing under the flow version; and no final-only setting is introduced. Runtime acknowledgement, snapshot, and expiry behavior remain in later tasks. - **Local implementation evidence:** Migration V12 stores the flow toggle and nullable positive node timeout. `PUT /api/v1/flow/{flowId}/timing` requires the current flow version and validates the complete node set before saving. Node create/edit requests apply the same enabled/disabled rules, and the flow editor exposes the toggle plus per-node timeout controls. Focused flow-service tests cover enable/disable, partial input, stale versions, and node-level validation. @@ -268,19 +269,19 @@ This prerequisite is complete. Manual-action and activity-timeline behavior rema - [x] Branch on the saved toggle, invalidate the acknowledgement wait, pause the next step if present, save the resolution deadline, and record lifecycle audit data atomically. Emit wake-up changes after commit. - Acceptance: disabled acknowledgement still completes; enabled acknowledgement pauses even on the final node; repeated acknowledgement does not extend the deadline; a stale send cannot bypass the pause. -- **Local implementation evidence (2026-10-06):** `EscalationAcknowledgementService` locks the run, validates the exact `SENT` step and current sent-step token, keeps disabled acknowledgement terminal as `COMPLETED` / `ACKNOWLEDGED`, and changes enabled acknowledgement to `ACKNOWLEDGED` with the saved step timeout, owner, deadline, and `ACKNOWLEDGED` audit event. The next unsent step is changed to `PAUSED` without changing its canonical shared `dueAt`; its in-memory wake-up is cancelled after commit. Final successful sends remain `OPEN` so the final recipient can acknowledge. Focused acknowledgement, consumer, and timer tests pass; the full Maven suite passes with PostgreSQL/RabbitMQ/Redis integration tests environment-gated and skipped. Independent read-only verifier verdict: **Achieved**. Deadline expiry/recovery, explicit resolution, and deployed verification remain later tasks. +- **Local implementation evidence (2026-10-06):** `EscalationAcknowledgementService` locks the run, validates the exact `SENT` step and current sent-step token, keeps disabled acknowledgement terminal as `COMPLETED` / `ACKNOWLEDGED`, and changes enabled acknowledgement to `ACKNOWLEDGED` with the saved step timeout, owner, deadline, and `ACKNOWLEDGED` audit event. The next unsent step is changed to `PAUSED` without changing its canonical shared `dueAt`; its in-memory wake-up is cancelled after commit. Final successful sends remain `OPEN` so the final recipient can acknowledge. Focused acknowledgement, consumer, and timer tests pass; the full Maven suite passes with PostgreSQL/RabbitMQ/Redis integration tests environment-gated and skipped. Deadline expiry/recovery, explicit resolution, and deployed verification remain later tasks. ### 7. Implement explicit resolution - [x] Add the agreed resolve action, actor/time persistence, idempotency, authorization, skipped steps, audit, and after-commit timer cancellation. - Acceptance: authenticated same-team members and the current acknowledging email recipient can resolve before the saved deadline; another team or an obsolete email owner cannot. Terminal runs stay terminal; resolution and timeout have one winner. No new role/state is introduced. -- **Local implementation evidence (2026-10-07):** `EscalationResolutionService` exposes separate team-member and recipient-token operations, locks the run, enforces the saved resolution deadline and current acknowledgement owner, transitions `ACKNOWLEDGED → RESOLVED`, persists resolving actor/time, clears active acknowledgement ownership, skips pending/scheduled/paused steps, records a `RESOLVED` audit event with the pre-clear step/source/token-hash facts, and cancels step wake-ups after commit. Recipient action eligibility uses the saved resolution deadline rather than token TTL; repeated recipient resolution requires the exact saved token hash plus the accepted step/source recorded in the resolution audit. Repeated same-actor resolution returns the saved result without another write; foreign-team, obsolete-token, late, terminal, and anonymous team requests are rejected. Focused service/controller/security tests pass; independent read-only review was **Inconclusive** only for PostgreSQL/deployed concurrency and rollback because those checks are environment-gated. Deadline expiry/recovery and UI remain later work. +- **Local implementation evidence (2026-10-07):** `EscalationResolutionService` exposes separate team-member and recipient-token operations, locks the run, enforces the saved resolution deadline and current acknowledgement owner, transitions `ACKNOWLEDGED → RESOLVED`, persists resolving actor/time, clears active acknowledgement ownership, skips pending/scheduled/paused steps, records a `RESOLVED` audit event with the pre-clear step/source/token-hash facts, and cancels step wake-ups after commit. Recipient action eligibility uses the saved resolution deadline rather than token TTL; repeated recipient resolution requires the exact saved token hash plus the accepted step/source recorded in the resolution audit. Repeated same-actor resolution returns the saved result without another write; foreign-team, obsolete-token, late, terminal, and anonymous team requests are rejected. Focused service/controller/security tests pass; PostgreSQL/deployed concurrency and rollback remain environment-gated. Deadline expiry/recovery and UI remain later work. ### 8. Implement deadline expiry and recovery - [x] Persist the acknowledgement wait after a successful send instead of immediate final-send exhaustion. Use shared deadline handling with current-owner validation, running-process retry, startup recovery, and the advance-or-exhaust branch; reuse durable publication machinery. - Acceptance: acknowledgement expiry continues or exhausts under the agreed timing mapping; resolution expiry makes the next step due immediately in all original-due-time comparisons or exhausts if none exists. No extra last-node logic, fresh wait after restart, automatic resend, or duplicate transition; failed publication remains recoverable. -- **Local implementation evidence (2026-10-07):** Successful sends persist the next step's `dueAt` as the current acknowledgement boundary; final sends persist their node wait and register a recoverable deadline. POST acknowledgement validates that boundary, cancels the final acknowledgement wake-up after commit, and schedules the saved resolution deadline. Expiry reloads and locks the run/step, exhausts final acknowledgement or resolution waits, and reopens a paused/pending next step with `dueAt=now` for earlier, equal, and later original due times. Deadline wake-ups recover saved final/resolution boundaries after restart, while durable publication recovery handles broker/database failures. Focused expiry/wake-up-scheduler/consumer/acknowledgement tests and the full local suite (190 tests, 0 failures/errors, 17 environment-gated skips) pass; PostgreSQL/deployed concurrency, rollback, and restart checks remain environment-gated, and no independent read-only subagent was available in this session. +- **Local implementation evidence (2026-10-07):** Successful sends persist the next step's `dueAt` as the current acknowledgement boundary; final sends persist their node wait and register a recoverable deadline. POST acknowledgement validates that boundary, cancels the final acknowledgement wake-up after commit, and schedules the saved resolution deadline. Expiry reloads and locks the run/step, exhausts final acknowledgement or resolution waits, and reopens a paused/pending next step with `dueAt=now` for earlier, equal, and later original due times. Deadline wake-ups recover saved final/resolution boundaries after restart, while durable publication recovery handles broker/database failures. Focused expiry/wake-up-scheduler/consumer/acknowledgement tests and the full local suite (190 tests, 0 failures/errors, 17 environment-gated skips) pass; PostgreSQL/deployed concurrency, rollback, and restart checks remain environment-gated. ### 9. Implement Escalate now diff --git a/docs/ui-implementation-plan.md b/docs/ui-implementation-plan.md index 509df49..9e103c1 100644 --- a/docs/ui-implementation-plan.md +++ b/docs/ui-implementation-plan.md @@ -1,8 +1,8 @@ -# AlertOps UI implementation plan +# ReplyTrail UI implementation plan ## Goal -Build an independently deployed web app that lets users run the AlertOps workflow: sign in, choose a team, create a task, configure an ordered escalation flow, start an escalation, and inspect its progress. This document records the initial UI implementation scope; the project goal is a production-ready product, with current release priorities in [the product launch checklist](product-launch-readiness.md). Every displayed status must come from the API; explanatory diagrams may describe the architecture but must be labeled as explanations. +Build an independently deployed web app that lets users run the ReplyTrail workflow: sign in, choose a team, create a task, configure an ordered escalation flow, start an escalation, and inspect its progress. This document records the initial UI implementation scope; the project goal is a production-ready product, with current release priorities in [the product launch checklist](product-launch-readiness.md). Every displayed status must come from the API; explanatory diagrams may describe the architecture but must be labeled as explanations. ## Stack and deployment boundary @@ -65,7 +65,7 @@ The follow-on backend and UI tickets are in [Team management UI task list](team- | Route | Page | Main content | | --- | --- | --- | -| `/` | Public overview | What AlertOps does; concise architecture diagram; sign-in CTA; explain SMTP email requirements and the meaning of `SENT`. | +| `/` | Public overview | What ReplyTrail does; concise architecture diagram; sign-in CTA; explain SMTP email requirements and the meaning of `SENT`. | | `/register`, `/login` | Authentication | Simple forms with visible API errors; unverified users are sent to the verification screen after login. | | `/verify-email?token=...` | Email verification | Confirm the one-time link with an explicit `POST`, request another link for the entered email, and continue to teams or an invitation. | | `/teams` | Team picker | List teams, create team, select team. After create, select the new team automatically. | diff --git a/docs/webhook-escalation-implementation-plan.md b/docs/webhook-escalation-implementation-plan.md index a2d3d55..7df24b4 100644 --- a/docs/webhook-escalation-implementation-plan.md +++ b/docs/webhook-escalation-implementation-plan.md @@ -5,7 +5,7 @@ Source audit: 2026-10-06. Track inspected progress and remaining release checks [Feature 2 of the launch checklist](product-launch-readiness.md#feature-2-create-and-start-an-escalation-through-a-webhook). This plan describes the target behavior, not proof that every item is implemented. -A team chooses a default response path for a webhook. When an external system sends a valid event, AlertOps creates one task, starts one run, and saves the complete JSON event for later viewing. A request can optionally choose a different path from the same team. +A team chooses a default response path for a webhook. When an external system sends a valid event, ReplyTrail creates one task, starts one run, and saves the complete JSON event for later viewing. A request can optionally choose a different path from the same team. ## Task fields diff --git a/pom.xml b/pom.xml index c84ed61..1eb26ce 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,7 @@ alertops 0.0.1-SNAPSHOT alertops - AlertOps backend service + ReplyTrail backend service 17 diff --git a/src/main/java/com/alertops/audit/model/AuditAction.java b/src/main/java/com/alertops/audit/model/AuditAction.java index 4e0c354..ff5bb7d 100644 --- a/src/main/java/com/alertops/audit/model/AuditAction.java +++ b/src/main/java/com/alertops/audit/model/AuditAction.java @@ -5,6 +5,8 @@ public enum AuditAction { CREATED, SCHEDULED, RESCHEDULED, + REPEAT_CREATED, + REPEAT_STOPPED, STARTED, CANCELLED, START_FAILED, diff --git a/src/main/java/com/alertops/flow_execution_engine/controller/EscalationController.java b/src/main/java/com/alertops/flow_execution_engine/controller/EscalationController.java index 9b6236f..4f95fcf 100644 --- a/src/main/java/com/alertops/flow_execution_engine/controller/EscalationController.java +++ b/src/main/java/com/alertops/flow_execution_engine/controller/EscalationController.java @@ -102,4 +102,11 @@ public ResponseEntity cancel(@PathVariable UUID escalationId) { return escalation == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(escalation); } + // Stops future daily or weekly runs while keeping existing runs available. + @PostMapping("/{escalationId}/stop-repeat") + public ResponseEntity stopRepeat(@PathVariable UUID escalationId) { + var escalation = escalationService.stopRepeating(escalationId); + return escalation == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(escalation); + } + } diff --git a/src/main/java/com/alertops/flow_execution_engine/dto/ScheduledEscalationRequest.java b/src/main/java/com/alertops/flow_execution_engine/dto/ScheduledEscalationRequest.java index 601045b..b87f42b 100644 --- a/src/main/java/com/alertops/flow_execution_engine/dto/ScheduledEscalationRequest.java +++ b/src/main/java/com/alertops/flow_execution_engine/dto/ScheduledEscalationRequest.java @@ -3,11 +3,14 @@ import java.time.LocalDate; import java.time.LocalTime; +import com.alertops.flow_execution_engine.model.RepeatType; + /** Local schedule fields supplied by the UI; the service converts them to UTC. */ public class ScheduledEscalationRequest { private LocalDate scheduleDate; private LocalTime scheduleTime; private String timezone; + private RepeatType repeatType = RepeatType.NONE; public LocalDate getScheduleDate() { return scheduleDate; @@ -32,4 +35,14 @@ public String getTimezone() { public void setTimezone(String timezone) { this.timezone = timezone; } + + // Returns the requested daily or weekly calendar rule. + public RepeatType getRepeatType() { + return repeatType; + } + + // Stores the requested calendar rule from the API boundary. + public void setRepeatType(RepeatType repeatType) { + this.repeatType = repeatType; + } } diff --git a/src/main/java/com/alertops/flow_execution_engine/messaging/EscalationRepeatSchedule.java b/src/main/java/com/alertops/flow_execution_engine/messaging/EscalationRepeatSchedule.java new file mode 100644 index 0000000..ab98405 --- /dev/null +++ b/src/main/java/com/alertops/flow_execution_engine/messaging/EscalationRepeatSchedule.java @@ -0,0 +1,8 @@ +package com.alertops.flow_execution_engine.messaging; + +import java.time.Instant; +import java.util.UUID; + +/** Requests an in-memory wake-up for the original escalation's next repeat. */ +public record EscalationRepeatSchedule(UUID escalationId, Instant nextRepeatAt) { +} diff --git a/src/main/java/com/alertops/flow_execution_engine/messaging/EscalationRepeatStopped.java b/src/main/java/com/alertops/flow_execution_engine/messaging/EscalationRepeatStopped.java new file mode 100644 index 0000000..5843aea --- /dev/null +++ b/src/main/java/com/alertops/flow_execution_engine/messaging/EscalationRepeatStopped.java @@ -0,0 +1,7 @@ +package com.alertops.flow_execution_engine.messaging; + +import java.util.UUID; + +/** Requests cancellation of an original escalation's repeat wake-up. */ +public record EscalationRepeatStopped(UUID escalationId) { +} diff --git a/src/main/java/com/alertops/flow_execution_engine/model/Escalation.java b/src/main/java/com/alertops/flow_execution_engine/model/Escalation.java index a5d3805..8a07acd 100644 --- a/src/main/java/com/alertops/flow_execution_engine/model/Escalation.java +++ b/src/main/java/com/alertops/flow_execution_engine/model/Escalation.java @@ -55,6 +55,16 @@ public class Escalation { private String scheduleTimezone; + @Enumerated(EnumType.STRING) + @Column(name = "repeat_type", nullable = false) + private RepeatType repeatType = RepeatType.NONE; + + @Column(name = "next_repeat_at") + private Instant nextRepeatAt; + + @Column(name = "repeat_source_id") + private UUID repeatSourceId; + @Column(name = "scheduled_start_retry_count", nullable = false) private int scheduledStartRetryCount; @@ -215,6 +225,36 @@ public void setScheduleTimezone(String scheduleTimezone) { this.scheduleTimezone = scheduleTimezone; } + // Returns the calendar rule owned by the original escalation. + public RepeatType getRepeatType() { + return repeatType; + } + + // Stores the calendar rule for this escalation row. + public void setRepeatType(RepeatType repeatType) { + this.repeatType = repeatType; + } + + // Returns the next repeat boundary that has not been materialized. + public Instant getNextRepeatAt() { + return nextRepeatAt; + } + + // Stores the next durable repeat boundary. + public void setNextRepeatAt(Instant nextRepeatAt) { + this.nextRepeatAt = nextRepeatAt; + } + + // Returns the original escalation ID for a generated occurrence. + public UUID getRepeatSourceId() { + return repeatSourceId; + } + + // Links a generated occurrence to its original escalation. + public void setRepeatSourceId(UUID repeatSourceId) { + this.repeatSourceId = repeatSourceId; + } + public int getScheduledStartRetryCount() { return scheduledStartRetryCount; } diff --git a/src/main/java/com/alertops/flow_execution_engine/model/RepeatType.java b/src/main/java/com/alertops/flow_execution_engine/model/RepeatType.java new file mode 100644 index 0000000..ac932a4 --- /dev/null +++ b/src/main/java/com/alertops/flow_execution_engine/model/RepeatType.java @@ -0,0 +1,8 @@ +package com.alertops.flow_execution_engine.model; + +/** Calendar repeat options supported by a scheduled escalation. */ +public enum RepeatType { + NONE, + DAILY, + WEEKLY +} diff --git a/src/main/java/com/alertops/flow_execution_engine/repository/EscalationRepository.java b/src/main/java/com/alertops/flow_execution_engine/repository/EscalationRepository.java index 1cf82b5..f43c75c 100644 --- a/src/main/java/com/alertops/flow_execution_engine/repository/EscalationRepository.java +++ b/src/main/java/com/alertops/flow_execution_engine/repository/EscalationRepository.java @@ -49,6 +49,15 @@ public interface EscalationRepository extends JpaRepository { """) List findAllScheduled(); + @Query(""" + select e from Escalation e + where e.repeatType <> com.alertops.flow_execution_engine.model.RepeatType.NONE + and e.nextRepeatAt is not null + order by e.nextRepeatAt asc, e.id asc + """) + // Finds original escalations whose next repeat still needs a wake-up. + List findAllRepeating(); + @Modifying @Query(""" UPDATE Escalation e diff --git a/src/main/java/com/alertops/flow_execution_engine/service/EscalationRepeatCalculator.java b/src/main/java/com/alertops/flow_execution_engine/service/EscalationRepeatCalculator.java new file mode 100644 index 0000000..e230d06 --- /dev/null +++ b/src/main/java/com/alertops/flow_execution_engine/service/EscalationRepeatCalculator.java @@ -0,0 +1,86 @@ +package com.alertops.flow_execution_engine.service; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +import com.alertops.flow_execution_engine.model.RepeatType; + +/** Calculates daily and weekly repeats from the original local calendar time. */ +public class EscalationRepeatCalculator { + + // Returns the first repeat strictly after the supplied instant. + public Instant nextAfter(Instant originalStart, String timezone, RepeatType repeatType, Instant after) { + validateInputs(originalStart, timezone, repeatType, after); + if (repeatType == RepeatType.NONE) { + return null; + } + + ZoneId zone = ZoneId.of(timezone); + ZonedDateTime original = originalStart.atZone(zone); + LocalDateTime candidate = original.toLocalDateTime(); + LocalDateTime localAfter = after.atZone(zone).toLocalDateTime(); + long daysFromOriginal = ChronoUnit.DAYS.between(original.toLocalDate(), localAfter.toLocalDate()); + long interval = repeatType == RepeatType.DAILY ? 1 : 7; + long periods = Math.max(0, Math.floorDiv(daysFromOriginal, interval)); + candidate = candidate.plusDays(periods * interval); + + Instant candidateInstant = resolve(candidate, zone); + while (!candidateInstant.isAfter(after)) { + candidate = candidate.plusDays(interval); + candidateInstant = resolve(candidate, zone); + } + return candidateInstant; + } + + // Returns the latest repeat at or before now, or empty before the first repeat. + public Optional latestAtOrBefore( + Instant originalStart, String timezone, RepeatType repeatType, Instant now) { + validateInputs(originalStart, timezone, repeatType, now); + if (repeatType == RepeatType.NONE) { + return Optional.empty(); + } + + ZoneId zone = ZoneId.of(timezone); + ZonedDateTime original = originalStart.atZone(zone); + LocalDateTime localNow = now.atZone(zone).toLocalDateTime(); + long daysFromOriginal = ChronoUnit.DAYS.between(original.toLocalDate(), localNow.toLocalDate()); + long interval = repeatType == RepeatType.DAILY ? 1 : 7; + if (daysFromOriginal < interval) { + return Optional.empty(); + } + + long periods = Math.floorDiv(daysFromOriginal, interval); + LocalDateTime candidate = original.toLocalDateTime().plusDays(periods * interval); + Instant candidateInstant = resolve(candidate, zone); + while (candidateInstant.isAfter(now)) { + candidate = candidate.minusDays(interval); + candidateInstant = resolve(candidate, zone); + } + return candidate.toLocalDate().isBefore(original.toLocalDate()) + ? Optional.empty() + : Optional.of(candidateInstant); + } + + // Applies the fixed DST policy for future calendar occurrences. + private Instant resolve(LocalDateTime localDateTime, ZoneId zone) { + List offsets = zone.getRules().getValidOffsets(localDateTime); + if (offsets.isEmpty()) { + return localDateTime.atZone(zone).toInstant(); + } + return localDateTime.toInstant(offsets.get(0)); + } + + // Rejects incomplete calculator inputs before applying a calendar rule. + private void validateInputs(Instant originalStart, String timezone, RepeatType repeatType, Instant reference) { + Objects.requireNonNull(originalStart, "originalStart"); + Objects.requireNonNull(timezone, "timezone"); + Objects.requireNonNull(repeatType, "repeatType"); + Objects.requireNonNull(reference, "reference"); + } +} diff --git a/src/main/java/com/alertops/flow_execution_engine/service/EscalationRepeatService.java b/src/main/java/com/alertops/flow_execution_engine/service/EscalationRepeatService.java new file mode 100644 index 0000000..87f0338 --- /dev/null +++ b/src/main/java/com/alertops/flow_execution_engine/service/EscalationRepeatService.java @@ -0,0 +1,118 @@ +package com.alertops.flow_execution_engine.service; + +import java.time.Clock; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; + +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import com.alertops.audit.model.AuditAction; +import com.alertops.audit.model.AuditEntityType; +import com.alertops.audit.model.AuditEvent; +import com.alertops.audit.service.AuditService; +import com.alertops.flow_execution_engine.messaging.EscalationRepeatSchedule; +import com.alertops.flow_execution_engine.messaging.EscalationStartSchedule; +import com.alertops.flow_execution_engine.model.Escalation; +import com.alertops.flow_execution_engine.model.EscalationStatus; +import com.alertops.flow_execution_engine.model.RepeatType; +import com.alertops.flow_execution_engine.repository.EscalationRepository; + +/** Creates one independent escalation run for the next saved repeat. */ +@Service +public class EscalationRepeatService { + private final EscalationRepository escalationRepository; + private final AuditService auditService; + private final ApplicationEventPublisher eventPublisher; + private final Clock clock; + private final EscalationRepeatCalculator repeatCalculator = new EscalationRepeatCalculator(); + + // Creates the repeat service with durable escalation and audit dependencies. + public EscalationRepeatService( + EscalationRepository escalationRepository, + AuditService auditService, + ApplicationEventPublisher eventPublisher, + Clock clock) { + this.escalationRepository = Objects.requireNonNull(escalationRepository, "escalationRepository"); + this.auditService = Objects.requireNonNull(auditService, "auditService"); + this.eventPublisher = Objects.requireNonNull(eventPublisher, "eventPublisher"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + @Transactional + // Creates the latest due child and advances the original repeat in one transaction. + public Optional createLatestDueRun(UUID escalationId, Instant now) { + if (escalationId == null || now == null) { + return Optional.empty(); + } + + Escalation original = escalationRepository.findByIdForUpdate(escalationId).orElse(null); + if (!isRepeating(original) || original.getNextRepeatAt().isAfter(now)) { + return Optional.empty(); + } + + Instant occurrenceAt = repeatCalculator + .latestAtOrBefore( + original.getScheduledStartAt(), + original.getScheduleTimezone(), + original.getRepeatType(), + now) + .filter(candidate -> !candidate.isBefore(original.getNextRepeatAt())) + .orElse(original.getNextRepeatAt()); + Instant nextRepeatAt = repeatCalculator.nextAfter( + original.getScheduledStartAt(), + original.getScheduleTimezone(), + original.getRepeatType(), + now); + + Escalation child = new Escalation(); + child.setName(original.getName()); + child.setTaskId(original.getTaskId()); + child.setFlowId(original.getFlowId()); + child.setTeamId(original.getTeamId()); + child.setStatus(EscalationStatus.SCHEDULED); + child.setScheduledStartAt(occurrenceAt); + child.setScheduleTimezone(original.getScheduleTimezone()); + child.setScheduledByUserId(original.getScheduledByUserId()); + child.setScheduledByUserEmail(original.getScheduledByUserEmail()); + child.setScheduledStartRetryCount(0); + child.setScheduledStartNextRetryAt(null); + child.setRepeatType(RepeatType.NONE); + child.setNextRepeatAt(null); + child.setRepeatSourceId(original.getId()); + Escalation savedChild = Objects.requireNonNull( + escalationRepository.save(child), "Saved repeated escalation is required"); + + original.setNextRepeatAt(nextRepeatAt); + escalationRepository.save(original); + auditService.record(new AuditEvent( + AuditEntityType.ESCALATION, + savedChild.getId(), + AuditAction.REPEAT_CREATED, + null, + EscalationStatus.SCHEDULED.name(), + original.getScheduledByUserId(), + original.getScheduledByUserEmail(), + clock.instant(), + null, + "repeatSourceId=" + original.getId() + ";scheduledStartAt=" + occurrenceAt)); + + eventPublisher.publishEvent(new EscalationStartSchedule(savedChild.getId(), occurrenceAt)); + eventPublisher.publishEvent(new EscalationRepeatSchedule(original.getId(), nextRepeatAt)); + return Optional.of(savedChild); + } + + // Confirms that the row is an original escalation with a future repeat boundary. + private boolean isRepeating(Escalation escalation) { + return escalation != null + && escalation.getRepeatType() != null + && escalation.getRepeatType() != RepeatType.NONE + && escalation.getNextRepeatAt() != null + && escalation.getScheduledStartAt() != null + && escalation.getScheduleTimezone() != null + && escalation.getRepeatSourceId() == null; + } +} diff --git a/src/main/java/com/alertops/flow_execution_engine/service/EscalationService.java b/src/main/java/com/alertops/flow_execution_engine/service/EscalationService.java index 6b14013..19309d6 100644 --- a/src/main/java/com/alertops/flow_execution_engine/service/EscalationService.java +++ b/src/main/java/com/alertops/flow_execution_engine/service/EscalationService.java @@ -12,6 +12,8 @@ import com.alertops.flow_execution_engine.messaging.EscalationStartCancelled; import com.alertops.flow_execution_engine.messaging.EscalationStartSchedule; import com.alertops.flow_execution_engine.model.EscalationStatus; +import com.alertops.flow_execution_engine.model.RepeatType; +import com.alertops.flow_execution_engine.messaging.EscalationRepeatStopped; import com.alertops.audit.model.AuditAction; import com.alertops.audit.model.AuditEntityType; import com.alertops.audit.model.AuditEvent; @@ -39,7 +41,9 @@ public class EscalationService { private final ApplicationEventPublisher eventPublisher; private final Clock clock; private final AuditService auditService; + private final EscalationRepeatCalculator repeatCalculator = new EscalationRepeatCalculator(); + // Creates the lifecycle service with the existing escalation dependencies. public EscalationService(EscalationRepository escalationRepository, FlowExecutionStateRepository flowExecutionStateRepository, FlowRepository flowRepository, @@ -102,6 +106,7 @@ public Escalation createEscalationForTeam( } @Transactional + // Schedules one escalation and optionally enables its daily or weekly repeats. public Escalation schedule(UUID escalationId, ScheduledEscalationRequest schedule) { AuthContext authContext = requireTeamContext(); AuditActor actor = requireSchedulingActor(authContext); @@ -117,6 +122,12 @@ public Escalation schedule(UUID escalationId, ScheduledEscalationRequest schedul Instant scheduledStartAt = resolveScheduledStart(schedule); String timezone = schedule.getTimezone().trim(); + RepeatType repeatType = schedule.getRepeatType() == null + ? RepeatType.NONE + : schedule.getRepeatType(); + Instant nextRepeatAt = repeatType == RepeatType.NONE + ? null + : repeatCalculator.nextAfter(scheduledStartAt, timezone, repeatType, scheduledStartAt); int updated = escalationRepository.scheduleIdle( escalationId, authContext.getTeamId(), @@ -134,6 +145,10 @@ public Escalation schedule(UUID escalationId, ScheduledEscalationRequest schedul escalation.setScheduledByUserEmail(actor.email()); escalation.setScheduledStartRetryCount(0); escalation.setScheduledStartNextRetryAt(null); + escalation.setRepeatType(repeatType); + escalation.setNextRepeatAt(nextRepeatAt); + escalation.setRepeatSourceId(null); + escalationRepository.save(escalation); auditService.record(new AuditEvent( AuditEntityType.ESCALATION, escalationId, AuditAction.SCHEDULED, fromStatus.name(), EscalationStatus.SCHEDULED.name(), actor.userId(), actor.email(), clock.instant(), null, null)); @@ -144,6 +159,7 @@ public Escalation schedule(UUID escalationId, ScheduledEscalationRequest schedul } @Transactional + // Reschedules only a non-recurring one-time escalation before it starts. public Escalation reschedule(UUID escalationId, ScheduledEscalationRequest schedule) { AuthContext authContext = requireTeamContext(); AuditActor actor = requireSchedulingActor(authContext); @@ -154,6 +170,11 @@ public Escalation reschedule(UUID escalationId, ScheduledEscalationRequest sched if (escalation.getStatus() != EscalationStatus.SCHEDULED) { throw EscalationException.transitionConflict("Only scheduled escalations can be rescheduled"); } + if ((escalation.getRepeatType() != null && escalation.getRepeatType() != RepeatType.NONE) + || escalation.getRepeatSourceId() != null) { + throw EscalationException.transitionConflict( + "Recurring escalation runs cannot be rescheduled"); + } EscalationStatus fromStatus = escalation.getStatus(); Instant scheduledStartAt = resolveScheduledStart(schedule); int updated = escalationRepository.rescheduleScheduled( @@ -184,6 +205,7 @@ public Escalation reschedule(UUID escalationId, ScheduledEscalationRequest sched } @Transactional + // Cancels one scheduled run without changing its original repeat rule. public Escalation cancelScheduled(UUID escalationId) { AuthContext authContext = requireTeamContext(); UUID cancelledByUserId = requireActorId(authContext); @@ -222,6 +244,37 @@ public Escalation cancelScheduled(UUID escalationId) { return saved; } + @Transactional + // Stops future repeats while preserving the original run and its history. + public Escalation stopRepeating(UUID escalationId) { + AuthContext authContext = requireTeamContext(); + UUID actorId = requireActorId(authContext); + Escalation escalation = escalationRepository.findByIdForUpdate(escalationId).orElse(null); + if (escalation == null || !authContext.getTeamId().equals(escalation.getTeamId())) { + return null; + } + if (escalation.getRepeatSourceId() != null) { + throw EscalationException.transitionConflict( + "Only the original escalation can stop its repeats"); + } + if (escalation.getRepeatType() == null + || escalation.getRepeatType() == RepeatType.NONE + || escalation.getNextRepeatAt() == null) { + return escalation; + } + + escalation.setNextRepeatAt(null); + escalationRepository.save(escalation); + auditService.record(new AuditEvent( + AuditEntityType.ESCALATION, escalationId, AuditAction.REPEAT_STOPPED, + escalation.getRepeatType().name(), escalation.getRepeatType().name(), + actorId, authContext.getEmail(), clock.instant(), null, null)); + if (eventPublisher != null) { + eventPublisher.publishEvent(new EscalationRepeatStopped(escalationId)); + } + return escalation; + } + public List getEscalations(int page, int size, String sortBy, String sortDir) { try { AuthContext authContext = AuthContextHolder.get(); diff --git a/src/main/java/com/alertops/flow_execution_engine/service/EscalationStartScheduler.java b/src/main/java/com/alertops/flow_execution_engine/service/EscalationStartScheduler.java index 8e18dd0..31ff6bb 100644 --- a/src/main/java/com/alertops/flow_execution_engine/service/EscalationStartScheduler.java +++ b/src/main/java/com/alertops/flow_execution_engine/service/EscalationStartScheduler.java @@ -12,6 +12,7 @@ import java.util.concurrent.ScheduledFuture; import jakarta.annotation.PreDestroy; +import org.springframework.beans.factory.annotation.Autowired; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; @@ -25,8 +26,11 @@ import com.alertops.flow_execution_engine.application.StartFlowExecutionUseCase; import com.alertops.flow_execution_engine.messaging.EscalationStartSchedule; import com.alertops.flow_execution_engine.messaging.EscalationStartCancelled; +import com.alertops.flow_execution_engine.messaging.EscalationRepeatSchedule; +import com.alertops.flow_execution_engine.messaging.EscalationRepeatStopped; import com.alertops.flow_execution_engine.model.Escalation; import com.alertops.flow_execution_engine.model.EscalationStatus; +import com.alertops.flow_execution_engine.model.RepeatType; import com.alertops.flow_execution_engine.repository.EscalationRepository; /** Durable one-time timers for escalation starts. PostgreSQL remains the source of truth. */ @@ -42,10 +46,14 @@ public class EscalationStartScheduler { private final StartFlowExecutionUseCase startFlowExecutionUseCase; private final FlowExecutionStateService flowExecutionStateService; private final EscalationStartRetryService retryService; + private final EscalationRepeatService repeatService; private final Duration retryDelay; private final Map timers = new ConcurrentHashMap<>(); + private final Map repeatTimers = new ConcurrentHashMap<>(); private volatile boolean shuttingDown; + // Creates the scheduler with durable start and repeat wake-up dependencies. + @Autowired public EscalationStartScheduler( EscalationRepository escalationRepository, TaskScheduler taskScheduler, @@ -53,6 +61,7 @@ public EscalationStartScheduler( StartFlowExecutionUseCase startFlowExecutionUseCase, FlowExecutionStateService flowExecutionStateService, EscalationStartRetryService retryService, + EscalationRepeatService repeatService, @Value("${alertops.scheduler.start-retry-delay:5s}") Duration retryDelay) { if (retryDelay == null || retryDelay.isZero() || retryDelay.isNegative()) { throw new IllegalArgumentException("Scheduled-start retry delay must be positive"); @@ -64,9 +73,11 @@ public EscalationStartScheduler( this.flowExecutionStateService = Objects.requireNonNull( flowExecutionStateService, "flowExecutionStateService"); this.retryService = Objects.requireNonNull(retryService, "retryService"); + this.repeatService = Objects.requireNonNull(repeatService, "repeatService"); this.retryDelay = retryDelay; } + // Registers one-time and repeat wake-ups after the schedule transaction commits. @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void onScheduled(EscalationStartSchedule schedule) { if (schedule == null) { @@ -75,8 +86,10 @@ public void onScheduled(EscalationStartSchedule schedule) { UUID escalationId = schedule.escalationId(); Instant scheduledStartAt = schedule.scheduledStartAt(); schedule(escalationId, scheduledStartAt); + scheduleRepeatIfEnabled(escalationId); } + // Cancels the one-time wake-up after a scheduled run is cancelled. @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void onCancelled(EscalationStartCancelled cancellation) { if (cancellation == null) { @@ -85,6 +98,23 @@ public void onCancelled(EscalationStartCancelled cancellation) { cancel(cancellation.escalationId()); } + // Registers the next repeat wake-up after its durable boundary advances. + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) + public void onRepeatScheduled(EscalationRepeatSchedule schedule) { + if (schedule != null) { + scheduleRepeat(schedule.escalationId(), schedule.nextRepeatAt()); + } + } + + // Cancels only the future repeat wake-up and leaves saved runs untouched. + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) + public void onRepeatStopped(EscalationRepeatStopped stopped) { + if (stopped != null) { + cancelRepeat(stopped.escalationId()); + } + } + + // Recovers all durable one-time scheduled starts after application startup. @EventListener(ApplicationReadyEvent.class) public void recoverScheduledStarts() { List scheduled = escalationRepository.findAllScheduled(); @@ -106,6 +136,20 @@ public void recoverScheduledStarts() { } } + // Recovers repeat wake-ups even when the original run is already terminal. + @EventListener(ApplicationReadyEvent.class) + public void recoverRepeatingEscalations() { + List repeating = escalationRepository.findAllRepeating(); + if (repeating == null) { + return; + } + for (Escalation escalation : repeating) { + if (escalation != null) { + scheduleRepeat(escalation.getId(), escalation.getNextRepeatAt()); + } + } + } + public void schedule(UUID escalationId, Instant scheduledStartAt) { if (escalationId == null || scheduledStartAt == null || shuttingDown) { return; @@ -128,6 +172,27 @@ public void schedule(UUID escalationId, Instant scheduledStartAt) { } } + // Registers one repeat wake-up while keeping only its cancellable handle in memory. + public void scheduleRepeat(UUID escalationId, Instant nextRepeatAt) { + if (escalationId == null || nextRepeatAt == null || shuttingDown) { + return; + } + TimerEntry replacement = new TimerEntry(); + TimerEntry previous = repeatTimers.put(escalationId, replacement); + if (previous != null) { + previous.cancel(); + } + try { + ScheduledFuture future = taskScheduler.schedule( + () -> handleRepeatTimer(escalationId, replacement), nextRepeatAt); + replacement.future = future; + } catch (RuntimeException failure) { + retryRepeatRegistration(escalationId, replacement); + logger.warn("Could not register repeat wake-up for escalation {}; startup recovery will retry", + escalationId, failure); + } + } + public void cancel(UUID escalationId) { if (escalationId == null) { return; @@ -138,6 +203,17 @@ public void cancel(UUID escalationId) { } } + // Cancels a repeat wake-up without changing the durable escalation history. + public void cancelRepeat(UUID escalationId) { + if (escalationId == null) { + return; + } + TimerEntry entry = repeatTimers.remove(escalationId); + if (entry != null) { + entry.cancel(); + } + } + // Timer callback: validate the registration, reload database state, wait if needed, then start. private void handleScheduledStartTimer(UUID escalationId, TimerEntry entry) { if (!isCurrentTimer(escalationId, entry)) { @@ -163,6 +239,83 @@ private boolean isCurrentTimer(UUID escalationId, TimerEntry entry) { && timers.get(escalationId) == entry && !shuttingDown; } + // Checks whether a repeat callback still owns the current in-memory handle. + private boolean isCurrentRepeatTimer(UUID escalationId, TimerEntry entry) { + return escalationId != null && entry != null + && repeatTimers.get(escalationId) == entry && !shuttingDown; + } + + // Schedules a repeat only when the database still marks the original as repeating. + private void scheduleRepeatIfEnabled(UUID escalationId) { + if (escalationId == null || shuttingDown) { + return; + } + escalationRepository.findById(escalationId) + .filter(escalation -> escalation.getRepeatType() != null) + .filter(escalation -> escalation.getRepeatType() != RepeatType.NONE) + .map(Escalation::getNextRepeatAt) + .ifPresent(nextRepeatAt -> scheduleRepeat(escalationId, nextRepeatAt)); + } + + // Reloads the original and creates only the latest missed repeat. + private void handleRepeatTimer(UUID escalationId, TimerEntry entry) { + if (!isCurrentRepeatTimer(escalationId, entry)) { + return; + } + Instant now = clock.instant(); + try { + Optional original = escalationRepository.findById(escalationId) + .filter(escalation -> escalation.getRepeatType() != null) + .filter(escalation -> escalation.getRepeatType() != RepeatType.NONE) + .filter(escalation -> escalation.getNextRepeatAt() != null); + if (original.isEmpty()) { + repeatTimers.remove(escalationId, entry); + return; + } + if (original.get().getNextRepeatAt().isAfter(now)) { + scheduleRepeat(escalationId, original.get().getNextRepeatAt()); + return; + } + Optional created = repeatService.createLatestDueRun(escalationId, now); + if (created.isEmpty()) { + scheduleRepeatFromDatabase(escalationId, entry); + } + } catch (RuntimeException failure) { + retryRepeatRegistration(escalationId, entry); + logger.warn("Could not create repeated escalation {}; retrying", escalationId, failure); + } + } + + // Restores or removes a repeat wake-up after a concurrent state change wins. + private void scheduleRepeatFromDatabase(UUID escalationId, TimerEntry entry) { + if (!isCurrentRepeatTimer(escalationId, entry)) { + return; + } + escalationRepository.findById(escalationId) + .filter(escalation -> escalation.getRepeatType() != null) + .filter(escalation -> escalation.getRepeatType() != RepeatType.NONE) + .filter(escalation -> escalation.getNextRepeatAt() != null) + .ifPresentOrElse( + escalation -> scheduleRepeat(escalationId, escalation.getNextRepeatAt()), + () -> repeatTimers.remove(escalationId, entry)); + } + + // Retries repeat registration while retaining the unchanged durable boundary. + private void retryRepeatRegistration(UUID escalationId, TimerEntry entry) { + if (!isCurrentRepeatTimer(escalationId, entry)) { + return; + } + try { + ScheduledFuture future = taskScheduler.schedule( + () -> handleRepeatTimer(escalationId, entry), clock.instant().plus(retryDelay)); + entry.future = future; + } catch (RuntimeException retryFailure) { + repeatTimers.remove(escalationId, entry); + logger.warn("Could not register repeat retry for escalation {}; startup recovery will retry", + escalationId, retryFailure); + } + } + private Optional loadScheduledEscalation(UUID escalationId, TimerEntry entry, Instant now) { if (escalationId == null || entry == null || now == null) { return Optional.empty(); @@ -284,10 +437,13 @@ private void recordTimerRegistrationFailure(UUID escalationId, Instant retryAt) } @PreDestroy + // Cancels all in-memory start and repeat wake-ups during application shutdown. public void stop() { shuttingDown = true; timers.values().forEach(TimerEntry::cancel); timers.clear(); + repeatTimers.values().forEach(TimerEntry::cancel); + repeatTimers.clear(); } private static final class TimerEntry { diff --git a/src/main/java/com/alertops/flow_execution_engine/service/FlowExecutionStateService.java b/src/main/java/com/alertops/flow_execution_engine/service/FlowExecutionStateService.java index 5d971fd..81dea65 100644 --- a/src/main/java/com/alertops/flow_execution_engine/service/FlowExecutionStateService.java +++ b/src/main/java/com/alertops/flow_execution_engine/service/FlowExecutionStateService.java @@ -1,5 +1,6 @@ package com.alertops.flow_execution_engine.service; +import java.time.Clock; import java.util.List; import java.util.Objects; import java.util.UUID; @@ -31,16 +32,20 @@ public class FlowExecutionStateService { EscalationRepository escalationRepository; StepSchedulingService stepSchedulingService; AuditService auditService; + private final Clock clock; + // Creates the service that starts an escalation and schedules its first alert. public FlowExecutionStateService( FlowExecutionStateRepository flowExecutionStateRepository, EscalationRepository escalationRepository, StepSchedulingService stepSchedulingService, - AuditService auditService) { + AuditService auditService, + Clock clock) { this.flowExecutionStateRepository = flowExecutionStateRepository; this.escalationRepository = escalationRepository; this.stepSchedulingService = stepSchedulingService; this.auditService = Objects.requireNonNull(auditService, "auditService"); + this.clock = Objects.requireNonNull(clock, "clock"); } @Transactional @@ -68,7 +73,7 @@ public String startFlowExecution( String actorEmail = authContext == null ? null : authContext.getEmail(); auditService.record(new AuditEvent( AuditEntityType.ESCALATION, escalationId, AuditAction.STARTED, fromStatus.name(), - EscalationStatus.OPEN.name(), actorId, actorEmail, Instant.now(), null, null)); + EscalationStatus.OPEN.name(), actorId, actorEmail, clock.instant(), null, null)); if (flow == null) { throw EscalationException.invalidRequest("The escalation flow is not available."); @@ -108,18 +113,19 @@ public String startFlowExecution( flowExecutionStateRepository.save(flowExecutionState); } FlowExecutionState flowExecutionState = flowExecutionStateRepository.findTopByProcessIdOrderByPositionAsc(escalationId); - stepSchedulingService.scheduleStep(flowExecutionState); + stepSchedulingService.scheduleStepImmediately(flowExecutionState, clock.instant()); return "Started Flow Execution for escalationId: " + escalationId; } catch (RuntimeException e) { throw e; } } + // Claims the escalation transition required by the selected start mode. private int claimStart(UUID escalationId, UUID teamId, FlowExecutionStartMode startMode) { return switch (startMode) { case IDLE -> escalationRepository.claimIdleForStart(escalationId, teamId); case SCHEDULED_DUE -> escalationRepository.claimScheduledForStart( - escalationId, teamId, java.time.Instant.now()); + escalationId, teamId, clock.instant()); case SCHEDULED_EARLY -> escalationRepository.claimScheduledForManualStart(escalationId, teamId); }; } diff --git a/src/main/java/com/alertops/messaging/EmailVerificationMailer.java b/src/main/java/com/alertops/messaging/EmailVerificationMailer.java index 0d08c74..7e0e8b2 100644 --- a/src/main/java/com/alertops/messaging/EmailVerificationMailer.java +++ b/src/main/java/com/alertops/messaging/EmailVerificationMailer.java @@ -23,6 +23,7 @@ public EmailVerificationMailer( this.fromAddress = fromAddress == null ? "" : fromAddress.trim(); } + // Sends a one-time link that verifies a new account email. public void sendVerificationEmail(User user, String verificationUrl) { JavaMailSender mailSender = mailSenderProvider.getIfAvailable(); if (mailSender == null || fromAddress.isBlank()) { @@ -35,9 +36,9 @@ public void sendVerificationEmail(User user, String verificationUrl) { message, true, StandardCharsets.UTF_8.name()); helper.setFrom(fromAddress); helper.setTo(user.getEmail()); - helper.setSubject("Verify your AlertOps email"); + helper.setSubject("Verify your ReplyTrail email"); helper.setText( - "Verify your AlertOps email address by opening this link:\n\n" + verificationUrl + "Verify your ReplyTrail email address by opening this link:\n\n" + verificationUrl + "\n\nThis link expires soon and can be used once.", """ @@ -47,11 +48,11 @@ public void sendVerificationEmail(User user, String verificationUrl) { - +
 
Verify your AlertOps email
Verify your ReplyTrail email

Confirm that you control this email address to finish setting up your account.

Verify email address

-

This link expires soon and can be used once. If you did not create an AlertOps account, you can ignore this email.

+

This link expires soon and can be used once. If you did not create a ReplyTrail account, you can ignore this email.

diff --git a/src/main/java/com/alertops/messaging/MessageConsumer.java b/src/main/java/com/alertops/messaging/MessageConsumer.java index b9b7d7d..b8bb405 100644 --- a/src/main/java/com/alertops/messaging/MessageConsumer.java +++ b/src/main/java/com/alertops/messaging/MessageConsumer.java @@ -111,7 +111,11 @@ private void deliverStepNotification(FlowExecutionState flowExecutionState, Esca String escalateNowUrl = nextNode == null ? null : acknowledgementService.createEscalateNowUrl(escalation, flowExecutionState, nextNode); - boolean mailSent = notification.sendEmail(flowExecutionState, acknowledgementUrl, escalateNowUrl); + Duration responseWindow = nextNode == null + ? flowExecutionState.getDuration() + : nextNode.getDuration(); + boolean mailSent = notification.sendEmail( + flowExecutionState, escalation, responseWindow, acknowledgementUrl, escalateNowUrl); // Persist total attempts, including successful SMTP submissions. flowExecutionState.setSendAttemptCount(sendAttemptCount + 1); if (mailSent) { diff --git a/src/main/java/com/alertops/messaging/Notification.java b/src/main/java/com/alertops/messaging/Notification.java index 8d31fc0..b596c87 100644 --- a/src/main/java/com/alertops/messaging/Notification.java +++ b/src/main/java/com/alertops/messaging/Notification.java @@ -1,6 +1,7 @@ package com.alertops.messaging; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.Objects; import java.util.UUID; @@ -15,6 +16,7 @@ import org.springframework.stereotype.Component; import org.springframework.web.util.HtmlUtils; +import com.alertops.flow_execution_engine.model.Escalation; import com.alertops.flow_execution_engine.model.FlowExecutionState; import jakarta.mail.internet.MimeBodyPart; @@ -39,9 +41,11 @@ public Notification( this.fromAddress = fromAddress == null ? "" : fromAddress.trim(); } - // Sends an alert with acknowledgement and optional immediate-escalation actions. + // Sends an escalation alert with context, response timing, and recipient actions. public boolean sendEmail( FlowExecutionState flowExecutionState, + Escalation escalation, + Duration responseWindow, String acknowledgementUrl, String escalateNowUrl) { if (flowExecutionState == null || isBlank(flowExecutionState.getUserEmail())) { @@ -70,6 +74,13 @@ public boolean sendEmail( String taskPriority = sanitizeMetadata(flowExecutionState.getTaskPriority()); String taskCategory = sanitizeMetadata(flowExecutionState.getTaskCategory()); String taskReferenceUrl = sanitizeMetadata(flowExecutionState.getTaskReferenceUrl()); + String escalationName = sanitizeSubject( + escalation == null ? "" : Objects.toString(escalation.getName(), "")); + UUID escalationIdentifier = escalation == null || escalation.getId() == null + ? flowExecutionState.getProcessId() + : escalation.getId(); + String escalationId = Objects.toString(escalationIdentifier, "unknown"); + String responseWindowText = formatResponseWindow(responseWindow); if (taskSource.isEmpty()) { taskSource = "Manual"; } @@ -83,9 +94,13 @@ public boolean sendEmail( subjectDetails = subjectDetails.substring(0, 97) + "..."; } + String subjectContext = escalationName.isBlank() ? subjectDetails : escalationName + " · " + subjectDetails; + if (subjectContext.length() > 100) { + subjectContext = subjectContext.substring(0, 97) + "..."; + } String markdown = buildMarkdown( - flowExecutionState, taskName, taskSource, taskPriority, taskCategory, taskReferenceUrl, - taskDetails, acknowledgementUrl, escalateNowUrl); + flowExecutionState, escalationName, escalationId, responseWindowText, taskName, taskSource, + taskPriority, taskCategory, taskReferenceUrl, taskDetails, acknowledgementUrl, escalateNowUrl); var message = mailSender.createMimeMessage(); var helper = new MimeMessageHelper( message, @@ -93,7 +108,7 @@ public boolean sendEmail( StandardCharsets.UTF_8.name()); helper.setFrom(fromAddress); helper.setTo(flowExecutionState.getUserEmail().trim()); - helper.setSubject("AlertOps · " + taskSource + " · " + subjectDetails); + helper.setSubject("ReplyTrail · " + taskSource + " · " + subjectContext); var alternative = new MimeMultipart("alternative"); var plainPart = new MimeBodyPart(); @@ -147,13 +162,13 @@ public boolean sendStartFailureEmail( } String plainText = """ - AlertOps could not start a scheduled escalation after all retry attempts. + ReplyTrail could not start a scheduled escalation after all retry attempts. Escalation: %s Escalation ID: %s Reason: %s - Review the escalation in AlertOps and follow your team's response procedure. + Review the escalation in ReplyTrail and follow your team's response procedure. """.formatted(safeName, Objects.toString(escalationId, "unknown"), safeReason); String html = """ @@ -165,7 +180,7 @@ public boolean sendStartFailureEmail(   Scheduled escalation failed to start -

AlertOps exhausted all start attempts for this scheduled escalation.

+

ReplyTrail exhausted all start attempts for this scheduled escalation.

Escalation: %s

Escalation ID: %s

Reason: %s

@@ -184,7 +199,7 @@ public boolean sendStartFailureEmail( var helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.name()); helper.setFrom(fromAddress); helper.setTo(recipientEmail.trim()); - helper.setSubject("AlertOps · START_FAILED · " + safeName); + helper.setSubject("ReplyTrail · START_FAILED · " + safeName); helper.setText(plainText, html); mailSender.send(message); return true; @@ -198,6 +213,9 @@ public boolean sendStartFailureEmail( // Builds the plain-text action content for one alert email. private String buildMarkdown( FlowExecutionState state, + String escalationName, + String escalationId, + String responseWindow, String taskName, String taskSource, String taskPriority, @@ -208,14 +226,19 @@ private String buildMarkdown( String escalateNowUrl) { String details = taskDetails.isBlank() ? "No task details were provided." : taskDetails; String recipient = Objects.toString(state.getUserEmail(), "unknown"); - String escalationId = Objects.toString(state.getProcessId(), "unknown"); String escalateNowAction = isBlank(escalateNowUrl) ? "" : "[Escalate now and notify the next person](%s)\n".formatted(escalateNowUrl); return """ # A response needs your attention - AlertOps has activated a response workflow. + ReplyTrail has activated a response workflow. + + ## Escalation + + - **Name:** %s + - **Escalation ID:** %s + - **Response window:** %s ## Task @@ -225,12 +248,11 @@ private String buildMarkdown( - **Category:** %s - **Reference URL:** %s - %s + ## Task details - ## Response reference + %s - - **Escalation ID:** %s - - **Assigned user:** %s + **Assigned user:** %s [Review and acknowledge this escalation](%s) @@ -240,62 +262,94 @@ private String buildMarkdown( --- - *Automated notification from AlertOps. Replies may not be monitored.* - """.formatted(taskName.isBlank() ? "Response needed" : taskName, taskSource, taskPriority, - taskCategory, taskReferenceUrl, details, - escalationId, recipient, acknowledgementUrl, escalateNowAction); + *Automated notification from ReplyTrail. Replies may not be monitored.* + """.formatted( + escalationName.isBlank() ? "Unnamed escalation" : escalationName, + escalationId, + responseWindow, + taskName.isBlank() ? "Response needed" : taskName, + taskSource, + taskPriority, + taskCategory, + taskReferenceUrl, + details, + recipient, + acknowledgementUrl, + escalateNowAction); } // Builds the safe HTML action content for one alert email. private String buildHtml(String markdown, String acknowledgementUrl, String escalateNowUrl) { String renderedMarkdown = HTML_RENDERER.render(MARKDOWN_PARSER.parse(markdown)) - .replace("

", "

") - .replace("

", "

") + .replace("

", "

") + .replace("

", "

") .replace("

", "

") .replace("