Skip to content
github-actions[bot] edited this page Nov 27, 2026 · 4 revisions

Generated from the thetowersdk repository. Edits made here are overwritten on the next push — change the source file instead.

Working in this repo (for AI agents)

This file is the canonical instruction set. CLAUDE.md and .github/copilot-instructions.md point here rather than duplicating it — edit this one.

What this package is

@beardedunicorn/thetowersdk gives you the game's data and a reader for a player's save file, so you can build calculators and tools for The Tower (TechTree Games' idle tower defence game). Its framework-free TypeScript core provides data and calculations. Explicit adapters handle save files, wiki requests, Sheets and MCP; random-state helpers expose their stateful behavior separately.

Everything here is about that one game. Nothing in this package is generic infrastructure.

Rule zero — what belongs in this package

Does this describe The Tower, or does it describe a program that uses The Tower?

The Tower belongs here. A program that uses it does not — that is what a platform layer is for, and the @tmrxjd/platform package in this monorepo is one, exactly like the one the README tells every consumer to write. No settings, no persisted state, no cross-page hub, no dropdown options, no sort or filter keys, no routes, no icons, no colours, and never the word tracker.

docs/ORGANIZATION_CONTRACT.md is binding: it fixes the domains, which may import which, the shape of every folder, how files are named, how long they may be, and what the public surface may contain. pnpm lint:organization enforces every rule and runs inside pnpm verify. Existing violations sit in .organization-baseline.json, which may only shrink.

Read it before adding a file, moving one, or naming anything.

Two more rules, before anything else

  1. Look up the mechanic before you describe it. This package gives values, not meaning. See Consult the wiki and the monorepo contract docs/AGENT_GAME_MECHANICS_CONTRACT.md — begin_mechanic_task is mandatory when MCP is available. It is not optional.
  2. Find the export; do not invent one. There are 3001 exports across 15 entry points. Use the map below, then list_exports with a filter, then get_export. A plausible-looking name you guessed will not exist.

Never claim a mechanic change is finished until the human tested and approved. Ledger statuses: researching | implementing | awaiting_user | user_approved | blocked — never done. Monorepo commits: docs/AGENT_COMMIT_SCHEMA.md (status/checkpoint default). Living map: docs/mechanics-map/MAP.md.

Where things are

MAP.md is the front door. It names every tree — src, scripts, mcp, wasm, examples, templates — and links to that tree's own map, which links to each directory's map, which lists every file with its purpose and its exports. In src, scripts, mcp and wasm, each file also carries a header naming its exports, what it depends on, and what depends on it. Every map links back up, so you can arrive anywhere and still find your way out.

All of that is generated by pnpm map, and pnpm lint:map (inside verify) fails if any of it has drifted. Do not edit a MAP.md or a ── file map block by hand — regenerate instead. The prose docblock above the block is hand-written, and is the one thing the generator cannot produce: if you add a file, write it a sentence saying why the file exists. A new directory needs a line in DIRECTORY_PURPOSE (scripts/map-the-repo.mjs) or the generator refuses to run.

The tables below stay by hand because they answer a different question — not "where is this file?" but "which entry point do I import from?".

Sizes are exports, not files — they say how much you are searching through.

Entry point Exports Holds Reach for it when
@beardedunicorn/thetowersdk/data 466 Game tables and catalogs You need a cost, a level curve, an effect value, a name
@beardedunicorn/thetowersdk/save 444 playerInfo.dat readers You need what a specific player has
@beardedunicorn/thetowersdk/mechanics 1467 Formulas You need to compute something the game computes
@beardedunicorn/thetowersdk/knowledge 377 What a number MEANS, and how it is misread You are modelling a mechanic, not just reading a value
@beardedunicorn/thetowersdk/charts 86 Curated chart datasets You are rendering a table the game shows
@beardedunicorn/thetowersdk/formatting 44 Number and duration display You need it to read the way the game shows it
@beardedunicorn/thetowersdk/wiki 38 Wikitext → Markdown, page fetch You need to know how a mechanic behaves
@beardedunicorn/thetowersdk/builders 28 Calculators that declare their own inputs You want a form, a command and a test from one place
@beardedunicorn/thetowersdk/save-decoder 5 The save reader with no Node imports You are decoding a save in a browser
@beardedunicorn/thetowersdk/node 2 The save decoder You have bytes and need a save root (Node only)
@beardedunicorn/thetowersdk/sheets 9 Reading and writing Google Sheets You are working against a community spreadsheet
@beardedunicorn/thetowersdk/bot 5 Every builder as a chat command You are building a Discord bot
@beardedunicorn/thetowersdk/contributions 5 Whose work this package carries You are rendering credits
@beardedunicorn/thetowersdk/assets 6 Naming rules for artwork you supply You are matching image files to catalog rows

These entry points are the whole surface. There is no @beardedunicorn/thetowersdk/internal/*: a module is exported from one of them or it is not part of the package. Needing something none of them exports is a gap worth reporting.

data — the game's tables

Catalogs are the entry into game data. Each is an array of typed rows.

Catalog What it holds
LAB_CATALOG Every research lab: levels, coin cost and duration per level, caps
CARD_IMPORT_CATALOG Cards, their ids, rarities and per-level values
MODULE_TEMPLATES · MODULE_SUBSTAT_CANONICAL_DATA Modules, rarities, substat definitions
ULTIMATE_WEAPON_IMPORT_CATALOG The nine weapons, their stats and plus-levels
BOT_IMPORT_CATALOG · GUARDIAN_CHIP_IMPORT_CATALOG Bots and guardian chips
VAULT_V29_HARMONY · VAULT_V29_POWER · VAULT_V29_ENEMY The vault since v29: categories, upgrades, key cost and value per level
VAULT_POWER_IMPORT_CATALOG · VAULT_HARMONY_IMPORT_CATALOG The two vault trees as they were before v29
RELIC_IMPORT_CATALOG Relics and their bonus types — read the note on units below
LAB_RESEARCH_IMPORT_CATALOG Research entries as the save stores them
PLAYER_DATA_FIELD_CATALOG Named save fields
CURRENCY_DEFINITIONS · TOWER_MODULE_TYPE_ENUM · RESEARCH_CATEGORY_ENUM Enumerations
getWorkshopStatDefinitions() Workshop stats — a function, because it builds from tables
GLOSSARY · lookupGlossary · expandAcronym What a term or acronym means

A cost is a plain number of coins. 1.1e15 is 1.1 quadrillion. There is no scaling factor to apply and no currency field to read first, so two labs can be added together directly.

Units are not uniform across a catalog. A relic bonus may be a percentage, metres, seconds or a multiplier, and the unit lives in the game's description text rather than beside the number. Check before you format one.

save — what a player has

The read*FromSaveRoot readers. The important ones:

Function Returns
readLabsFromSaveRoot Research levels, what is maxed, the active queue
readWorkshopFromSaveRoot Upgrade levels, enhancements, saved presets
readModulesFromSaveRoot Owned modules, rarities, substats, what is equipped
readCardsFromSaveRoot Card levels, copies, mastery, equipped slots
readUltimateWeaponsFromSaveRoot Weapon levels, unlocks, plus-levels, stones
readVaultFromSaveRoot · readRelicsFromSaveRoot · readBotsFromSaveRoot · readGuardiansFromSaveRoot The rest of the account
readLifetimeFromSaveRoot · readDissonanceCycleWavesFromSaveRoot Totals, and the best wave per tier this dissonance cycle
listImportableBattleRuns Run history, with every stored field

Rules that hold for all of them:

  • They return null rather than throwing when a save predates a feature. Always check.
  • Read warnings — what they could not interpret, rather than dropping it silently.
  • Never mutate parsedRoot. Callers run many extractors over the same object.
  • Arrays are positional and over-allocated. relicsUnlocked[112] is relic 112; unused slots are not always zero, and the card level array pads with 1. Use the unlock flag where one exists.
  • A save can be older than the catalog. 305 relics in the catalog and 236 in the save means the rest are absent, not locked. Do not present them as things the player is missing.

mechanics — the formulas

1467 exports. By area, so you know which filter to pass `list_exports`:
Area ~Exports Covers
Enemies 276 Wave/tier base health and damage, type multipliers, level skip, elite spawns, wave-info panel
Damage 147 Crit, multishot, bounce, rend armor, thorns, shockwave, land mines, knockback, tower fire and range
Ultimates 92 The shared hit/absorb pipeline, Chrono Field, Poison Swamp, Inner Land Mines, Golden Tower, Black Hole, Death Wave, Spotlight
Economy 91 Coin and drop simulation, interest, ROI scaling, cost tables
Workshop 58 Attack, defence and utility stat curves
Effective Paths 54 The upgrade-order solver — see below
Bots and guardians 51 Hit multipliers, range and coverage, medal planning, cooldowns
Labs 34 Research durations, costs, speed modifiers
Modules · Cards 33 Module stat computation, card effect lookup
Battle conditions 22 Resistance levels, tournament heat, counter labs

Effective Paths — the upgrade-order solver

Ports the community Effective Paths spreadsheet: given an account, what to buy next for the most effect per unit of cost.

Model Planner Variants
eHP planEffectiveHealthPath lab-time · lab-coins · stone · coin
eRegen planEffectiveRegenPath lab-time · lab-coins
eDamage planEffectiveDamagePath lab-time · lab-coins · stone · coin · keys
eEcon planEffectiveEconomyPath time · coin · stone
eEcon Discount planEffectiveEconomyDiscountPath ranks coins saved, not earned

Every planner takes { config, levels, variant, steps } and returns { steps, excluded, issues }.

  • config = the account: what is unlocked, owned, equipped. Start from zeroEffective*Config().
  • levels = how far each candidate is bought. Start from ZERO_EFFECTIVE_*_LEVELS and fill it — a missing key is undefined, which becomes a NaN the planner refuses.
  • excluded = candidates not offered, each with a reason. A candidate is planned or it is explained, never neither. A short path usually means everything else is at its cap.
  • issues = why nothing could be planned. Empty on every plan that ran.

EFFECTIVE_*_UPGRADES lists the candidates with the id, band, key and sheetName you map your own data onto. The README has a worked example.

Consult the wiki before describing a mechanic

This package supplies the game's data and formulas. It does not document game behaviour: a table gives a value, not what that value means, when it applies, or what it interacts with. Confirm behaviour against the community wiki before describing it in code, comments or output.

Forced MCP workflow (same for Cursor, Claude, Copilot):

begin_mechanic_task { mechanic, intent, relatedHints? }
wiki_page   { title }     # every related title from the task — not one
define_term { term }
record_mechanic_note { token, mechanic, facts, sources, relatesTo? }
record_work_status   { token, title, status, summary }

Also:

wiki_search { query: "wave skip" }
wiki_page   { title: "Wave Skip" }
wiki_page   { title: "Cards", section: "Costs" }

In code, fetchFandomPageAsMarkdown from @beardedunicorn/thetowersdk/wiki does the same. Without MCP, the wiki is at the-tower-idle-tower-defense.fandom.com.

Behaviour that is not derivable from the data alone includes ability sources (one weapon's damage scaling from another's stat), unlock thresholds spanning several entities, and units — a relic bonus may be metres or seconds where a neighbouring one is a percentage, and the unit appears only in the game's description text.

Offline use. Set TOWER_WIKI_DIR to a directory of slug.md pages; both tools read it before the network. Every response reports source: "local" | "cache" | "fandom" | "gamevault", so a stale local page is distinguishable from a fresh fetch.

Living map. Set TOWER_MECHANICS_MAP_DIR to override where record_mechanic_note writes (default: monorepo docs/mechanics-map).

Wiki content and licensing

The wiki declares CC-BY-SA; this package is MIT, so wiki text is fetched rather than bundled.

CC-BY-SA permits redistribution and adaptation — converting wikitext to Markdown is an adaptation — provided the result carries the same licence, credits the source, and records that it was changed. Content may therefore be distributed as a separate package declaring license: "CC-BY-SA-3.0" with an attribution notice. TOWER_WIKI_DIR is the integration point for such a package.

The entry points, and which to use

Import Use it for
@beardedunicorn/thetowersdk/data Game tables — costs, levels, effects, catalogs, reference tables
@beardedunicorn/thetowersdk/save Reading a player's playerInfo.dat into typed values
@beardedunicorn/thetowersdk/node Decoding the save file (needs Node; browsers see the recipe in the README)
@beardedunicorn/thetowersdk/formatting Numbers and durations formatted the way the game shows them
@beardedunicorn/thetowersdk/mechanics Formulas — enemy scaling, damage, drops, workshop stats
@beardedunicorn/thetowersdk/wiki Fandom wikitext → Markdown, and fetching a page

Import from the subpath, not the root barrel, unless you genuinely want everything.

There is no path past the entry points. The package used to export its source tree as @beardedunicorn/thetowersdk/internal/*; it no longer does. If something you need is not exported, that is a gap worth reporting.

Rules that will save you a bad afternoon

Extractors return null, they do not throw. A save written before a feature existed has no data for it. Always check:

const labs = readLabsFromSaveRoot(parsedRoot)
if (!labs) return

Read warnings. Extractors report what they could not interpret rather than dropping it silently. A populated warnings usually means the save shape changed.

Save arrays are positional and over-allocated. relicsUnlocked[112] is relic 112. Arrays are often longer than the number of real entities, and unused slots are not always zero — the card level array pads with 1, not 0. Use the unlock flag when one exists, not the level.

A save can be older than the catalog. If the catalog has 305 relics and the save array has 236, the rest are absent, not locked. Do not present them as things the player is missing.

Never mutate parsedRoot. Callers run many extractors over the same object.

Do not invent a name. The game's names, and the community shorthand for them, are in the glossary: lookupGlossary('SR'), expandAcronym('ILM'). Several acronyms are ambiguous, and a confident wrong expansion is worse than none. If a term is not in the glossary, look it up in the catalogs rather than guessing — the MCP server's define_term does both.

Formulas under mechanics/ are approximations. They are fitted to observed behaviour and drift at very high waves and tiers. Do not use them where an exact match to the game matters.

effective-paths-* is a transcription, and the sheet is the authority. Not these files' comments or other reference material — the spreadsheet. Every rule cites the cell it came from (eEcon!E6, eDamage Coins!EZ2) and effective-paths-cell-references.test.ts enumerates those citations and pins how many there are. When it fails because you added one, read the cell before updating the count; that failure is the prompt, not paperwork.

Before deriving a number in this area, know how the spreadsheet API misleads — chiefly that a spilled range reads as empty through both read_range and FORMULA render while COUNTA sees a hundred rows of it. That has twice been mistaken for a missing feature.

A planner explains everything it leaves out. plan.excluded carries a reason per candidate, and planPath's onSkip reports the three ways the loop passes one over. Keep it that way: a path that stops after one step usually means every other candidate is at its cap, and without a reason that is indistinguishable from a bug. The rule is planned, or explained — never neither.

A path variant is refused, not guessed at. lab is a damage band and lab-time is a variant. Passing the band matched no band's variant list, skipped every candidate, and returned an empty path that looked exactly like a finished account. All four planners now throw and name what they publish. Do not soften that into a default.

Conventions this package enforces

pnpm lint:conventions checks these; it runs in CI and will fail a PR.

  • File names are kebab-case and say what the file is. Inside data/ and save/ the directory already gives the context, so the file is named for the thing: save/labs.ts, not save/labs-from-save.ts.
  • Everything public is exported from its barrel (src/<area>/index.ts). A module that is not exported cannot be imported by anyone, which is almost never what you meant.
  • No default exports. Named exports only, so tooling and re-exports stay predictable.
  • Extractors are extract<Thing>FromSaveRoot(root) and return T | null.
  • Data tables are SCREAMING_SNAKE_CASE readonly arrays or records. Same shape every time — no one-off exports that behave differently from their neighbours.
  • No imports from a barrel inside the same area. Import the sibling module directly; importing your own index.ts creates a cycle.
  • The package never imports itself by name. Inside src/, use relative paths — @beardedunicorn/thetowersdk/... only resolves when a build happens to exist and breaks as soon as clean runs.

Anchor an oracle node to the code that implements it

When you write a knowledge-oracle node for a mechanic that has an implementation in src/mechanics/ or src/save/, name that implementation in implementedBy.

This is not bookkeeping. src/mechanics/coverage/oracle-links.ts resolves those symbols back to the file that exports them, which is the only thing joining the knowledge graph to the source tree. Today it links 10 of 192 mechanics modules and 3 of 48 save modules — small because 194 of the 336 implementedBy symbols are defined inside the knowledge compartments themselves, which is fine for a claim about a game constant and no use at all for a claim about a mechanic this package computes.

  • implementedBy must name something public — re-exported from src/data, src/mechanics, src/save or src/knowledge. knowledge-exports.test.ts enforces it and its failure message gives the two valid fixes.
  • Do not name a symbol just to raise the count. A node whose claim is about a game constant should keep pointing at that constant; forcing an implementation link fabricates coverage.
  • coverage-inventories-are-current.test.ts carries a ratchet on the linked counts. Raise it when the number grows; never lower it to make a change pass. A drop means a node lost its implementedBy or a module was renamed out from under one.
  • After changing implementedBy, rebuild and run node scripts/link-coverage-inventories.mjs, or the inventory drift test fails.

Checking things without writing a script

There is an MCP server in mcp/. Point your agent at it and you can list exports, read a table, define a term, decode a save, run an extractor, and plan an Effective Path directly — useful for confirming a value instead of assuming one.

pnpm build && pnpm mcp

plan_effective_path is the quickest way to see which candidates a path offers and why the rest are out, without writing a scratch script. It plans from a zero config, so read it for structure rather than for numbers.

wiki_search and wiki_page are the ones to reach for first when the question is "how does X work" rather than "what value does X have". See the top of this file.

Verifying a value

Use a source's own accessor rather than a positional offset. When checking data against an external source, address it the way the source does. An index computed by counting rows is a second thing that can be wrong, and it fails silently by appearing to disagree with correct data.

Check the fixture before the code. A failing test more often means an unrepresentative fixture — invented identifiers, an inverted nested structure, a stub returning a different shape than the real collaborator — than a defect in what it tests.

Assert against the source, not against the implementation. A test that recomputes the expression it is checking passes regardless of whether the expression is right. Call the exported function and compare with a value read from the source it models.

Prove a guard by introducing the fault it catches. A guard that cannot be made to fail has not been shown to work. Confirm the edit that introduces the fault actually applied.

Constrain values to what the source allows, not to what seems reasonable. Validation tighter than the source rejects legitimate data. Where a check rejects input by returning an empty result, that outcome is indistinguishable from "nothing to do" unless the reason is reported alongside it.

Reproduce a calculation from its inputs. Working backwards from a rendered number introduces formatting and rounding as unknowns.

Read the exit status of the command you ran, not of the pipe. cmd | tail reports the tail's status, so a failed build, a rejected push and a guard that found problems all read as success. This shipped three release commits to a public repository with the message Release and, an hour later, was misread again while checking whether a guard failed properly. Capture to a file and check $?, or run the command bare.

A test that asserts a class was applied has not checked that anything is visible. A docs highlight was queried by class, found, and reported working three times while every entry rendered the identical colour — a global a { color } outranked the utility class. Assert the computed value, or look at it.

A guard reports on the part of the tree it can see. A source-only check cannot validate JSON content or filenames. When adding a check, state its domain and assert the domain is complete — scripts/the-checks-run.test.ts does this for the checks in this package.

A default implemented in one reader is not a default. claimType defaulted to objective in a doc comment and in the graph emitter, so the JSON had it on every node and the TypeScript API had it on two thirds. Both answers were correct code reading identical content. Apply it once, at the surface consumers use.

Rule out a stale artefact before reading source. Empty or unchanged output is frequently a cached bundle, a module-graph cache, or the wrong host. Reload without cache and check the served file's timestamp first.

Before you open a PR

pnpm install
pnpm verify      # lint + conventions + types + build + tests

Individually: pnpm lint, pnpm lint:conventions, pnpm type-check, pnpm test, pnpm test:schema, pnpm build.

Commit types publish. Every push to main is versioned and released automatically from its Conventional Commit types: fix: is a patch, feat: a minor, ! or BREAKING CHANGE: a major, and anything else releases nothing. The commit subject becomes the changelog line. Never edit the version in package.json or add a CHANGELOG.md entry by hand — see the Releases section of CONTRIBUTING.md.

A breaking change carries its migration. A commit marked ! or BREAKING CHANGE: adds a section to MIGRATION.md in the same pull request: what changed and which exports it touches, who is affected, what a caller must change (with a before and after taken from the code at both versions, never from memory), and a value they can assert to confirm the new behavior. The changelog is generated; the migration guide is written by hand, so a breaking change without its section is not finished.

Adding things

A new extractor — put it in src/save/, export it from src/save/index.ts, return null when the data is absent, and add a test. Index-mapping bugs are silent: they misreport a player's data rather than failing, so a test with a real shape is worth more than it looks.

A new data table — put it in src/data/, export it from src/data/index.ts, and declare its schema in src/data/schemas.ts so pnpm test:schema validates it. If it introduces names, rerun node scripts/generate-glossary.mjs so the glossary covers them.

A new formula — put it in src/mechanics/, export it from src/mechanics/index.ts, and say in the doc comment whether it is exact or fitted.

Any new exported function — run pnpm calculators:generate, so calc_run can call it by name. It rewrites src/calculators/specs.generated.ts from the source, and pnpm lint:calculators (inside verify) fails until you do. One worth explaining gets a curated entry in a src/calculators/specs-*.ts file instead, with a real because, invariants and a sample; the generator then leaves it out.

A test for any of it — three rules, each of which has already caught a real fault here and each of which was learned by shipping the opposite:

  1. Do not restate the implementation. A test that computed cost / (rate * 23) and compared it against cost / (rate * 23) stayed green when the constant became 24. Call the export.
  2. Pin several states, not one. A constant agrees with a formula at exactly one input — four frozen rates here each matched at a different single point and were wrong everywhere else.
  3. Prove it by breaking what it guards. Change the value the test exists to pin and watch it fail by name. If it does not, it is testing itself.

What not to do

  • Do not add a runtime dependency without a strong reason. There is exactly one (zod), and that keeps the package usable everywhere.
  • Do not put site-specific concerns here — persistence, UI, cloud sync, analytics. This package models the game, not any one application.
  • Do not describe where the data came from. Document what a value is and what breaks if it changes, not its provenance.

Clone this wiki locally