# Graceful stop: `std::session` and `event<jmvcc_stop>`
Give resources back when `/build` or a deploy kills running threads: sessions, the stop protocol, costs, what is verified. Open for any game with long sessions (crafting with a wait, rounds, runs).

`/build` and a deploy kill every running thread AT ONCE (verified): a player in the middle of forging or a match
loses it. Any game with long sessions (a craft with a wait, a round, a dungeon run, anything that took resources
and gives them back later) wraps the START of each session and returns resources in `event<jmvcc_stop>`.
The pattern is a flag: set it when you take, clear it when you give the result, and give only while it is set —
then the refund and the reward never both happen:
```js
event<player_right_click> {
  std::session("ковка") {           // entry of a NEW session: the click / event where it all begins
    %player%_ore -= 3
    %player%_forging = 1             // taken: from now on jmvcc_stop owes it back
    code::wait(10, time_unit = "SECONDS")
    if (%player%_forging == 1) {     // jmvcc_stop may have refunded it during the wait
      %player%_forging = 0
      player::give_items(item("diamond"), 1)
    }
  }
}
event<jmvcc_stop> {                  // one player (target = player): give back, save; NO code::wait
  if (%player%_forging == 1) { %player%_ore += 3; %player%_forging = 0 }
}
```
- `event<jmvcc_stop>` runs on EVERY quit, for players who were in no session, and can run twice for one player
  (a stop, then `#jmvcc cancel`, then their quit): it must be idempotent — refund only under a flag, reset it.
- While the world is stopping (`#jmvcc build`, below) a NEW `std::session` is refused: action bar "&cМир уходит на
  стройку — новое начать нельзя" + `entity.villager.no`, the body is skipped, the code after the block runs. Started
  sessions play out. Not blocked: a session nested in another, functions called from inside (they share `var`),
  `event<jmvcc_stop>` and the functions it calls, and processes started from inside with `name()` or
  `local_variables_mode = "COPY"` (verified: they get a copy of the caller's `var`). Inside a session
  `code::start_process(...)` without a mode or with `"SHARE"` is a compiler warning: use `"COPY"`.
- Mark only the ENTRY, not every function: functions and processes are called inside important tasks too.
  Do not wrap a `repeat::forever()` world loop (the session would never end; the stop then waits for its timeout),
  and start a long-lived game-loop process OUTSIDE a session: a process started inside counts as inside for its
  whole life, so its own rounds would never be refused.
- The open-session count is per owner: the player (`%uuid%`) in player events (also `mob_kill_player`,
  `projectile_damage_player`, ...) and in all functions and processes, the entity (`value::uuid`) in `entity_*`
  events, `"world"` in world code. A player's count is reset when they quit (their threads die mid-way), an
  entity's in `entity_death`. A NO_TARGET process that works for a player and may outlive their quit:
  `std::session("ковка", uuid) { ... }` — kept apart, a quit does not touch it (otherwise the stop may not wait for it).
  In a NO_TARGET process `%uuid%` / `%player%` stay literal text and `value::uuid` is 0 (verified): pass the
  player's uuid as an argument when the process needs it.
- `return` / `break` / `continue` / `code::stop_repeat()` / `code::end_thread()` out of the body close the session
  automatically. A called function that ends the thread or stops the caller's loop (`code::end_thread()`,
  `code::stop_repeat()` outside its own loop) skips the close: compiler warning — return a flag and `return` /
  `break` in the session body itself. A server error caught by an enclosing `try` closes it too. A server error in
  the body (the line stops) or a thread killed from outside
  leaves it counted (a player's until they quit, `"world"` until the world restarts); the stop then waits for its timeout.
- `event<jmvcc_stop>` runs: when a player quits (for them, FIRST in your `player_quit`: it sees the player's state
  before your quit code cleans it up; a server error in it stops your quit code too — keep it simple; whether items
  can still be given there is NOT verified), and at the end of a graceful stop (for every online player). A plain
  `/build` (and `client deploy`) runs it too: the server fires `player_quit` for every player first, then
  `world_stop` in the same tick with no players left (verified) — so world-wide saves go in your own
  `event<world_stop>`, per-player ones in `jmvcc_stop`. Once a graceful stop ran it, a quit does not run it again
  (until the stop is cancelled). `code::wait` in it is a compile error (code after
  wait in world_stop never runs, verified); a function with wait called from it is a warning. Several
  `event<jmvcc_stop>` (e.g. in imports) all run.
- Your own `player_chat` / `player_quit` / `world_stop` handlers keep working: the compiler puts its part at their
  start. `#jmvcc ...` chat messages never reach any of your `player_chat` handlers.
- Protocol (the bridge / `jmvcc client` speaks it; you rarely type it): `build [timeout_s]` (default 90), `cancel`,
  `status` from a player with DEVELOPER or OWNER rights — the mod sends a custom click packet `jmvcc:cmd` with
  data `{cmd:"build 30"}` (invisible; a world without the receiver just ignores it); typed by hand, the chat
  message `#jmvcc build 30` works too and is cancelled (nobody sees it). Replies
  are log lines to the asker only: `jmvcc:draining <s>`, then a boss bar countdown for everyone once a second, then
  `jmvcc:ready-to-stop` + title "&aМожно /build" (all sessions done or timeout, `jmvcc_stop` finished for everyone —
  up to 5 s after the count); `jmvcc:cancelled`; `jmvcc:status draining=<0|1> busy=<n>`. No `jmvcc:draining` within
  3 s = an old module without graceful stop. The code never does `/build` itself. The world leaves the stop by
  itself when the asker quits before `ready-to-stop`, or when no `/build` came within 60 s after it
  (`jmvcc:cancelled` to the asker).
- Cost: one `>` per session start (≈1) and 2×4 cheap actions for the count; in normal play nothing per tick (one
  text check per chat message, one map write and one compare per quit).
- Generated only when the module has `std::session` or `event<jmvcc_stop>`; other modules compile exactly as before.
  Verified on the server (bench/server-check-26.jc, 2026-11-04): sessions, refusal while stopping, nested / function /
  COPY / SHARE / explicit-owner processes pass and a mode-less process is refused, early exits close the count,
  `jmvcc_stop` from the NO_TARGET drain process before `ready-to-stop`, `cancel`, the 60 s auto-cancel, `/build`
  via quit, both transports, `jmvcc client stop` and `deploy --graceful`. NOT checked: the asker quitting
  mid-stop, giving items in `player_quit`, a second player without rights.
