---
name: gamesbymarco-characters
description: Read and edit the GamesbyMarco Character Manager's D&D characters, inventory, homebrew subclasses, campaigns, encounters, maps, tokens, combat, and appearance files through its APIs. Use for agent-assisted character and tabletop management.
---

# Character Manager

Read the [GamesbyMarco platform skill](https://gamesbymarco.com/SKILL.md) first
for authentication, permissions, HTTP contracts, and atomic-write limits. This
file describes the app's collection schema introduced in PR #22. Use the skill
and modules from the same deployed app version; do not assume older account
blobs or keys still work.

## Connect and choose the target

- Obtain the app's actual URL/name from the user or app discovery. Do not infer
  its deployment name from the GitHub repository name. Call it `APP` below.
- Use `https://admin.gamesbymarco.com/data/APP` for token-authenticated data
  operations. Use the app origin for static modules, JSON catalogues, and blobs.
- Send a securely supplied API token only as `Authorization: Bearer …`; never
  include it in URLs, committed scripts, app JavaScript, output, or this file.
- Resolve the acting username with `GET https://APP.gamesbymarco.com/api/auth/me`
  using that token. Select the requested character/campaign by ID after listing
  candidates. The storage API is shared across app users: owner-prefixed keys
  are an app convention, not a security boundary. Respect the requested player's
  data and the app's DM/player rules; do not impersonate a DM to bypass them.
- Public app data is readable publicly; writes need app membership. Private
  apps require membership to read. The app's own skill follows that visibility.
- Assume one writer per player's sheets. Before an agent edits owned data,
  have the player finish pending sheet saves and avoid editing that sheet at
  the same time. Reload the sheet after the agent's edit: sheets do not watch
  remote changes. Live map edits can run alongside other players.

## HTTP transport

Let `BASE = https://admin.gamesbymarco.com/data/APP`. Percent-encode the **entire
key** as one path segment; a key containing `%` needs that character encoded too.

| Operation | Method and path under BASE | Body / result |
| --- | --- | --- |
| Read record | `GET /kv/{encodedKey}` | `{key,value}`; 404 means absent |
| Write record | `PUT /kv/{encodedKey}` | Send `{value:document}`; replaces this record |
| Delete record | `DELETE /kv/{encodedKey}` | 204 |
| List records | `GET /collections/{name}?limit=500&cursor=…` | `{items:[{key,value}],nextCursor}` |
| Read versions | `POST /kv/atomic/read` | Send `{keys:[...]}`; returns `{items:[{key,value,version}]}` |
| Atomic change | `POST /kv/atomic/commit` | Send `{requestId,checks,writes}`; returns `{items:[...]}` |

Follow `nextCursor` until null, encoding the cursor as a query parameter.
Collection listings contain values but **no versions**. Use list APIs for lists,
not key discovery followed by individual GETs. Write a known collection key
with PUT: collection insertion generates a random suffix and therefore does
not fit keys whose suffix must equal a character ID or child identity.
Omit TTL for persistent game data. For PUT, read the existing record and
preserve unrelated fields; there is no field-level PATCH endpoint.

For JavaScript services below, adapt HTTP to this SDK interface:

```js
// api(path, method, body) sends authenticated JSON to BASE, parses the response,
// and throws {status, code: response.error, keys: response.keys} on errors.
// Treat 404 as null ONLY for get; never swallow other HTTP errors.
const kv = {
  get: async key => (await api('/kv/' + encodeURIComponent(key), 'GET'))?.value ?? null,
  set: async (key, value) => (await api('/kv/' + encodeURIComponent(key), 'PUT', {value})).value,
  delete: key => api('/kv/' + encodeURIComponent(key), 'DELETE'),
  collection: {list: (name, options = {}) =>
    api('/collections/' + encodeURIComponent(name) + '?' + new URLSearchParams(options), 'GET')},
  readMany: async keys => (await api('/kv/atomic/read', 'POST', {keys})).items,
  commit: async payload => (await api('/kv/atomic/commit', 'POST', payload)).items,
};
```

Preserve each commit's exact payload, app, authenticated identity, and start
time in a local action journal **before** sending. The services retain pending
operations in browser sessionStorage (memory only outside a browser); a CLI
adapter must keep a durable journal itself. If delivery is uncertain, retry
that identical payload/requestId, not a newly calculated relative action.
On a definite 409 `conflict`, re-read and recompute with a new request ID.
Stop uncertain retries after 23 hours; the server retains receipts for 24 hours.
Do not split a compound live action to evade the 100-key or 16 MiB limits.

## Storage map

Define `U` as the lowercase hex encoding of the username's UTF-8 bytes, **not**
URL encoding: `ada` → `616461`. Keep username spelling/case unchanged.
Define `Q = encodeURIComponent(username)`, `C = characterId`, `P = campaignId`,
`E = encounterId`, and `T = tokenId`. Keep all existing IDs stable.
Character/subclass IDs match `[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}` excluding
`constructor`, `prototype`, and `__proto__`. Campaign/encounter/token IDs match
`[a-z0-9][a-z0-9_-]{2,39}`. Use UUIDs for new character/child identities;
use the app's `newCode()` for campaign/encounter/token codes.

| Record key | Contents |
| --- | --- |
| `characters-U:C` | Character core, including `id` and `_lists` |
| `subclasses-U:S` | One custom subclass definition, `id=S` |
| `character-items-U:C:path:I` | One child row `{characterId:C,path,order,value}` |
| `campaign-characters-U:C` | Canonical campaign assignment / full member |
| `campaigns:P` | Campaign metadata |
| `campaign:P:activity` | Campaign `{sequence,writeId?}` guard and watch hint |
| `campaign-members-P:Q:C` | Full member, identical to canonical assignment |
| `campaign-encounters-P:E` | Copy of encounter metadata for campaign listing |
| `encounters:E` | Encounter metadata |
| `encounter:E:map` | One authored map document |
| `encounter:E:combat` | One turn tracker |
| `encounter:E:activity` | Encounter `{sequence,writeId?}` guard and watch hint |
| `encounter:E:beacon` | Optional `{tokenId,at,revision}` ping |
| `encounter-tokens-E:T` | Token core/statistics |
| `encounter-positions-E:T` | Token position/movement |
| `encounter-members-E:Q` | Standalone member `{username,joinedAt}` |

The collection name is everything before the **first** colon. There is no
persisted whole-account object, character-order array, or embedded campaign
roster/encounter array. `Store.data`, loaded campaigns, and loaded rooms are
assembled views—never PUT them back as a single record.

## Characters, inventory, and subclasses

Read `characters-U`, `character-items-U`, and `subclasses-U` with pagination.
Use [collections.mjs](./collections.mjs) (`readAccountRecords`, `assembleAccount`,
`accountRecords`) to assemble/disassemble the UI representation. In a source
checkout these files are under `src/`; the deployed bundle has flat filenames.
Preserve unknown fields and stable child IDs when editing.

The core holds identity/progression (`name`, `species`, `class`, `level`,
`background`, `subclassId`, `classHistory`, `multiclass`), ability scores,
choices, HP, conditions, counters, wallet, spell selections, notes, appearance,
and timestamps. Use the following field families rather than inventing aliases:

| Concern | Core fields / rules |
| --- | --- |
| Abilities | `abilities.{str,dex,con,int,wis,cha}`, whole scores 1–30 |
| HP / death | `hp.{current,temp}`, `deathSaves.{success,fail}`, `hpRolls`, `revivalPenalty` |
| Currency | `wallet.{cp,sp,ep,gp,pp}`, nonnegative integer coin counts |
| Resources | `resources`, `spellSlotsUsed`, `temporarySpellSlots`, `pactSlotsUsed`, `hitDiceUsed`, `hitDiceUsedByDie` store counters/uses |
| State | `conditions`, `exhaustion`, `toggles`, `reductions`, `restCooldowns`, `conditionRecovery` |
| Spells | `spells.known`, `spells.prepared` contain catalogue IDs; preserve other class-specific spell fields |
| Class features | Preserve `arcaneWard`, `primalCompanion`, `wildShape`, `wildShapeKnown`, `warGodsBlessing`, and other feature state |

Use [store.mjs](./store.mjs) `newCharacter()` for defaults,
`normalizeCharacter()` and `validateCharacterShape(character, DATA)` for
validation. Validation returns an error string or null. Use catalogue IDs from
the deployed `classes.json`, `species.json`, `backgrounds.json`, `equipment.json`,
`spells.json`, `feats.json`, and related JSON files; do not store display names as
IDs. For derived HP maximum, AC, attack bonuses, or resource capacities, use
`derive(character, DATA)` from [rules.mjs](./rules.mjs), rather than guessing or
persisting a derived result as an unrelated core field. Assemble DATA as in
[main.mjs](./main.mjs), including the PHB subclass catalogue.

Split these paths into child rows: `inventory`, `equipment`, `customActions`,
`expenses`, `itemEffects`, `customResources`, `spells.custom`. Do not embed their
arrays in the persisted core. `_lists` names the paths present on that character;
reconstruct them as arrays, append their rows ordered by `order`, then remove
`_lists` from the assembled character. Other compact lists remain core fields.

For each child, suffix `I` is `value.uid` if present, otherwise `value._entryId`.
Do not confuse an inventory catalogue `value.id` with its per-character `uid`.
`value._order` and row `order` must agree. New entries need a stable identity and
an order greater than existing entries for that path. Removing one item must
not renumber its siblings. A custom resource also has its own logical `id` used
by `resources`; preserve it separately from `_entryId`.

Example stored inventory row (under
`character-items-616461:hero:inventory:item-123`):

```json
{"characterId":"hero","path":"inventory","order":0,"value":{"uid":"item-123","id":"torch","quantity":2,"_order":0}}
```

Edit its quantity with one PUT of the complete updated row. Add `inventory` to
core `_lists` if this is the character's first inventory list. Keep quantities
within 0–100000. Use [inventory.mjs](./inventory.mjs) for purchases, money,
equipping, attunement, and consumption so their related fields stay coherent.
For a complex sheet edit, assemble → modify → validate → `accountRecords` →
diff the old/new record maps; PUT/DELETE only changed records. Flush owned
writes before joining a campaign or syncing sheet HP/appearance to the map.

Store custom subclasses in `subclasses-U:S`. Use the same JSON shape as built-in
subclasses (`id`, `name`, `classId`, `features`, choices, resources, typed effects).
Use [subclasses.mjs](./subclasses.mjs) `validateSubclass(sub, DATA)` and
`planSubclassImports(...)`; consult `custom-subclass.example.json` and the
shipped subclass catalogues. Preserve `subclassId` references, including
multiclass state. Do not switch a used definition to another class. When
removing a custom definition, clear affected character references unless the
built-in catalogue provides that same ID. Prefer `Store.saveSubclasses` and
`Store.removeSubclass` for the app's supported operations.

For character deletion, use `Store.remove(C)` followed by `await Store.saveNow()`
(check its boolean result/error). Its deletion transaction removes the core,
canonical campaign assignment, and campaign roster row while bumping campaign
activity; child rows are then cleaned up. Do not just DELETE the character core
and leave a live party member behind. `Store.load(username, kv)` needs a local
storage adapter in a CLI; retain local drafts on save failures.

## Campaigns and encounters

A campaign has exactly one active encounter. Its metadata is
`{version:1,id,title,dmUser,activeEncounterId,createdAt,revision}`. The full member
is `{campaignId,username,characterId,slot,joinedAt,token}`; `slot` is unique within
the roster (0–99), and `token` supplies `id,name,hp,maxHp,ac,speed,initiative` and
optional appearance. A character can belong to only one campaign.

Campaign players are projected into every encounter, including future ones.
Do not copy membership into each room. A player's first position or HP override
may exist without the other record: absent overrides inherit the campaign
member's token and stable `partySpawns`. Departed player overrides may remain
stored but are ignored by projection. Use loaded room tokens, not raw token
listings, to enumerate players. Standalone encounter membership uses its own
member collection; campaign membership supersedes a sheet's standalone link.

Use the deployed [campaign-service.mjs](./campaign-service.mjs) and
[encounter-service.mjs](./encounter-service.mjs) for shared writes. Download the
matching modules and their relative imports into a local workspace for Node,
or import them in the app's browser origin with its existing `kv` SDK. No new
server-side game-action endpoint exists: these services translate game intents
into the ordinary GamesbyMarco read/list/atomic HTTP APIs.

```js
import {createEncounterService} from './encounter-service.mjs';
import {createCampaignService} from './campaign-service.mjs';
const encounters = createEncounterService({kv, username});
const campaigns = createCampaignService({kv, username, encounters});
// Supply the real authenticated actor, not an arbitrary DM username.
const campaign = await campaigns.create({title:'Val di Noto',
  encounter:{title:'The mill',template:'blank',width:16,height:12}});
const next = await campaigns.createEncounter(campaign.meta.id,
  {title:'The forest',template:'blank',width:24,height:18});
await campaigns.setActive(campaign.meta.id, next.meta.id);
```

Use `campaigns.listMine/load/memberships/forCharacter` for discovery;
`campaigns.join(P,{characterId:C,token})` for a saved character;
`campaigns.leave(P,C,ownerUsername)` for departure (another owner requires DM).
Joining must atomically claim the canonical assignment and roster row, check
that the character exists, and respect campaign/map capacity. Creation must
publish the campaign and its first complete room together.

For a player's action, resolve `campaigns.forCharacter(C)` immediately before
choosing the encounter and token; dispatch with `campaignActiveOnly:true`:

```js
const {member,campaign} = await campaigns.forCharacter(characterId);
await encounters.dispatch(campaign.meta.activeEncounterId, {
  type:'nudgeToken', tokenId:member.token.id, dx:1, dy:0,
  campaignActiveOnly:true,
});
```

If membership is null, do not invent a campaign. If the active encounter changes,
resolve the route again; do not force the action onto the previous map.
For standalone rooms use `encounters.create({title,template:'blank',width,height})`.

| Intent for `encounters.dispatch(E, action)` | Action fields |
| --- | --- |
| Rename / displayed floor (DM) | `{type:'setTitle',title}` / `{type:'setFloor',floorId}` |
| Add token | `{type:'addToken',token:{id,kind,name,x,y,hp,maxHp,ac,speed,initiative,ownerUser?,characterId?,creatureId?,floorId?,appearance?}}` |
| Remove token (DM) | `{type:'removeToken',tokenId}`; campaign players leave through campaign service |
| Move / undo / Dash | `nudgeToken` with `dx,dy`; `moveToken` with `x,y`; `undoMove`, `dashToken`, `resetTokenMovement` with `tokenId` |
| DM placement | `{type:'placeToken',tokenId,x,y,floorId?}` |
| HP | `{type:'adjustHp',tokenId,delta}` / `{type:'setHp',tokenId,value}` / `{type:'syncCharacterHp',tokenId}` |
| Initiative | `{type:'setInitiative',tokenId,value}` (null or whole score; before combat) |
| Combat (DM) | `startCombat`, `nextTurn`, `endCombat`, `resetMovement` |
| Token statistics (DM) | `{type:'updateToken',tokenId,patch}`; patch allows `name,hp,maxHp,ac,speed,ownerUser,hidden` |
| Appearance / ping | `{type:'setTokenAppearance',tokenId,appearance}` / `{type:'pingToken',tokenId,at}` |
| Replace map (DM) | `{type:'setMap',map,expectedRevision:loadedRoom.map.revision}` |

Treat HP on a sheet and HP on a map as distinct values. Sync is explicit and
absolute; do not apply a second relative delta to emulate a sync.
Movement is in grid cells (five feet each); position tracks `x,y,floorId`,
`movementUsed,movementBonus,dashCount,movementEpoch,previousMove?,revision`.
The core tracks identity, ownership, HP/maxHP, AC, speed, initiative, appearance,
hidden state, and its own `revision`. Never copy assembled `positionRevision`
into the core. Combat stores `{active,round,order,turnIndex,turnEpoch,revision}`;
movement from an earlier epoch counts as unused. The table remains responsible
for adjudicating attacks and movement limits; don't add stricter game rules.

## Shared-write invariants

Prefer the services over hand-written compound operations. If a requested edit
has no service method (for example, renaming a campaign), follow these rules:

1. Read all decision records with `readMany`. For a paginated campaign/room,
   read its activity guard before listing and verify the same opaque version
   after all reads; retry if changed. Include the campaign guard/meta for a
   campaign room. Every shared writer must maintain this protocol.
2. Validate the assembled result with `validateCampaign`, `validateMember`,
   `validateEncounter`, or `validateMap` as applicable. Keep DM, owner, membership,
   capacity, token identities, and active-room constraints intact.
3. Commit related changes together with checks on the versions read, including
   guards and absent new keys (`version:null`). Increment the relevant activity
   `sequence` and assign a new `writeId` in that same commit. JSON `revision`
   and activity sequence numbers are not replacements for server versions.
4. Every room mutation bumps `encounter:E:activity`. Changes affecting campaign
   discovery/capacity (`addToken`, `removeToken`, `setTitle`, `setFloor`) also bump
   `campaign:P:activity`; keep `encounters:E` and `campaign-encounters-P:E`
   metadata copies consistent, including `monsterCount`. Membership/activation
   changes bump campaign activity. A campaign rename checks/writes its metadata
   plus activity and increments metadata revision.
5. On conflict, re-read and validate the original intent against current state.
   On uncertain delivery, resolve the existing receipt. Never report success
   from an optimistic local result. Read back the affected records after an
   agent operation, without reloading unrelated owned lists.

Do not delete the active encounter or leave a campaign without an encounter.
There is no campaign/encounter delete service; deleting those aggregates needs
an explicit cleanup of references, memberships, and child records, not a single
DELETE. Do not guess a destructive cleanup for an ordinary edit request.
Watch notifications are invalidation hints without replay; the app's live
subscriptions also poll to recover missed events. Never apply an isolated SSE
payload as a complete room. Owned sheet edits need no watch or atomic commit.

## Maps and files

Use [map-document.mjs](./map-document.mjs) `blankMap`, `importMap`, `editMap`,
`makeObject`, `refreshTiles`, and `validateMap`; use [map-catalog.mjs](./map-catalog.mjs)
for asset/material IDs. A v2 map has `format:'cortile-map'`, `version:2`, dimensions,
`grid`, `environment`, `layers`, `floors`, `sets`, `revision`, and derived `tiles`.
Each floor has `id,name,base,rooms,walls,objects,terrain,lights`. Keep this authored
document together; its arrays are not KV collections. Preserve globally unique
map-item IDs, 1–8 floors, 4–128 dimensions, and at most 2,500 items. Refresh derived
collision tiles after edits and save through `setMap` with the loaded revision;
never overwrite a conflict silently. Keep tokens on valid floors within bounds.

Appearance references live in the character core and, separately, token cores.
Upload immutable files to the **app origin** `POST /api/blobs` as multipart
`file` plus a unique `key` (e.g. `character-<uuid>`), then store references, never
base64 or external URLs. Read bytes with `GET /api/blobs/{encodedKey}`. Inspect
[character-appearance.mjs](./character-appearance.mjs) for `inspectCharacterGlb`
and `validAppearance`: use self-contained GLB 2.0 for models and PNG/JPEG/WebP
for pictures, at most 10 MiB each. Reference shape:
`{model?:{key,name,size,mime,previewKey?,orientation?,upAxis?,turn?},picture?:{key,name,size,mime}}`.
Validate before upload/save. Do not delete a blob still referenced by a sheet,
roster, or encounter; a roster's initial appearance and each room's overrides
may outlive a sheet edit. File deletion is `DELETE /api/blobs/{encodedKey}`.
