TableTower/docs/DESIGN.md
RobinFiredrake e5d3873cb2 DESIGN.md: open items, terminology decisions, Coderstanding how-to
Open items for the next session (repo privacy waiting on the user, a
playtest of the renamed build, a stale worktree), the glossary as a
decision, built-in templates, the next files to split, uninvestigated
scanner warnings, and the parallel-split agent brief.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:18:15 -06:00

23 KiB
Raw Blame History

TableTower — Design and Status

Engine: Godot 4.7.2 (GDScript) · Started: 2026-11-08 · Last updated: 2026-11-09 (file splits, duplicate-code and terminology passes; see §10)

This is the starting point for anyone picking the project up, including a new Claude session. It records what TableTower is, how it's built, how to work on it, where things stand, and what's next.

Detailed references:

  • docs/LOGIC.md: the rule language and every logic feature: card kinds, expressions, effects, variables, conditional pipes, routers, dynamic options and the file keys.
  • docs/PLAIN.md: the Plain Build usability layer: plain-language display, fill-in builders, Check cards, card inputs, collections and the "why" trace.
  • README.md: user-facing usage notes and command-line/screenshot flags.

Open items for the next session (as of 2026-11-09)

  • Repo privacy (waiting on the user). The Forgejo instance is internet-facing. The user wants every one of their repos private, with digit and Niles/sock as collaborators.
    • Today only RobinFiredrake/TableTower is public.
    • Niles/sock's username wasn't found: logged-out user search for "niles" or "sock" returns nothing.
    • Needed from the user: that exact username, plus an API token (repository read/write and user read, passed as FORGEJO_TOKEN), or they do it in the web UI themselves.
    • Don't go looking for stored credentials.
  • Hands-on playtest of the split/renamed build. The user had a first look after the file splits ("looking fine so far"), but the terminology pass hasn't been tried by hand.
  • Stale worktree. .claude/worktrees/agent-aa27e470dd86ce971 (branch split-table-card) stayed locked by a finished agent. Its work is merged, so run git worktree remove -f -f on it, then delete the branch.

1. What TableTower is

A desktop app for building random roll tables and rolling on them, for tabletop GMs, players and anyone using random prompts. Tables are cards on a felt board, joined by copper pipes. A roll flows down the pipes from card to card, and the path lights up.

On top of plain tables, a logic layer lets a board ask the player questions, remember values, repeat steps, branch, and print a sheet. A whole procedure, such as generating a character, can run as one chain.

Product principles (from the user)

  • General-purpose. Not built for any one game. The Traveller board (§8) is only a capability test, used to find missing general features. Don't build game-specific features.
  • Play mode stays simple for use at the game table. Advanced controls belong in Build mode.
  • Readable by normal people. Rules show in plain words by default. The rule text is still stored, and visible through the Plain/Text switch and "Edit as text".
  • The visual design is settled: felt green, copper pipes, brass for lit and selected things, Rokkitt (display) and Atkinson Hyperlegible (body). See ui/style.gd. Match it and don't restyle.

2. Feature summary (all on main)

Board and rolling

  • Cards and pipes. Cards show their numbered results and a die button. Drag from a result's ● onto another card to lay a pipe.
  • Rolling. Results flicker and land, and a bead travels each pipe. Shift-click fast-rolls with no animation.
  • Play / Build modes. Collapse a card or Collapse all. Pan, zoom (8%–150%), Fit and a minimap (Map).
  • Table types. Weighted plain tables, ranged dice tables (1d100, 2d6, any expression such as 2d6 + dm(@str)), and card mode (a deck with no repeats, with Reshuffle).
  • Pipe options. A count (a number or an expression), "save as", Only if conditions, and Otherwise. A result's conditions and counts are evaluated once, as a snapshot, before any pipe runs.
  • Text in results. [[Table]] inline references, {@var} / {hero} values, and BBCode formatting.
  • The result tray shows the chain as chips with effect lines, a sheet headline, Earlier rolls, a Variables tab, Copy (text, BBCode, with details) and Why this? on each step.

