8 Commits

Author SHA1 Message Date
Alexander Rozhenko
e1f06e3405 Lead with a short project overview and app screenshots 2026-11-18 00:40:21 -04:00
Torres
f4ebd33329 Keep the gallery open on touch and remove rows that leave a List filter 2026-11-18 00:38:17 -04:00
Alexander Rozhenko
beeace231d fix #3: guard breakdown() so a delisted mid-batch card cannot 500 the deck
A section can outlive an ad: when a card's listing left the active pool after compose and has no swipe history, it is absent from the engine's by_id map. breakdown() indexed the missing row without a guard, so one such card 500'd GET /api/section (and /api/listing/{id}) - live incident 2026-11-15: section 57 + delisted listing 298. Degrade to no-signal lines instead. Regression test added; before/after verified on a copy of the live DB (section 500 -> 200; forge rebuild 200).
2026-11-15 11:06:51 -04:00
Alexander Rozhenko
79e7a4f61f fix #2: header pill refreshes itself after swipes, undo and new batches
loadStats() only ran once at boot, so the live/fresh/new pill (and the
list sub-line) went stale until a full reload. Refresh it, debounced and
fire-and-forget, after any decision change, when a new batch lands, and
on app foreground. Adds two fe_walk_v11 regression checks + a UI-SPEC note.
2026-11-13 15:58:36 -04:00
Alexander Rozhenko
618cd4a61c docs: refresh README deployment status (live 2026-11-12, sidecar authorized, nightly chain) (#1) 2026-11-13 15:01:31 -04:00
Torres
66d3cc4da3 docs: apply the v1.1 UI-SPEC amendments (A-I) from V1.1-BUILD.md
§2 card geometry contain/blur bullet · §2 loud empty state · §7.3 header
pill fresh counter · §10.1 batch-formula-v2 composition sentence · §10.2
dry-catalog note · §10.3 violet SECOND LOOK band + dossier mirror · §10.5
minimal rubric + rubric_debug visibility · §11.3/§11.4 info-first doors
and the viewer walk-back chain.
2026-11-13 14:05:33 -04:00
Torres
35138bdc22 test(v1.1): fe_walk_v11 harness (89 checks, 3 staged catalogs) + polish from the walk
- app/fe_walk_v11.py: self-contained headless walk — stages rich /
  returns-only / dead-catalog Dbs, boots the scratch server on 9455
  (OPENROUTER_API_KEY unset), and verifies all ten items on the real page:
  keyboard map + guards + no-scroll, tap flow + Esc chains (deck and list
  paths), contain/blur computed styles, minimal rubric + debug toggle
  round-trip, the 0/25 -> 25/25 counter with undos, dry messaging, fresh
  pill, loud empty2 + nightly-recovery, violet bands, B1 regressions
  (flip clamps, one .topcard, no-lock storm) and the full P3 loop.
- Keyboard: ArrowDown/Backspace now no-op while a sheet is open (arrows
  work on the deck only — spec note); found by the walk.
- get_section: an empty composed section (fully drained catalog)
  recomposes on read once pool_counts shows stock again — the nightly
  import re-lights the deck without a manual forge (item 8 recovery).
2026-11-13 14:04:11 -04:00
Torres
08f945a029 feat(v1.1): item 10 — Second Look band in violet (bold fill + border)
.band.sl re-tinted to the confirmed violet palette (#c4b5fd text,
rgba(124,58,237,.22) fill, rgba(167,139,250,.65) border, weight 800);
wildcard stays amber for contrast. The card band mirrors into the
dossier body (new #dband, static variant of the pill) on return and
wildcard listings; new-slot dossiers show no band. bandHTML/bandLabel
split reuses the same labels on both surfaces.
2026-11-13 13:54:01 -04:00
11 changed files with 1078 additions and 164 deletions

145
README.md
View File

@@ -1,142 +1,19 @@
# Bike-Tinder # Bike-Tinder
A private, Tinder-style web app for browsing the motorcycle market: swipe real listings (like / nope / maybe), see everything on one editable list, and let the deck learn your taste. Built for Glenn; runs on the Rotarran, published to the tailnet only. Find your next motorcycle without sorting through the same classifieds every night. Bike-Tinder is a private, self-hosted web app that puts motorcycle listings from Kijiji in Nova Scotia and New Brunswick into a photo-first swipe deck.
**Status:** Phase 3 (personalization) built on `dev` (2026-11-11): sections of 25 (wildcards + second looks + new), taste engine with match points, tank gauges, dossier "Why this rank", real Trends tab, agent pass (mock / live / fallback). Phase 2 remains shipped as-is; deployment (podman stack) shipped 2026-11-12 — stack live under `podman-stack-bike-tinder.service`, nightly import + agent read + DB backup armed; the private phone URL (`https://biketinder.tailf35a34.ts.net`) awaits the one-time Tailscale sidecar authorization. Swipe right to like a bike, left to pass, or up if you're on the fence. Open a card to check the price, mileage, and photos. The searchable List lets you revisit a bike or change your mind later. As you swipe, the deck learns what you tend to like and brings more of those bikes forward.
**B1 (photo experience v2)** built on `dev`: full photo galleries mirrored locally, deck flips (tap left/right thirds, clamped), segment bars, a fullscreen viewer (swipe nav, pinch/double-tap zoom, pull-down close), and repeat rotation (a re-shown card leads at its next photo). See UI-SPEC §11 + the "B1 develop notes" section below. ## A look at the app
## How it works | Swipe deck | Bike details |
| :---: | :---: |
| ![Bike-Tinder swipe deck with a motorcycle photo and Like, Nope, and Maybe controls](docs/images/swipe-deck.png) | ![Bike details showing the photo, asking price, mileage, and listing information](docs/images/bike-details.png) |
``` *Screenshots from the app with demo listings.*
[single-source crawler] → [nightly importer] → [app DB] → [API + PWA deck] → Glenn's thumb
↓
[swipe history] → [ranking]
```
- **Crawl** — **Kijiji** (NS + NB; decided 2026-11-10 — see `docs/SOURCES.md`) is swept nightly by the existing hunt crawler; a script-only importer folds the results in. No LLM involved, zero token cost. ## Documentation
- **Import** — the importer upserts the source's catalog into the app database: new listings appear, changes update, vanished listings retire after repeated misses (never a blocked page, never a guess).
- **Deck** — a Tinder-like PWA: card stack, drag to swipe, big buttons. Like / Nope / Maybe. "It's a match" moment when you like something.
- **List & edit** — every entry in one table; re-file any call later (a nope can become a like).
- **Ranking** — cold start uses the hunt's rubric score; a cheap, fully explainable swipe-boost lands first (v1.x), then a small learned model (Phase 3, retrained nightly) orders the deck by *your* taste. "Because you liked X" chips, never a black box.
## Docs - [How it works](docs/HOW-IT-WORKS.md) — catalog, swipe history, and ranking
- [Development and deployment](docs/DEVELOPMENT.md) — local setup, tests, and operations
- [`docs/SOURCES.md`](docs/SOURCES.md) — the v1 source decision (candidates, evidence, choice) - [Interface and gestures](docs/UI-SPEC.md) · [Roadmap](docs/PLAN.md)
- [`docs/DESIGN.md`](docs/DESIGN.md) — architecture, components, data flow, deployment
- [`docs/DATA-MODEL.md`](docs/DATA-MODEL.md) — database schema + sync semantics
- [`docs/RANKING.md`](docs/RANKING.md) — cold-start + learned ranking design
- [`docs/UI-SPEC.md`](docs/UI-SPEC.md) — screens, gestures, Tinder-fidelity goals
- [`docs/PLAN.md`](docs/PLAN.md) — phases, acceptance criteria, status
## Branches
- `main` — stable trunk (docs + verified code); the default branch.
- `dev` — active development; build work lands here first.
- `release` — deployable cuts; the Rotarran stack tracks this branch.
## Run & develop
Everything runs from the repo root (Python 3.13+, stdlib where possible).
```sh
# one-time setup
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt # fastapi + uvicorn (+ httpx for tests)
# import the hunt state into the DB (idempotent; safe to re-run any time)
python3 -m app.importer --state-dir ~/.hermes/scripts/motorcycle-hunt.d --db data/bike-tinder.sqlite3
# mirror card images into data/img/ (polite: ~1 req/s, skip-existing, resumable)
.venv/bin/python -m app.imgfetch --db data/bike-tinder.sqlite3
.venv/bin/python -m app.imgfetch --limit 15 # small test runs
# serve the app (127.0.0.1:9453 by default)
.venv/bin/python -m app.serve --db data/bike-tinder.sqlite3 --port 9453
# self-check: P1 + P2 + P3 (25 checks, temp DB copies only)
.venv/bin/python -m app.selfcheck
# P3: agent pass — mock is deterministic + offline (tests, offline forge);
# --live needs OPENROUTER_API_KEY (+ optional BT_AGENT_MODEL); --dry-run
# validates the payload and writes nothing; --print-summary prints exactly
# the strike summary a live pass would be sent.
.venv/bin/python -m app.agentpass --db /tmp/bt-copy.sqlite3 --mock
.venv/bin/python -m app.agentpass --db /tmp/bt-copy.sqlite3 --print-summary --dry-run
# P3: run a scratch server against a COPY (NEVER point a dev server at
# data/bike-tinder.sqlite3 while the live service owns it — use port 9454).
cp data/bike-tinder.sqlite3 /tmp/bt-copy.sqlite3
.venv/bin/python -m app.serve --db /tmp/bt-copy.sqlite3 --img-dir data/img --port 9454
curl -s http://127.0.0.1:9454/api/section # first read composes a section
curl -s -X POST http://127.0.0.1:9454/api/section/forge \
-H 'Content-Type: application/json' -d '{"size": 8}' # mock pass + compose
# proof CLI: ranked deck + counts (read-only)
python3 -m app.deck --db data/bike-tinder.sqlite3 --top 15
```
Key routes: `/` (PWA), `/api/health`, `/api/stats`, `/api/deck?limit=&cursor=` (read-only
legacy fallback), `POST /api/swipe` / `DELETE /api/swipe/{id}`, `/api/list?decision=&sort=&q=&limit=&offset=`,
`/api/listing/{id}`, `POST /api/import`, `POST /api/badge/seen`, `/img/{id}`
(cached file → 302 source CDN → 404 placeholder).
P3 (Phase 3): `GET /api/section`, `POST /api/section/forge` `{size}`,
`GET /api/trends`, `POST /api/agent/run` `{source: mock|live}`,
`POST /api/prefs` `{key: forge_mode, value: ondemand|strict}`. Listing
payloads carry `points`, `tank {value, band}`, `slot`, `round_next`,
`points_breakdown`. Full contract: `docs/UI-SPEC.md` §10 + `docs/RANKING.md`
Stage 2 + the task brief.
`data/` and `.venv/` are gitignored — the DB, image mirror and venv are local state.
## B1 develop notes (photo experience v2)
- **Columns** (guarded in `db.init_db`): `listings.imgs TEXT` (JSON array of
gallery URLs, page order; entry 0 = the primary = `img_url`) ·
`swipes.last_photo_idx INTEGER` (photo on screen at swipe time; drives §11.5
rotation `(last+1) % n`; NULL = photo 0).
- **Importer** copies the hunt state's `imgs[]` into `listings.imgs`; `img_url`
stays the state `img` and falls back to `imgs[0]`. Re-imports are
byte-stable (selfcheck proves it on the 640-row copy).
- **Route:** `GET /img/{id}?i=n` — mirrored file → CDN 302 → 404. `i=0`
(default) keeps the legacy chain (`{id}.webp`, then `{id}_0.webp`, then
`img_url`); `i>0` serves `{id}_{n}.webp` with the CDN fallback from
`imgs[n]`. Out-of-range/unknown → 404.
- **Mirror:** `app/imgfetch.py` downloads every `imgs[n]`. The primary (n=0)
lands at the legacy `data/img/{id}.webp` (one canonical file — no duplicate
fetch); extras land at `data/img/{id}_{n}.webp`. Same politeness as P2
(~1 req/s, skip-existing, `.part`-atomic, per-file CLI progress).
- **Payload:** deck/section/list/listing items add `n_photos` (int) and
`last_photo_idx` (int|null). `POST /api/swipe` accepts optional `photo_idx`
(non-negative int; persisted; absent key preserves, explicit null clears).
- **Frontend:** tap LEFT/RIGHT third = photo flip (clamped, no wrap, commits
nothing), CENTER third = fullscreen viewer (ⓘ still wins); segment bars per
photo (Tinder-style; band chips drop to `top:22px` when segments exist);
viewer = swipe nav + pinch 1×–4× + double-tap 1×↔2.5× + ✕/pull-down close
(returns to the same card/photo); re-shown cards lead at `(last+1) % n`;
preloads the top card's next photo + next card's lead; `sw.js` cache is
`bike-tinder-v3`.
- **FE walk (evidence):** `app/fe_walk_b1.py` — deterministic, headless:
```sh
.venv/bin/python -m app.fe_walk_b1 setup # fixtures: copy DB + 701-706 synthetics + local photos
env -u OPENROUTER_API_KEY .venv/bin/python -m app.serve \
--db /var/home/admin/dev/bike-tinder-b1/test-walk.sqlite3 \
--img-dir /var/home/admin/dev/bike-tinder-b1/test-img \
--host 127.0.0.1 --port 9454 # scratch server (mock forge)
.venv/bin/python -m app.fe_walk_b1 # 390 DOM checks
```
- **Test data:** `b1/test-state/` = hunt-state sample with `imgs` (8/3-photo
galleries; refresh `fetched_at` before an import gate test) ·
`b1/test-img/` = staged `{id}_{n}.webp` photos · `b1/test-copy.sqlite3` =
pristine live-DB snapshot (selfcheck copies it; never write to it).
## Deployment (planned)
A small podman compose stack on the Rotarran under `/var/mnt/DATA/podman-stacks/bike-tinder/`, its own systemd user unit (`Delegate=yes`), SQLite database. The stack ships its own Tailscale node (sidecar container — no host-tailnet coupling) and serves the app privately at `https://biketinder.tailf35a34.ts.net`. Single user; reachable only from Glenn's own devices.
## Crew
- **Glenn** — owner; the thumb that swipes.
- **Alex** — resident agent; architecture, orchestration, docs.
- **Torres** — engineer; builds and maintains this repo.

View File

@@ -501,6 +501,22 @@ def create_app(db_path, img_dir, state_dir=None):
conn, engine, size=25, conn, engine, size=25,
profile_version=prof['version'] if prof else None, profile_version=prof['version'] if prof else None,
note='cold compose (first read)') note='cold compose (first read)')
else:
# item 8: an empty composed section (the catalog was fully
# drained) recomposes on the read once stock exists — the
# nightly-import recovery path. Zero items + zero pool
# keeps serving the empty section (loud empty2).
n_items = conn.execute(
'SELECT COUNT(*) AS n FROM section_items'
' WHERE section_id=?', (sec['id'],)).fetchone()['n']
if n_items == 0 and any(secmod.pool_counts(conn).values()):
prof = secmod.latest_profile(conn)
engine = secmod.build_engine(conn, prof, now=utcnow())
secmod.close_section(conn, sec, utcnow(), status='closed')
sec = secmod.compose_section(
conn, engine, size=25,
profile_version=prof['version'] if prof else None,
note='refill compose (stock returned)')
return section_state(conn, sec) return section_state(conn, sec)
finally: finally:
conn.close() conn.close()

