Files
magik/tests/commander.test.js
masi 14daed4c54 Add market prices to the card index and the deck total
Prices were already in the Scryfall bulk download, so this adds no
dependency and no new fetch: the work is deciding what a card's price
means, given that the index keeps one row per card and a card has many
printings.

It is the median of the ordinary printings. The kept printing underprices
about a third of the legal pool because it is chosen for art and identity
and is usually a cheap reprint; the maximum is worse, since premium and
bundled listings put a $870 Sol Ring in the data. The median lands where a
player recognises the number and ignores the outliers. It is a market
value, not a build cost.

Two filter decisions are deliberate and easy to undo by accident: Reserved
List printings are included, because that is where Commander's banned
Power 9 live and excluding them priced Ancestral Recall and Time Walk at
nothing, while memorabilia is excluded because a Collectors' Edition box is
not a single card. Banned cards fall back to their banned printings.

deckValue counts unpriced cards instead of treating them as free, so a
total is always labelled with what it left out.

Also implements scripts/verify-cards.mjs. package.json and the index skill
both documented `pnpm cards:verify` but the script did not exist; it now
runs in deploy and fails on a card priced at exactly zero, which is the
failure mode the missing-price guard exists to prevent.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-02 13:17:09 -03:00

396 lines
16 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,
deckValue,
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)
})
/**
* Deck value.
*
* The engine sums prices it has and refuses to invent the ones it does not, so
* these cover both the arithmetic and the honesty of the total.
*/
test('a deck with no priced cards is worth nothing and says so', () => {
const deck = emptyDeck()
deck.commanders = [{ id: atraxa.id, name: atraxa.name }]
deck.cards = [{ id: solRing.id, name: solRing.name, qty: 1 }]
const byId = new Map([[atraxa.id, atraxa], [solRing.id, solRing]])
const { total, unpriced } = deckValue(deck, byId)
assert.equal(total, 0)
// A card with no price is not a card worth $0.00.
assert.equal(unpriced, 2)
})
test('deck value counts quantity and includes the commander', () => {
const pricedAtraxa = { ...atraxa, priceUsd: 30 }
const pricedRing = { ...solRing, priceUsd: 2.1 }
const pricedSwamp = { ...swamp, priceUsd: 0.32 }
const deck = emptyDeck()
deck.commanders = [{ id: pricedAtraxa.id, name: pricedAtraxa.name }]
deck.cards = [
{ id: pricedRing.id, name: pricedRing.name, qty: 4 },
{ id: pricedSwamp.id, name: pricedSwamp.name, qty: 36 },
]
const byId = new Map([
[pricedAtraxa.id, pricedAtraxa],
[pricedRing.id, pricedRing],
[pricedSwamp.id, pricedSwamp],
])
const { total, unpriced } = deckValue(deck, byId)
// 30 commander + (4 x 2.10) + (36 x 0.32)
assert.equal(total, 49.92)
assert.equal(unpriced, 0)
})
test('a card that cannot be resolved is not reported as unpriced', () => {
// An unknown card is a lookup failure, not a missing price. The deck list
// validator already reports it; double-counting it here would make the two
// panels disagree about how many cards are missing.
const deck = emptyDeck()
deck.cards = [{ id: 'nope', name: 'Orim, the Seraphic', qty: 2 }]
const { total, unpriced } = deckValue(deck, new Map())
assert.equal(total, 0)
assert.equal(unpriced, 0)
})
test('a null price is unpriced, not free', () => {
const nullPriced = { ...solRing, priceUsd: null }
const deck = emptyDeck()
deck.cards = [{ id: nullPriced.id, name: nullPriced.name, qty: 3 }]
const { total, unpriced } = deckValue(deck, new Map([[nullPriced.id, nullPriced]]))
assert.equal(total, 0)
assert.equal(unpriced, 3)
})