9.9 KiB
9.9 KiB
HANDOFF.md — Session Handoff (OVERWRITE at the end of every phase or when context is getting long)
Read order for a new session:
NOTES.md→STATUS.md→ this file → then work. If this file disagrees with the code, trust the code and fix this file.
1. Where we are
- Last completed step: 10.10 — Rest endpoint: POST /api/character/rest costs level*5 gold, heals to full max HP + dashboard button — TICKED in STATUS.md
- Next step: Phase 10.11 — Natural HP regeneration: +1% max HP/min, lazy computation, new migration adds hp_updated_at
- Updated: 2026-10-23
- Was the last session cut off mid-task? No
2. Verified state (run these first)
| Command | Expected |
|---|---|
npm install |
succeeds |
npm run migrate |
applies 001–006 / "nothing to do" |
npm test |
227 passing, 0 failing (85 unit + 142 integration incl. 5 rest endpoint tests) |
npm run seed:dev |
creates demo user "demo"/"demo123", hero "Aldric" (warrior), starter gear |
npm start + curl localhost:3000/ |
200 HTML landing page |
Open /game.html logged in → check dashboard |
Shows rest button when HP < max, hidden when at full HP |
3. What exists now (files that matter)
src/services/characterService.js— Addedrest()function: costs level*5 gold, heals to full max HP, errors NOTHING_TO_HEAL/INSUFFICIENT_GOLDsrc/routes/character.js— AddedhandleResthandler, exportedpostRestsrc/app.js— MountedPOST /api/character/restroutepublic/game.html— Added#rest-sectiondiv with#rest-btnbutton (hidden by default)public/css/main.css— Added.btn-reststylespublic/js/game.js— AddedinitRestUI(),handleRest(), callsinitRestUIfromloadCharacter, attaches click handlertests/integration/step-10.10.test.js— 5 tests (happy heal, full HP rejection, insufficient gold, cross-user isolation, level scaling)
4. Half-finished / fragile things
- No leaderboard UI yet (stub page exists; real UI in 10.17).
- HP never regenerates naturally; only level-up/rest restores it. (10.11 next)
- No restart-persistence test for sessions.
npm run seedscript in package.json points to nonexistentscripts/seed.js.- Equipment bonuses not yet passed into combat (Issue #5 in STATUS.md).
- Starter gear documented but not auto-created on character creation.
GET /api/zonesdocumented in API.md but not implemented (Issue #2).- Mobile nav uses emoji icons (⚔️ 🏕️ 🎒) — verify they render acceptably on all platforms.
- 10.11 next: Natural HP regeneration — +1% max HP/min, lazy computation like energy, migration adds hp_updated_at
5. Decisions & deviations from the docs
- D-004..D-007 in
docs/DECISIONS.md(combat rounds, equipment counted once, session store, clock). - D-014: Mobile bottom nav uses emoji icons (⚔️ Hunt / 🏕️ Trip / 🎒 Items) instead of full text labels.
- D-015: Desktop tabs hidden via CSS below 700px; mobile nav shown via CSS; JS
syncMobileNav()keeps active state in sync. - D-016:
applyXpGaininsrc/game/leveling.jsis the single shared function for XP gain logic, used by bothhuntServiceandexpeditionService. - D-017: Landing page
public/index.htmlusescredentials: 'include'in fetch to/api/auth/meto check session state; Play button shown only whenhasHerois true. - D-018: Link-checker test skips API endpoints (
/api/...) since they're not static files. - D-019: Rate limiters use
process.env.NODE_ENV === 'test' ? 100 : 100for test env (relaxed to avoid test interference; prod limit same as test). - D-020:
allocatePointsinleveling.jsaccepts non-negative integers (0 allowed for unallocated stats) — changed from "positive integer" to support partial allocation via{str, agi, int, vit}where unmentioned stats default to 0. - D-021: Allocation UI uses
container.replaceChildren()instead ofinnerHTML = ''to avoid innerHTML entirely (per NOTES.md constraint).
6. Gotchas learned
npm testmust benode --testwith NO path/glob; files must be named*.test.js.- better-sqlite3-session-store ignores
expired.clear: false; that's why the timer is unref'd. - Statement caches are per-DB-handle (WeakMap) in huntService; copy that pattern for new services.
- Verify test COUNT, not just "all passing".
- Node.js
fetchdoesn't persist cookies across calls — extractSet-Cookieheader and pass manually in integration tests. - SQL
SELECT idfrom inventory returns the auto-increment row id; rename withAS inventory_idwhen you also needitem_id. - Transaction callback args must match the call order exactly. (This is the 10.1 bug — double-check param/call order in every new transaction.)
- Error responses from route-level
AppErrors do NOT includedatafield. setNowaffects ALLnow()calls including those in service logic.- Shop API returns
{ ok: true, data: { stock: [...], character: {...} } }— field isstock, notstocks. - Shop stock items have flat fields (
itemId,buyPrice), not nested (item.id). - New characters have NO inventory items (starter gear not auto-created yet).
GET /api/zonesdocumented in API.md but not implemented.- Hero profile endpoint is PUBLIC — no
requireAuthmiddleware. - Profile page is public: no auth.js guard needed; uses ?name= query param for lookup.
- Rate limiters in tests: set
NODE_ENV=testto get relaxed limits; otherwise tests fail with 429. seed-dev.jsmust checkNODE_ENV=productionbefore anyrequire()that loads config (config throws on placeholder SECRET).- Express
sendFilerejects../path segments — usepath.resolve()+path.join()for absolute paths. express.staticsends its own 404 responses; catch-all must be placed BEFORE static middleware.- Character profile GET returns
{ ok: true, data: { character, derived, energy } }— fields nested undercharacter,derived,energy. - Register returns 201 (Created), not 200.
- Character creation returns 201 (Created), not 200.
- Expedition start uses
defIdin request body (notexpeditionId). - Expedition claim uses
expeditionIdin request body. - Expedition start response returns
data.expedition.id— capture this for claim. src/utils/timeexports{ now, setNow, resetNow }directly —const time = require(...), notconst { time }.- Inventory sell endpoint (
POST /api/shop/sell) only acceptsmaterial-type items. handleListInventoryinsrc/routes/inventory.js— parameter name must beres, not_res.- Character profile response has
energyatdata.energy.current, NOTdata.character.energy. - 10.3:
expeditionService.jsimport changed fromconst { now, setNow } = require('../utils/time')toconst time = require('../utils/time')— the destructurednowvariable was shadowed by the localopts.now ?? time.now()pattern. - 10.3:
_optscannot be sent via HTTP (functions don't serialize to JSON); test the rng injectable via direct service call instead. - 10.4:
req.session.usernamemust be set in bothhandleRegisterandhandleLogin— register was the gap./mereads it, so without it username is always empty string. - 10.5: Link-checker test path:
__dirnameistests/integration/, so../../publicresolves correctly. API endpoints (/api/...) must be excluded since they're not static files. - 10.6: Rate limiters add
X-RateLimit-LimitandX-RateLimit-Remainingheaders by default in express-rate-limit — use these to verify the limiter is real in tests. - 10.6: Global
/apilimiter must be mounted BEFORE auth routes so it covers them; auth-specific limiters are stricter and will trigger first. - 10.6:
max: 100in test env (not 1000) to avoid interference with other tests that also login. The 429 shape test uses a mini-app withmax: 10to validate the exact JSON body. - 10.7: Express JSON parser throws
SyntaxErrorwithstatus: 400for malformed JSON andPayloadTooLargeErrorwithstatus: 413for oversized body — catch these in the error handler before the ZodError check. - 10.7:
req.path.startsWith('/api/')is more reliable thanreq.accepts('html')for deciding JSON vs HTML on unknown paths — Node.js fetch defaults to accepting HTML. - 10.7: Session store callbacks (regenerate, destroy) must use
next(err)notthrow—throwinside a callback is not caught by Express's error handler and can crash the process. - 10.8:
leveling.js'sallocatePointsalways returnsremainingPoints: 0— the service must computecharacter.unspent_points - totalitself. - 10.8: zod
.strictObjectwith optional fields needs.refine()to require at least one field present. - 10.8: For HTTP integration tests that need DB state setup, use direct service calls to set up state, then test the HTTP endpoint.
- 10.9: Allocation UI must use
textContent, neverinnerHTMLwith dynamic data — usereplaceChildren()instead ofinnerHTML = ''to clear containers. - 10.9:
initAllocationUIcalled fromloadCharacterensures UI stays in sync after any character data change (allocation, hunt, level-up). - 10.10:
setupHerohelper must use.then()chain (notreturn async () => { ... }) — the latter returns a function that doesn't execute when awaited. - 10.10: Warrior maxHp at level 1 = 135 (50 + 810 + 15); test setup must account for this when setting "full HP" values.
7. Next-step briefing
- Next step: 10.11 — Natural HP regeneration: +1% max HP/min, computed lazily like energy.
- New migration (next unused number, likely 007) adds
hp_updated_at INTEGERcolumn to characters table; backfill existing rows withenergy_updated_at. - Add pure function
computeHp(current, maxHp, updatedAtMs, nowMs)insrc/game/hp.jswith unit tests (partial minute, cap at max, clock backwards, large gap). - Apply computeHp before HP checks in: hunting,
getCharacterProfile, potion use, and rest. - Heals/damage must set
hp_updated_at = now.