# Editorial workflow and priority

## Configuration (Prompt 4A)

Workflow configuration belongs to core news. `workflow_templates` holds stable
ULID-addressed families with a current version pointer. Each change appends an
immutable `workflow_template_versions` snapshot and its own statuses/transitions.
Stories must pin the snapshot ID, rather than the mutable family pointer.
Historical graphs remain available even after a new default is selected.

Status keys are configurable, including custom review stages. The seeded graph
has draft, submitted, admin_review, editing, verification, scheduled, published,
returned, rejected, on_hold, merged, unpublished and archived. Its actions cover
every action listed in Prompt 4. Definitions require one initial status, a final
status, valid endpoints, unique (source, action) pairs and reachable statuses.
Return/reject/unpublish/takedown cannot drop their reason requirement. Assigning
an editor requires an assignee; editor_publish must retain the publishing setting
condition. Condition data is allow-listed, with no executable expressions.

`workflow_settings` contains current global/category/desk/user overrides;
`workflow_setting_versions` retains every value, actor, reason and active flag.
Setting changes require `base_version` (0 when creating); graph changes require
their current version. A stale edit returns 409 `workflow_version_conflict`.
Disabling an override creates a version and restores fallback behavior.

Effective settings resolve in this order, highest precedence first: user, desk,
category, global, template defaults. Graphs remain pinned; effective settings are
read live. This distinction lets publishing switches apply to existing stories
without silently changing their transition graph. Template defaults initially
disable editor publishing for the admin flow and enable it for trusted-editor
and small-newsroom flows. An explicit global override supersedes those defaults.

Global defaults are reporter_lock_on_submit=true, admin_verification=required,
auto_assign=manual, fasttrack_p0=false, anti_starvation enabled for P3/P4 with a
one-level bump after the decision target, and escalation roles system-admin then
super-admin. Auto-assignment accepts manual, round_robin, by_category,
by_district and least_loaded. Verification accepts required, optional,
skip_trusted. No setting executes user-supplied code.

### Endpoints

All paths are under `/api/v1/cms/workflow`. All use `workflow.configure`, CMS
authentication/ability, active-user, mandatory 2FA and rate-limit middleware. That
permission is dangerous, so a recent 2FA confirmation is required. Configuration
is system-wide: the policy additionally requires unrestricted data scope.

| Method | Path | Behavior |
| --- | --- | --- |
| GET | `templates` | Page list; filters key/is_default, sorts key/version/created_at/uid |
| POST | `templates` | Create a family and version 1 |
| GET, PATCH | `templates/{uid}` | Read current graph / append a complete new graph |
| GET | `templates/{uid}/versions/{number}` | Read an immutable historical graph |
| GET | `settings` | Inspect effective settings and saved overrides |
| PATCH | `settings` | Append a setting value/version |
| GET | `settings/{uid}/versions/{number}` | Read a setting snapshot |

Template updates send a complete graph, `base_version` and a reason. The stable
family key cannot be renamed. Selecting a new default versions both families
atomically; a default cannot be removed without a replacement. Lists accept
`page`, `per_page` (1–100), Spatie-whitelisted `filter` and `sort` parameters.

Setting example:

```json
{
  "key": "editor_can_publish",
  "value": true,
  "scope_type": "global",
  "base_version": 0,
  "reason": "Allow editors to publish"
}
```

Scoped settings add `scope` containing a category, desk or user ULID. GET
`settings` accepts optional template/user/desk/category ULIDs to inspect an
effective context. Every response uses public UIDs and the API date/envelope
format. Snapshot rows are protected against Eloquent update/delete.

### Seeders, audit and cache

`WorkflowSeeder` installs admin-approves-everything, trusted-editors-publish,
small-newsroom, opinion, video, e-paper and sponsored families, plus global
settings. The e-paper family has no Story content types; the future e-paper
module owns its entity. Existing graphs, settings and removed role grants survive
reseeding. Seed version: `2026.11.1`.

`workflow.editor.publish` is a distinct capability for setting-gated editor
publishing. The first workflow seed grants it to the existing system editor and
desk-head roles, with an audit record. Later seeds preserve administrator edits.
It does not grant `workflow.publish`, and direct denies still take precedence.

`AuditService` records workflow_template_versioned and
workflow_setting_versioned, including before/after definitions or values,
version numbers, actor and reason. `WorkflowConfigChanged` dispatches after
commit; its listener immediately invalidates CacheService tag `workflow` and
keys `workflow:templates` / `workflow:settings` (TTL 1 hour). Mutations use
`lock:workflow:config` (Redis DB 4, TTL 60s) plus a database transaction.
Configuration writes read fresh rows rather than cached heads.

The workspace has no usable Git metadata; per-step commits cannot be created.

## Engine (Prompt 4B)