Logic cards (docs/LOGIC.md)

  • Choice: "Which option" (pick, with Random), "How many" (a number) or "Open ended" (text). The pop-up can be minimized, and its options preview where they lead.
  • Loop: repeat N times, while a condition holds, or until it does. Then "Afterwards".
  • Router: if / else if / otherwise cases; the first true case runs.
  • Check: roll + modifier against a target, with Success and Failure outlets. Sets nat, total and effect.
  • Variable cards (with a starting value) and Collection cards (e.g. Skills, whose members are @skill_*).
  • Sheet: a live template, e.g. a character sheet.
  • Changes (stored as effects) on any result: @x = …, +=, -=, reset @prefix_*, list add/remove, and @[expr] indirect names.
  • Dynamic pick options from a collection or list (options_from, options_where), plus show_if on any option.
  • Card inputs: a card declares inputs, and pipes pass values (with), scoped to that pipe's part of the roll.
  • A 10,000-action limit per roll. The roller uses an explicit stack, so long loops don't overflow.

Building (Build mode)

  • The inspector, docked right. It edits the selected card, result or pipe:
    • effects as rows ("[Subtract] [1] from [Luck]")
    • conditions as rows ("[Luck] [is at least] [2]", with and/or)
    • pipe inputs, Otherwise, count and saves-as
    • kind-specific card fields
    • a value picker with "+ New value…"
    • "Edit as text" everywhere
  • Plain / Text switch in the top bar.
  • Undo/redo (Ctrl+Z, Ctrl+Shift+Z / Ctrl+Y, or ↶ ↷) for every board edit. Typing and dragging merge into one step.
    • Collapse/expand isn't undoable.
    • Rolls, variables and decks aren't undoable.
    • Collection members aren't undoable either.
  • Group cards. Frames that collapse whole blocks. Ctrl/Shift-click or Ctrl-drag to select, Ctrl+G to group, then drag cards in or out, rename, ungroup or delete. Arrange ▾ → Pack collapsed groups.
  • Templates. Save a card, group or selection, with {$param} fill-ins. Insert from "+ Card ▾ → From template…". The library is in user://templates/, and generic built-ins are in templates/: skill check (a Check card, 2d6 + modifier vs target), ask-and-repeat, pick menu, counter and simple sheet.
  • Search (button or Ctrl+F) jumps to cards, opens groups and flashes the card.
  • Test board (Board ▾): hundreds of random rolls plus static checks. It reports errors, dead ends, unreached cards and lint, and clicking an item jumps to the card.
  • Collections (switcher in the top bar). Import and export via Board ▾: TableTower JSON, JSON Canvas, GraphML (both ways), plus Mermaid and DOT (export only).

3. Architecture

core/       engine, no UI, testable headless
  tower_board.gd      a collection (tables, groups), JSON, format v2 + migration
  roll_table.gd       a card: kind, dice, entries, logic fields, factories (RollTable.create)
  table_entry.gd      a result: text, weight, range, effects, pipes (+count/save/when/otherwise/with), show_if, when
  roller.gd           coroutine roller with an explicit stack (_chain loop, roll/pipe steps,
                      apply_starting_values) plus delegators to its parts:
    roll_pipes.gd       pipe_plan snapshot, card inputs (`with`)
    roll_cards.gd       weighted picks, router, check, loops
    roll_choice.gd      choice requests, dynamic options, show_if, asking
    roll_tree.gd        flatten, step lookups, lit keys, pipe/entry keys
    roll_lint.gd        lint_*, endless_cycles
  roll_context.gd     per-roll state: chain and board variables, prompt hook, actions, depth
  expr.gd / effects.gd     expression evaluation (Godot Expression + rewrites), effect statements
  text_expander.gd    [[refs]], {vars}, {@prefix_*}, {= expr}; formatter.gd: BBCode safety and stripping
  dice.gd / deck_state.gd  dice parsing and distributions, card-mode decks
  describe.gd         rules → plain words, labels, why sentences; kind_label / choice_label
                      (the only place card-kind and choice-type names are defined)
  builder.gd          effect/condition models ↔ text, known_values
  board_tester.gd     simulation and static checks (used by the Test board UI and the CLI)
  library_store.gd / state_store.gd   collections on disk / local state (decks, variables, history, settings)
  table_group.gd, template_kit.gd, template_library.gd, sample_board.gd
io/         json_io (canonical + import), canvas_io, graphml_io, mermaid_exporter, dot_exporter
ui/         main.gd: the app shell (shared fields, _ready, cards, collapse, input) with one-line
            delegators to RefCounted helpers that hold `m: Main`:
              main_cli (every CLI/screenshot flag), main_rolling, main_editing, main_groups,
              main_history (undo), main_navigation (search/focus/minimap/arrange),
              main_top_bar (bar, toast, rules switch), main_state (decks, variables),
              main_collections, main_templates, main_inspector
            table_card.gd + table_card_{header,rows,editing,value,text}.gd
            result_tray.gd + tray_chips, tray_text, earlier_rolls
            table_settings_dialog.gd + table_settings_rules (validation/apply), settings_kind_fields
            and: board_view, card_layer, pipe_layer, port_layer, group_layer, group_card, minimap,
            why_popover, choice_dialog, table_preview, details_popup, inspector*, value_picker,
            rules_view, search_panel, board_search, board_layout, edit_history, test_board_dialog,
            template_*, io_menu, collection_switcher, variables_panel, modal_card, rich_text, style
