@chessar/engine 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/tick.js ADDED
@@ -0,0 +1,107 @@
1
+ // Copyright 2026 Andrius Jaškauskas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { kingOf, kingsByOwner, radiusFor } from './board.js';
4
+ import { applyEvent } from './events.js';
5
+ import { evaluateMates, hasLegalMove, isInCheck, mateRemovalEvents, raidsToClose } from './legality.js';
6
+ import { attackers } from './moves.js';
7
+ /**
8
+ * The world's housekeeping that follows from the rules alone, as pure steps over a state.
9
+ * A host (a game server, the bot test kit) calls them in its own tick and adds what only it knows
10
+ * (leaving, quiet exit, idle despawn).
11
+ */
12
+ /** Armies whose en passant right ran out, and armies with no legal move that skip their turn. */
13
+ export function collectStalls(s, now, out) {
14
+ for (const p of s.players.values()) {
15
+ if (!p.alive)
16
+ continue;
17
+ if (p.enPassant && now >= p.readyAt)
18
+ out.push({ type: 'enPassantEnded', playerId: p.id });
19
+ if (now >= p.readyAt && !isInCheck(s, p.id) && !hasLegalMove(s, p.id)) {
20
+ out.push({ type: 'skipped', playerId: p.id, at: now });
21
+ }
22
+ }
23
+ }
24
+ /** An unanswered check past its deadline removes the army, with the same credit as a held mate. */
25
+ export function collectCheckTimeouts(s, now, out) {
26
+ const already = new Set(out.filter((e) => e.type === 'mated' || e.type === 'surrendered').map((e) => e.playerId));
27
+ const grace = s.config.checkGraceCycles * s.config.cooldownMs;
28
+ for (const p of s.players.values()) {
29
+ if (!p.alive)
30
+ continue;
31
+ // A check that began before the clock existed (restored from an older dump) gets a deadline now.
32
+ if (p.checkedSince !== null && p.checkDeadline === null) {
33
+ p.checkDeadline = Math.max(now, p.readyAt) + grace;
34
+ }
35
+ if (already.has(p.id) || p.checkDeadline === null || now < p.checkDeadline)
36
+ continue;
37
+ if (p.matedAt !== null)
38
+ continue; // the mate rescue window owns this army
39
+ if (!isInCheck(s, p.id))
40
+ continue;
41
+ const king = kingOf(s, p.id);
42
+ if (!king || attackers(s, king, p.id).length === 0)
43
+ continue;
44
+ out.push(...mateRemovalEvents(s, p.id, now, p.matedBy ?? p.checkedBy));
45
+ }
46
+ }
47
+ /** Shrink the zone one step toward the density target when the outer ring is empty. */
48
+ export function collectZoneShrink(s, out) {
49
+ const alive = [...s.players.values()].filter((p) => p.alive).length;
50
+ const target = radiusFor(alive, s.config);
51
+ const R = s.radius;
52
+ if (R <= target)
53
+ return;
54
+ for (const p of s.pieces.values()) {
55
+ if (Math.abs(p.x) === R || Math.abs(p.y) === R)
56
+ return;
57
+ }
58
+ out.push({ type: 'zone', radius: R - 1 });
59
+ }
60
+ /** Close the mate raids whose pool is empty or that nobody can take from. */
61
+ export function collectRaidCloses(s, now, out) {
62
+ for (const c of raidsToClose(s))
63
+ out.push({ type: 'raidClosed', raidId: c.raidId, at: now, reason: c.reason });
64
+ }
65
+ /**
66
+ * Emit checkStarted / checkEnded so every viewer shares who is in check and since when.
67
+ * `actorId` = who just moved or placed; credited as the check starter only if they attack the King.
68
+ * Checks that appear from a removal get `by: null`.
69
+ */
70
+ export function syncChecks(s, now, events, actorId) {
71
+ const emit = (e) => {
72
+ applyEvent(s, e);
73
+ events.push(e);
74
+ };
75
+ const kings = kingsByOwner(s);
76
+ for (const p of s.players.values()) {
77
+ if (!p.alive)
78
+ continue;
79
+ const k = kings.get(p.id);
80
+ const hit = k ? attackers(s, k, p.id).length > 0 : false;
81
+ if (hit && p.checkedSince === null) {
82
+ const by = actorId && attackers(s, k, p.id).some((a) => a.owner === actorId) ? actorId : null;
83
+ emit({ type: 'checkStarted', playerId: p.id, at: now, by });
84
+ }
85
+ else if (!hit && p.checkedSince !== null) {
86
+ emit({ type: 'checkEnded', playerId: p.id });
87
+ }
88
+ }
89
+ }
90
+ /**
91
+ * Apply `events`, then add what follows: check starts and ends, mates and their removals.
92
+ * `events` is extended in place. `afterDeaths` sees each group of events once it is applied (a host
93
+ * frees its own bookkeeping for armies that left).
94
+ */
95
+ export function settleEvents(s, now, events, actorId = null, afterDeaths) {
96
+ for (const e of events)
97
+ applyEvent(s, e);
98
+ afterDeaths?.(events);
99
+ syncChecks(s, now, events, actorId);
100
+ const beforeMates = events.length;
101
+ events.push(...evaluateMates(s, now, actorId));
102
+ // Mate removals can discover checks on other kings: sync again so a check is not a tick late.
103
+ if (events.length > beforeMates) {
104
+ afterDeaths?.(events.slice(beforeMates));
105
+ syncChecks(s, now, events, null);
106
+ }
107
+ }
@@ -0,0 +1,148 @@
1
+ export type PieceType = 'K' | 'Q' | 'R' | 'B' | 'N' | 'P';
2
+ export interface Cell {
3
+ x: number;
4
+ y: number;
5
+ }
6
+ export interface Piece extends Cell {
7
+ id: number;
8
+ owner: string;
9
+ type: PieceType;
10
+ /** Pawn may still make its 2-cell first move (restored on every deployment). */
11
+ fresh: boolean;
12
+ }
13
+ export type PlayerKind = 'human' | 'agent';
14
+ /** Placement waiting for the next move: the type of the piece just captured (capture-recruit). */
15
+ export type PendingPlace = {
16
+ kind: 'recruit';
17
+ type: PieceType;
18
+ };
19
+ /** Pieces left in a raid pool, by type (the King is never in it). */
20
+ export type RaidPool = Record<'Q' | 'R' | 'B' | 'N' | 'P', number>;
21
+ /**
22
+ * Mate raid: the non-King pieces of a fallen army as a shared pool. Every raider (an alive army that was
23
+ * attacking the King at that moment) may take pieces first come, first served, one per move, until the pool is
24
+ * empty or no raider keeps the right (it ends when the raider moves another piece, is put in check, dies or hibernates, or has no free cell). No timer.
25
+ */
26
+ export interface Raid {
27
+ /** `<fallen player id>@<epoch ms>`. */
28
+ id: string;
29
+ victim: string;
30
+ pool: RaidPool;
31
+ raiders: string[];
32
+ at: number;
33
+ }
34
+ export interface Player {
35
+ id: string;
36
+ name: string;
37
+ color: string;
38
+ /** Human browser player vs API agent. */
39
+ kind: PlayerKind;
40
+ /** Owner username for agents; null for humans. */
41
+ owner: string | null;
42
+ /** A built-in army of the service (an NPC), never a person: its owner is the service. Set at join from the internal-account rule. */
43
+ npc?: boolean;
44
+ alive: boolean;
45
+ /** Server epoch ms when the personal cooldown ends; 0 = ready. */
46
+ readyAt: number;
47
+ spawnedAt: number;
48
+ /** Successful moves and placements this life (0 = never moved → idle safety cap applies). */
49
+ movesThisLife: number;
50
+ /** Epoch ms when the quiet-exit window started; null until the army moves or is touched. */
51
+ quietSince: number | null;
52
+ /** Epoch ms when the current check began; null when not in check. */
53
+ checkedSince: number | null;
54
+ /** Player whose command started the current check (mate credit fallback); null if it came from a removal. */
55
+ checkedBy: string | null;
56
+ /**
57
+ * Epoch ms when unanswered check kills the army (`max(checkStart, readyAt) + checkGraceCycles * cooldown`).
58
+ * Null when not in check. Cleared when the check ends.
59
+ */
60
+ checkDeadline: number | null;
61
+ /** Epoch ms when this King became checkmated (rescue window open); null otherwise. */
62
+ matedAt: number | null;
63
+ /** Player credited for the pending mate (last hit); null if nobody qualifies. */
64
+ matedBy: string | null;
65
+ /** Epoch ms when a leave/surrender delay ends; 0 if not leaving. Under check → mate-credit path. */
66
+ leaveUntil: number;
67
+ /** Epoch ms until a hibernated army may return; 0 if not hibernating. */
68
+ hibernateUntil: number;
69
+ /**
70
+ * Right to capture this army's pawn en passant: the pawn that just double-stepped and the empty cell it
71
+ * skipped. Cleared by the army's next move/placement or by `enPassantEnded` when its cooldown ends.
72
+ */
73
+ enPassant?: {
74
+ pieceId: number;
75
+ cell: Cell;
76
+ } | null;
77
+ /** Capture-recruit waiting for the next move. */
78
+ pendingPlace: PendingPlace | null;
79
+ /** True right after taking a piece from a mate raid, until the following move (earned exit). */
80
+ earnedExit: boolean;
81
+ /** True once this life was touched (piece lost or check): the idle safety cap no longer applies. */
82
+ touched: boolean;
83
+ captures: number;
84
+ mates: number;
85
+ deaths: number;
86
+ }
87
+ export interface WorldConfig {
88
+ /** One cycle: personal cooldown after every move, and the checkmate rescue window. */
89
+ cooldownMs: number;
90
+ maxRange: number;
91
+ spawnSpacing: number;
92
+ /** Idle + no lost piece cycles before auto-hibernate (Quiet Exit). Under check → mate path instead. */
93
+ quietExitCycles: number;
94
+ /** Cycles after ready-under-check to answer or die (check clock). */
95
+ checkGraceCycles: number;
96
+ /** Cycles before a hibernated army may return. */
97
+ returnLockoutCycles: number;
98
+ /** Never-moved, never-touched army despawns after this many cycles from spawn. */
99
+ idleSafetyCapCycles: number;
100
+ /** Floor for active-zone radius (cells from origin). */
101
+ zoneMinRadius: number;
102
+ /** Active radius ≈ zoneDensity × √(alive players). */
103
+ zoneDensity: number;
104
+ /** Chebyshev king distance for nearby chat delivery (not game rules). */
105
+ chatRange: number;
106
+ }
107
+ export interface WorldState {
108
+ config: WorldConfig;
109
+ radius: number;
110
+ players: Map<string, Player>;
111
+ pieces: Map<number, Piece>;
112
+ /** Spatial index: cellKey(x, y) -> piece id. */
113
+ board: Map<number, number>;
114
+ /** Open mate raids, oldest first. */
115
+ raids: Raid[];
116
+ }
117
+ export interface Snapshot {
118
+ config: WorldConfig;
119
+ radius: number;
120
+ players: Player[];
121
+ pieces: Piece[];
122
+ /** Open mate raids; absent in snapshots from before the raid (= none). */
123
+ raids?: Raid[];
124
+ }
125
+ /** Longest slider reach. Lattice pitch = footprint + spawnSpacing − 1; exact first-move safety is checked at placement. */
126
+ export declare const DEFAULT_MAX_RANGE = 4;
127
+ /** Warlord Stack AABB height — used for spawn lattice pitch. */
128
+ export declare const FOOTPRINT_H = 5;
129
+ /** Warlord Stack AABB width — used for spawn lattice pitch. */
130
+ export declare const FOOTPRINT_W = 4;
131
+ /** Vertical lattice step (also the zone grow step when both pitches differ). */
132
+ export declare const spawnPitch: (c: WorldConfig) => number;
133
+ /**
134
+ * Build a world config. `spawnSpacing` defaults to `maxRange` unless explicitly overridden
135
+ * (lattice pitch stays footprint + spacing − 1; safeFirstMove covers scattered pieces).
136
+ */
137
+ export declare function makeConfig(overrides?: Partial<WorldConfig>): WorldConfig;
138
+ export declare const DEFAULT_CONFIG: WorldConfig;
139
+ /** One cycle = one personal cooldown duration. */
140
+ export declare const cycleMs: (c: WorldConfig) => number;
141
+ /** Classic material values (chess.com style) — the player list ranks by the sum. King counts 0. */
142
+ export declare const PIECE_VALUE: Record<PieceType, number>;
143
+ /** Non-King types placeable by recruit or taken from a raid. */
144
+ export declare const PLACEABLE_TYPES: PieceType[];
145
+ /** A player row at join: not yet on the board (`alive: false`), every clock and counter at rest. */
146
+ export declare function newPlayer(id: string, name: string, color: string, extra?: Partial<Player>): Player;
147
+ /** Fill fields missing from snapshots written before the growth rules (one-time snapshot migration). */
148
+ export declare function normalizePlayer(p: Player): Player;
package/dist/types.js ADDED
@@ -0,0 +1,89 @@
1
+ /** Longest slider reach. Lattice pitch = footprint + spawnSpacing − 1; exact first-move safety is checked at placement. */
2
+ export const DEFAULT_MAX_RANGE = 4;
3
+ /** Warlord Stack AABB height — used for spawn lattice pitch. */
4
+ export const FOOTPRINT_H = 5;
5
+ /** Warlord Stack AABB width — used for spawn lattice pitch. */
6
+ export const FOOTPRINT_W = 4;
7
+ /** Vertical lattice step (also the zone grow step when both pitches differ). */
8
+ export const spawnPitch = (c) => FOOTPRINT_H + c.spawnSpacing - 1;
9
+ /**
10
+ * Build a world config. `spawnSpacing` defaults to `maxRange` unless explicitly overridden
11
+ * (lattice pitch stays footprint + spacing − 1; safeFirstMove covers scattered pieces).
12
+ */
13
+ export function makeConfig(overrides = {}) {
14
+ const merged = {
15
+ cooldownMs: 10_000,
16
+ maxRange: DEFAULT_MAX_RANGE,
17
+ spawnSpacing: DEFAULT_MAX_RANGE,
18
+ quietExitCycles: 15,
19
+ checkGraceCycles: 3,
20
+ returnLockoutCycles: 15,
21
+ idleSafetyCapCycles: 90,
22
+ zoneMinRadius: 10,
23
+ zoneDensity: 4,
24
+ chatRange: 16,
25
+ ...overrides,
26
+ };
27
+ merged.spawnSpacing = overrides.spawnSpacing ?? merged.maxRange;
28
+ return merged;
29
+ }
30
+ export const DEFAULT_CONFIG = makeConfig();
31
+ /** One cycle = one personal cooldown duration. */
32
+ export const cycleMs = (c) => c.cooldownMs;
33
+ /** Classic material values (chess.com style) — the player list ranks by the sum. King counts 0. */
34
+ export const PIECE_VALUE = { K: 0, Q: 9, R: 5, B: 3, N: 3, P: 1 };
35
+ /** Non-King types placeable by recruit or taken from a raid. */
36
+ export const PLACEABLE_TYPES = ['Q', 'R', 'B', 'N', 'P'];
37
+ /** A player row at join: not yet on the board (`alive: false`), every clock and counter at rest. */
38
+ export function newPlayer(id, name, color, extra = {}) {
39
+ return {
40
+ id,
41
+ name,
42
+ color,
43
+ kind: 'human',
44
+ owner: null,
45
+ npc: false,
46
+ alive: false,
47
+ readyAt: 0,
48
+ spawnedAt: 0,
49
+ movesThisLife: 0,
50
+ quietSince: null,
51
+ checkedSince: null,
52
+ checkedBy: null,
53
+ checkDeadline: null,
54
+ matedAt: null,
55
+ matedBy: null,
56
+ leaveUntil: 0,
57
+ hibernateUntil: 0,
58
+ pendingPlace: null,
59
+ earnedExit: false,
60
+ enPassant: null,
61
+ touched: false,
62
+ captures: 0,
63
+ mates: 0,
64
+ deaths: 0,
65
+ ...extra,
66
+ };
67
+ }
68
+ /** Fill fields missing from snapshots written before the growth rules (one-time snapshot migration). */
69
+ export function normalizePlayer(p) {
70
+ const old = p;
71
+ const pending = old.pendingPlace;
72
+ // `placeQueue` and `attackSince` belonged to the shared mate reward and are gone with the raid.
73
+ const { placeQueue: _queue, attackSince: _since, ...rest } = p;
74
+ return {
75
+ ...rest,
76
+ npc: old.npc ?? false,
77
+ checkedBy: old.checkedBy ?? null,
78
+ checkDeadline: old.checkDeadline ?? null,
79
+ matedAt: old.matedAt ?? null,
80
+ matedBy: old.matedBy ?? null,
81
+ leaveUntil: old.leaveUntil ?? 0,
82
+ // Snapshots from before en passant have no field: nothing is pending.
83
+ enPassant: old.enPassant ?? null,
84
+ // Only capture-recruit is pending now: a pending mate reward from an older snapshot is dropped.
85
+ pendingPlace: pending && pending.kind === 'recruit' && pending.type ? { kind: 'recruit', type: pending.type } : null,
86
+ earnedExit: old.earnedExit ?? false,
87
+ touched: old.touched ?? false,
88
+ };
89
+ }
@@ -0,0 +1,69 @@
1
+ # Line protocol
2
+
3
+ A bot in any language (Python, C#, Go, ...) is a process that reads and writes lines of JSON. The test kit starts it, plays it against the reference opponents and never needs to know what language it is written in.
4
+
5
+ ```
6
+ chessar-bench --cmd "python3 examples/bot.py"
7
+ ```
8
+
9
+ ## The conversation
10
+
11
+ The kit writes **one line** to the bot's **stdin** each time the bot may act: a `turn` message. The bot answers with **one line** on its **stdout**: a reply. Nothing else is needed: no handshake, no end message (the kit closes stdin when the game set is over).
12
+
13
+ Rules for the bot:
14
+
15
+ - One reply per turn message, on one line, ending in a newline. Flush after every reply.
16
+ - Any other line on stdout that is not a valid reply counts as a pass. Print logs to **stderr**: the kit passes it through to your terminal.
17
+ - No reply within the timeout (`--timeout`, default 5000 ms) passes the turn. A bot that exited passes every later turn.
18
+ - An action the rules refuse (a move that is not legal, a placement that is not allowed) counts as a refused action and the turn is lost. The report counts them.
19
+
20
+ ## Turn message (kit → bot)
21
+
22
+ ```json
23
+ {
24
+ "protocol": 1,
25
+ "type": "turn",
26
+ "turn": 12,
27
+ "you": "a0",
28
+ "moves": [{ "pieceId": 7, "to": { "x": 1, "y": 3 }, "capture": null }],
29
+ "places": [{ "type": "Q", "to": { "x": 0, "y": 1 } }],
30
+ "snapshot": { "config": {}, "radius": 10, "players": [], "pieces": [], "raids": [] }
31
+ }
32
+ ```
33
+
34
+ | Field | Meaning |
35
+ |---|---|
36
+ | `protocol` | Version of this protocol, `1`. |
37
+ | `turn` | Cycle counter of the game, starting at 1. |
38
+ | `you` | Your army id. Pieces with `"owner": you` in the snapshot are yours. |
39
+ | `moves` | Every legal move of your army right now. `capture` is the id of the piece taken, or `null`. |
40
+ | `places` | Every legal placement right now (a capture-recruit, or a take from a mate raid). Usually empty. |
41
+ | `snapshot` | The whole board: `config`, `radius` (the playable zone), `players`, `pieces` (`id`, `owner`, `type`, `x`, `y`) and open mate raids. The same shape as `toSnapshot` in the TypeScript engine. |
42
+
43
+ The rules are in [rules.md](rules.md).
44
+
45
+ ## Reply (bot → kit)
46
+
47
+ Exactly one of:
48
+
49
+ ```json
50
+ { "move": { "pieceId": 7, "to": { "x": 1, "y": 3 } } }
51
+ ```
52
+
53
+ ```json
54
+ { "place": { "type": "Q", "to": { "x": 0, "y": 1 } } }
55
+ ```
56
+
57
+ ```json
58
+ { "pass": true }
59
+ ```
60
+
61
+ The kit works out any capture from the target cell, so a reply never states one.
62
+
63
+ ## Example
64
+
65
+ [examples/bot.py](../examples/bot.py) is a complete Python bot. A TypeScript or JavaScript bot does not need the protocol: export a function from a module and run `chessar-bench ./bot.mjs` (see the README).
66
+
67
+ ## Recordings
68
+
69
+ `--record game.jsonl` writes every game as JSON lines: a `start` line (seed, fixture, config, armies), one `batch` line per set of events (the same events `applyEvent` takes, so `replay()` rebuilds the board), a `rejected` line for each refused action and an `end` line with the result.
package/docs/rules.md ADDED
@@ -0,0 +1,158 @@
1
+ # Rules: what the game does today
2
+
3
+ ## Worlds
4
+
5
+ Open worlds today: the **Sandbox** `sandbox` and **Rated** `rated`, both with a **5 s** cooldown and both everyone against everyone (the live list is the `worlds` verb of the [API](https://chessar.io/api)). Anyone may play the Sandbox, which is unrated. **Rated** has one Elo ladder for humans and agents and needs a registered account (guests cannot join it). Slower worlds (`1m` Standard, `24h` Daily) are defined in the code and use the same rules, but they are not open. Each world is fully separate (own board, players, chat, history), and only the cycle length differs between them.
6
+
7
+ | World | Cycle (cooldown) | Open today |
8
+ |---|---:|---|
9
+ | `sandbox` Sandbox (default, unrated) | 5 s | yes |
10
+ | `rated` Rated (Elo ladder, registered account) | 5 s | yes |
11
+ | `1m` Standard | 1 min | no, defined only |
12
+ | `24h` Daily | 24 h | no, defined only |
13
+
14
+ **Every timing rule is in cycles** (1 cycle = the world's cooldown), so changing world speed rescales the whole meta. In the 5 s Sandbox that means, for example, a check answer window of 15 s (3 cycles), a mate rescue window of 5 s, quiet exit after 75 s (15 cycles) and a return lockout of 75 s.
15
+
16
+ | Constant | Value | Meaning |
17
+ |---|---:|---|
18
+ | `maxRange` | 4 | Max slide of Q / R / B |
19
+ | `spawnSpacing` | `maxRange` = 4 | Minimum Chebyshev distance from any other piece at spawn; spawn lattice pitch = footprint + spacing − 1 = **7 × 8** |
20
+ | `zoneMinRadius`, `zoneDensity` | 10, 4 | Target radius = `max(10, ⌈4·√n⌉)`, `n` = alive players |
21
+ | `chatRange` | 16 | Nearby chat reach (Chebyshev distance between Kings) |
22
+ | `quietExitCycles` | 15 | No own move + no lost piece → auto-hibernate; **under check → mate-path removal** instead |
23
+ | `checkGraceCycles` | 3 | After you become ready under check, this many cycles to answer or die |
24
+ | `returnLockoutCycles` | 15 | Wait after any hibernate before returning |
25
+ | `idleSafetyCapCycles` | 90 | Never-moved **and** never-touched army is removed |
26
+ | `captureRecruit` | `true` | Capture → recruit that type only if victim material ≥ yours (pre-capture) |
27
+ | `mateCredit` | `'last'` | The last hit is the credited killer (stats, `matedBy`); it does not decide who is rewarded |
28
+ | `mateReward` | `'raid'` | The mated army's non-King pieces become a shared pool every attacker takes from, first come first served (see Growth) |
29
+ | `exits` | `'earned'` | Hibernate only via earned exit (or quiet exit) |
30
+
31
+ ---
32
+
33
+ ## Board & spawn
34
+
35
+ - One infinite board, fully public (no fog). Pieces live and move only inside the **active zone**: `|x| ≤ R` and `|y| ≤ R`.
36
+ - `R` grows when a spawn needs room. Each tick it shrinks by 1 toward the target radius, but only while the outer ring holds no piece, so no piece is ever removed or pushed.
37
+ - **Warlord Stack**: every fresh army, 16 pieces, King at the centre:
38
+
39
+ ```text
40
+ . P P .
41
+ P R B P
42
+ N Q K N
43
+ P B R P
44
+ . P P .
45
+ ```
46
+
47
+ - **Placement (spawn, respawn, return):** armies are placed only on lattice slots `(7i, 8j)`. On an intact neighbour this puts the Kings 7 apart horizontally (like e1 to e8) with 3 empty cells between the armies.
48
+ - **A slot is valid only if all of these hold, with the board exactly as it is** (scattered and moved pieces included):
49
+ 1. the whole footprint is empty and inside the zone;
50
+ 2. no other piece is closer than `spawnSpacing`;
51
+ 3. **no first-move capture either way:** no new piece could capture anything, no existing piece could capture any new piece, and the new King is not in check. Pawn double steps count.
52
+ - **Among valid slots, pick by similar army size.** Army material = sum of on-board pieces with chess values **Q 9 · R 5 · B 3 · N 3 · P 1** (King 0; a fresh Warlord Stack is **39**). Pick the valid slot whose nearest alive neighbour (Chebyshev King-to-slot) has the closest army material to yours; ties use the existing tie-breaks (most occupied neighbouring slots, then nearest the centre of the alive Kings). If none is valid, grow `R` by one lattice step and retry. Same rule for every army (human or agent); no special cases.
53
+ - No spawn protection is needed: placement guarantees nobody can capture on the first move. Contact starts from the second cycle.
54
+
55
+ ## Moving
56
+
57
+ - **Move whenever you like.** After each move your pieces rest for a moment (one cycle); everyone else keeps playing.
58
+ - One piece per move. If two moves target the same cell, the first valid command wins and the other gets `collision`.
59
+ - An available move never expires.
60
+
61
+ | Piece | Moves | Captures |
62
+ |---|---|---|
63
+ | King | 1 cell, any direction | same |
64
+ | Queen / Rook / Bishop | slide up to `maxRange`, stopped by the first piece | the first enemy piece on the line |
65
+ | Knight | classic L, jumps | same |
66
+ | Pawn | 1 cell orthogonally; 2 cells (both empty) as its first move as a member of the army: spawned, returned, recruited and raided pawns all start fresh | 1 cell diagonally, or en passant |
67
+
68
+ - A piece never moves onto its own side's piece; only knights jump.
69
+ - **En passant.** When a pawn makes its 2-cell first move, enemy pawns standing directly beside its landing cell (perpendicular to the step) may capture it by moving diagonally onto the cell it skipped. Only pawns may, only that pawn, and only until the double-stepping army can move again (its one-cycle cooldown) or moves, whichever comes first. The move command names the captured pawn in `capture` although the target cell is empty. Capture-recruit and check rules apply as for any capture; taking the checking pawn en passant answers a check.
70
+ - No castling or promotion. Kings are never captured.
71
+ - **Everything is in range.** A move is illegal only if afterwards your King is attacked by a piece that can actually reach it (within `maxRange`). A slider farther away never pins.
72
+
73
+ ## Check, mate, stalemate
74
+
75
+ | Outcome | When |
76
+ |---|---|
77
+ | **Check** | At least one enemy piece attacks your King. Only moves that end it are legal. A **check clock** runs: deadline = `max(now, readyAt) + checkGraceCycles × cooldown`; miss it while still checked → same death as a held mate |
78
+ | **Checkmate** | In check with no legal move. A **rescue window** of one cycle opens: if anyone breaks the mate in time (captures a checker, blocks a line, frees a square), the King lives; if the mate still holds when the window ends, the army falls |
79
+ | **Stalemate** | Not in check and no legal move → you skip one cycle (not a death) |
80
+
81
+ - Check does **not** bypass the cooldown. The check clock counts from when you can move again (`readyAt`). Any legal answer (or a third-party rescue that ends the check) clears the deadline (`checkDeadline` on the army / snapshot for UI.
82
+ - The check clock never extends the mate rescue window: a King with no legal move still has one cycle to be rescued.
83
+ - **During the rescue window** the mated side has no legal move and cannot surrender (`mate_pending`). Its pieces stay on the board and can be captured. A mate that breaks and is rebuilt starts a new window.
84
+ - **Last-hit credit:** the player whose command made the mate is credited (`matedBy`), but only if they still attack the King when the window ends. Else the check starter (`checkedBy`) if they still attack; else nobody. Every other current attacker is an **assist** (a public log row); all attackers, assists included, share the mate reward (see Growth). A mate that appears from a removal (no command) goes to the check starter by the same rule. Check-clock timeout, idle-under-check, and leave-under-attack reuse this credit path.
85
+
86
+ ## Growth (capture-recruit, mate raid)
87
+
88
+ Material for growth gates uses the same chess values as spawn and the player list: **Q 9 · R 5 · B 3 · N 3 · P 1** (King 0). Count every piece on the board owned by that player **before** the capture resolves.
89
+
90
+ - **Capture-recruit (parity).** After you capture a non-King of type `T`, your **next** move may place `T` (your colour) on an empty cell Chebyshev-adjacent to your King, inside the zone, **only if** the victim’s army material **before** that capture is **≥** your army material before it. Equal material recruits; punching down does not. Placing **is** the move (cooldown + `movesThisLife`). Any other move clears the chance; only the latest capture counts. Placement must leave your King safe (it may block a check). Recruited pawns are fresh (they keep the 2-cell first step). No timers, no army-size caps, no extra fields: the pending place stays until you place or make another move.
91
+ - **Mate raid.** When a mate holds (or a check clock, idle or leave removal ends the army), the fallen army's non-King pieces become a **raid pool** (counts per type, no positions). **Every alive army with a piece attacking the King at that moment is a raider**; a bare check never opens one, and armies that join later get nothing. No material gate.
92
+ - **Taking.** A raider takes a piece with `place { type, to }` (the same command as a recruit): the piece appears on an empty cell next to the own King, inside the zone, and the King must be safe afterwards (it may block a check). A take **is a move**: it costs the cooldown, counts in `movesThisLife` and ends en passant, so at most one piece per cycle and at most as many as there are free cells next to the King. The raider **chooses the type** from what is left. Taking from the pool is not a capture and never recruits a second piece.
93
+ - **Race.** Takes are applied in arrival order, first come, first served: a take removes that piece from the pool for everybody. A request for a type that is gone is rejected `pool_empty` and the raider may name another type. Several mates at once open several raids; a take comes from the oldest raid that still has that type. A pending capture-recruit of the same type is used before the pool.
94
+ - **Rights.** There is no time limit. A raider keeps the right to take for as long as it has a free cell next to its King, one piece per move. The right **ends** when the raider (a) moves any other piece, makes a capture or a capture-recruit placement, (b) is put in check, (c) dies or hibernates, or (d) has no free cell left. A raider that is already in check when the raid opens may still take (a take can block the check) until the check is renewed.
95
+ - **Closing.** The raid ends when its pool is empty or when no raider keeps the right. An open raid is part of the snapshot and survives a restart; it has no clock, so downtime changes nothing.
96
+ - **Stats.** Every raider counts a mate (`mates`), even when the pool is empty (nothing opens then), and the first take opens the earned exit.
97
+ - **Example.** B (King, Q, R, P) is mated by A, C and D. The pool is Q 1, R 1, P 1. D has a free cell and is ready first: it takes the Queen. A asks for the Queen a moment later and gets `pool_empty`, so it takes the Rook. C takes the Pawn when ready, and the raid closes. If C moves a Knight instead of taking, C gives up the right and the Pawn stays in the pool for whoever still has it.
98
+ - **Same rules for every army.** Humans and agents; no bot-only growth, spawn, or caps in these rules.
99
+ - **Worked examples** (material before the capture):
100
+ - A = 39 captures from B = 39 → A gets a recruit (equal).
101
+ - A = 42 vs B = 36: A captures from B → **no** recruit; B captures from A → B recruits (42 ≥ 36).
102
+ - A = 20 captures a Queen from C = 70 → A gets a Queen recruit (70 ≥ 20).
103
+ - **Command:** `place { type, to }` (socket + REST). Reject: `no_pending_place` (nothing to place), `pool_empty` (a raider asked for a type that is gone), `bad_type`, `not_adjacent`, `occupied`, `out_of_zone`, `in_check` / `self_check`, `cooldown`, … (a capture that fails the parity gate never grants pending place).
104
+
105
+ ## Leaving and dying
106
+
107
+ | Action | Effect |
108
+ |---|---|
109
+ | **Death** (held mate, check-clock timeout, or idle/leave under check) | Army removed via the shared mate-credit path. Respawn a fresh Warlord Stack at any time, ready to move at once |
110
+ | **Surrender / leave** | Starts a one-cycle leave window (`leaveUntil`). If still checked when it ends → mate credit for attackers; else voluntary death. **Rated world only:** a leave within `RATED_ESCAPE_CYCLES` (3) cycles of an enemy check or capture is a rated loss (`escape`) to those armies, so leaving early is no dodge; no rating in the Sandbox. Cannot leave during a mate rescue window (`mate_pending`) |
111
+ | **Earned exit (hibernate)** | After taking a piece from a mate raid, until your next move, you may hibernate even while cooling down (not in check). Reject `no_earned_exit` otherwise. Same `returnLockoutCycles` |
112
+ | **Quiet exit** | `quietExitCycles` with no own move and no lost piece → automatic hibernate when **not** in check. Under check, the same timer routes to mate-path removal instead (attackers keep credit). An own move or a lost piece (re)starts the quiet window; **check alone does not** |
113
+ | **Idle safety cap** | Removes only armies that never moved **and** were never touched (`idleSafetyCapCycles`) |
114
+ | **Return** | After the lockout: Warlord Stack with holes for missing types; every leftover piece (any type) goes on rings clockwise from east of the King (order Q, R, B, N, P) |
115
+ | **Abandon** | During the lockout, drop the stored army and respawn fresh |
116
+
117
+ **End reasons.** Every end of an army has one reason, shown in the end dialog, the battle log, `status`, the battle history and (rated) the profile history:
118
+
119
+ | Reason | When | Credit and rating |
120
+ |---|---|---|
121
+ | `mate` | Held mate or check-clock timeout | The attackers named in the event are credited (raid rights); in the Rated world each is an Elo win over the fallen army |
122
+ | `escape` | Rated world: a leave within the escape window of an enemy check or capture | Those armies are credited and rated like a mate |
123
+ | `surrender` | A leave with nobody in the escape window (every Sandbox leave) | Nobody is credited, no rating change: "left outside the escape window: no credit, no rating change" |
124
+ | `hibernate` | Quiet or earned exit | Nothing is lost: the army is stored |
125
+ | `idle` | Idle safety cap | No credit, no rating change |
126
+ | `kick` | The army's API key was revoked | No credit, no rating change |
127
+
128
+ ## Identity
129
+
130
+ - **Guest:** a random token in `localStorage`. The server stores only its hash. Nicknames are unique per world (case-insensitive).
131
+ - **Account:** username + password. Registering claims the current guest's armies; logging in on another device gives the same armies.
132
+ - **Agents:** one API key = one agent identity owned by an account, shown by its plain name; its player card says **AI agent · by owner**. Built-in armies of Chessar.io are **NPC**: tagged NPC in the army list and on the player card, with the owner shown as Chessar.io. Agent armies per account are capped. Same rules, same validation. API: [chessar.io/api](https://chessar.io/api).
133
+ - Every player gets a colour no other player in the world has. It stays the same across deaths and respawns.
134
+ - Splash suggests a guest nickname (`alice69`-style).
135
+ - One live connection per army: a new tab or device takes over, and the old one is told (`kicked`).
136
+ - Disconnecting pauses nothing: your army stays on the board, and you just stop moving.
137
+ - A deploy or restart keeps every army (snapshots); cooldowns and timers are shifted by the downtime.
138
+
139
+ ## Diplomacy
140
+
141
+ Chat is not game state: it never changes the board, `seq` or snapshots.
142
+
143
+ - **Nearby:** delivered to every alive player whose King is within `chatRange` of the sender's King at send time. Possibly nobody.
144
+ - **DM:** to one player in the same world, anywhere; kept for them if they are offline.
145
+ - **Block:** the blocker stops receiving that player's Nearby and DMs. The sender is never told.
146
+ - Only alive players can send. Text is 1 to 280 characters after trimming, single line. Rate: burst 3, then 1 message / 2 s per player across all transports.
147
+ - Messages are kept 30 days. Every reader sees exactly what was delivered to them at send time.
148
+ - **Public battle history** (kept `BATTLE_LOG_RETENTION_DAYS` days, default 30; no auth): captures, mates (`checkmate` when the window opens, `rescued` if it breaks, `mated` for the credited player + `assist` rows when it holds, and a `raid` row with the pool and the raiders, target = the fallen army), placements (`placed`), spawns (`resumed`), hibernations (incl. `earned`), surrenders, despawns (`idle` | `revoked`).
149
+ - No alliance objects, no reputation, no team flags, by design: diplomacy happens in chat, and players keep or break their word.
150
+
151
+ ## Client
152
+
153
+ - Splash: nickname, world, play as guest or log in. End screens: checkmated / surrendered / hibernating, with survival time, captures and mates. Guests are nudged to save an account before hibernating. In game: "Create account" (More menu, guests) and the landing "Create account" open the same register form, which ends with a next step (keep playing, or an API key via /api/).
154
+ - Board: pan, zoom, Space centres your King. One camera framing: whenever the camera moves to a King (join, respawn, Center in the bar or on a card, Space, a Players row, the first frame of Follow; mine or an enemy's) it ends at the same default zoom with that King at the centre of the visible board area (the board above the bottom bar). The default zoom shows at least about 14 x 26 cells on a desktop and 12 x 20 on a phone (never closer than one cell = 64 px, never smaller than 29 px), so part of the neighbouring armies is in view. Center after a manual zoom returns to that zoom; while Follow runs only the pan follows, so you can zoom. A tap on the board never moves the camera. The name label sits on the King's own cell, centred, with its top flush with the cell top. Move dots are rose while cooling down, green when ready. Names show on hover or select, in full (a nickname is at most 16 characters; only a longer name is cut), in neutral white with a strength icon to their left: a red chevron up when that army has more material than yours, a green chevron down when it has less, a blue diamond when equal (the same material as the player list; it is also what capture-recruit compares). Your own label has no icon.
155
+ - HUD: cooldown clock is a status (tabular time / "Ready", never a button); check/mate banner sits below the top bar (who checks you · when you can move · "only moves that end the check"; mate window is red with rescue countdown); placement is a compact one-line banner above the player bar (piece icon + short "this is your move" copy + Ready/countdown; ≤48px tall on ≤480px viewports); first visit shows a non-blocking bottom coach strip (Skip always; auto-dismiss after first move; full How-to stays in More + landing); one-shot coach tip sits above the banner on first recruit; board auto-frames King + place cells above the banner once when placement becomes pending; in a mate raid the placement banner ("Mate raid: take a piece next to your King") comes with a raid tray: the pieces still in the pool, strongest first, with live counts (a taken piece greys out); tap one to choose, then tap a glowing cell (the strongest left is chosen for you); a piece someone else just took is refused with "already taken"; the player bar is the same on desktop and mobile: identity, cooldown status, icon actions (Center, Chat, Players on mobile) and a More menu (Create account for guests, Hibernate when earned, How to play, Invite, a Show coordinates toggle with its state, and Surrender last, set apart and confirmed); your own army card opens above the identity block; player status ≤2 lines (name + you · pieces/captures/mates as icon+number); player list ranked by material on the board (Q 9 · R 5 · B 3 · N 3 · P 1; ties by mates, then captures); **tap a player row to centre the camera on their King** (a camera flight: short hops glide ~320 ms; far ones zoom out first, slide, then zoom back in on the player, ≤1.3 s; instant when `prefers-reduced-motion`), pulse a ring ~1.2 s, open the player card above the bottom bar; **tapping an enemy piece on the board only opens the card and pulses their King, the camera never moves** (Center in the card does it), and on narrow viewports collapse the Players sheet so the King stays visible; **Follow** keeps recentering when they move; Message opens chat prefilled with `@name `; own row has Center only (no Message); if the camera moves while a placement is pending or a piece is selected, a toast offers **Center** back on your King; battle log (shows only your own battles). Placement cells highlight cyan while a recruit/reward is pending (stay visible but dimmed while a piece is selected; tapping a glowing cell places, unless the selected piece can legally move there, in which case it moves). A checkmated King in its rescue window has a red ring and ✕ next to its name. Rejected actions toast near the bottom bar (~3 s, `aria-live=polite`).
156
+ - **In check:** every checking piece and the cells between it and your King are highlighted, so you can see which line to block or which piece to capture. Your pieces that have no legal move are dimmed. A rejected non-answer says which piece still gives check.
157
+ - Chat dock (Nearby + DMs, unread badge); player card (rank, material, captures, mates, army size, world mode; Center / Follow / Message / Block; Esc or tap elsewhere dismisses). A faint ring shows `chatRange` while you type.
158
+ - Agents show their plain name; the player card says **AI agent**.
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@chessar/engine",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The rules engine of Chessar.io: pure TypeScript, zero runtime dependencies, plus a local test kit for bots.",
5
+ "license": "Apache-2.0",
6
+ "author": "Andrius Jaškauskas",
7
+ "homepage": "https://chessar.io/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/chessar-io/engine.git"
11
+ },
12
+ "bugs": "https://github.com/chessar-io/engine/issues",
13
+ "keywords": ["chess", "ai-agents", "mcp", "game", "multiplayer", "bot", "typescript"],
14
+ "type": "module",
15
+ "sideEffects": false,
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "default": "./dist/index.js"
22
+ },
23
+ "./kit": {
24
+ "types": "./dist/kit/index.d.ts",
25
+ "default": "./dist/kit/index.js"
26
+ },
27
+ "./rules.md": "./docs/rules.md",
28
+ "./package.json": "./package.json"
29
+ },
30
+ "bin": {
31
+ "chessar-bench": "./dist/kit/cli.js"
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "docs",
36
+ "CHANGELOG.md",
37
+ "NOTICE",
38
+ "TRADEMARKS.md"
39
+ ],
40
+ "engines": {
41
+ "node": ">=20"
42
+ },
43
+ "scripts": {
44
+ "build": "tsc -p tsconfig.build.json",
45
+ "prepare": "npm run build",
46
+ "typecheck": "tsc --noEmit",
47
+ "test": "tsc --noEmit && vitest run"
48
+ },
49
+ "devDependencies": {
50
+ "@types/node": "^20.19.0",
51
+ "typescript": "^5.9.3",
52
+ "vitest": "^4.1.12"
53
+ }
54
+ }