`WorkflowService::transition()` runs inside `lock:wf:{story}` + a DB transaction:
permission + scope (AccessService), the edge exists for the current status, its
conditions (`editor_can_publish`, `admin_verification`, `actor_roles`,
`priority_in`, `on_duty`, `fasttrack_p0`), reason / assignee, a first review with a
1–5 relevance rating, then status change, revision, field diff, `story_transitions`
row and `StoryTransitioned`. Invalid actions answer 422 `workflow_transition_invalid`
with `allowed_actions`. `GET cms/stories/{uid}/actions` lists what the caller can do now.

| Endpoint | Permission | Notes |
| --- | --- | --- |
| `POST cms/stories/{uid}/transition` | per edge | `action`, `reason`, `assignee`, `relevance`, `rejection_reason`, `scheduled_at`, `merge_into`, `priority`, `priority_reason`, `content` |
| `GET cms/stories/{uid}/actions` | story read | drives CMS buttons |
| `GET cms/stories/{uid}/history` | story read | actor, role, time, status, waiting seconds, field diff |
| `POST cms/stories/{uid}/assign` | `workflow.assign` | assign/reassign without a status change; omit `assignee` to auto-assign (`strategy` or the `auto_assign` setting) |
| `POST cms/stories/{uid}/priority` | `workflow.priority.override` | `priority`, `reason` (required); reporter notified; SLA targets recalculated |
| `GET cms/queues` | `workflow.review` \| `workflow.publish` \| `content.stories.view.*` | waiting stories in scope; P0 → P4 then longest waiting (index `story_work_queue`); filters `status`, `priority`, `desk`, `district`, `assignee` |
| `GET/POST/PATCH/DELETE cms/duty-shifts` | `workflow.duty.manage` + unrestricted scope | duty roster (audited) |

Auto-assign strategies (`AssignmentService::choose`): `round_robin`, `by_category`
(desk members), `by_district` (home district), `least_loaded` (fewest active
assignments); candidates are active, 2FA-enrolled editors/desk heads who may edit
the story. `manual` requires an explicit assignee.

**Scheduled publish / embargo**: `workflow:publish-scheduled` (every minute, lock
`lock:workflow:publish-scheduled`) publishes `scheduled` stories whose
`scheduled_at` and `embargo_until` have passed, through `publish_as_is` as the user
who scheduled them (so permission, scope, embargo and media-ready checks still
apply). Failures are audited as `story_scheduled_publish_failed`.

**Merge**: `merge` (reason required, `merge_into` target uid) under
`lock:workflow:merge`.

**Reviews and rejection reasons**: `story_reviews` (relevance 1–5 on the first
review, notes); `RejectionReasonsSeeder` seeds fake_fabricated, misleading,
not_newsworthy, duplicate, incomplete, legal_risk, plagiarised, out_of_beat,
poor_quality, other (with `affects_accuracy` for Prompt 7 scorecards).

## Priority, SLA and duty (Prompt 4C)

`PriorityLevelsSeeder` (first action / decision minutes): P0 Flash 5/10, P1 Urgent
15/30, P2 High 30/120, P3 Normal 120/360, P4 Low 1440/4320, with colour, alert
channels (P0/P1: database, mail, sms, push, broadcast) and sound (`flash-alert` for P0).

* **On submit** the reporter's priority applies (default P3; P0 needs
  `priority_reason`), then `AutoRaiseRulesSeeder` rules can only raise it:
  keywords भूकम्प, बाढी, पहिरो, दुर्घटना, मृत्यु, earthquake, flood, landslide → P1;
  3+ reporters on the same `event_key` within 60 minutes → P1.
* **SLA** (`SlaService`): one `story_slas` row while the story waits (submitted,
  admin_review, editing, verification, on_hold), targets counted from submission. A
  precise `SlaCheckJob` is queued at the first-action target (`critical` for P0/P1,
  `high` otherwise); `workflow:sla-sweep` (every minute) warns at 80 % of the
  running window, escalates one step along `escalation_chain` on breach and every 5
  minutes after, and bumps starving P3/P4 stories one level once
  (`anti_starvation`). Every step is audited (`story_sla_warning`,
  `story_sla_escalated`, `story_priority_changed`). The check never waits on a busy
  `lock:wf:{story}` — the next sweep retries.
* **Duty roster**: P0/P1 submission alerts go to on-duty reviewers first (others get
  only the in-app entry while someone is on duty).
* **P0 fast-track** (setting `fasttrack_p0`, off by default): an on-duty user with
  `workflow.fasttrack.publish` can `editor_publish` a P0 story straight from
  submitted/admin_review. A `post_publish_verifications` task (due in 30 minutes) is
  created, audited (`story_fast_tracked`) and verifiers are notified.
* **P0 lock takeover**: on a P0 story, an edit lock idle for 2 minutes (no heartbeat)
  can be taken by any editor without `content.lock.override`; audited as
  `story_lock_overridden` and the previous holder gets a `lock_handover` notification.

Staff notifications are described in [notifications.md](notifications.md).