tools/      simulate_board.gd (headless simulator CLI), test_window.sh (background test windows)
tests/      test_*.gd: 25 headless suites
templates/  built-in templates · examples/logic_demo.json (original demo board) · assets/fonts (OFL)

Key implementation facts

  • Lazy cards. Cards hidden inside collapsed groups aren't built, so main.card_for(id) can return null. Pipe, port and card layers redraw only when something changes.
  • Undo (ui/edit_history.gd) snapshots each table and group separately, sharing unchanged ones.
  • Prompts. The roller awaits ctx.prompt for choices, and the UI shows progress before each pop-up.
  • Rules display. The UI reads plain or text mode through RulesView and main.rules_plain(), and main.rules_view_changed signals a switch.
  • Shared builders, use them rather than copying: Style.menu_button, Style.font_colors, Style.field_colors, TableCard.vbox/hbox, InspectorKit.* (fields, focused_tag/refocus, as_text_link), Main.file_dialog/export_dialog, JsonIO.entry_line/finish_import.
  • Keep files small. Aim for under ~400 lines; split by area into helper objects as above. Next candidates, all 540–700 lines:
    • core: describe, roll_table, expr
    • ui: choice_dialog, inspector_card, inspector, main, edit_history
    • io: json_io

4. Data and storage

  • Collections: user://collections/<id>.json, format_version 2 ({format_version, id, name, tables, groups?}). On Linux that's ~/.local/share/godot/app_userdata/TableTower/.
  • Local state (never exported): user://state/state.json holds decks, board variables, history (cap 50) and settings (last_collection, minimap, inspector collapsed, rules_view). Templates live in user://templates/.
  • Installed collections today: my-tables (migrated from the old board.json, backed up as board.json.bak) and traveller-chargen. Backups of earlier Traveller boards are traveller-chargen.before-*.json.bak in the app data folder.

5. Working on it

