# Card effect compiler The card database from Scryfall is English prose. The game engine cannot execute prose, so `backend/src/effects/` compiles every oracle-text line into a small JSON AST. The AST is the canonical form for the engine. A pretty-printer renders the same AST as readable card source, and a matching interpreter reads that source back, so a human can replace the generated implementation of a card without touching JSON. This is deliberately **not** a rules engine. It answers "what does the card say?" in machine-readable form. "What happens when it resolves?" belongs to the engine that consumes these nodes. ## Pipeline ```text Scryfall oracle text -> normalize (card name, "this creature", contractions, reminder text) -> classify (keyword / triggered / activated / static / spell effect) -> parse targets, values, costs, conditions, durations -> JSON AST + card-source rendering data/card-overrides/.js -> safe source interpreter -> JSON AST used instead of the generated one ``` Every line is parsed as a whole. If any part of a line is not understood, the line becomes `{ "kind": "unsupported", "reason": ..., "text": ... }` instead of a guessed effect. A wrong effect is worse than a missing one. ## Commands From `backend/`: ```bash npm run compile:cards # writes data/card-effects.json and data/card-effects.js npm test # compiler, source interpreter, and engine tests npm run dev # API for the frontend editor ``` Current output over the imported Commander pool (32,116 cards): ```text Cards: 14,239 supported, 10,088 partial, 7,789 unsupported Ability lines: 38,132/60,470 parsed (63.1%) ``` - **supported** — every ability line parsed. - **partial** — at least one line parsed, at least one unsupported. - **unsupported** — no line parsed. The unsupported lines are the work queue. Re-running the compiler after adding patterns updates the numbers. ## Output files | File | Contents | | ---- | -------- | | `data/card-effects.json` | Array of `CompiledCard` ASTs, one per oracle card | | `data/card-effects.js` | The same cards rendered as card source | | `data/card-overrides/.js` | Human-authored implementations, one file per card | The two generated files are git-ignored. Overrides are ordinary source files and should be committed. Compiled cards carry the Scryfall `typeLine`, and the game catalog uses it. An override can declare its own type line with `card(...)`; that value wins when the card is loaded into a game. ## Card source Card source looks like a JavaScript module, but it is **not executed as JavaScript**. `src/effects/source.ts` tokenizes and evaluates a deliberately small expression subset against a fixed builder API. There is no `eval`, no `new Function`, no imports, no property writes and no access to globals: an unrecognized name or method is a parse error. This matters because `PUT /cards/:oracleId/implementation` is unauthenticated. A card exports its type line and an array of abilities: ```js export default card('Creature — Human Cleric', [ keywords('Flying', 'Ward {2}'), triggered(when.enters(each(permanents.other().withType('creature'))), [ gainLife(you, 1), ]), activated([tapCost()], [ addMana(you, mana('{G}')), ]), ]) ``` Plain `export default [...]` is still accepted and uses the Scryfall type line. Multi-face cards export `faces(face('Name', 'Type line', [...]), ...)` in card order: ```js export default faces( face('Front', 'Instant', [spell([draw(you, 2)])]), face('Back', 'Creature — Human', [keyword('Flying')]), ) ``` Every effect list also accepts a callback. A single expression is one effect; a block is several effects, separated by newlines, `;` or `,`: ```js export default card('Creature — Human Cleric', [ triggered(when.enters(self), () => draw(you, 1)), activated([tapCost()], () => { gainLife(you, 1) draw(you, 1) }), ]) ``` Arrays stay valid and are still used for costs, `modal` modes, ability lists, `card`, `faces` and `face`. The formatter emits callbacks for effect lists and `card(typeLine, abilities)` at the top level. The formatter writes the same shape, so a generated implementation can be copied, edited and saved as an override. `formatCard` and `parseCardSource` round-trip: comments are ignored, a leading `// Card [status]` line is optional, and `const` declarations are allowed for reuse: ```js const dragons = permanents.withType('creature').withSubtype('dragon').youControl() export default card('Creature — Human Cleric', [ staticAbility([staticPump(each(dragons), 1, 1)]), ]) ``` ### Abilities | Call | Meaning | | ---- | ------- | | `keyword(name, value)` | One keyword, optionally parameterized | | `keywords(...names)` | Several keywords from one oracle line | | `triggered(event, effects, options)` | `When`/`Whenever`/`At` ability | | `activated(costs, effects, options)` | Cost `:` effect, including loyalty | | `staticAbility(effects, options)` | Continuous effect or restriction | | `spell(effects, options)` | Effect line of an instant or sorcery | | `additionalCost(costs, options)` | Additional cost | | `alternativeCost(costs, options)` | Alternative cast, possibly free | | `overload(cost)` | Overload alternate cost | | `chapter(chapters, effects, options)` | Saga chapter ability | | `levelBand(min, max, power, toughness)` | Level band | | `levelPt(power, toughness)` | Level P/T line | | `unsupported(reason, text)` | Preserved text plus a reason | `options` accepts `condition` and `optional`; activated abilities also accept `timing: 'sorcery'` and `activationsPerTurn`. ### Selectors and targets Selectors start from `permanents`, `cards` or `creatures` and chain filters: ```js permanents.withType('creature').withSubtype('dragon').withColor('red') .other().tapped().youControl().powerAtLeast(4) ``` Available filters include `withType`, `withSubtype`, `withSupertype`, `withColor`, `withKeyword`, `withoutKeyword`, `withoutType`, `other`, `tapped`, `untapped`, `attacking`, `token`, `nontoken`, `equipped`, `enchanted`, `youControl`, `opponentControls`, `controlledBy`, `ownedBy`, `named`, `inZone`, `withCounter`, `powerAtLeast`/`powerAtMost`, `toughnessAtLeast`/`toughnessAtMost`, `manaValueAtLeast`/`manaValueAtMost` and `matchingAny`. Targets wrap a selector or player: ```js target(permanents.withType('creature')) each(creatures.withColor('red')) pick(cards.withType('land'), { upTo: 2 }) divided(3, creatures.attacking()) targetSpell(permanents.withType('instant')) targetAbility() ``` Fixed targets are `self`, `triggerSubject`, `previousTarget`, `anyTarget` and `targetPlayerOrPlaneswalker`. Players are `you`, `opponent`, `eachOpponent`, `eachPlayer`, `targetPlayer`, `thatPlayer`, `itsController` and `itsOwner`. Values are numbers, `X`, `itsPower`, `itsToughness`, `count(selector)`, `cardsInHand(player)`, `maxCardsInHand()`, `maxOpponentCount(selector)`, `totalManaValue(selector)`, `totalPower(selector)`, `anyNumber()` and `eventAmount()`. ### Effects, costs and statics Effects are camelCase builders, one array entry or callback statement each: ```js damage(target(permanents.withType('creature')), 3) draw(you, 2) gainLife(you, 1) createToken(you, 1, token({ types: ['creature'], subtypes: ['goblin'], colors: ['red'], power: 1, toughness: 1 })) putCounters(target(permanents.withType('creature')), '+1/+1', 2) destroy(target(permanents.withType('creature'))) addMana(you, mana('{G}{G}')) search(you, cards.withType('creature'), 1, { destination: 'battlefield', shuffle: true }) pump(each(creatures.youControl()), 1, 1, untilEndOfTurn) ``` Costs are distinct from effects: `manaCost('{2}{U}')`, `tapCost()`, `untapCost()`, `sacrificeSelf()`, `payLife(3)`, `discardCost(1)`, `removeCountersCost('+1/+1', 1)`, `exileSelf()`, `choice([...])` and the rest of the cost builders in `source.ts`. Static effects are also distinct, so their AST shape is unambiguous: `staticPump`, `staticGrant`, `staticRestrict`, `staticSetPt`, `grantAbility`, `entersTapped`, `entersWithCounters`, `control`, `choose`, `replace`, `costReduction`, `costIncrease`, `searchRestriction` and `exileInsteadOfGraveyard`. `entersTapped` takes an optional `unlessCost` builder for "you may pay N life; if you don't, it enters tapped": `entersTapped(self, { unlessCost: payLife(2) })`. Durations are `permanent` (default), `untilEndOfTurn`, `untilYourNextTurn`, `untilEndOfYourNextTurn`, `untilEndOfCombat`, `untilControllersNextUntapStep` and `whileSourceOnBattlefield`. Triggers live under `when`: `when.enters`, `when.dies`, `when.attacks`, `when.blocks`, `when.attacksOrBlocks`, `when.entersOrAttacks`, `when.entersOrDies`, `when.leavesBattlefield`, `when.dealsDamage`, `when.upkeep`, `when.endStep`, `when.beginCombat`, `when.firstMainPhase`, `when.postcombatMainPhase`, `when.cast`, `when.becomesLevel`, `when.draw`, `when.counterPlaced`, `when.becomesTarget`, `when.lifeGained` and `when.lifeLost`. Conditions are top-level calls such as `yourTurn()`, `youControl(selector, n)`, `opponentControls(selector)`, `lifeAtLeast(player, n)`, `wasKicked()`, `ifYouDo()`, `ifYouDont()` and `otherwise()`. The full list is the set of condition builders in `source.ts`. Nested structures are effect lists (array or callback) or `ifThen`/`modal`: ```js triggered(when.upkeep(you), [ ifThen(youControl(permanents.withType('artifact'), 3), [draw(you, 1)]), ]) spell([ modal(1, 1, [[draw(you, 2)], [gainLife(you, 3)]]), ]) ``` ## Manual implementations The frontend at `/cards` lists cards and filters to `needs-work` by default. Select a card, edit its source, and save. The API validates the source before writing it, so a typo never replaces a working file. Overrides take precedence during `npm run compile:cards`; invalid override files stop the compile with the line number. | Method | Path | Purpose | | ------ | ---- | ------- | | `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, source, manual flag | | `PUT` | `/cards/:oracleId/implementation` | Validate and save `{ "source": "..." }` | | `DELETE` | `/cards/:oracleId/implementation` | Delete the override, restore generated output | | `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for card source from the card's oracle text | | `GET` | `/cards/:oracleId/override` | Raw saved source, `404` when absent | | `GET` | `/stats` | Supported, partial, unsupported, and manual counts | `CARD_OVERRIDES_DIR` changes the storage directory (useful for tests). ### AI drafts The editor's **Draft with AI** button calls `POST /cards/:oracleId/translate`. The backend sends the card's oracle text to an [OpenRouter](https://openrouter.ai/) model and returns card source, without saving it. The response is parsed before it reaches the browser, so prose or a non-parseable guess is reported as an error instead of replacing the editor. Set `OPENROUTER_API_KEY` on the backend to enable the route. `OPENROUTER_MODEL` defaults to `google/gemini-2.5-flash-lite`. The system prompt contains the source reference and a strict output contract: card source only, no explanations, Markdown, code fences or card header, and no invented operations. Output is capped at 1,200 tokens. A fenced answer is unwrapped defensively, but an invalid answer is not retried (that would spend more tokens). The translator uses the default model only; there is no per-request model picker. ## AST The types live in `src/effects/types.ts`. A card contains one or more abilities: ```jsonc { "oracle_id": "...", "name": "Soul Warden", "typeLine": "Creature — Human Cleric", "status": "supported", "abilities": [ { "kind": "triggered", "event": { "kind": "enters", "subject": { "kind": "object", "selector": { "other": true, "types": ["creature"] }, "mode": "each" } }, "effects": [ { "op": "life", "player": "you", "amount": { "kind": "number", "value": 1 }, "mode": "gain" } ], "optional": false, "text": "Whenever another creature enters, you gain 1 life." } ] } ``` ### Ability kinds | Kind | Meaning | Example | | ---- | ------- | ------- | | `keyword` | One parameterless or parameterized keyword | `Flying`, `Ward {2}`, `Crew 3` | | `keywords` | Several keywords on one oracle line | `Flying, vigilance` | | `triggered` | `When`/`Whenever`/`At` ability | `When this enters, draw a card.` | | `activated` | Cost `:` effect, including loyalty | `{T}: Add {G}.` | | `static` | Continuous effect or restriction | `Creatures you control get +1/+1.` | | `spell` | Effect line of an instant or sorcery | `Draw two cards.` | | `alternative_cost` | Alternative cast with a condition, possibly free | `If you control a commander, you may cast this without paying its mana cost.` | | `overload` | Overload alternate cost; the engine widens the spell's targets | `Overload {6}{U}` | | `unsupported` | Preserved text plus a reason | `Choose one —` | ### Effects | `op` | Payload | | ---- | ------- | | `damage` | `target`, `amount`, optional `source` | | `draw`, `discard`, `mill` | `player`, `amount` | | `life` | `player`, `amount`, `mode: gain \| lose` | | `pump` | `target`, `power`, `toughness`, `duration` | | `grant` | `target`, `keyword`, optional `value`, `duration` | | `put_counters`, `remove_counters` | `target`, `counter`, `amount` | | `create_token` | `player`, `amount`, `token` | | `destroy`, `exile`, `tap`, `untap`, `regenerate` | `target` | | `sacrifice` | `player`, `target`, optional `unless` cost | | `counter` | `what`, `target`, optional `unless` cost | | `return_to_hand`, `return_to_battlefield`, `put_on_top` | `target` | | `search`, `shuffle` | player, selector, destination, optional `split` destination | | `add_mana` | `player`, `mana` (`symbols` or `any_color`) | | `scry`, `surveil` | `player`, `amount` | | `fight` | two targets | | `energy` | `player`, `amount` | | `attach` | target to attach this/trigger object to | | `restriction` | target, rule, duration | | `keyword_action` | `action`, optional `amount`, `detail`, `target` | | `proliferate` | no payload | | `hideaway` | `amount`; exiles the top card and links it to the source | | `play_exiled` | `player`, optional `free`; plays a card linked with `hideaway` | | `exile_graveyards` | no payload; exiles all cards from every graveyard | ### Targets, values, costs - **Targets** are `self`, `trigger_subject`, `any`, `player`, `spell`, `ability`, or `object` with an `ObjectSelector` and mode `target` / `each` / `choose`. - **Selectors** carry types, subtypes, controller, colors, zone, tapped/attacking state, `other`, `attached: equipped|enchanted`, and `includeSelf`. - **Values** are `number`, `x`, `count(selector)`, `source_power`, `source_toughness`, `cards_in_hand`, or `event_amount`. - **Costs** are mana symbols, tap/untap, tapping another permanent, energy, loyalty, life, discard, sacrifice, self-exile, mill, and removing counters. - **Conditions** cover controlling permanents, commander control, turn ownership, tapped source, life totals, graveyard/hand/library size, total power, distinct permanent names, and this-turn attacks and damage. - **Static effects** include pumps, keyword grants, restrictions, enters tapped/with counters, control, choices, replacements, cost reduction/increase, search restriction, and exiling cards instead of putting them into graveyards. - **Durations** cover permanent, end of turn, your next turn, the end of your next turn, end of combat, controller's next untap step, and while the source remains. ## How a line is parsed 1. Reminder text in parentheses is removed. Card names and "this creature" / "this permanent" become `this`. 2. Pure keyword lines are recognized from Scryfall's keyword list plus the parameterized keyword table. 3. Trigger prefixes (`When this enters`, `Whenever this attacks`, `At the beginning of your upkeep`, ...) become a `TriggerEvent`. 4. A colon splits an activated ability into costs and effects. 5. A leading duration (`Until end of turn, ...`) moves to the end of the effect, where the duration parser expects it. 6. Otherwise a static effect is attempted. 7. Instant/sorcery lines fall back to a one-shot effect (`kind: "spell"`). 8. Anything left over is `unsupported`. Effects are split on sentences, `, then`, and `and` only when both sides parse. `When you do, ...` becomes a reflexive `if you do` condition. `it` becomes the trigger subject only when no explicit target/`that` appears in the same effect; ambiguous pronouns stay unsupported. ## Adding support For a single card, open the frontend editor, edit the source, and save; no compiler change is needed. For a whole class of cards: 1. Run `npm run compile:cards` and pick a frequent unsupported pattern. 2. Add a regex + AST builder in `src/effects/compile.ts` (or a target/value parser in `src/effects/parse.ts`). 3. Add a focused test in `test/effects.test.ts`. 4. Run `npm test` and `npm run compile:cards`. Prefer narrow, anchored patterns. A broad pattern that misreads one card is a game bug that is hard to find later. ## Known gaps The remaining unsupported lines are mostly: - modal abilities (`Choose one —` and bullets) - replacement effects (`If ... instead`, `As ... enters, ...`) - continuous-effect layers and dependency rules - copy, control-change, and type-change effects - alternative/additional costs and cost modifiers - level/class/saga structures and chapter abilities - quoted token abilities and copying tokens - complex pronoun/context resolution and "for each" scaling beyond simple counts - dice, stickers, attractions, dungeons, and other supplemental mechanics None of these are blocked by the AST; each needs a parser pattern and an engine implementation.