Files
magik/tests/commander.test.js
masi a07522a189 MAGIK — Commander deck builder
React 19 SPA + node:http/node:sqlite API in one container. Card data is
baked into the image from a Scryfall bulk build, so the runtime never calls
Scryfall. No server-side user state: decks live in the browser and travel in
the share URL, which is why there is no PVC and replicas: 1 is correct.

Adds a README covering the architecture and the reasoning behind it, and
publishes the project skills under .claude/skills/.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-01 21:12:19 -03:00

334 lines
13 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
DECK_SIZE,
averageManaValue,
commanderIdentity,
deckSize,
emptyDeck,
manaCurve,
offIdentityColors,
partnerWith,
primaryType,
typeBreakdown,
validateDeck,
} from '../src/lib/commander.js'
/**
* The rules engine is the part of this app that has to be right: a deck it
* calls legal is a deck a player can take to a table. These tests cover each
* construction rule, and the boundaries around it.
*/
/** Builds a card record with the fields the engine reads. */
const card = (name, over = {}) => ({
id: name.toLowerCase().replace(/\W+/g, '-'),
name,
cmc: 3,
typeLine: 'Creature',
oracleText: '',
colorIdentity: '',
commanderEligible: false,
isPartner: false,
isBasicLand: false,
bannedInCommander: false,
...over,
})
const atraxa = card('Atraxa, Grand Unifier', {
typeLine: 'Legendary Creature — Phyrexian',
colorIdentity: 'WUBG',
commanderEligible: true,
cmc: 4,
})
const solRing = card('Sol Ring', { colorIdentity: 'C', typeLine: 'Artifact', cmc: 1 })
const commandTower = card('Command Tower', { colorIdentity: '', typeLine: 'Land', cmc: 0 })
const swamp = card('Swamp', { typeLine: 'Basic Land — Swamp', isBasicLand: true })
const forest = card('Forest', { typeLine: 'Basic Land — Forest', isBasicLand: true })
const lutri = card('Lutri, the Disgraced', { colorIdentity: 'UB', bannedInCommander: true })
const brainstorm = card('Brainstorm', { colorIdentity: 'U', typeLine: 'Instant', cmc: 0 })
/** A deck of `n` distinct legal cards plus the given commander. */
function legalDeck(commander = atraxa) {
const entries = Array.from({ length: DECK_SIZE - 1 }, (_, i) => ({
id: `filler-${i}`,
name: `Filler ${i}`,
qty: 1,
}))
return {
...emptyDeck('Test deck'),
id: 'deck-1',
commanders: [{ id: commander.id, name: commander.name }],
cards: entries,
}
}
function lookup(deck, ...cards) {
return new Map(cards.map((c) => [c.id, c]))
}
test('deck size counts the commander and every copy', () => {
const deck = emptyDeck()
assert.equal(deckSize(deck), 0)
deck.cards = [{ id: 'a', name: 'A', qty: 4 }]
assert.equal(deckSize(deck), 4)
deck.commanders = [{ id: 'c', name: 'C' }]
assert.equal(deckSize(deck), 5)
})
test('a commander deck is exactly 100 cards', () => {
const deck = legalDeck()
const byId = lookup(deck, atraxa)
const result = validateDeck(deck, byId)
assert.equal(result.size, 100)
assert.ok(!result.issues.some((i) => i.rule === 'size'))
})
test('a short deck says how many cards are missing', () => {
const deck = legalDeck()
deck.cards = deck.cards.slice(0, 90)
const result = validateDeck(deck, lookup(deck, atraxa))
const issue = result.issues.find((i) => i.rule === 'size')
assert.ok(issue)
assert.match(issue.message, /Add 9 more cards/)
assert.equal(result.valid, false)
})
test('an oversized deck says how many to remove', () => {
const deck = legalDeck()
deck.cards = [...deck.cards, { id: 'extra', name: 'Extra', qty: 1 }]
const issue = validateDeck(deck, lookup(deck, atraxa)).issues.find((i) => i.rule === 'size')
assert.match(issue.message, /Remove 1 card/)
})
test('a deck with no commander is invalid', () => {
const result = validateDeck(legalDeck(), new Map())
assert.ok(result.issues.some((i) => i.rule === 'commander'))
})
test('a card that cannot be a commander is rejected as one', () => {
const lyevok = card('Lyevok the Behemoth', { commanderEligible: false, typeLine: 'Creature' })
const deck = legalDeck(lyevok)
const result = validateDeck(deck, lookup(deck, lyevok))
const issue = result.issues.find((i) => i.rule === 'commander')
assert.match(issue.message, /cannot be a Commander/)
})
test('colour identity is the commander identity', () => {
const deck = { ...emptyDeck(), commanders: [{ id: atraxa.id, name: atraxa.name }], cards: [] }
assert.deepEqual([...commanderIdentity(deck, lookup(deck, atraxa))].sort(), ['B', 'G', 'U', 'W'])
})
test('a card outside the commander identity is reported with its colour', () => {
// Atraxa is WUBG, so a mono-red card is the offending one — a card whose
// identity is a subset of the Commander's is always fine.
const redCard = card('Bolt', { colorIdentity: 'R', typeLine: 'Instant', cmc: 1 })
const inside = card('U Stone', { colorIdentity: 'UB', typeLine: 'Instant', cmc: 1 })
const deck = legalDeck()
deck.cards[0] = { id: redCard.id, name: redCard.name, qty: 1 }
deck.cards[1] = { id: inside.id, name: inside.name, qty: 1 }
const byId = lookup(deck, atraxa, redCard, inside)
const result = validateDeck(deck, byId)
const issue = result.issues.find((i) => i.rule === 'identity')
assert.ok(issue)
assert.match(issue.message, /red/)
assert.deepEqual(issue.cards, [redCard.id])
assert.equal(offIdentityColors(deck, byId).get('R').length, 1)
})
test('a partner pair is allowed when both cards are partners', () => {
const ikor = card('Ikor, Silverbow', { typeLine: 'Legendary Creature — Human Artificer', commanderEligible: true, isPartner: true })
const akkas = card('Akkas, Trophy Collector', { typeLine: 'Legendary Creature — Goblin Artificer', commanderEligible: true, isPartner: true })
const deck = legalDeck(ikor)
deck.commanders.push({ id: akkas.id, name: akkas.name })
const result = validateDeck(deck, lookup(deck, ikor, akkas))
assert.ok(!result.issues.some((i) => i.rule === 'commander'), 'partner pair should be accepted')
})
test('a second commander that is not a partner is rejected', () => {
const bruna = card('Bruna, the Fading Light', { typeLine: 'Legendary Creature — Spirit', commanderEligible: true })
const deck = legalDeck()
deck.commanders.push({ id: bruna.id, name: bruna.name })
const result = validateDeck(deck, lookup(deck, atraxa, bruna))
const issue = result.issues.find((i) => i.rule === 'commander')
assert.match(issue.message, /not a Partner commander/)
})
test('"Partner with <name>" restricts the pairing to that card', () => {
const kiora = card('Kiora, Behemoth Beckoner', {
typeLine: 'Legendary Planeswalker — Kiora',
oracleText: 'Kiora, Behemoth Beckoner may be your commander. Partner with Akkas, Trophy Collector.',
commanderEligible: true,
isPartner: true,
})
const akkas = card('Akkas, Trophy Collector', { typeLine: 'Legendary Creature', commanderEligible: true, isPartner: true })
const wrong = card('Somebody Else', { typeLine: 'Legendary Creature', commanderEligible: true, isPartner: true })
assert.equal(partnerWith(kiora), 'Akkas, Trophy Collector')
const good = legalDeck(kiora)
good.commanders.push({ id: akkas.id, name: akkas.name })
assert.ok(!validateDeck(good, lookup(good, kiora, akkas)).issues.some((i) => i.rule === 'commander'))
const bad = legalDeck(kiora)
bad.commanders.push({ id: wrong.id, name: wrong.name })
const issue = validateDeck(bad, lookup(bad, kiora, wrong)).issues.find((i) => i.rule === 'commander')
assert.match(issue.message, /can only lead a deck with Akkas, Trophy Collector/)
})
test('a non-basic land may not be duplicated', () => {
const deck = legalDeck()
deck.cards[0] = { id: commandTower.id, name: commandTower.name, qty: 2 }
const issue = validateDeck(deck, lookup(deck, atraxa, commandTower)).issues.find((i) => i.rule === 'singleton')
assert.match(issue.message, /only basic lands may be duplicated/)
})
test('basic lands may be duplicated', () => {
const deck = legalDeck()
deck.cards = [
...deck.cards.slice(2, 41),
{ id: swamp.id, name: swamp.name, qty: 40 },
{ id: forest.id, name: forest.name, qty: 20 },
]
const byId = lookup(deck, atraxa, swamp, forest)
const result = validateDeck(deck, byId)
assert.equal(result.size, 100)
assert.ok(!result.issues.some((i) => i.rule === 'singleton'))
})
test('the commander may not also appear in the 99', () => {
const deck = legalDeck()
deck.cards[0] = { id: atraxa.id, name: atraxa.name, qty: 1 }
const issue = validateDeck(deck, lookup(deck, atraxa)).issues.find((i) => i.rule === 'singleton')
assert.match(issue.message, /is your Commander/)
})
test('a banned card is reported, commander or not', () => {
const deck = legalDeck()
deck.cards[0] = { id: lutri.id, name: lutri.name, qty: 1 }
const issue = validateDeck(deck, lookup(deck, atraxa, lutri)).issues.find((i) => i.rule === 'ban')
assert.match(issue.message, /Banned in Commander: Lutri, the Disgraced/)
})
test('every problem is reported at once, not one at a time', () => {
const deck = emptyDeck('Broken')
deck.id = 'deck-1'
deck.cards = [{ id: lutri.id, name: lutri.name, qty: 3 }]
const result = validateDeck(deck, lookup(deck, atraxa, lutri))
const rules = new Set(result.issues.map((i) => i.rule))
assert.ok(rules.has('commander'), 'no commander')
assert.ok(rules.has('size'), 'wrong size')
assert.ok(rules.has('singleton'), 'duplicates')
assert.ok(rules.has('ban'), 'banned card')
})
test('the mana curve buckets 7 and above together', () => {
const deck = {
...emptyDeck(),
cards: [
{ id: brainstorm.id, name: brainstorm.name, qty: 3 },
{ id: solRing.id, name: solRing.name, qty: 1 },
],
}
assert.deepEqual(manaCurve(deck, lookup(deck, brainstorm, solRing)), [3, 1, 0, 0, 0, 0, 0, 0])
})
test('the type breakdown counts each card once, by its first matching type', () => {
const creature = card('A Warrior', { typeLine: 'Legendary Creature — Goblin Warrior', cmc: 2 })
const artifact = card('An Orb', { typeLine: 'Artifact — Equipment', cmc: 6 })
const deck = {
...emptyDeck(),
cards: [
{ id: creature.id, name: creature.name, qty: 2 },
{ id: artifact.id, name: artifact.name, qty: 1 },
],
}
const byId = lookup(deck, creature, artifact)
const breakdown = Object.fromEntries(typeBreakdown(deck, byId).map((t) => [t.type, t.count]))
assert.equal(breakdown.Creature, 2)
assert.equal(breakdown.Artifact, 1)
assert.equal(breakdown.Sorcery, 0)
})
test('a two-faced card belongs to exactly one column', () => {
// Transform planeswalkers carry both faces in one type line, so a plain
// substring test would list the card twice and make the column count
// disagree with the rows shown.
const jace = card('Jace, Vryn’s Prodigy', {
typeLine: 'Legendary Creature — Human Wizard // Legendary Planeswalker — Jace',
cmc: 2,
})
const deck = { ...emptyDeck(), cards: [{ id: jace.id, name: jace.name, qty: 1 }] }
const byId = lookup(deck, jace)
assert.equal(primaryType(jace), 'Creature')
const counts = typeBreakdown(deck, byId)
.filter((t) => t.count > 0)
.map((t) => t.type)
assert.deepEqual(counts, ['Creature'])
// The rule the deck view filters its rows by has to be the same one.
const listed = deck.cards.filter((c) => primaryType(byId.get(c.id)) === 'Creature')
assert.equal(listed.length, 1)
assert.equal(
deck.cards.filter((c) => primaryType(byId.get(c.id)) === 'Planeswalker').length,
0,
)
})
test('a card the index cannot resolve belongs to no column at all', () => {
// Grouping it anywhere would put a blank row in a deck list; dropping it
// would hide it. The rules panel reports it by name instead.
assert.equal(primaryType(undefined), '')
const deck = { ...emptyDeck(), cards: [{ id: '', name: 'Orim, the Seraphic', qty: 1 }] }
const counts = typeBreakdown(deck, new Map()).filter((t) => t.count > 0)
assert.deepEqual(counts, [])
})
test('average mana value weights quantities and includes the commander', () => {
const cheap = card('Cheap', { cmc: 1 })
const dear = card('Dear', { cmc: 9 })
const deck = {
...emptyDeck(),
commanders: [{ id: atraxa.id, name: atraxa.name }],
cards: [
{ id: cheap.id, name: cheap.name, qty: 3 },
{ id: dear.id, name: dear.name, qty: 1 },
],
}
// commander 4, three 1s and one 9: 16 across 5 cards
assert.equal(averageManaValue(deck, lookup(deck, atraxa, cheap, dear)), 3.2)
})
test('a card the index no longer knows is an error, not a crash', () => {
const deck = legalDeck()
const byId = lookup(deck) // nothing resolved
const result = validateDeck(deck, byId)
assert.ok(result.issues.some((i) => /no longer in the card index/.test(i.message)))
assert.equal(result.valid, false)
})
test('a card the index cannot resolve is reported by name, not skipped', () => {
// An import keeps the entry with an empty id. Every other check skips it —
// no singleton, no identity, no ban — so without this rule a deck with
// unresolvable cards in it would read as clean.
const deck = legalDeck()
// Everything except the two named cards resolves, so the rule has to find
// exactly those two rather than reporting the whole deck.
const byId = new Map([...deck.cards.slice(2).map((e) => [e.id, card(e.name, {})]), [atraxa.id, atraxa]])
deck.cards[0] = { id: '', name: 'Orim, the Seraphic', qty: 1 }
deck.cards[1] = { id: '', name: 'Kozilek’s Return', qty: 2 }
const result = validateDeck(deck, byId)
const issue = result.issues.find((i) => i.rule === 'missing')
assert.ok(issue, 'unresolved cards are not reported')
assert.match(issue.message, /^2 cards are not in the card index/)
assert.match(issue.message, /Orim, the Seraphic/)
assert.match(issue.message, /Kozilek’s Return/)
// A duplicated unknown card is still not a singleton error: the singleton
// rule is about cards the engine can actually see.
assert.ok(!result.issues.some((i) => i.rule === 'singleton'))
assert.equal(result.valid, false)
})