Basics

  • Godot: ~/apps/Godot_v4.7.2-stable_linux.x86_64. A desktop launcher "TableTower (Godot)" opens the editor on the project.

  • Tests: for t in tests/test_*.gd; do godot --headless --path . -s "res://$t" -- --sample; done. All must print PASS: 0 failure(s). After adding class_name files, run godot --headless --path . --import first.

  • Smoke test: godot --headless --path . --quit-after 120 -- --sample, which must print no SCRIPT ERROR.

  • Simulator: godot --headless --path . -s res://tools/simulate_board.gd -- --board=<json> --start=<id> --runs=N [--check] [--prefer=regex] [--quiet].

  • Windowed runs and screenshots: always go through tools/test_window.sh -- --sample --screenshot=/path.png [flags].

    • It runs the game as window class "TableTower Test", and a KWin rule (KDE Plasma 6, Wayland, in ~/.config/kwinrulesrc) keeps that class unfocused and behind other windows.
    • Never open a test window with plain godot --path ..
    • Don't minimize test windows; Godot stops rendering when minimized.
  • Screenshot and state flags, read in ui/main_cli.gd and in some UI files; README lists the main ones:

    • Setup and roll: --board, --roll, --fast, --answers, --build, --rules=text, --why.
    • Inspector and focus: --inspect=tid[:eid][>to], --search, --focus, --minimap.
    • Tools and layout: --test-board, --pack, --perf, --window=WxH.
  • Coderstanding (the user's structure scanner, https://forgejo.smhub.duckdns.org/digit/coderstanding) saves tokens on audits and big reads.

    • Not installed permanently. Clone it into the scratchpad, make a venv, pip install <clone>.
    • Keep its config and data out of the repo. Set XDG_CONFIG_HOME=<scratch>/xdgconf, then coderstanding add tabletower <repo> --data <scratch>/cs_data and coderstanding rescan tabletower.
    • Commands: outline <Class> (functions with line ranges), hotspots, dupes (string literals only), warnings, find, uses, brief.
    • Copied code: dupes doesn't find copied code blocks; use a sliding-window line hash for that.
  • Launching for the user to look at (not a test): plain godot --path . in the background is fine, so the window comes to the front.

Git and agent workflow

  • Git: remote origin = git@forgejo.smhub.duckdns.org:RobinFiredrake/TableTower.git. Work on a feature branch and merge to main when the user asks (fast-forward). End commit messages with the Co-Authored-By line.
  • Agents. Large features have been split across parallel agents in git worktrees, each owning specific files:
    • Worktrees start from an old commit, so each brief says git reset --hard <branch> first.
    • Merge one by one, run every suite and the simulator, take screenshots, then fix the seams.
    • Brief each agent to keep the public API of the file it owns (one-line delegators), so parallel splits don't conflict. Only tests may change in several branches at once.
    • Merged feature branches still exist locally and on the server (pipe-board, fast-roll, logic-cards, groups-templates, boards-v2, undo-options, plain-build); they can be deleted.

6. Decisions on record

  • The three-pane UI from the first design was replaced by the pipe board (a user request: simpler at the table).
  • Variables are kept between rolls until changed or reset, so a character sheet survives other rolls.
  • A variable card's starting value is applied, if the variable isn't set, when a top-level roll starts.
  • Expression dice clamp beyond the end ranges. Plain dice tables report gaps instead.
  • Pipe conditions and counts are a snapshot taken when the result is chosen. Two true Only-if pipes both run; routers give exactly one.
  • a if c else b is refused (Godot's Expression returns the wrong branch); use if(c, a, b).
  • Collapse/expand isn't undoable. Collection members aren't undoable.
  • Rules are stored as text, and the plain layer sits on top of it, so old boards open unchanged.
  • Traveller-derived content stays out of the repo (§8).
  • Terminology (2026-11-09). UI text uses these words; code and JSON keys keep their old names.
    • Card: anything on the felt. "Roll table" means only the roll kind.
    • Result, never "entry" or "row" (code: TableEntry, entries).
    • Change in plain text, "effect" only in Text mode (code and JSON: effects).
    • Pipe. Pipes are deleted, like cards and results. "Remove" is for taking an item out of something.
    • Reset = back to the starting value, or erased if the value has no card. "Clear" only when a value really is erased.
    • Dice always read 2d6 / d6. 2D is accepted as input only.
    • Choice types: "Which option / How many / Open ended", from Describe.choice_label.
    • JSON keys aren't renamed. A rename needs a format bump plus migration.

7. Known gaps and bugs

  • Only one pipe per target per result. Pipes are keyed by target id, so the mockup's two pipes into Loot (Tier 3 "only if", Tier 1 "otherwise") can't be built. Lifting this needs pipe ids in the model, the file format, the UI keys (tid:eid>to) and undo.
  • Long pipe labels are cut with "…" in narrow gaps, and labels draw behind cards.
  • The Why pop-over opens above the tray and can cover the bottom of the board.
  • Not tried by hand yet: all of this was verified with headless tests and screenshots only. A hands-on playtest with a checklist is overdue.
  • The Linux export preset exists, but the 4.7.2 export templates aren't installed. They're a large download and the user hasn't approved it. There are no Windows or Mac presets.
  • Loading a big board with every group expanded takes about 5 s (building TableCard nodes).
  • Group frames are rectangles, so a non-member card lying inside one looks like a member. Pipes into a collapsed group can't be clicked.
  • Groups aren't kept in the Canvas and GraphML exports. Logic keys survive only in TableTower JSON.
  • {= } dice in live sheet and variable displays re-roll when the display refreshes.
  • Not yet looked into: Coderstanding warnings.
    • Signals emitted but never connected: ModalCard.closed, SearchPanel.closed.
    • A possible wrong handler in ModalCard.segmented (pressed → on_change; probably a false positive from a bound callable).
    • Large class cycles in ui/ (expected from the main back-references).

8. The Traveller test board (private)

  • Location. Private content derived from the user's Mongoose Traveller 2e rulebook lives in ~/Repos/Godot/TableTower-private/ (outside git; see its README). That covers the rules digest (traveller/chargen.json), the board generator (traveller/board/build_board.py, python3 -I) and the generated board.
  • The board itself. It's installed as collection traveller-chargen: 662 cards, 23 groups, routers, dynamic options and show_if. It runs clean in the simulator (start card new_traveller).
  • Still worked around:
    • global "argument" variables (@x_offer, @x_lvl) feeding shared skill cards
    • natural-roll pre-rolls (rs, ra, rc)
    • .replace() chains for names
    • counters instead of len()
    • about 70 reset statements
    • a guard before empty dynamic picks
  • Not automated: group steps (Connections, skill packages, shared ships), contact naming, gear choice, medical bills, anagathics, the Psion career, Noble titles, and the total skill cap.
  • Open question for the user: "Raise a skill you already have" counts level-0 skills as held (the rules reading); the user's earlier example was level 1+.

9. Improvement ideas, roughly by value

  1. Hands-on playtest with a checklist, then fix what feels wrong. Highest value now that Build mode has changed a lot.
  2. Several pipes to the same card (pipe ids). It unlocks Tier 3 "only if" plus Tier 1 "otherwise" into one card.
  3. Port the Traveller board to the new features:
    • card inputs instead of the @x_* argument variables
    • Check cards
    • nat
    • collections This also tests them end to end.
  4. Small engine additions:
    • len(list)
    • sum / max over a prefix (enables "best of these skills" and skill caps)
    • a fallback path when a dynamic pick has no options, instead of stopping the roll
    • telling unset from 0
    • lists that keep duplicates
    • effects that run after pipes
    • nicer display names ("Jack-of-all-Trades")
  5. Onboarding: a guided tutorial board, a cheat-sheet panel, and templates surfaced as "starter blocks".
  6. Sheet output: save a finished sheet as text or Markdown; keep finished characters as a list.
  7. Comfort: a UI scale setting, colour-blind-friendly lit pipes, optional seeded rolls.
  8. Groups: nested groups, only true members inside frames, clickable pipes into collapsed groups, and groups in the Canvas and GraphML exports.
  9. Linked templates: a plan exists. Copies record template uid, revision and role, and offer "Update available" with a per-field merge.
  10. Faster expanded-board loads.
  11. Builds: install the export templates (needs the user's OK), add Windows and Mac presets.
  12. From the original design: a big-button quick-roll view, cross-collection references ([[Collection/Table]]), touch support.
  13. Naming suggestions not yet applied (from the 2026-11-09 audit):
    • Rename the Collection card kind (e.g. "List"), so "collection" means only the saved set.
    • Label the check margin "Margin" instead of "Effect".
    • Keep raw @name / {@x} / "BBCode" out of Play mode.
    • "Endless loop" → "Never finishes".
    • Drop the _ on helpers used across files.
    • EffectsBuilder/ConditionBuilder → *Editor, LibraryStore → CollectionStore.
    • Keep JSON keys as they are; document the key ↔ UI mapping in LOGIC.md.
  14. Housekeeping: delete merged branches (also split-table-card, see Open items). Keep LOGIC.md and PLAIN.md in step with features.

10. History

2026-11-08 (one long session): board and core features

  1. Initial Godot project and the original design doc. An HTML mockup became the pipe board, built in Godot.
  2. First feature wave (parallel agents): weights, dice expressions, card mode, text references and BBCode, collections and local state, import/export, a Linux preset, the play-side UI, and the app shell (settings, collection switcher, import/export menu).
  3. Fast roll (Shift-click).

Logic cards 4. Logic cards: choice, loop, variable and sheet cards, effects, expressions, the 10,000-action limit and a coroutine roller. 5. The Traveller board was generated and simulated from the rulebook digest.

Building tools 6. Group cards and templates. Choice pop-up minimize and option previews. 7. Conditional pipes and routers, search, minimap, packing, lazy cards (the board opens in 0.38 s, was 5 s), and Test board. 8. Undo/redo, and dynamic options with show_if and @[expr]. The Traveller board was regenerated with them (792 → 662 cards).

Plain Build 9. The usability mockup, then Plain Build: plain words, the inspector with builders, Check cards, card inputs, collections, Why this?, the Plain/Text switch, and starting values applied.

2026-11-09: token diet 10. Split the oversized files (main.gd 3679 → 617 lines plus 11 helpers; table_card, roller, table_settings_dialog and result_tray likewise) with no behaviour change, then a duplicate-code pass guided by the Coderstanding scanner (shared Style/InspectorKit/JsonIO/Main helpers, dead flags and fields removed). A terminology pass followed: - One Describe.kind_label / choice_label for every kind and choice name. - Choice types are "Which option / How many / Open ended". - Dice read "2d6", never "2D". - The built-in skill check is now a real Check card (builtin:skill-check). - "result" and "change" replace "entry", "row" and "effect" in UI text. - Pipes are deleted, not removed; reset reads "Reset".