876
app/fe_walk_v11.py Normal file
View File

@@ -0,0 +1,876 @@
"""v1.1 FE walk — headless-chromium proof of every v1.1 item on the real page.
Self-contained: stages its own temp DBs (never the live file), boots the
scratch server on 127.0.0.1:9455 (never 9453), runs the walks, kills the
server. Mock forge only (OPENROUTER_API_KEY is not consulted — the server
is started with the key unset).
cd /var/home/admin/dev/bike-tinder-v11/build
.venv/bin/python -m app.fe_walk_v11 setup # (auto-runs at walk start)
.venv/bin/python -m app.fe_walk_v11 # full walk
Phases:
WALK1 (rich: pristine catalog + synthetic multi-photo fixtures 701-706,
705 a liked return) — items 1, 2, 3, 4, 7, 10, B1 §11 regressions
(flip clamps / one .topcard / no-lock swipe storm), full P3 loop
(compose -> strike all -> report -> forge), item 6 non-dry.
WALK2 (returns-only: every active pre-swiped maybe) — item 5 counter
(0/N -> 1/N -> undo -> sweep -> 25/25 hot -> report counts),
item 6 dry caption + dry forge status.
WALK3 (0/0/0: returns one-shot-burned) — item 8 loud empty2, nightly-
import recovery (a fresh listing re-lights the deck).
"""
import json
import os
import re
import shutil
import sqlite3
import subprocess
import sys
import time
import urllib.request
ARENA = '/var/home/admin/dev/bike-tinder-v11'
REPO = os.path.join(ARENA, 'build')
PRISTINE = os.path.join(ARENA, 'scratch-v11-pristine.sqlite3')
WALK1 = os.path.join(ARENA, 'scratch-v11-walk1.sqlite3')
WALK2 = os.path.join(ARENA, 'scratch-v11-walk2.sqlite3')
WALK3 = os.path.join(ARENA, 'scratch-v11-walk3.sqlite3')
IMG = os.path.join(ARENA, 'img-v11')
MEDIA = os.path.join(ARENA, 'media-sample-v11')
SHOTS = os.path.join(ARENA, 'shots-v11')
BASE_URL = 'http://127.0.0.1:9455'
PORT = 9455
CDN = ('https://media.kijiji.ca/api/v1/ca-prod-dealer-ads/images/x/%s'
'?rule=kijijica-640-webp')
FIX = {
701: (8, 'gallery-8'),
702: (3, 'gallery-3'),
703: (2, 'gallery-2'),
704: (1, 'single-photo'),
705: (8, 'return-rotation'),
706: (0, 'zero-photo'),
}
SCORE_BASE = 2000
server_proc = None
page = None
# --- staging ---------------------------------------------------------------
def stage_img_files():
os.makedirs(IMG, exist_ok=True)
names = sorted(m for m in os.listdir(MEDIA) if m.endswith('.webp'))
assert len(names) == 12, names
k = 0
for lid in sorted(FIX):
n = FIX[lid][0]
if n == 0:
continue
if n == 1:
shutil.copy2(os.path.join(MEDIA, names[k % len(names)]),
os.path.join(IMG, '%d.webp' % lid))
k += 1
continue
for i in range(n):
shutil.copy2(os.path.join(MEDIA, names[k % len(names)]),
os.path.join(IMG, '%d_%d.webp' % (lid, i)))
k += 1
def seeds():
"""Fixture rows + return candidates on a temp copy; returns the maybe-pair."""
from app import db as dbmod
conn = sqlite3.connect(WALK1)
conn.row_factory = sqlite3.Row
try:
dbmod.init_db(conn) # guarded B1/P3 migrations
for lid in sorted(FIX):
n = FIX[lid][0]
imgs = [CDN % ('x%d-%d' % (lid, i)) for i in range(n)]
img = imgs[0] if imgs else None
score = SCORE_BASE + (750 - lid)
conn.execute("DELETE FROM listings WHERE id=?", (lid,))
conn.execute(
"INSERT INTO listings (id, region, src_id, title, url, status,"
" img_url, imgs, score, first_seen, desc) VALUES"
" (?, 'ns', ?, ?, ?, 'active', ?, ?, ?,"
" '2026-11-11T00:00:00Z', ?)",
(lid, 'v11fix%d' % lid, 'V1.1 test %s' % FIX[lid][1],
'https://www.kijiji.ca/v-motorcycles/v11/%d' % lid,
img, json.dumps(imgs) if imgs else None, score,
'V1.1 fixture'))
conn.execute(
"INSERT OR REPLACE INTO swipes (listing_id, action, created_at,"
" last_photo_idx) VALUES (705, 'like', '2026-11-08T00:00:00Z', 0)")
# fresh fixtures: round-1 events keep them OUT of the wildcard pool
for lid in FIX:
conn.execute(
"INSERT INTO swipe_events (listing_id, action, round,"
" section_id) VALUES (?, ?, 1, NULL)",
(lid, 'like' if lid == 705 else 'maybe'))
# second reserved maybe-return: the highest-scored existing swiped
# active swings to maybe so 705 keeps its reserved return slot
x = conn.execute(
"SELECT s.listing_id FROM swipes s"
" JOIN listings l ON l.id = s.listing_id"
" WHERE l.status='active' ORDER BY l.score DESC LIMIT 1"
).fetchone()['listing_id']
conn.execute("UPDATE swipes SET action='maybe' WHERE listing_id=?", (x,))
conn.execute(
"UPDATE swipe_events SET action='maybe' WHERE listing_id=?"
" AND round=1", (x,))
conn.execute("UPDATE sections SET status='closed'"
" WHERE status!='closed'")
conn.commit()
return x
finally:
conn.close()
def setup():
assert os.path.exists(PRISTINE), 'pristine copy missing'
os.makedirs(SHOTS, exist_ok=True)
stage_img_files()
shutil.copy2(PRISTINE, WALK1)
seeds()
shutil.copy2(PRISTINE, WALK2)
conn = sqlite3.connect(WALK2)
try:
conn.execute('DELETE FROM section_items')
conn.execute("UPDATE sections SET status='closed'"
" WHERE status!='closed'")
conn.execute(
"""INSERT INTO swipes (listing_id, action, created_at)
SELECT id, 'maybe', '2026-11-01T00:00:00Z' FROM listings
WHERE status='active'
AND id NOT IN (SELECT listing_id FROM swipes)""")
conn.execute(
"""INSERT INTO swipe_events (listing_id, action, round, section_id)
SELECT id, 'maybe', 1, NULL FROM listings
WHERE status='active'
AND id NOT IN (SELECT listing_id FROM swipe_events)""")
conn.commit()
finally:
conn.close()
print('setup: walk DBs staged (%s, %s)' % (WALK1, WALK2))
# --- server ----------------------------------------------------------------
def start_server(db_path):
global server_proc
env = dict(os.environ)
env.pop('OPENROUTER_API_KEY', None) # mock forge pass only
server_proc = subprocess.Popen(
[os.path.join(REPO, '.venv/bin/python'), '-m', 'app.serve',
'--db', db_path, '--img-dir', IMG, '--host', '127.0.0.1',
'--port', str(PORT), '--state-dir',
os.path.join(ARENA, 'state-v11')],
cwd=REPO, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
for _ in range(60):
try:
with urllib.request.urlopen(BASE_URL + '/api/health',
timeout=2) as r:
if r.status == 200:
return
except Exception:
pass
time.sleep(0.25)
raise RuntimeError('scratch server did not come up')
def stop_server():
global server_proc
if server_proc:
server_proc.terminate()
try:
server_proc.wait(timeout=5)
except subprocess.TimeoutExpired:
server_proc.kill()
server_proc = None
# --- walk helpers ----------------------------------------------------------
CHECKS = [0, 0]
def wait(selector, timeout=10000):
page.wait_for_selector(selector, timeout=timeout)
def ok(msg):
CHECKS[0] += 1
print('ok ' + msg)
def bad(msg):
CHECKS[1] += 1
print('FAIL ' + msg)
page.screenshot(path=os.path.join(SHOTS, 'fail-%s.png' % int(time.time())))
raise SystemExit(1)
def check(cond, msg):
if cond:
ok(msg)
else:
bad(msg)
def top_state():
return page.evaluate("""() => {
const t=document.querySelector('.topcard');
const r={topcards:document.querySelectorAll('.topcard').length,
photo:null, segOn:-1, segs:0, band:null, bandClass:null};
if(!t) return r;
const s=t.querySelector('.segments');
if(s){ r.segs=s.children.length;
[...s.children].forEach((x,k)=>{ if(x.classList.contains('on'))
r.segOn=k; }); }
const p=t.querySelector('.phwrap img.photo');
if(p) r.photo=p.getAttribute('src');
const b=t.querySelector('.band');
if(b){ r.band=b.textContent; r.bandClass=b.className; }
return r; }""")
def top_id():
t = top_state()
if not t['photo']:
return None
m = re.search(r'/img/(\d+)(?:\?i=\d+)?$', t['photo'] or '')
return int(m.group(1)) if m else None
def sect_pill():
return page.evaluate("() => ({txt:document.getElementById('sect').textContent,"
" hot:document.getElementById('sect').classList.contains('hot')})")
def pile_len():
return page.evaluate("() => document.querySelectorAll('.topcard').length +"
" + [...document.querySelectorAll('#stage .card')].filter("
" e=>!e.classList.contains('topcard')).length")
def key(k):
page.keyboard.press(k)
time.sleep(0.08)
def api(path):
with urllib.request.urlopen(BASE_URL + path, timeout=10) as r:
return json.loads(r.read())
def api_post(path, body):
req = urllib.request.Request(BASE_URL + path,
data=json.dumps(body).encode(),
headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(req, timeout=30) as r:
return json.loads(r.read())
def section_body():
return api('/api/section')
def flick(ms=350):
time.sleep(ms / 1000.0)
def tap_center():
b = page.evaluate("""() => { const el=document.querySelector('.topcard');
const r=el.getBoundingClientRect();
return {x:r.x+r.width/2,y:r.y+r.height*0.72}; }""")
page.mouse.click(b['x'], b['y'])
time.sleep(0.08)
def tap_side(side):
b = page.evaluate("""() => { const el=document.querySelector('.topcard');
const r=el.getBoundingClientRect();
return {x:r.x, w:r.width, y:r.y+r.height*0.72}; }""")
x = b['x'] + (0.16 if side == 'left' else 0.84) * b['w']
page.mouse.click(x, b['y'])
time.sleep(0.08)
def taps(clicks, gap=40):
# real commit storm through the like button: the no-lock law must
# survive button-speed swipes
for _ in range(clicks):
page.evaluate("() => document.getElementById('btnLike').click()")
time.sleep(gap / 1000.0)
def dossier_on():
return page.evaluate(
"() => document.getElementById('detail').classList.contains('on')")
def viewer_on():
return page.evaluate(
"() => document.getElementById('viewer').classList.contains('on')")
def dhero_click():
b = page.evaluate("""() => { const el=document.getElementById('dhero')||
document.querySelector('.dhero');
const r=el.getBoundingClientRect();
return {x:r.x+r.width/2,y:r.y+r.height/2}; }""")
page.mouse.click(b['x'], b['y'])
time.sleep(0.15)
# --- WALK1: rich deck ------------------------------------------------------
def walk_rich():
check(page.url.startswith(BASE_URL), 'page served from the app root')
wait('.topcard')
flick(800)
body = section_body()
check(len(body['items']) == 25, 'rich compose serves 25 items')
check(body['recipe']['new'] == 21 and body['recipe']['return'] == 2
and body['recipe']['wildcard'] == 2,
'recipe 21/2/2 on the rich pool (the sign-off shape)')
by_id = {i['id']: i for i in body['items']}
for lid in (701, 702, 703, 704, 706):
check(lid in by_id and by_id[lid]['slot'] == 'new',
'fixture %s sits in the fresh slots' % lid)
check(by_id[705]['slot'] == 'return', '705 composes into a return slot')
t = top_state()
check(t['topcards'] == 1, 'exactly one .topcard on load')
check(top_id() == 701, 'top card is the highest-scored fixture (701)')
# item 3: computed styles on the top card (fit + backdrop)
css = page.evaluate("""() => { const c=document.querySelector('.topcard');
const p=c.querySelector('.phwrap img.photo');
const b=c.querySelector('.phwrap .phblur');
return {fit:getComputedStyle(p).objectFit,
blur:!!b, bg:b?b.style.backgroundImage:null,
src:p.getAttribute('src')}; }""")
check(css['fit'] == 'contain', 'item 3: card photo object-fit == contain')
check(bool(css['blur']) and css['src'] in (css['bg'] or ''),
'item 3: card backdrop exists and mirrors the photo URL')
page.screenshot(path=os.path.join(SHOTS, 'item3-card-fit.png'))
# --- item 5+1: strikes through the real key map ------------------------
check(sect_pill()['txt'] == '0/25', 'fresh rich section starts 0/25')
key('ArrowUp')
check(sect_pill()['txt'] == '1/25', 'ArrowUp (maybe) -> 1/25')
key('ArrowDown')
check(sect_pill()['txt'] == '0/25', 'ArrowDown (undo) -> 0/25')
key('ArrowUp')
check(sect_pill()['txt'] == '1/25', 're-decide -> 1/25')
key('Backspace')
check(sect_pill()['txt'] == '0/25', 'Backspace is the undo alias')
pill_before = sect_pill()['txt']
# scroll prevention spy
page.evaluate("""() => { window.__prev=[]; document.addEventListener(
'keydown',e=>window.__prev.push([e.key,e.defaultPrevented])); }""")
key('ArrowLeft')
key('ArrowRight')
prevented = page.evaluate("""() => window.__prev.filter(
p=>p[0].startsWith('Arrow')).map(p=>p[1])""")
check(all(prevented), 'item 1: arrows defaultPrevented (no page scroll)')
pn = sect_pill()['txt']
check(int(pn.split('/')[0]) == int(pill_before.split('/')[0]) + 2,
'ArrowLeft/ArrowRight commit through the normal path (%s -> %s)'
% (pill_before, pn))
# --- item 1: text-input guard (list search) ---------------------------
page.evaluate("() => document.querySelector('.tab[data-tab=list]').click()")
wait('#lsearch')
page.evaluate("""() => { const s=document.getElementById('lsearch');
s.focus(); }""")
page.keyboard.type('abc')
before_search = page.evaluate(
"() => document.getElementById('lsearch').value")
check(before_search == 'abc', 'search input accepts typing (focus guard on)')
for kk in ('ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'):
page.keyboard.press(kk)
flick(60)
check(page.evaluate(
"() => document.getElementById('lsearch').value") == 'abc',
'arrows inside the search input never swipe (text + value unchanged)')
check(sect_pill()['txt'] == pn,
'input-focused arrows leave the section counter untouched')
page.keyboard.press('Backspace')
check(page.evaluate(
"() => document.getElementById('lsearch').value") == 'ab',
'Backspace edits text while an input owns focus (no undo fired)')
page.evaluate("() => document.querySelector('.tab[data-tab=deck]').click()")
flick(300)
# --- item 2: center tap -> dossier -> hero -> viewer; Esc/Es ----------
tid_before = top_id()
src_before = top_state()['photo']
pill_pre_tap = sect_pill()['txt']
tap_center()
check(sect_pill()['txt'] == pill_pre_tap,
'item 2: center tap commits nothing')
check(dossier_on(), 'item 2: center tap opens the dossier')
check(not viewer_on(), 'item 2: no viewer on center tap')
check(bool(page.evaluate(
"() => document.getElementById('dtitle').textContent")),
'dossier carries the card title')
dhero_click()
check(viewer_on(), 'dossier hero tap opens the viewer (photo 0)')
vidx = page.evaluate("""() => { const im=document.getElementById('vimg');
return {src:im.getAttribute('src'),
fot:getComputedStyle(im).objectFit}; }""")
check(vidx['fot'] == 'contain', 'item 3: viewer vimg stays contain (no diff)')
page.screenshot(path=os.path.join(SHOTS, 'item3-viewer.png'))
# arrows are inert while the viewer is open
pill_now = sect_pill()['txt']
for kk in ('ArrowLeft', 'ArrowRight', 'ArrowUp'):
page.keyboard.press(kk)
check(sect_pill()['txt'] == pill_now,
'arrows are inert while the viewer is open')
key('Escape')
check(not viewer_on() and dossier_on(),
'Esc closes the viewer only (dossier stays open)')
key('Escape')
check(not dossier_on() and not viewer_on(),
'second Esc closes the dossier to the deck')
check(top_id() == tid_before and top_state()['photo'] == src_before,
'walk-back leaves the same card on the same photo')
# item 2 A5: list row -> dossier -> viewer -> Esc -> dossier -> Esc -> list
page.evaluate("() => document.querySelector('.tab[data-tab=list]').click()")
wait('#lrows .row')
flick(400)
thumb_fit = page.evaluate("""() => { const t=document.querySelector(
'.thumb'); return t?getComputedStyle(t).objectFit:null; }""")
check(thumb_fit == 'cover', 'item 3: list thumbs stay cover (no diff)')
page.evaluate("""() => document.querySelector('#lrows .row').click()""")
flick(400)
check(dossier_on(), 'list row tap opens the dossier')
dhero_click()
check(viewer_on(), 'list dossier hero opens the viewer')
key('Escape')
check(not viewer_on() and dossier_on(), 'Esc: viewer -> dossier (list)')
key('Escape')
check(not dossier_on()
and page.evaluate("() => document.getElementById('listScreen')"
".classList.contains('on')"),
'second Esc returns to the list screen')
page.evaluate("() => document.querySelector('.tab[data-tab=deck]').click()")
flick(300)
# arrows inert while the dossier is open
tap_center()
check(dossier_on(), 'dossier open for the key-inertness check')
before_pill = sect_pill()['txt']
for kk in ('ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'):
page.keyboard.press(kk)
flick(40)
check(sect_pill()['txt'] == before_pill,
'arrow keys are inert while the dossier is open')
# item 10+4: dossier band + minimal rubric on the fresh card
db = page.evaluate("""() => { const b=document.getElementById('dband');
if(b.style.display==='none') return {off:true};
return {off:false, cls:b.className}; }""")
check(bool(db.get('off')), 'dossier on a fresh card shows no band')
drank = page.evaluate("""() => { const d=document.getElementById('drank');
return {shown:d.style.display!=='none',
pts:document.getElementById('dpts').textContent,
lines:document.getElementById('dlines').innerHTML,
foot:document.getElementById('dfoot').textContent}; }""")
check(re.search(r'^\d+%$', drank['pts']),
'item 4: rank block shows gauge + NN%% (%s)' % drank['pts'])
check(not drank['lines'] and not drank['foot'],
'item 4: breakdown lines + footer hidden with rubric_debug off')
dc = page.evaluate("""() => { const p=document.getElementById('dphoto');
const b=document.getElementById('dblur');
return {fit:getComputedStyle(p).objectFit,
bg:b.style.backgroundImage}; }""")
check(dc['fit'] == 'contain' and bool(dc['bg']),
'item 3: dossier hero fits contain over its backdrop')
page.screenshot(path=os.path.join(SHOTS, 'item3-dossier.png'))
key('Escape')
# item 2: side taps still flip (clamped), never open a sheet
before_photo = top_state()['photo']
tap_side('left')
check(top_state()['photo'] == before_photo, 'left tap clamps at photo 0')
check(not dossier_on() and not viewer_on(),
'side taps never open sheets (B1 §11.2 regression)')
tap_side('right')
check(top_state()['photo'] != before_photo, 'right tap flips forward')
# --- item 4: rubric_debug on -> breakdown appears ----------------------
api_post('/api/prefs', {'key': 'rubric_debug', 'value': 'on'})
page.reload(wait_until='networkidle')
wait('.topcard')
flick(400)
tap_center()
check(dossier_on(), 'dossier open for the debug-mode check')
drank = page.evaluate("""() => { const d=document.getElementById('drank');
if(d.style.display==='none') return {shown:false};
return {shown:true,
lines:document.getElementById('dlines').textContent,
foot:document.getElementById('dfoot').textContent}; }""")
check(bool(drank['shown']) and bool(drank['lines']),
'item 4: rubric_debug on -> breakdown lines render')
page.screenshot(path=os.path.join(SHOTS, 'item4-debug-on.png'))
key('Escape')
page.evaluate("() => document.querySelector('.tab[data-tab=trends]').click()")
flick(300)
page.evaluate("() => document.getElementById('tRubOff').click()")
flick(400)
check(api('/api/section').get('prefs', {}).get('rubric_debug') == 'off',
'Trends toggle wrote rubric_debug=off to the server')
heck = page.evaluate("""() => document.getElementById(
'tRubOff').classList.contains('on')""")
check(bool(heck), 'toggle UI paints the off state')
page.evaluate("() => document.querySelector('.tab[data-tab=deck]').click()")
flick(300)
# --- item 7: header pill
stats = api('/api/stats')
pill_txt = page.evaluate(
"() => document.getElementById('pill').textContent")
check(('%d live' % stats['live']) in pill_txt
and ('%d fresh' % stats['fresh']) in pill_txt,
'item 7: pill reads live + fresh (%s)' % pill_txt.replace('\n', ' '))
# --- v1.1.1 (issue #2): the header pill keeps itself live --------------
pl0 = api('/api/stats')
key('ArrowRight') # probe swipe, undone right after
flick(300)
pl1 = api('/api/stats')
dl = time.time() + 5
ptx = ''
while time.time() < dl:
ptx = page.evaluate("() => document.getElementById('pill').textContent")
if ('%d fresh' % pl1['fresh']) in ptx:
break
time.sleep(0.2)
check(('%d fresh' % pl1['fresh']) in ptx and ('%d live' % pl1['live']) in ptx,
'issue #2: pill refreshes itself after a swipe, no reload (%s -> %s)'
% (pl0['fresh'], ptx))
key('ArrowDown') # undo the probe swipe (net-zero)
flick(300)
pl2 = api('/api/stats')
dl = time.time() + 5
while time.time() < dl:
ptx = page.evaluate("() => document.getElementById('pill').textContent")
if ('%d fresh' % pl2['fresh']) in ptx:
break
time.sleep(0.2)
check(('%d fresh' % pl2['fresh']) in ptx,
'issue #2: pill refreshes itself after an undo, no reload (%s)' % ptx)
# --- B1 no-lock: rapid commit storm (no sheet, no lock) ----------------
before = sect_pill()['txt']
taps(2, 40)
flick(500)
t = top_state()
check(t['topcards'] == 1, 'no-lock storm keeps exactly one .topcard')
after = sect_pill()['txt']
check(int(after.split('/')[0]) - int(before.split('/')[0]) == 2,
'both storm swipes landed (%s -> %s)' % (before, after))
# --- item 10 + P3 loop: sweep to the return band and exhaust ------------
bands = {}
for _ in range(30):
tid = top_id()
if tid is not None and tid in by_id:
slot = by_id[tid]['slot']
if slot in ('return', 'wildcard') and slot not in bands:
bands[slot] = page.evaluate("""() => { const b=document.querySelector(
'.topcard .band'); if(!b) return null;
const s=getComputedStyle(b);
return {cls:b.className, color:s.color, bg:s.backgroundColor,
text:b.textContent}; }""")
if not page.evaluate("() => document.querySelector('.topcard')"):
break
key('ArrowRight')
flick(80)
check(bool(bands.get('return')),
'item 10: a SECOND LOOK card topped and carried its band')
if bands.get('return'):
check(bands['return']['color'] == 'rgb(196, 181, 253)',
'item 10: SL band text is the violet tint')
check(bands['return']['bg'] == 'rgba(124, 58, 237, 0.22)',
'item 10: SL band fill is violet 22%')
check('SECOND LOOK' in bands['return']['text'],
'item 10: SL band label intact')
page.screenshot(path=os.path.join(SHOTS, 'item10-card-band.png'))
if bands.get('wildcard'):
check('wild' in bands['wildcard']['cls'],
'item 10: wildcard band keeps its amber variant')
# dossier band on a return item: drive the real openDetail path
ret_item = next((i for i in body['items'] if i['slot'] == 'return'), None)
db = page.evaluate("""(item) => { openDetail(item, {type:'deck'});
const b=document.getElementById('dband');
const s=getComputedStyle(b);
return {off:b.style.display==='none', color:s.color,
bg:s.backgroundColor, text:b.textContent}; }""", ret_item)
check(not db['off'] and db['color'] == 'rgb(196, 181, 253)'
and 'SECOND LOOK' in db['text'],
'item 10: dossier mirrors the violet SECOND LOOK band')
key('Escape')
# finish the section -> report -> forge
for _ in range(10):
if not page.evaluate("() => document.querySelector('.topcard')"):
break
key('ArrowRight')
flick(80)
wait('#report.on, #empty2.on', timeout=10000)
rep = page.evaluate("""() => ({report:document.getElementById('report')
.classList.contains('on'),
dry:document.getElementById('dryCap').style.display!=='none',
counts:document.getElementById('repCounts').textContent,
empty2:document.getElementById('empty2').classList.contains('on')})""")
check(bool(rep['report']), 'P3 loop: report card owns the exhausted deck')
check(not rep['dry'], 'item 6: rich batch shows no dry caption')
check(not rep['empty2'], 'item 8: empty2 stays hidden while stock remains')
check(sect_pill()['hot'], 'pill is hot at the section end')
page.screenshot(path=os.path.join(SHOTS, 'p3-report.png'))
sec_before = section_body()['section']['id']
page.evaluate("() => document.getElementById('btnForge').click()")
wait('.topcard', timeout=20000)
check(section_body()['section']['id'] != sec_before,
'forge opened a brand-new section')
pill = sect_pill()
check(re.search(r'^\d+/25$', pill['txt']),
'new section pill starts at a plain N/25 (%s)' % pill['txt'])
check(not dossier_on() and not viewer_on(), 'forge leaves no sheets open')
print('rich walk complete')
# --- WALK2: returns-only (counter fix + dry messaging) ---------------------
def walk_returns_only():
wait('.topcard')
flick(800)
body = section_body()
check(len(body['items']) == 25 and body['recipe']['new'] == 0,
'returns-only catalog composes 25 second looks (recipe %s)'
% json.dumps(body['recipe']))
check(body['progress']['decided'] == 0
and body['progress']['total'] == 25,
'item 5: fresh batch reads 0/25 (old code painted 25/25)')
pill = sect_pill()
check(pill['txt'] == '0/25' and not pill['hot'],
'pill shows 0/25, no premature hot state')
# one real strike -> 1/25 (in-section event, not lifetime verdict)
key('ArrowRight')
pill = sect_pill()
check(pill['txt'] == '1/25', 'first strike -> 1/25 (%s)' % pill['txt'])
check(section_body()['progress']['decided'] == 1,
'server truth agrees: one in-section decision')
key('ArrowUp')
check(sect_pill()['txt'] == '2/25', 'ArrowUp maybe -> 2/25')
key('ArrowDown')
check(sect_pill()['txt'] == '1/25', 'ArrowDown undo -> 1/25')
key('Backspace')
check(sect_pill()['txt'] == '0/25', 'Backspace undo -> 0/25')
# mixed actions -> report counts proven in-section only
key('ArrowLeft')
key('ArrowUp')
key('ArrowRight')
check(sect_pill()['txt'] == '3/25', 'three strikes -> 3/25 (clamped)')
# sweep to exhaustion
for _ in range(30):
if not page.evaluate("() => document.querySelector('.topcard')"):
break
key('ArrowRight')
flick(60)
wait('#report.on', timeout=10000)
pill = sect_pill()
check(pill['txt'] == '25/25' and pill['hot'],
'pill clamps at 25/25 and goes hot (never 26/25)')
counts = api('/api/section')['counts']
check(counts['likes'] + counts['maybes'] + counts['nopes'] == 25,
'report counts the 25 in-section verdicts (not lifetime)')
rep = page.evaluate("""() => ({dry:document.getElementById('dryCap')
.style.display!=='none',
status:document.getElementById('forgeStatus').textContent})""")
check(bool(rep['dry']), 'item 6: dry caption shows on the 0-fresh report')
# dry forge -> the sentence + a fresh 0/25 returns-only deck
page.evaluate("() => document.getElementById('btnForge').click()")
for _ in range(40):
st = page.evaluate(
"() => document.getElementById('forgeStatus').textContent")
if 'Catalog fully reviewed' in st:
break
flick(250)
st = page.evaluate(
"() => document.getElementById('forgeStatus').textContent")
check('Catalog fully reviewed — fresh listings arrive with the next'
' 08:30 import; showing second looks' in st,
'item 6: dry forge status shows the exact BACKLOG sentence')
wait('.topcard', timeout=15000)
body = section_body()
check(body['recipe']['new'] == 0 and body['progress']['decided'] == 0,
'dry forge decks another 25 second looks at 0/25')
print('returns-only walk complete')
# --- WALK3: dead catalog (loud empty2) -------------------------------------
def burn_returns(db_path):
conn = sqlite3.connect(db_path)
try:
conn.execute('DELETE FROM section_items')
conn.execute("UPDATE sections SET status='closed'"
" WHERE status!='closed'")
conn.execute(
"""INSERT INTO section_items (section_id, listing_id, slot,
position)
SELECT (SELECT id FROM sections ORDER BY id DESC LIMIT 1),
listing_id, 'return', 1 FROM swipes
WHERE listing_id IN (SELECT id FROM listings
WHERE status='active')""")
conn.commit()
finally:
conn.close()
def walk_dead_catalog():
body = section_body()
check(body['pool'] == {'fresh': 0, 'returns': 0, 'wildcards': 0},
'item 8: drained catalog reports pool 0/0/0')
check(body['items'] == [], 'compose emits zero items on a dead pool')
wait('#empty2.on', timeout=10000)
st = page.evaluate("""() => { const e=document.getElementById('empty2');
return {on:e.classList.contains('on'),
txt:e.textContent,
report:document.getElementById('report').classList.contains('on')}; }""")
check(bool(st['on']), 'item 8: loud empty2 owns the stage')
check('No more new bikes!' in st['txt'] and '08:30' in st['txt'],
'item 8: exact title + next-import line')
check(not st['report'], 'item 8: report card masked on the dead catalog')
page.screenshot(path=os.path.join(SHOTS, 'item8-empty2.png'))
# forge on the dead catalog: still empty2, no wasted Forge invitation
page.evaluate("() => document.getElementById('btnForge').click()")
flick(1500)
st = page.evaluate("""() => { const e=document.getElementById('empty2');
return {on:e.classList.contains('on'),
report:document.getElementById('report').classList.contains('on')}; }""")
check(bool(st['on']) and not st['report'],
'forge on 0/0/0 leaves empty2 (report never re-invites)')
# nightly import simulated: a brand-new listing re-lights the deck
stop_server()
conn = sqlite3.connect(WALK3)
try:
lid = 990
conn.execute("DELETE FROM listings WHERE id=?", (lid,))
conn.execute(
"INSERT INTO listings (id, region, src_id, title, url, status,"
" img_url, score, first_seen, desc) VALUES"
" (?, 'ns', 'v11night', 'Fresh overnight listing',"
" 'https://www.kijiji.ca/v-motorcycles/v11/990', 'active',"
" NULL, 50, '2026-11-13T08:30:00Z', 'arrived with the import')",
(lid,))
conn.commit()
finally:
conn.close()
start_server(WALK3)
page.reload(wait_until='networkidle')
wait('.topcard', timeout=15000)
st = page.evaluate("""() => ({empty2:document.getElementById('empty2')
.classList.contains('on'), top:!!document.querySelector('.topcard')})""")
check(bool(st['top']) and not st['empty2'],
'item 8: one fresh listing clears empty2 and relights the deck')
print('dead-catalog walk complete')
# --- WALK0: hand the rich DB a quick dry run through items 1 acceptance ---
def main():
global page
setup() # always: fresh staged DBs per run
# clear any stray scratch server left by an aborted run
import signal
for line in subprocess.run(
['ps', '-eo', 'pid,args'], capture_output=True,
text=True).stdout.splitlines():
if 'app.serve' in line and str(PORT) in line:
try:
os.kill(int(line.split()[0]), signal.SIGTERM)
except (ValueError, ProcessLookupError):
pass
time.sleep(0.5)
try:
from playwright.sync_api import sync_playwright
except ImportError:
print('playwright missing — run: .venv/bin/python -m app.fe_walk_v11')
return 1
with sync_playwright() as pw:
exe = os.path.expanduser(
'~/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome')
if not os.path.exists(exe):
exe = None
# phase 1: rich
start_server(WALK1)
try:
browser = pw.chromium.launch(headless=True, executable_path=exe,
args=['--no-sandbox'])
ctx = browser.new_context(viewport={'width': 390, 'height': 844},
has_touch=True, is_mobile=True)
page = ctx.new_page()
page.goto(BASE_URL + '/', wait_until='networkidle')
walk_rich()
ctx.close()
finally:
stop_server()
# phase 2: returns-only (uses WALK2 fresh from setup)
start_server(WALK2)
try:
browser = pw.chromium.launch(headless=True, executable_path=exe,
args=['--no-sandbox'])
ctx = browser.new_context(viewport={'width': 390, 'height': 844},
has_touch=True, is_mobile=True)
page = ctx.new_page()
page.goto(BASE_URL + '/', wait_until='networkidle')
walk_returns_only()
ctx.close()
finally:
stop_server()
# phase 3: dead catalog
shutil.copy2(WALK2, WALK3)
burn_returns(WALK3)
start_server(WALK3)
try:
browser = pw.chromium.launch(headless=True, executable_path=exe,
args=['--no-sandbox'])
ctx = browser.new_context(viewport={'width': 390, 'height': 844},
has_touch=True, is_mobile=True)
page = ctx.new_page()
page.goto(BASE_URL + '/', wait_until='networkidle')
walk_dead_catalog()
ctx.close()
finally:
stop_server()
print('---')
print('%d/%d walk checks passed' % (CHECKS[0], CHECKS[0] + CHECKS[1]))
return 1 if CHECKS[1] else 0
if __name__ == '__main__':
sys.exit(main())

View File

@@ -934,6 +934,10 @@ def test_p3_points_and_band():
br = eng.breakdown(1) br = eng.breakdown(1)
assert {b['source'] for b in br} <= {'rubric', 'taste', 'agent'} assert {b['source'] for b in br} <= {'rubric', 'taste', 'agent'}
assert br[0]['source'] == 'rubric' assert br[0]['source'] == 'rubric'
# regression (#3): a listing OUTSIDE the engine's pool (delisted
# mid-batch, never swiped) must degrade quietly, not crash the render
assert eng.points(9999) is None
assert eng.breakdown(9999) == []
def test_p3_payload_additions(): def test_p3_payload_additions():
@@ -959,6 +963,39 @@ def test_p3_payload_additions():
shutil.rmtree(d, ignore_errors=True) shutil.rmtree(d, ignore_errors=True)
def test_issue3_section_survives_midsection_delist():
"""#3 regression: one card delisted after compose must not 500 the deck.
The section render asks the taste engine for a breakdown of every
card. A listing that left the active pool mid-batch AND has no swipe
history is not in the engine's by_id map; the unguarded lookup used
to raise, killing GET /api/section and GET /api/listing/{id} with a
500 (live incident 2026-11-15: section 57 + delisted listing 298).
"""
d, c, db_path = p3_env()
try:
sec = c.get('/api/section')
assert sec.status_code == 200, sec.status_code
body = sec.json()
conn = _sq_conn(db_path)
ev_ids = {r['listing_id'] for r in conn.execute(
'SELECT DISTINCT listing_id FROM swipe_events')}
it = next((x for x in body['items'] if x['id'] not in ev_ids), None)
assert it is not None, 'fixture section has no unswiped card'
conn.execute("UPDATE listings SET status='gone' WHERE id=?",
(it['id'],))
conn.commit()
conn.close()
r = c.get('/api/section')
assert r.status_code == 200, r.status_code
assert it['id'] in [x['id'] for x in r.json()['items']]
one = c.get('/api/listing/%d' % it['id'])
assert one.status_code == 200, one.status_code
assert one.json()['points_breakdown'] == []
finally:
shutil.rmtree(d, ignore_errors=True)
# --- B1 checks (photo experience v2, UI-SPEC §11 / DATA-MODEL B1) ----------- # --- B1 checks (photo experience v2, UI-SPEC §11 / DATA-MODEL B1) -----------
def make_b1_item(title, imgs=None, img=None, price='$5,000', km='8000'): def make_b1_item(title, imgs=None, img=None, price='$5,000', km='8000'):
@@ -1751,6 +1788,8 @@ P3_API_TESTS = [
('p3: agentpass mock determinism + live fallback', test_p3_agentpass_mock_and_fallback), ('p3: agentpass mock determinism + live fallback', test_p3_agentpass_mock_and_fallback),
('p3: points/band function known answers', test_p3_points_and_band), ('p3: points/band function known answers', test_p3_points_and_band),
('p3: payload additions (list/listing/section)', test_p3_payload_additions), ('p3: payload additions (list/listing/section)', test_p3_payload_additions),
('p3: mid-section delist keeps the deck up (#3)',
test_issue3_section_survives_midsection_delist),
] ]

View File

@@ -144,7 +144,8 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
.sect.hot{color:var(--accent1)} .sect.hot{color:var(--accent1)}
.band{position:absolute;top:12px;left:12px;z-index:4;max-width:78%;font-size:11px;font-weight:650;letter-spacing:.4px;border-radius:999px;padding:4px 9px;pointer-events:none;line-height:1.35;user-select:none} .band{position:absolute;top:12px;left:12px;z-index:4;max-width:78%;font-size:11px;font-weight:650;letter-spacing:.4px;border-radius:999px;padding:4px 9px;pointer-events:none;line-height:1.35;user-select:none}
.band.wild{color:#ffb43a;background:rgba(255,180,58,.14);border:1px solid rgba(255,180,58,.35)} .band.wild{color:#ffb43a;background:rgba(255,180,58,.14);border:1px solid rgba(255,180,58,.35)}
.band.sl{color:rgba(255,255,255,.85);background:rgba(255,255,255,.10);border:1px solid rgba(255,255,255,.22)} .band.sl{color:#c4b5fd;background:rgba(124,58,237,.22);border:1px solid rgba(167,139,250,.65);font-weight:800}
.dband{position:static;display:inline-block;margin-top:6px}
.report{position:absolute;inset:6px 14px 2px;display:none;flex-direction:column;align-items:center;justify-content:center;gap:8px;border:1px dashed #2a2a33;border-radius:18px;color:var(--mut);text-align:center;padding:24px;font-size:13.5px;z-index:3} .report{position:absolute;inset:6px 14px 2px;display:none;flex-direction:column;align-items:center;justify-content:center;gap:8px;border:1px dashed #2a2a33;border-radius:18px;color:var(--mut);text-align:center;padding:24px;font-size:13.5px;z-index:3}
.report.on{display:flex} .report.on{display:flex}
.report b{color:#fff;font-size:16px} .report b{color:#fff;font-size:16px}
@@ -255,6 +256,7 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
<div class="dtitle" id="dtitle"></div> <div class="dtitle" id="dtitle"></div>
<div class="drow"><div class="dprice" id="dprice"></div><div class="dsub" id="dsub"></div></div> <div class="drow"><div class="dprice" id="dprice"></div><div class="dsub" id="dsub"></div></div>
<div class="dchips" id="dchips"></div> <div class="dchips" id="dchips"></div>
<div class="band dband" id="dband" style="display:none"></div>
<div class="drank" id="drank" style="display:none"> <div class="drank" id="drank" style="display:none">
<div class="tankwrap" id="drankTank"></div> <div class="tankwrap" id="drankTank"></div>
<div style="flex:1;min-width:0"> <div style="flex:1;min-width:0">
@@ -413,6 +415,7 @@ function setDecision(id, act, secId=null, photoIdx=null){
localDecisions.set(id, act); localDecisions.set(id, act);
updateRowDecision(id, act); // optimistic paint updateRowDecision(id, act); // optimistic paint
enqueue(id, act, secId, photoIdx); enqueue(id, act, secId, photoIdx);
refreshStats(); // v1.1.1 (#2): every decision change nudges the header counters
} }
/* ---------- payload -> display helpers ---------- */ /* ---------- payload -> display helpers ---------- */
@@ -488,14 +491,19 @@ function setStamps(el,a,b,c){
el.querySelector('.stamp.nope').style.opacity=b; el.querySelector('.stamp.nope').style.opacity=b;
el.querySelector('.stamp.maybe').style.opacity=c; el.querySelector('.stamp.maybe').style.opacity=c;
} }
function bandHTML(item){ // P3 system bands — the ONLY card-face additions function bandLabel(item){ // P3 system bands — text for card + dossier
if(item.slot==='wildcard') return `<div class="band wild">WILDCARD · maybe you&rsquo;ll like this one instead</div>`; if(item.slot==='wildcard') return 'WILDCARD · maybe you’ll like this one instead';
if(item.slot==='return'){ if(item.slot==='return'){
const verb= item.decision==='like'?'liked':item.decision==='maybe'?'maybed':item.decision==='nope'?'noped':'seen'; const verb= item.decision==='like'?'liked':item.decision==='maybe'?'maybed':item.decision==='nope'?'noped':'seen';
return `<div class="band sl">SECOND LOOK — you ${verb} this</div>`; return 'SECOND LOOK — you '+verb+' this';
} }
return ''; return '';
} }
function bandHTML(item){ // card face only
const lbl=bandLabel(item);
if(!lbl) return '';
return `<div class="band${item.slot==='wildcard'?' wild':' sl'}">${lbl}</div>`;
}
/* ---------- B1 §11: photo galleries ---------- */ /* ---------- B1 §11: photo galleries ---------- */
function nPhotos(it){ // payload n_photos; tolerant of old APIs function nPhotos(it){ // payload n_photos; tolerant of old APIs
const n= it&&typeof it.n_photos==='number'?it.n_photos:(it&&it.img?1:0); const n= it&&typeof it.n_photos==='number'?it.n_photos:(it&&it.img?1:0);
@@ -653,6 +661,7 @@ async function loadSection(){
buffer.push(...fresh); buffer.push(...fresh);
fillPile(); fillPile();
updateSectionUI(body); updateSectionUI(body);
refreshStats(); // v1.1.1 (#2): a new batch landed — freshen the counters
}catch(e){ setTimeout(()=>loadSection(),15000); } }catch(e){ setTimeout(()=>loadSection(),15000); }
finally{ deckLoading=false; } finally{ deckLoading=false; }
maybeRefill(); maybeRefill();
@@ -809,6 +818,14 @@ function openDetail(data,ctx){
$('dprice').textContent=priceFor(data); $('dprice').textContent=priceFor(data);
$('dsub').textContent=subFor(data); $('dsub').textContent=subFor(data);
$('dchips').innerHTML=cardChips(data).map(x=>`<span class="chip">${x}</span>`).join(''); $('dchips').innerHTML=cardChips(data).map(x=>`<span class="chip">${x}</span>`).join('');
// item 10: the card band mirrors into the info view (violet SL / amber wild)
const db=$('dband');
const bl=bandLabel(data);
if(bl){
db.className='band'+(data.slot==='wildcard'?' wild':' sl')+' dband';
db.textContent=bl;
db.style.display='inline-block';
}else{ db.style.display='none'; }
const rows=[ const rows=[
["Year",data.year!=null?String(data.year):null], ["Year",data.year!=null?String(data.year):null],
["Odometer",data.km!=null?(fmtNum(data.km)+' km'):null], ["Odometer",data.km!=null?(fmtNum(data.km)+' km'):null],
@@ -864,19 +881,20 @@ function closeDetail(){ const d=$('detail'); d.style.transition=''; d.style.tran
$('dclose').onclick=closeDetail; $('dclose').onclick=closeDetail;
$('dclose').addEventListener('pointerdown',e=>e.stopPropagation()); $('dclose').addEventListener('pointerdown',e=>e.stopPropagation());
/* pull-down-to-close (grabber bar + photo) */ /* pull-down-to-close (grabber bar + photo) */
let dDragY=null; let dDragY=null, heroTapped=false;
function dStart(e){ dDragY=e.clientY; $('detail').style.transition='none'; try{e.currentTarget.setPointerCapture(e.pointerId)}catch(_){} } function dStart(e){ heroTapped=false; dDragY=e.clientY; $('detail').style.transition='none'; try{e.currentTarget.setPointerCapture(e.pointerId)}catch(_){} }
function dMoveH(e){ if(dDragY===null) return; const dy=Math.max(0,e.clientY-dDragY); $('detail').style.transform=`translateY(${dy}px)`; } function dMoveH(e){ if(dDragY===null) return; const dy=Math.max(0,e.clientY-dDragY); $('detail').style.transform=`translateY(${dy}px)`; }
function dEndH(e){ if(dDragY===null) return; const dy=Math.max(0,e.clientY-dDragY); dDragY=null; function dEndH(e){ if(dDragY===null) return; const dy=Math.max(0,e.clientY-dDragY); dDragY=null;
if(dy>110){ closeDetail(); } if(dy>110){ closeDetail(); }
else { const d=$('detail'); d.style.transition='transform .25s cubic-bezier(.2,.8,.3,1)'; d.style.transform=''; else { const d=$('detail'); d.style.transition='transform .25s cubic-bezier(.2,.8,.3,1)'; d.style.transform='';
/* B1 §11.3: a tap on the dossier HERO opens the fullscreen viewer at heroTapped=e.type==='pointerup' && dy<=6 && e.currentTarget.classList.contains('dhero');
photo 0. When the dossier sits over the deck, the viewer back-chain } }
walks Esc back to the dossier (item 2), then to the deck. */ /* Open on the completed click. Opening on touch pointerup puts the new
if(e.type==='pointerup' && dy<=6 && e.currentTarget&&e.currentTarget.classList backdrop under the finger just in time to receive the same tap's click. */
&& e.currentTarget.classList.contains('dhero') && dData&&dData.img){ document.querySelector('.dhero').addEventListener('click',()=>{
openViewer(dData,0,{type:'dossier', backToDetail:dEntry}); if(heroTapped && dData && dData.img) openViewer(dData,0,{type:'dossier', backToDetail:dEntry});
} } } heroTapped=false;
});
[document.querySelector('.dgrab'),document.querySelector('.dhero')].forEach(el=>{ if(!el) return; el.addEventListener('pointerdown',dStart); el.addEventListener('pointermove',dMoveH); el.addEventListener('pointerup',dEndH); el.addEventListener('pointercancel',dEndH); }); [document.querySelector('.dgrab'),document.querySelector('.dhero')].forEach(el=>{ if(!el) return; el.addEventListener('pointerdown',dStart); el.addEventListener('pointermove',dMoveH); el.addEventListener('pointerup',dEndH); el.addEventListener('pointercancel',dEndH); });
function dAction(a){ function dAction(a){
const ctx=dCtx; closeDetail(); const ctx=dCtx; closeDetail();
@@ -1067,10 +1085,14 @@ function renderList(){
} }
/* optimistic decision updates for whichever screens show this listing */ /* optimistic decision updates for whichever screens show this listing */
function updateRowDecision(id, act){ function updateRowDecision(id, act){
const find=[listItems]; const it=listItems.find(x=>x.id===id);
for(const arr of find){ if(it){
const it=arr.find(x=>x.id===id); it.decision=act;
if(it) it.decision=act; if(listCtl.decision!=='all' && listCtl.decision!==(act||'undecided')){
listItems=listItems.filter(x=>x!==it);
$('lrows').querySelector(`.row[data-i="${id}"]`)?.remove();
if(!listItems.length) renderList(); // existing empty state
}
} }
const el=$('lrows').querySelector(`.rc[data-i="${id}"]`); const el=$('lrows').querySelector(`.rc[data-i="${id}"]`);
if(el) el.querySelectorAll('.rbtn').forEach(b=>b.classList.toggle('on',b.dataset.s===act)); if(el) el.querySelectorAll('.rbtn').forEach(b=>b.classList.toggle('on',b.dataset.s===act));
@@ -1097,7 +1119,6 @@ $('lrows').addEventListener('click',e=>{
if(!it) return; if(!it) return;
const next= it.decision===s?null:s; // tapping the lit button clears const next= it.decision===s?null:s; // tapping the lit button clears
setDecision(id,next); setDecision(id,next);
if(next===null && (listCtl.decision===s)) renderList(); // row leaves a filtered view
}); });
$('fdec').addEventListener('click',e=>{ $('fdec').addEventListener('click',e=>{
const chip=e.target.closest('.fchip'); if(!chip) return; const chip=e.target.closest('.fchip'); if(!chip) return;
@@ -1191,6 +1212,19 @@ async function loadStats(){
fetch('/api/badge/seen',{method:'POST'}).catch(()=>{}); fetch('/api/badge/seen',{method:'POST'}).catch(()=>{});
} }
} }
/* v1.1.1 (issue #2): loadStats only ran at boot, so the header pill and the
list sub-line went stale after every swipe until a full reload. Refresh
shortly after any decision change (swipes, undo, dossier/list/matches
edits) and whenever a new batch lands. Coalesced + fire-and-forget: a
swipe never waits on it. */
let statsTimer=null;
function refreshStats(){
if(statsTimer) return; // bursts collapse into one read
statsTimer=setTimeout(()=>{ statsTimer=null; loadStats(); },600);
}
/* foreground/resume: catch anything that changed while the app slept
(e.g. the 08:30 import) without waiting for the next swipe */
document.addEventListener('visibilitychange',()=>{ if(!document.hidden) refreshStats(); });
/* ---------- P3 section UI: progress pill + report + forge + modes ---------- */ /* ---------- P3 section UI: progress pill + report + forge + modes ---------- */
let sectDecided=0, sectTotal=0; let sectDecided=0, sectTotal=0;
@@ -1282,6 +1316,7 @@ $('btnForge').onclick=async()=>{
buffer.push(...fresh); buffer.push(...fresh);
fillPile(); fillPile();
updateSectionUI(body); updateSectionUI(body);
refreshStats(); // v1.1.1 (#2): forged batch — freshen the counters
if(pile.length){ $('report').classList.remove('on'); } if(pile.length){ $('report').classList.remove('on'); }
// item 8: a zero-item forge on a fully drained catalog -> empty2, // item 8: a zero-item forge on a fully drained catalog -> empty2,
// no lone Forge button inviting a wasted agent run // no lone Forge button inviting a wasted agent run
@@ -1367,11 +1402,12 @@ document.addEventListener('keydown',e=>{
else if($('detail').classList.contains('on')) closeDetail(); else if($('detail').classList.contains('on')) closeDetail();
return; // Esc never forges or navigates tabs return; // Esc never forges or navigates tabs
} }
if(k==='ArrowDown'){ e.preventDefault(); undo(); return; } const sheetOpen=()=>$('detail').classList.contains('on')||$('viewer').classList.contains('on');
if(k==='Backspace'){ undo(); return; } if(k==='ArrowDown'){ e.preventDefault(); if(!sheetOpen()) undo(); return; }
if(k==='Backspace'){ if(!sheetOpen()) undo(); return; }
if(k==='ArrowLeft'||k==='ArrowRight'||k==='ArrowUp'){ if(k==='ArrowLeft'||k==='ArrowRight'||k==='ArrowUp'){
e.preventDefault(); e.preventDefault();
if($('detail').classList.contains('on')||$('viewer').classList.contains('on')) return; if(sheetOpen()) return;
const el=pile[0]&&pile[0].el; const el=pile[0]&&pile[0].el;
if(el) commit(el, k==='ArrowLeft'?'nope':k==='ArrowRight'?'like':'maybe'); if(el) commit(el, k==='ArrowLeft'?'nope':k==='ArrowRight'?'like':'maybe');
} }

View File

@@ -379,8 +379,13 @@ class TasteEngine:
"""Source-labeled breakdown lines for the dossier.""" """Source-labeled breakdown lines for the dossier."""
row = self.by_id.get(listing_id) row = self.by_id.get(listing_id)
lines = [] lines = []
lines.append({'source': 'rubric', 'label': 'rubric fit', # issue #3: a section can outlive an ad. A listing that left the
'value': int(row['score'] or 0)}) # active pool mid-batch (and has no swipe history) is not in
# by_id; its breakdown degrades to no-signal lines instead of a
# TypeError that would 500 the whole section render.
if row is not None:
lines.append({'source': 'rubric', 'label': 'rubric fit',
'value': int(row['score'] or 0)})
for label, s, _d, _v in self.contributions(listing_id)[:3]: for label, s, _d, _v in self.contributions(listing_id)[:3]:
lines.append({'source': 'taste', 'label': label, lines.append({'source': 'taste', 'label': label,
'value': round(s, 1)}) 'value': round(s, 1)})

42
docs/DEVELOPMENT.md Normal file
View File

@@ -0,0 +1,42 @@
# Development and deployment
Run these commands from the repo root. The container uses Python 3.14. Use a scratch database and a different port from any running instance; the example binds only to localhost.
```sh
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
mkdir -p data/dev-img
# Optional: seed a development catalog from motorcycle-hunt snapshots.
.venv/bin/python -m app.importer --state-dir /path/to/hunt-snapshots --db data/dev.sqlite3
# Local app and read-only deck preview.
.venv/bin/python -m app.serve --host 127.0.0.1 --port 9454 --db data/dev.sqlite3 --img-dir data/dev-img
.venv/bin/python -m app.deck --db data/dev.sqlite3 --top 15
# Run separately from the dev server.
.venv/bin/python -m app.selfcheck
```
`data/` and `.venv/` are local and ignored by Git. The `app.imgfetch` CLI can cache images for a development catalog; use `--help` for options. The nightly process in the live stack imports the catalog, refreshes the taste profile, and backs up SQLite.
For an offline taste-profile pass, run `app.agentpass --mock` against a development database with swipe history. To inspect the inputs without writing a profile, use `--print-summary --dry-run`. The optional live provider is configured outside the repo. Never use the running instance's DB for test writes; use SQLite's backup API if you need a consistent copy of a database in use. The legacy browser walks (`app.fe_walk_b1`, `app.fe_walk_v11`) need Playwright, Chromium, and staged scratch fixtures; inspect their fixture paths before running them.
## API entry points
| Area | Routes |
| --- | --- |
| Status | `GET /api/health`, `GET /api/stats` |
| Browse | `GET /api/section`, `GET /api/list`, `GET /api/listing/{id}` |
| Decide | `POST /api/swipe`, `DELETE /api/swipe/{id}` |
| Refresh | `POST /api/import`, `POST /api/section/forge`, `POST /api/agent/run` |
| Preferences | `POST /api/prefs`, `POST /api/badge/seen` |
| Display | `GET /api/trends`, `GET /img/{id}?i=n` |
For data contracts, see [Data model](DATA-MODEL.md), [Ranking](RANKING.md), and the [UI spec](UI-SPEC.md).
## Deployment
The [Podman Compose definition](../deploy/docker-compose.yml) runs the app and a Tailscale sidecar for private access. The [systemd user unit](../deploy/podman-stack-bike-tinder.service) owns the running containers. Keep deployment-specific configuration outside Git and retain independent backups of the SQLite data. Do not expose the single-user app directly to the public internet.
Development lands on `dev`, verified changes move to `main`, and the running stack follows `release`. Build the candidate image before restarting the service. After cutover, check `/api/health` and confirm that the HTTP shell matches the intended revision. Keep the previous image for rollback.

17
docs/HOW-IT-WORKS.md Normal file
View File

@@ -0,0 +1,17 @@
# How Bike-Tinder works
## From classifieds to cards
The motorcycle-hunt crawler collects Kijiji listings in Nova Scotia and New Brunswick. The importer reads the crawler's snapshots, adds new listings, updates existing ones, and retires listings only after repeated misses. A blocked or failed fetch isn't proof that a listing is gone. See [Sources](SOURCES.md) and the [data model](DATA-MODEL.md).
The web app reads that catalog from SQLite and presents listings in a swipe deck or a searchable List. Your current verdict is editable; the app also records swipe events for ranking. Tap the sides of a deck card to browse its photos, the center to open the details, or the photo in the details view to open the fullscreen gallery. See the [interface spec](UI-SPEC.md) for gesture and keyboard behavior.
## Ranking and photos
With no swipe history, the deck starts with the motorcycle hunt's scoring rubric. Once there is history, the app builds a taste profile and uses it when ordering future batches. Batches can mix fresh bikes, wildcards, and second looks. A model runs outside the swipe path: the swipe itself never waits for a model response. See [Ranking](RANKING.md) and [Design](DESIGN.md).
The importer retains gallery URLs in source order. The running stack keeps primary photos locally; when a requested gallery photo isn't cached, the app redirects to the source image. A missing photo uses a placeholder. See [the gallery mirror backlog](BACKLOG.md#gallery-mirror-gap-found-2026-11-12-filing-for-a-later-phase).
## More detail
[Development and deployment](DEVELOPMENT.md) covers setup and testing. The [roadmap](PLAN.md) and [backlog](BACKLOG.md) cover planned work.

View File

@@ -20,6 +20,7 @@
### Card geometry ### Card geometry
- `.card{position:absolute;left:14px;right:14px;top:6px;bottom:34px;border-radius:18px;overflow:hidden;background:var(--card);box-shadow:0 0 0 1px rgba(255,255,255,.07),0 18px 40px rgba(0,0,0,.5);will-change:transform;touch-action:none}` - `.card{position:absolute;left:14px;right:14px;top:6px;bottom:34px;border-radius:18px;overflow:hidden;background:var(--card);box-shadow:0 0 0 1px rgba(255,255,255,.07),0 18px 40px rgba(0,0,0,.5);will-change:transform;touch-action:none}`
- Photo full-bleed (`object-fit:cover`); bottom gradient 52% tall (transparent → rgba(0,0,0,.55) @55% → .88). Info block at bottom:14px: chips row → title (23px/800, clamp 2 lines) → price (20px/600) → sub (13px, var(--mut)). - Photo full-bleed (`object-fit:cover`); bottom gradient 52% tall (transparent → rgba(0,0,0,.55) @55% → .88). Info block at bottom:14px: chips row → title (23px/800, clamp 2 lines) → price (20px/600) → sub (13px, var(--mut)).
- Photo fit is **contain** (v1.1): the whole photo is shown uncropped over a soft blurred backdrop of the same image (option C). The backdrop is decorative (blurred, dimmed, overflow-clipped); the sharp photo sits on top with a gentle shadow. The fullscreen viewer already fits; list thumbs stay `cover` (56px).
- No photo → placeholder panel: 45° repeating stripes (#141419/#18181f), centered copy: "Photo pending — thumbnail backfill queued". - No photo → placeholder panel: 45° repeating stripes (#141419/#18181f), centered copy: "Photo pending — thumbnail backfill queued".
- ⓘ button: 32px circle, top-right of card (rgba(0,0,0,.45), 1px rgba(255,255,255,.25) border) → opens the dossier for that card. - ⓘ button: 32px circle, top-right of card (rgba(0,0,0,.45), 1px rgba(255,255,255,.25) border) → opens the dossier for that card.
- Chips: 11px/600, rgba(255,255,255,.14) bg, radius 999px. Production content: max 3 = seller chip ("Dealer" only when seller_type=dealer) + first 2 extras. - Chips: 11px/600, rgba(255,255,255,.14) bg, radius 999px. Production content: max 3 = seller chip ("Dealer" only when seller_type=dealer) + first 2 extras.
@@ -51,6 +52,8 @@
### Empty state ### Empty state
Dashed panel, copy exactly: **"You're all caught up."** / "New bikes arrive nightly — next import 08:30." / "↺ brings the last card back." Undo restores the last card. Dashed panel, copy exactly: **"You're all caught up."** / "New bikes arrive nightly — next import 08:30." / "↺ brings the last card back." Undo restores the last card.
§2's quiet "You're all caught up." remains only for legacy (pre-section) mode. In section mode, when the deck can serve nothing at all — no fresh listings, no eligible second looks, no wildcards — the deck shows a prominent **"No more new bikes!"** panel with "New bikes arrive nightly — next import 08:30." and, when true, "↺ brings the last card back." This panel supersedes the report card in that state only; the report card remains the end-of-section screen whenever more cards can still be served (v1.1).
## 3. Dossier (fullscreen sheet) — one sheet, both doors ## 3. Dossier (fullscreen sheet) — one sheet, both doors
Opened from deck ⓘ (or tap) AND list row tap. iOS-sheet geometry: top gap 26px; `border-radius:18px 18px 0 0`; bg #0f0f13; slide-in `.3s cubic-bezier(.2,.8,.3,1)` from `translateY(103%)`. Backdrop: rgba(0,0,0,.38), z 69/70. Opened from deck ⓘ (or tap) AND list row tap. iOS-sheet geometry: top gap 26px; `border-radius:18px 18px 0 0`; bg #0f0f13; slide-in `.3s cubic-bezier(.2,.8,.3,1)` from `translateY(103%)`. Backdrop: rgba(0,0,0,.38), z 69/70.
@@ -87,7 +90,7 @@ Opened from deck ⓘ (or tap) AND list row tap. iOS-sheet geometry: top gap 26px
1. **Data wiring.** Deck buffer from `GET /api/deck` (limit 40, opaque cursor); refill when buffer <5 and a cursor exists. List from `GET /api/list`. Dossier from the row/card payload. Header from `GET /api/stats`. 1. **Data wiring.** Deck buffer from `GET /api/deck` (limit 40, opaque cursor); refill when buffer <5 and a cursor exists. List from `GET /api/list`. Dossier from the row/card payload. Header from `GET /api/stats`.
2. **Swipe persistence.** Commits fire `POST /api/swipe` optimistically — the UI never waits. Failures go to a retry queue (attempts at ~2s/5s/10s, then every 15s while the tab lives); toast "Couldn't save — retrying" on first failure. Undo fires `DELETE /api/swipe/{id}` through the same queue. 2. **Swipe persistence.** Commits fire `POST /api/swipe` optimistically — the UI never waits. Failures go to a retry queue (attempts at ~2s/5s/10s, then every 15s while the tab lives); toast "Couldn't save — retrying" on first failure. Undo fires `DELETE /api/swipe/{id}` through the same queue.
3. **Badge.** `POST /api/badge/seen` once per session when the deck first renders. Header shows "{live} live" always; "· {new} new" only when new>0. 3. **Badge.** `POST /api/badge/seen` once per session when the deck first renders. Header pill shows `{live} live · {fresh} fresh` always, and `· {new} new` only when new > 0. `fresh` = active listings with no swipe (the deck's new-pool predicate) — v1.1. The pill and the list sub-line refresh themselves shortly after any decision change (swipes, undo, dossier/list/matches edits) and whenever a new batch lands — no reload needed (v1.1.1, issue #2).
4. **List filters + search** per §4 (mockup had placeholder chips only). 4. **List filters + search** per §4 (mockup had placeholder chips only).
5. **Matches real (§5); Trends stays stub.** 5. **Matches real (§5); Trends stays stub.**
6. **Images.** Every card/thumb references `/img/{id}` (server: cached file → 302 CDN → 404 → placeholder). The client never hotlinks directly. 6. **Images.** Every card/thumb references `/img/{id}` (server: cached file → 302 CDN → 404 → placeholder). The client never hotlinks directly.
@@ -119,7 +122,7 @@ Human (parent-run after build): Glenn swipes a real deck from his phone and edit
- The deck serves ONE section at a time: 25 cards (default). A section is the unit of a swipe burst; when it is exhausted, the next one is forged (with an agent pass in between — §10.2). - The deck serves ONE section at a time: 25 cards (default). A section is the unit of a swipe burst; when it is exhausted, the next one is forged (with an agent pass in between — §10.2).
- Header right side, next to the stats: section progress "7/25" (12px/650, muted; turns `--accent1` at 25/25; fits within the existing header, no layout shift). - Header right side, next to the stats: section progress "7/25" (12px/650, muted; turns `--accent1` at 25/25; fits within the existing header, no layout shift).
- Section composition (engine side — RANKING.md): ≤5 SECOND LOOK cards + 2 WILDCARD cards + the remainder new. - Section composition (engine side — RANKING.md): every batch targets 25 cards = fresh first (up to 23 slots) + ≥2 SECOND LOOK cards whenever eligible stock exists + 2 WILDCARD cards; when fresh < 23, second looks fill the remainder up to 25. Re-nope returns stay ≤2 per batch; fresh shortfalls are never padded (v1.1).
- ALL §2 mechanics apply unchanged inside a section: 5-deep stack, `.topcard` invariant, no-lock commit, stamps, undo; the buffer refills from the pinned section order. - ALL §2 mechanics apply unchanged inside a section: 5-deep stack, `.topcard` invariant, no-lock commit, stamps, undo; the buffer refills from the pinned section order.
### 10.2 Section report + forge ### 10.2 Section report + forge
@@ -133,13 +136,14 @@ Human (parent-run after build): Glenn swipes a real deck from his phone and edit
- **Forge mode `ondemand` (default):** primary button **"Forge next 25"**. Tap → inline status "The agent is reading your strikes…" → new section hydrates. If the pass fails: "Agent offline — forging on the last read." and the forge still lands (fallback profile). - **Forge mode `ondemand` (default):** primary button **"Forge next 25"**. Tap → inline status "The agent is reading your strikes…" → new section hydrates. If the pass fails: "Agent offline — forging on the last read." and the forge still lands (fallback profile).
- **Forge mode `strict`:** button disabled; caption "Waiting for the nightly read — next section after the agent runs." - **Forge mode `strict`:** button disabled; caption "Waiting for the nightly read — next section after the agent runs."
- Both modes: small toggle row under the actions — "Forge: on demand ⇄ strict" (persists `prefs['forge_mode']`). - Both modes: small toggle row under the actions — "Forge: on demand ⇄ strict" (persists `prefs['forge_mode']`).
- When a forged batch reports `new: 0` the report shows: "Catalog fully reviewed — fresh listings arrive with the next 08:30 import; showing second looks." and the forge reads the same note in its status line (v1.1).
- Undo from the report screen re-opens the section with the last card (§2 undo semantics). - Undo from the report screen re-opens the section with the last card (§2 undo semantics).
### 10.3 Card bands (the ONLY card-face additions) ### 10.3 Card bands (the ONLY card-face additions)
- Position: top-left inset (12px); `pointer-events:none`; no layout shift; no effect on stack metrics or drag. 11px/650, letter-spacing .4px, radius 999px, padding 4px 9px, max-width 78%; may wrap to 2 lines. - Position: top-left inset (12px); `pointer-events:none`; no layout shift; no effect on stack metrics or drag. 11px/650, letter-spacing .4px, radius 999px, padding 4px 9px, max-width 78%; may wrap to 2 lines.
- **WILDCARD — maybe you'll like this one instead** — color `#ffb43a`; bg `rgba(255,180,58,.14)`; border `1px solid rgba(255,180,58,.35)`. - **WILDCARD — maybe you'll like this one instead** — color `#ffb43a`; bg `rgba(255,180,58,.14)`; border `1px solid rgba(255,180,58,.35)`.
- **SECOND LOOK — you {liked|maybed|noped} this** — color `rgba(255,255,255,.85)`; bg `rgba(255,255,255,.10)`; border `1px solid rgba(255,255,255,.22)`. - **SECOND LOOK — you {liked|maybed|noped} this** — color `#c4b5fd`; bg `rgba(124,58,237,.22)`; border `1px solid rgba(167,139,250,.65)`; font-weight 800. Wildcard stays amber (`#ffb43a` family values unchanged) for contrast. The same band renders in the dossier ("info view") when the listing's slot is `return` or `wildcard` (v1.1).
- No other text may sit on the card face in v3. - No other text may sit on the card face in v3.
### 10.4 Tank gauge (match points, non-numeric) ### 10.4 Tank gauge (match points, non-numeric)
@@ -151,9 +155,10 @@ Human (parent-run after build): Glenn swipes a real deck from his phone and edit
### 10.5 Dossier — "Why this rank" ### 10.5 Dossier — "Why this rank"
- New block after chips, before "The machine": - New block after chips, before "The machine":
- Gauge + "{points}/100" (17px/700). - Gauge + "{points}%" (17px/700).
- Up to 4 breakdown lines, strongest first, muted: "· {feature} {±n}"; agent contributions render as "· agent: {why} {±n}". - Up to 4 breakdown lines, strongest first, muted: "· {feature} {±n}"; agent contributions render as "· agent: {why} {±n}".
- Footer: "from {N} strikes · read {relative}" (N = events count; time = profile version time). - Footer: "from {N} strikes · read {relative}" (N = events count; time = profile version time).
- Hidden-by-default detail: the breakdown lines and the "from N strikes" footer render only when `prefs['rubric_debug'] === 'on'` (default `'off'`). With the pref off the block shows **the tank gauge + "{points}%"** only — the minimal rubric display. The toggle lives in the Trends "Actions" area (why-breakdown on ⇄ off, same control style as the forge-mode toggle) — v1.1.
- This is the only numeric display in the app (accepted — it exists for audit). - This is the only numeric display in the app (accepted — it exists for audit).
### 10.6 Trends tab (real) ### 10.6 Trends tab (real)
@@ -192,14 +197,15 @@ Top→bottom:
### 11.3 Fullscreen viewer ### 11.3 Fullscreen viewer
- Tap the CENTER third → fullscreen viewer opens on the photo currently shown. - Tap the photo in the dossier hero → fullscreen viewer opens (starts at photo 0). Direct card→viewer is retired (see §11.4); the viewer is reached from the dossier (v1.1).
- Viewer: horizontal swipe = prev/next (clamp); pinch-zoom + double-tap = zoom (1×–~4×); segment bars stay visible; close via ✕ (36px, top-left) or pull-down (grabber or photo, `dy > 110` — the §3 idiom). Closing returns to the same card, same photo position; deck state untouched. - Viewer: horizontal swipe = prev/next (clamp); pinch-zoom + double-tap = zoom (1×–~4×); segment bars stay visible; close via ✕ (36px, top-left) or pull-down (grabber or photo, `dy > 110` — the §3 idiom). Closing returns to the same card, same photo position; deck state untouched.
- Also opens from the dossier hero (starts at photo 0). Same sheet geometry as the dossier (z-band 69/70), photo-first: no body, no actions row. - Also opens from the dossier hero (starts at photo 0). Same sheet geometry as the dossier (z-band 69/70), photo-first: no body, no actions row.
- Viewer close (✕, pull-down, or Esc) returns to the dossier; the next Esc returns to the deck (v1.1).
### 11.4 Doors (supersedes the old tap→dossier) ### 11.4 Doors (supersedes the old tap→dossier)
- ⓘ (top-right of card) → dossier (unchanged). The card face now owns: **sides = flip, center = fullscreen**; the "tap anywhere → dossier" gesture is RETIRED. - ⓘ (top-right of card) → dossier (unchanged). The card face now owns: **sides = flip, center = dossier (bike data first)**; the "tap anywhere → dossier" gesture is RETIRED and the B1 center-tap→fullscreen gesture is RETIRED in favour of it (v1.1).
- The dossier stays reachable from ⓘ and from list rows (§3/§4 unchanged). - Tapping the photo in the dossier hero opens the fullscreen image viewer (§11.3). Viewer close (✕, pull-down, or Esc) returns to the dossier; the next Esc returns to the deck. The dossier stays reachable from ⓘ and from list rows (§3/§4 unchanged).
### 11.5 Repeat rotation ### 11.5 Repeat rotation

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

BIN
docs/images/swipe-deck.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB