Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions README.md

Large diffs are not rendered by default.

31 changes: 30 additions & 1 deletion scripts/verify-readme.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const CLOSING =
const PLANNED_AREAS =
/^(Play protocol \/ WS|Matchmaking|Implementation)$/i
const BUILT_AREAS =
/^(README|Axum scaffold|Postgres migrations|Redis presence|Auth|Session cookies \/ CSRF|Age-appropriate defaults|WS Hello\/Welcome\/Ping|Game event log|Move apply|Clocks|Lag compensation)$/i
/^(README|Axum scaffold|Postgres migrations|Redis presence|Auth|Session cookies \/ CSRF|Age-appropriate defaults|WS Hello\/Welcome\/Ping|Game event log|Move apply|Clocks|Lag compensation|Offers)$/i

const fail = (msg) => {
console.error(`FAIL: ${msg}`)
Expand Down Expand Up @@ -164,6 +164,7 @@ if (!statusTableMatch) {
let sawMoveApplyBuilt = false
let sawClocksBuilt = false
let sawLagBuilt = false
let sawOffersBuilt = false
let sawImplPlanned = false
for (const [, areaRaw, stateRaw] of stateCells) {
const area = areaRaw.trim()
Expand Down Expand Up @@ -213,6 +214,9 @@ if (!statusTableMatch) {
if (/^Lag compensation$/i.test(area) && /^Built$/i.test(state)) {
sawLagBuilt = true
}
if (/^Offers$/i.test(area) && /^Built$/i.test(state)) {
sawOffersBuilt = true
}
if (PLANNED_AREAS.test(area) && !/^Planned$/i.test(state)) {
fail(`STATUS row "${area}" must stay Planned until code exists; got "${state}"`)
}
Expand Down Expand Up @@ -246,6 +250,9 @@ if (!statusTableMatch) {
if (!sawLagBuilt) {
fail('STATUS must include "| Lag compensation | Built |"')
}
if (!sawOffersBuilt) {
fail('STATUS must include "| Offers | Built |"')
}
if (!sawImplPlanned) fail('STATUS must include "| Implementation | Planned |"')
if (!process.exitCode) ok("STATUS rows use Planned/Built correctly")
}
Expand Down Expand Up @@ -487,6 +494,28 @@ if (
ok("Lag compensation surface documented")
}

const offersRs = join(repoRoot, "src", "game", "offers.rs")
const offersTest = join(repoRoot, "tests", "offers.rs")
if (!existsSync(offersRs) || !existsSync(offersTest)) {
fail("Offers sources missing (src/game/offers.rs, tests/offers.rs)")
} else {
ok("Offers sources present")
}

if (
!readme.includes("offer_draw") ||
!readme.includes("OfferState") ||
!readme.includes("ABORT_DENIED") ||
!readme.includes("OFFER_INVALID") ||
!readme.includes("offers")
) {
fail(
"README must document offer_draw, OfferState, OFFER_INVALID/ABORT_DENIED, and offers tests"
)
} else {
ok("Offers surface documented")
}

if (!existsSync(join(repoRoot, "src", "lib.rs")) || !existsSync(join(repoRoot, "src", "main.rs"))) {
fail("Axum scaffold source missing (src/lib.rs, src/main.rs)")
} else {
Expand Down
15 changes: 15 additions & 0 deletions src/game/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,7 @@ pub async fn apply_move_with_rtt(
zeroed.b_ms = 0;
}
write_flag_to_meta(&mut meta, color, &zeroed);
meta.pending_offer = None;
meta.ended_reason = Some(format!("flag:{}", outcome.result));
save_meta(conn, game_id, &meta).await?;
return Err(ApplyError::Flagged { outcome });
Expand All @@ -290,12 +291,26 @@ pub async fn apply_move_with_rtt(
.ok_or_else(|| ApplyError::IllegalMove(uci.to_owned()))?;
let next_fen = next.to_fen();

// Snapshot clocks + lag quotas for one-ply takeback; clear pending offers (CV-165).
meta.prev_clock_w_ms = meta.clock_w_ms;
meta.prev_clock_b_ms = meta.clock_b_ms;
meta.prev_active = if meta.active.is_empty() {
board_active.to_owned()
} else {
meta.active.clone()
};
meta.prev_active_started_ms = meta.active_started_ms;
meta.prev_lag_quota_w_ms = meta.lag_quota_w_ms;
meta.prev_lag_quota_b_ms = meta.lag_quota_b_ms;
meta.pending_offer = None;

// Deduct effective elapsed then add Fischer increment (ADR-005).
match tick_meta_on_move_compensated(&meta, seat, ts, lag_comp) {
ClockTick::Flagged { color, clocks } => {
// Same `ts` as peek should not flag; treat as internal fault.
let outcome = flag_outcome_for_position(&fen, color).map_err(ApplyError::Corrupt)?;
write_flag_to_meta(&mut meta, color, &clocks);
meta.pending_offer = None;
meta.ended_reason = Some(format!("flag:{}", outcome.result));
save_meta(conn, game_id, &meta).await?;
return Err(ApplyError::Flagged { outcome });
Expand Down
1 change: 1 addition & 0 deletions src/game/clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,7 @@ pub fn write_flag_to_meta(meta: &mut super::events::GameMeta, color: &str, pair:
}
meta.ended = true;
meta.ended_reason = Some("flag".to_owned());
meta.pending_offer = None;
}

#[cfg(test)]
Expand Down
95 changes: 91 additions & 4 deletions src/game/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ use serde::{Deserialize, Serialize};
/// Standard chess starting position FEN (six fields).
pub const START_FEN: &str = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";

/// Pending draw or takeback offer (cleared on move apply or response).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PendingOffer {
/// `"draw"` or `"takeback"`.
pub kind: String,
/// Seat that created the offer (`"w"` / `"b"`).
pub by: String,
}

/// Durable-enough live meta for a Redis game (initial FEN + seats + clocks).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GameMeta {
Expand Down Expand Up @@ -44,6 +53,26 @@ pub struct GameMeta {
/// Last server-measured one-way lag estimate for Black (ms).
#[serde(default)]
pub lag_one_way_b_ms: u64,
/// Time class for abort first-move windows (ADR-005): bullet/blitz/rapid/classical/correspondence.
#[serde(default = "default_time_class")]
pub time_class: String,
/// Open draw/takeback offer, if any (CV-165).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pending_offer: Option<PendingOffer>,
/// Clock snapshot before the last accepted ply (one-ply takeback restore).
#[serde(default)]
pub prev_clock_w_ms: u64,
#[serde(default)]
pub prev_clock_b_ms: u64,
#[serde(default)]
pub prev_active: String,
#[serde(default)]
pub prev_active_started_ms: u64,
/// Lag quota snapshot before the last accepted ply (restored on takeback).
#[serde(default)]
pub prev_lag_quota_w_ms: u64,
#[serde(default)]
pub prev_lag_quota_b_ms: u64,
/// True after a terminal result (flag, resign, …) has been recorded.
#[serde(default)]
pub ended: bool,
Expand All @@ -52,6 +81,10 @@ pub struct GameMeta {
pub ended_reason: Option<String>,
}

fn default_time_class() -> String {
"blitz".to_owned()
}

impl Default for GameMeta {
fn default() -> Self {
Self {
Expand All @@ -68,6 +101,14 @@ impl Default for GameMeta {
lag_quota_b_ms: 0,
lag_one_way_w_ms: 0,
lag_one_way_b_ms: 0,
time_class: default_time_class(),
pending_offer: None,
prev_clock_w_ms: 0,
prev_clock_b_ms: 0,
prev_active: String::new(),
prev_active_started_ms: 0,
prev_lag_quota_w_ms: 0,
prev_lag_quota_b_ms: 0,
ended: false,
ended_reason: None,
}
Expand All @@ -82,20 +123,66 @@ pub struct MoveEvent {
pub ts: u64,
}

/// Append-only game events. Only `Move` changes the board for FEN replay.
/// Append-only game events. Only `Move` changes the board for FEN replay
/// (and `Takeback` undoes the latest net Move; see `replay_fen`).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "typ")]
pub enum GameEvent {
#[serde(rename = "Move")]
Move { seq: u64, uci: String, ts: u64 },
Move {
seq: u64,
uci: String,
ts: u64,
},
/// Non-position note (pairing, admin). Ignored by FEN replay.
ServerNote { seq: u64, text: String, ts: u64 },
ServerNote {
seq: u64,
text: String,
ts: u64,
},
/// Draw or takeback offered (audit; pending also mirrored on meta).
Offer {
seq: u64,
kind: String,
by: String,
ts: u64,
},
/// Accept/decline/withdraw of a pending offer.
OfferResponse {
seq: u64,
kind: String,
by: String,
accept: bool,
ts: u64,
},
Resign {
seq: u64,
by: String,
ts: u64,
},
Abort {
seq: u64,
by: String,
ts: u64,
},
/// Undo the net Move with `undone_seq` (replay pops that ply).
Takeback {
seq: u64,
undone_seq: u64,
ts: u64,
},
}

impl GameEvent {
pub fn seq(&self) -> u64 {
match self {
Self::Move { seq, .. } | Self::ServerNote { seq, .. } => *seq,
Self::Move { seq, .. }
| Self::ServerNote { seq, .. }
| Self::Offer { seq, .. }
| Self::OfferResponse { seq, .. }
| Self::Resign { seq, .. }
| Self::Abort { seq, .. }
| Self::Takeback { seq, .. } => *seq,
}
}

Expand Down
17 changes: 12 additions & 5 deletions src/game/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
//! Legal apply + PROTOCOL MoveRejected codes: CV-162.
//! Clocks + Fischer increment + flag: CV-163 / ADR-005.
//! Lag compensation quota from server RTT: CV-164.
//! Draw / takeback / resign / abort: CV-165.

mod apply;
mod clock;
mod events;
mod lag;
mod offers;
mod replay;
mod store;

Expand All @@ -21,15 +23,20 @@ pub use clock::{
is_flagged_at, is_flagged_at_compensated, remaining_at, tick_on_move, tick_on_move_compensated,
ClockPair, ClockTick, FlagClaimError, FlagOutcome,
};
pub use events::{GameEvent, GameMeta, MoveEvent, START_FEN};
pub use events::{GameEvent, GameMeta, MoveEvent, PendingOffer, START_FEN};
pub use lag::{
active_seat_credit_ms, credit_lag, effective_elapsed_ms, estimated_game_ms, initial_quota_ms,
peek_credit_ms, seed_lag_quotas, LagCredit, LagTracker, ESTIMATE_INC_MOVES, QUOTA_CAP_MS,
QUOTA_FLOOR_MS,
};
pub use replay::replay_fen;
pub use offers::{
abort, abort_allowed, abort_window_ms, game_end_offer_json, offer_draw, offer_error_json,
offer_state_json, offer_takeback, resign, respond_offer, GameEndOut, OfferError, OfferOutcome,
OfferRejectCode, OfferStateOut, OFFER_DRAW, OFFER_TAKEBACK,
};
pub use replay::{net_move_events, replay_fen};
pub use store::{
append_move_event, create_game, delete_game, game_events_key, game_meta_key, load_events,
load_meta, reconstruct_fen, save_meta, GameLogError, GAME_KEY_PREFIX, MAX_EVENTS, MAX_FEN_LEN,
MAX_GAME_ID_LEN, MAX_PLAYER_ID_LEN, MAX_UCI_LEN,
append_game_event, append_move_event, create_game, delete_game, game_events_key, game_meta_key,
load_events, load_meta, reconstruct_fen, save_meta, GameLogError, GAME_KEY_PREFIX, MAX_EVENTS,
MAX_EVENT_BYTES, MAX_FEN_LEN, MAX_GAME_ID_LEN, MAX_META_BYTES, MAX_PLAYER_ID_LEN, MAX_UCI_LEN,
};
Loading
Loading