Compare commits

...

6 Commits

Author SHA1 Message Date
Torres
2160ba6ce8 feat(v1.1): item 9 — batch formula v2 compose rewrite (AMENDS the frozen '<=5 returns' rule)
Allocator now: reserved returns (>=2 whenever eligible stock exists,
role order, surprising-gate on reserved nope slots, cap-4 family) ->
wildcards (2) -> fresh (remainder, capped at 23; wilds draw from the
fresh pool without consuming fresh slots) -> fill returns to size (role
order, <=2 re-nopes total, two-pass family cap: 4 preferred, 8 rescue for
fill slots only). MAX_RETURNS dies; FRESH_CAP=23, MIN_RETURNS=2,
RETURN_FILL_FAMILY_CAP=8 land. Rich day = 21 fresh + 2 second looks +
2 wildcards (the sign-off shape); dry day fills to 25 with returns; 0/0/0
composes an empty section; shortfalls are never padded.

Docs: module docstring, RANKING.md section recipe and DATA-MODEL returns
eligibility rewritten to the v1.1 contract (+ rubric_debug pref noted).

Selfcheck: A1-A8 compose matrix on deterministic staged pools (21/2/2
rich; 5 fresh + 20 SL fill incl. wild-from-fresh derivation; 21/2/2
sign-off; 12-return dry with <=2 nopes + LAST_TWO re-compose; 40 fresh ->
23+2 then the 15 leftover with zero overlap; 0/0/0 empty; family-cap 8
fill rescue; rested/gate-blocked re-nope rules). Pool-honest note: the
spec's A2 '5 fresh + 18 returns + 2 wild' assumed 7 fresh listings —
wildcards are by definition never-swiped, so a 5-fresh day reads 5 fresh
total (3 new + 2 wild) + 20 second looks.
2026-11-13 13:53:33 -04:00
Torres
a1455aade4 feat(v1.1): items 7-8 — fresh counter pill + loud 'No more new bikes!' empty state
Item 7: /api/stats gains fresh (actives with no swipe row — the deck's
new-pool predicate verbatim); the header pill reads 'N live · M fresh'
(new badge unchanged); old APIs without fresh render no segment.

Item 8: sections.pool_counts() answers can-the-forge-serve-anything from
the composer's own candidate SQLs (stock answer, LAST_TWO not applied)
and rides every section_state body. The FE adds #empty2 ('No more new
bikes!' + 08:30 line + undo note): shown whenever the pile/buffer drain
and pool is 0/0/0 (report masked), on a zero-item dry forge too; undo
hides it; legacy .empty untouched. UpdateUI repaints the caption per
hydrate; the stats key-set selfcheck gains fresh.
2026-11-13 13:42:08 -04:00
Torres
0d2e5a592f feat(v1.1): item 6 — dry-catalog messaging (forged batches with 0 fresh are labeled)
section_state now mirrors the composed recipe at body.recipe; the forge
note appends 'catalog fully reviewed' when the batch has zero fresh cards.
The FE shows the BACKLOG sentence in the report (dryCap) and in the forge
status line whenever recipe.new===0 with cards served; a non-dry forge
behaves exactly as before. No new fetch loops.
2026-11-13 13:39:22 -04:00
Torres
98d345ceee fix(v1.1): item 5 — section counter keys off in-section events (2/2 -> 3/2 bug)
A card is decided only when a swipe event carries THIS section's id;
the lifetime swipes.action a second look wears into its section no longer
paints it as pre-decided. progress/undecided, report counts (latest
in-section event per listing) and maybe_exhaust all use the new
section_decided_ids() set; read path only, no writes. Every section_state
item carries decided_this_section; the FE counts server truth unless a
local intent is in flight, and sectDecided is clamped to sectTotal
everywhere (commit + paintSect) so the pill can never read past N/N.

Semantics note: completing a section now means striking EVERY item in it
(returns re-struck on their second look) — the exhaust selfcheck was
updated to strike all items, matching the deck's real flow. Undo-on-a-
return residual (event stays after the DELETE) is the accepted Q5 clamp-
only behavior, covered by a dedicated selfcheck case.
2026-11-13 13:38:18 -04:00
Torres
ac613e680a feat(v1.1): item 4 — minimal rubric (gauge + %) and rubric_debug 'why' toggle
- prefs API accepts the new rubric_debug key (off|on), the only new runtime
  write in v1.1; every section_state body now carries prefs.rubric_debug.
- fillRank renders the tank gauge + rounded % by default; the breakdown
  lines, audit footer and the quiet listing-enrichment fetch run only when
  the pref is on. List rows and the card face stay rubric-free (unchanged).
- Trends 'Actions' gains a 'Why breakdown: off | on' row in the setMode
  style; updateSectionUI repaints it on every section hydrate.
2026-11-13 13:31:21 -04:00
Torres
e67f8a0cda feat(v1.1): items 1-3 — keyboard map, info-first tap flow, photos = fit + blurred backdrop
Item 1: ArrowLeft/Right/Up drive nope/like/maybe through commit(); ArrowDown
and Backspace (kept alias) drive undo(); Esc closes the top open sheet only
(viewer -> dossier -> deck, inert on report). Text inputs/TEXTAREA/SELECT/
contentEditable swallow keys; arrow defaults are prevented (no page scroll).

Item 2: card center tap now opens the dossier (bike data first); side taps
keep flipping photos; the direct card -> viewer door is retired. The deck
dossier records its pile entry; the hero tap opens the viewer with a
backToDetail chain so Esc walks viewer -> dossier -> deck (repeatable).

Item 3: deck card + dossier hero photos switch from cover to contain over a
soft blurred backdrop of the same image (option C, demo panel C); thumb and
fullscreen viewer untouched; nophoto paths render no backdrop.
2026-11-13 13:30:09 -04:00
6 changed files with 775 additions and 80 deletions

View File

@@ -238,6 +238,14 @@ def create_app(db_path, img_dir, state_dir=None):
live = conn.execute(
"SELECT COUNT(*) AS n FROM listings WHERE status='active'"
).fetchone()['n']
# item 7: fresh = active with no swipe row (the deck's new-pool
# predicate, verbatim). A swipe of ANY age removes freshness.
fresh = conn.execute(
"SELECT COUNT(*) AS n FROM listings l"
" WHERE l.status='active'"
" AND NOT EXISTS (SELECT 1 FROM swipes s"
" WHERE s.listing_id = l.id)"
).fetchone()['n']
badge = get_pref(conn, 'badge_seen_at') or ''
new = conn.execute(
"SELECT COUNT(*) AS n FROM listings"
@@ -253,6 +261,7 @@ def create_app(db_path, img_dir, state_dir=None):
' ORDER BY id DESC LIMIT 1').fetchone()
return {
'live': live,
'fresh': fresh,
'new': new,
'likes': per['like'],
'maybes': per['maybe'],
@@ -451,11 +460,20 @@ def create_app(db_path, img_dir, state_dir=None):
sec = conn.execute('SELECT * FROM sections WHERE id=?',
(sec['id'],)).fetchone()
mode = get_pref(conn, 'forge_mode', 'ondemand')
decided_ids = secmod.section_decided_ids(conn, sec)
items = [p3_payload(conn, engine, r, slot=r['slot'],
include_breakdown=True)
for r in data['items']]
for p in items:
# item 5: decided IN this section (real verdict), not the joined
# lifetime swipes decision — present on EVERY item so the FE's
# local-intent branch can't misfire
p['decided_this_section'] = p['id'] in decided_ids
data['items'] = items
data['mode'] = mode
data['recipe'] = (json.loads(sec['recipe']) if sec['recipe'] else {})
data['pool'] = secmod.pool_counts(conn)
data['prefs'] = {'rubric_debug': get_pref(conn, 'rubric_debug', 'off')}
data['can_forge'] = (mode != 'strict'
or secmod.fresh_profile_exists(conn, sec))
data['counts'] = secmod.section_counts(conn, sec)
@@ -522,6 +540,11 @@ def create_app(db_path, img_dir, state_dir=None):
conn, engine, size=size,
profile_version=prof['version'] if prof else None,
note=note)
# v1.1 item 6: label the dry-catalog state on the forge note
recipe = (json.loads(newsec['recipe'])
if newsec['recipe'] else {})
if recipe.get('new') == 0:
note = '%s · catalog fully reviewed' % (note or '')
return section_state(conn, newsec, note=note)
finally:
conn.close()
@@ -653,7 +676,8 @@ def create_app(db_path, img_dir, state_dir=None):
def set_pref_endpoint(body: dict):
key = body.get('key')
value = body.get('value')
allowed = {'forge_mode': ('ondemand', 'strict')}
allowed = {'forge_mode': ('ondemand', 'strict'),
'rubric_debug': ('off', 'on')}
if key not in allowed or value not in allowed[key]:
raise HTTPException(status_code=400,
detail='unknown or invalid pref')

View File

@@ -1,8 +1,12 @@
"""Bike-Tinder P3 section engine — compose / read / exhaust / forge.
The deck is one finite SECTION at a time (default 25 cards):
2 wildcards + <=5 returns (<=2 nopes, "surprising" only) + remainder new,
per docs/RANKING.md + docs/DATA-MODEL.md "P3 additions".
v1.1 batch formula (amends the frozen "<=5 returns" rule — one-shot,
re-nope and one-return rules unchanged): every batch targets 25 cards =
fresh first (up to 23 slots) + >=2 second looks whenever eligible stock
exists + the 2 wildcard slots; when fresh < the remainder, second looks
FILL the batch up to 25 (family cap relaxes to 8 for fill returns only).
Fresh exhausted -> returns-only batches; returns exhausted -> fresh-only;
both -> an empty composed section (the loud empty state, item 8).
Pinned order within a section (position 1 first):
new (points DESC) -> returns (maybe > like > nope, points DESC within
@@ -11,10 +15,12 @@ Pinned order within a section (position 1 first):
wildcard stretches sit at the back. (Wildcard placement inside the deck
is not pinned anywhere in the frozen docs — noted in the P3 report.)
Constraints: <=4 per non-NULL family per section; >=3 price bands when the
pool allows (soft repair swaps new-slot items within the final list).
A re-nope (round>=2 nope event) rests an item: no more second looks.
Rounds cap at 2 for influence (taste.py); returns are offered once.
Constraints: <=4 per non-NULL family per section (fill-return slots relax
to <=8); >=3 price bands when the pool allows (soft repair swaps new-slot
items within the final list). <=2 re-nope returns per batch (reserved
nope slots must be "surprising"). A re-nope (round>=2 nope event) rests
an item: no more second looks. Rounds cap at 2 for influence (taste.py);
returns are offered once.
Modes: 'ondemand' (default) — forge runs the agent pass then composes;
'strict' — forge refuses (409) unless a taste_profile strictly newer than
@@ -26,9 +32,11 @@ from . import taste as tastemod
from .taste import NOPE
FAMILY_CAP = 4
MAX_RETURNS = 5
RETURN_FILL_FAMILY_CAP = 8
MAX_RETURN_NOPES = 2
WILDCARDS = 2
FRESH_CAP = 23
MIN_RETURNS = 2
DEFAULT_SIZE = 25
MIN_BANDS = 3
@@ -262,6 +270,11 @@ def compose_section(conn, engine, size=DEFAULT_SIZE, profile_version=None,
Caller closes/reports any prior section first. `engine` scores the
candidates (a TasteEngine over active listings + events + profile).
v1.1 slot math (see module docstring; this amends the frozen "<=5
returns" rule): reserved returns (>=2 when eligible stock exists) ->
wildcards (2) -> fresh (capped at 23) -> fill returns to `size`
(family cap 4 preferred, 8 rescue; <=2 re-nopes total).
"""
import datetime
now = now or datetime.datetime.now(datetime.timezone.utc).replace(
@@ -297,18 +310,18 @@ def compose_section(conn, engine, size=DEFAULT_SIZE, profile_version=None,
top_bands = {tastemod.price_band(r['price_num']) for r in top3
if tastemod.price_band(r['price_num']) is not None}
# 2) returns: maybe > like > nope, points DESC within role; nopes must be
# "surprising" (points >=55 or net-positive family); <=5, <=2 nopes.
# Budget: wildcards keep their 2 slots; returns never push the
# section past `size`.
wanted_rets = min(MAX_RETURNS, max(0, size - min(WILDCARDS, size)))
# 2) reserved returns: the >=2 guarantee (role order maybe > like > nope,
# points DESC within role). Nopes must be "surprising" for RESERVED
# slots only (points >=55 or net-positive family); <=2 re-nope
# returns per batch overall; family cap 4 applies here.
role_order = {'maybe': 0, 'like': 1, 'nope': 2}
ret_ordered = sorted(ret_cands, reverse=True,
key=lambda r: (-role_order.get(r['verdict'], 9),
_points_key(engine, r)))
rets = []
nope_count = 0
for cand in sorted(ret_cands, reverse=True,
key=lambda r: (-role_order.get(r['verdict'], 9),
_points_key(engine, r))):
if len(rets) >= wanted_rets:
for cand in ret_ordered:
if len(rets) >= min(MIN_RETURNS, size):
break
fam = cand['family']
if fam and fam_count.get(fam, 0) >= FAMILY_CAP:
@@ -325,7 +338,8 @@ def compose_section(conn, engine, size=DEFAULT_SIZE, profile_version=None,
if fam:
fam_count[fam] = fam_count.get(fam, 0) + 1
# 3) wildcards: min(2, size), preferred different family AND price band
# 3) wildcards: min(2, remaining slots), preferred different family AND
# price band (existing novel/preferred pick, unchanged)
liked_ids = [r['listing_id'] for r in conn.execute(
"SELECT listing_id FROM swipes WHERE action='like'")]
nov = novelty(rows_by_id, liked_ids,
@@ -339,7 +353,7 @@ def compose_section(conn, engine, size=DEFAULT_SIZE, profile_version=None,
and (tastemod.price_band(r['price_num']) is None
or tastemod.price_band(r['price_num']) not in top_bands)]
n_wilds = min(WILDCARDS, size)
n_wilds = min(WILDCARDS, max(0, size - len(rets)))
wilds = []
avail = sorted([r for r in wild_cands if r['id'] not in picked_ids],
key=wild_key)
@@ -355,12 +369,41 @@ def compose_section(conn, engine, size=DEFAULT_SIZE, profile_version=None,
picked_ids.add(cand['id'])
if fam:
fam_count[fam] = fam_count.get(fam, 0) + 1
n_wilds = len(wilds) # pool shortfall reverts to new
n_wilds = len(wilds) # pool shortfall reverts to fresh/fill
# 4) new fills the remainder of the section (size - returns - wildcards)
want_new = max(0, size - len(rets) - n_wilds)
# 4) fresh fills the remainder (size - returns - wildcards), never
# beyond FRESH_CAP. Wildcards draw from the fresh pool but do NOT
# count against the fresh-slot cap (25 - 0 - 2 = 23 new + 2 wild on
# a returns-free rich day; 21 new + 2 wild + 2 returns when both
# guarantees hold — the sign-off shape). Pool-limited by what the
# wildcard pick left in new_cands; a dry wild pool reverts slots.
want_new = min(size - len(rets) - len(wilds), FRESH_CAP,
max(0, len(new_cands) - len(wilds)))
picked_new = pick_new(engine, new_cands, want_new, fam_count, picked_ids)
# 5) fill returns to size: role order; re-nope cap <=2 total (reserved
# included, no surprising gate here); two-pass family cap — prefer
# <=4, rescue pass relaxes to <=8 for FILL slots only (fresh picks
# and reserved returns keep 4). Deterministic: role order, points
# DESC within role.
for pass_cap in (FAMILY_CAP, RETURN_FILL_FAMILY_CAP):
for cand in ret_ordered:
if len(rets) >= size - len(picked_new) - n_wilds:
break
if cand['id'] in picked_ids:
continue
fam = cand['family']
if fam and fam_count.get(fam, 0) >= pass_cap:
continue
if cand['verdict'] == NOPE and nope_count >= MAX_RETURN_NOPES:
continue
rets.append(cand)
picked_ids.add(cand['id'])
if cand['verdict'] == NOPE:
nope_count += 1
if fam:
fam_count[fam] = fam_count.get(fam, 0) + 1
# final pinned order: new -> returns -> wildcards
ordered = list(picked_new) + rets + wilds
@@ -425,16 +468,58 @@ def section_items(conn, section):
ORDER BY si.position ASC""", (section['id'],)).fetchall()
def section_decided_ids(conn, section):
"""Listing ids with a swipe event stamped in THIS section.
The decided set for progress/report/exhaustion is always these ids —
never the lifetime `swipes.action` verdict (a second-look card enters
its section wearing an old decision; only an in-section event means it
was actually decided here). The join keeps out-of-section stray events
honest (same shape `section_counts` uses).
"""
return {r['listing_id'] for r in conn.execute(
"""SELECT e.listing_id FROM swipe_events e
JOIN section_items si
ON si.section_id = e.section_id
AND si.listing_id = e.listing_id
WHERE e.section_id = ?""", (section['id'],))}
def pool_counts(conn):
"""Stock answer to \"can the forge serve anything?\" — fresh / eligible
returns / wildcards candidate counts, each from the composer's own
candidate SQL. The per-section LAST_TWO exclusion inside compose_section
is deliberately NOT applied here: the answer is about stock, not about
what one batch will pick (item 8)."""
def _count(sql):
return conn.execute(
'SELECT COUNT(*) AS n FROM (%s)' % sql).fetchone()['n']
return {'fresh': _count(NEW_POOL_SQL),
'returns': _count(RETURNS_SQL),
'wildcards': _count(WILDCARD_SQL)}
def section_counts(conn, section):
"""Per-action counts + second-look / wildcard engagement for this
section (events stamped with this section_id only)."""
counts = {'likes': 0, 'maybes': 0, 'nopes': 0}
for item in section_items(conn, section):
if item['decision'] == 'like':
# one verdict per listing: the latest in-section event wins (an undo +
# re-swipe within a section must not double-count the report numbers)
latest = {}
for ev in conn.execute(
"""SELECT e.listing_id, e.action FROM swipe_events e
JOIN section_items si
ON si.section_id = e.section_id
AND si.listing_id = e.listing_id
WHERE e.section_id = ?
ORDER BY e.id ASC""", (section['id'],)):
latest[ev['listing_id']] = ev['action']
for action in latest.values():
if action == 'like':
counts['likes'] += 1
elif item['decision'] == 'maybe':
elif action == 'maybe':
counts['maybes'] += 1
elif item['decision'] == 'nope':
elif action == 'nope':
counts['nopes'] += 1
restruck = conn.execute(
"""SELECT COUNT(DISTINCT e.listing_id) AS n FROM swipe_events e
@@ -458,8 +543,9 @@ def maybe_exhaust(conn, section, now):
"""Flip an all-decided open section to 'report' (returns the fresh row)."""
if section['status'] != 'open':
return section
decided_ids = section_decided_ids(conn, section)
items = section_items(conn, section)
if all(it['decision'] is not None for it in items):
if items and not [it for it in items if it['id'] not in decided_ids]:
close_section(conn, section, now, status='report')
return conn.execute('SELECT * FROM sections WHERE id=?',
(section['id'],)).fetchone()
@@ -470,7 +556,8 @@ def read_section(conn, section, now):
"""Meta + items + progress + exhausted for GET /api/section."""
section = maybe_exhaust(conn, section, now)
items = section_items(conn, section)
decided = sum(1 for it in items if it['decision'] is not None)
decided_ids = section_decided_ids(conn, section)
decided = sum(1 for it in items if it['id'] in decided_ids)
return {
'section': {
'id': section['id'],

View File

@@ -382,7 +382,17 @@ def test_api_stats_health():
conn.close()
s = c.get('/api/stats').json()
assert s['live'] == active, (s['live'], active)
assert set(s) == {'live', 'new', 'likes', 'maybes', 'nopes', 'last_import'}
assert set(s) == {'live', 'fresh', 'new', 'likes', 'maybes',
'nopes', 'last_import'} # v1.1 item 7: + fresh
# fresh = actives with no swipe row (the deck's new-pool predicate)
conn = sqlite3.connect(os.path.join(d, 'test.sqlite3'))
expect_fresh = conn.execute(
"SELECT COUNT(*) AS n FROM listings l"
" WHERE l.status='active'"
" AND NOT EXISTS (SELECT 1 FROM swipes s"
" WHERE s.listing_id = l.id)").fetchone()[0]
conn.close()
assert s['fresh'] == expect_fresh, (s['fresh'], expect_fresh)
assert s['last_import'] is not None and s['last_import']['ok'] is True
assert s['new'] == expect_new, (s['new'], expect_new)
h = c.get('/api/health').json()
@@ -739,7 +749,9 @@ def test_p3_exhaust_and_report():
c.post('/api/prefs', json={'key': 'forge_mode', 'value': 'ondemand'})
f = c.post('/api/section/forge', json={'size': 6}).json()
sid = f['section']['id']
for it in [i for i in f['items'] if i['decision'] is None]:
# v1.1 (item 5): EVERY item needs an in-section strike to complete
# the section — returns re-enter the deck and are re-struck too.
for it in f['items']:
r = c.post('/api/swipe', json={'listing_id': it['id'],
'action': 'like', 'section_id': sid})
assert r.status_code == 200
@@ -1279,6 +1291,456 @@ def test_b1_swipe_photo_idx():
shutil.rmtree(d, ignore_errors=True)
# --- v1.1 checks (temp copies of the source DB only — see p3_env) ----------
def test_v11_item5_section_counter():
"""Returns-only section must read 0/N decided until real in-section
events exist; report counts and exhaustion key off those events."""
d, c, db_path = p3_env()
try:
conn = _sq_conn(db_path)
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()
conn.close()
s = c.get('/api/section').json() # cold compose
total = s['progress']['total']
assert total > 0, s
assert s['recipe']['new'] == 0, s['recipe']
# every item wears a LIFETIME verdict but zero in-section decisions
for it in s['items']:
assert it['decision'] is not None, it['id']
assert it['decided_this_section'] is False, it['id']
assert s['progress']['decided'] == 0, s['progress']
sec_id = s['section']['id']
# list edit (no section_id) must not count as an in-section decision
lid0 = s['items'][0]['id']
c.post('/api/swipe', json={'listing_id': lid0, 'action': 'like'})
assert c.get('/api/section').json()['progress']['decided'] == 0
# first real in-section swipe -> 1/total
c.post('/api/swipe', json={'listing_id': lid0, 'action': 'like',
'section_id': sec_id})
s2 = c.get('/api/section').json()
assert s2['progress']['decided'] == 1, s2['progress']
# second -> 2/total; report counts reflect in-section verdicts only
lid1 = s2['items'][1]['id']
c.post('/api/swipe', json={'listing_id': lid1, 'action': 'maybe',
'section_id': sec_id})
s3 = c.get('/api/section').json()
assert s3['progress']['decided'] == 2, s3['progress']
assert s3['counts']['likes'] == 1, s3['counts']
assert s3['counts']['maybes'] == 1, s3['counts']
# undo residual (Q5, accepted): DELETE clears the swipe row but the
# section-stamped event stays -> count holds (clamp-only behavior)
c.delete('/api/swipe/%d' % lid1)
s4 = c.get('/api/section').json()
assert s4['progress']['decided'] == 2, s4['progress']
c.post('/api/swipe', json={'listing_id': lid1, 'action': 'maybe',
'section_id': sec_id})
# strike the rest in-section -> report flips, counts match verdicts
for it in s4['items']:
if it['id'] not in (lid0, lid1):
c.post('/api/swipe', json={'listing_id': it['id'],
'action': 'maybe',
'section_id': sec_id})
s5 = c.get('/api/section').json()
assert s5['exhausted'] is True
assert s5['section']['status'] == 'report'
assert s5['progress']['decided'] == total, s5['progress']
assert s5['counts']['likes'] == 1, s5['counts']
assert s5['counts']['maybes'] == total - 1, s5['counts']
# a fresh returns-only section of the same shape composes cleanly
# (lifetime verdicts present, in-section decided == 0 again)
f = c.post('/api/section/forge', json={}).json()
assert f['recipe']['new'] == 0, f['recipe']
assert f['progress']['decided'] == 0, f['progress']
for it in f['items']:
assert it['decision'] is not None and not it['decided_this_section']
finally:
shutil.rmtree(d, ignore_errors=True)
def test_v11_item7_stats_fresh():
"""Item 7: /api/stats.fresh counts actives with no swipe row and moves
on swipe (the deck's new-pool predicate)."""
d, c, db_path = p3_env()
try:
conn = _sq_conn(db_path)
rows = conn.execute(
"SELECT id FROM listings WHERE status='active' LIMIT 5"
).fetchall()
assert len(rows) == 5
ids = [r['id'] for r in rows]
conn.execute("UPDATE listings SET status='gone' WHERE status='active'")
conn.execute("DELETE FROM swipes WHERE listing_id IN (%s)"
% ','.join('?' * len(ids)), ids)
conn.execute("DELETE FROM swipe_events WHERE listing_id IN (%s)"
% ','.join('?' * len(ids)), ids)
for lid in ids:
conn.execute("UPDATE listings SET status='active' WHERE id=?", (lid,))
for lid in ids[:3]:
conn.execute(
"INSERT INTO swipes (listing_id, action, created_at)"
" VALUES (?, 'maybe', '2026-11-01T00:00:00Z')", (lid,))
conn.commit()
conn.close()
st = c.get('/api/stats').json()
assert st['live'] == 5, st
assert st['fresh'] == 2, st # 2 of 5 still never-touched
# swiping one of the untouched pair moves fresh to 1 on next read
c.post('/api/swipe', json={'listing_id': ids[3], 'action': 'like'})
assert c.get('/api/stats').json()['fresh'] == 1
finally:
shutil.rmtree(d, ignore_errors=True)
def test_v11_item8_pool_and_dry():
"""Item 8/6: pool counts ride section_state; 0/0/0 composes an empty
section; a fresh=0, returns>0 catalog labels the forge note dry."""
d, c, db_path = p3_env()
try:
conn = _sq_conn(db_path)
conn.execute('DELETE FROM section_items')
conn.execute("UPDATE sections SET status='closed'"
" WHERE status!='closed'")
# every active gets a maybe swipe + round-1 event (returns alive,
# fresh + wildcards drained)
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()
conn.close()
s = c.get('/api/section').json() # dry but alive
assert s['pool']['fresh'] == 0 and s['pool']['returns'] > 0, s['pool']
assert s['recipe']['new'] == 0 and len(s['items']) > 0
f = c.post('/api/section/forge', json={}).json()
assert f['recipe']['new'] == 0 and len(f['items']) > 0
assert 'catalog fully reviewed' in (f.get('note') or ''), f.get('note')
# drain returns too (one-shot) + wildcards: pool 0/0/0 -> empty compose
conn = _sq_conn(db_path)
conn.execute("DELETE FROM section_items")
conn.execute("UPDATE sections SET status='closed'"
" WHERE status!='closed'")
# burn return eligibility: every active already had its return slot
# -> re-insert one-shot return rows for all of them
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()
conn.close()
s2 = c.get('/api/section').json()
assert s2['pool'] == {'fresh': 0, 'returns': 0, 'wildcards': 0}, s2['pool']
assert s2['items'] == []
assert s2['recipe']['new'] == 0 and s2['recipe']['return'] == 0
assert s2['recipe']['wildcard'] == 0, s2['recipe']
finally:
shutil.rmtree(d, ignore_errors=True)
# --- item 9: batch formula v2 compose matrix (A1-A8, staged pools) --------
def _v11_wipe(conn):
"""Reset a temp copy to a controlled catalog: no sections/swipes/events,
everything parked 'gone' (rows kept so ids/families can be re-used)."""
conn.execute('DELETE FROM section_items')
conn.execute('DELETE FROM sections')
conn.execute('DELETE FROM swipes')
conn.execute('DELETE FROM swipe_events')
conn.execute("UPDATE listings SET status='gone' WHERE status!='dup'")
def _v11_ids(conn, n, start=0):
return [r['id'] for r in conn.execute(
'SELECT id FROM listings ORDER BY id LIMIT ? OFFSET ?',
(n, start))]
def _v11_activate(conn, ids, family=None, score=None):
for lid in ids:
if score is None:
conn.execute("UPDATE listings SET status='active', family=?"
" WHERE id=?", (family, lid))
else:
conn.execute("UPDATE listings SET status='active', family=?,"
" score=? WHERE id=?", (family, score, lid))
def _v11_stage_returns(conn, ids, action='maybe', rests=()):
"""swipes row + round-1 event per id; rests get a round-2 nope event
(the REST rule bars them from returns forever)."""
rests = set(rests)
for lid in ids:
conn.execute("INSERT INTO swipes (listing_id, action, created_at)"
" VALUES (?, ?, '2026-11-01T00:00:00Z')",
(lid, action))
conn.execute("INSERT INTO swipe_events (listing_id, action, round,"
" section_id) VALUES (?, ?, 1, NULL)", (lid, action))
if lid in rests:
conn.execute("INSERT INTO swipe_events (listing_id, action,"
" round, section_id) VALUES (?, 'nope', 2, NULL)",
(lid,))
def _v11_stage_fresh(conn, ids, seen=False):
"""No swipes row (=fresh). seen=True drops wildcard eligibility via a
round-1 event (fresh pool and wildcard pool are otherwise the same)."""
for lid in ids:
if seen:
conn.execute("INSERT INTO swipe_events (listing_id, action,"
" round, section_id) VALUES (?, 'maybe', 1, NULL)",
(lid,))
def _v11_stage_support(conn, ids, family):
"""Gone-status listings whose events tilt a family's net (nope-gate)."""
for lid in ids:
conn.execute("UPDATE listings SET family=? WHERE id=?", (family, lid))
conn.execute("INSERT INTO swipe_events (listing_id, action, round,"
" section_id) VALUES (?, 'like', 1, NULL)", (lid,))
def _v11_compose(db_path, size=25):
from . import sections as secmod
conn = db.connect(db_path)
db.init_db(conn)
engine = secmod.build_engine(
conn, now=datetime.datetime.now(datetime.timezone.utc).replace(
tzinfo=None))
sec = secmod.compose_section(conn, engine, size=size)
recipe = json.loads(sec['recipe'])
items = [dict(r) for r in secmod.section_items(conn, sec)]
conn.commit()
conn.close()
return recipe, items, engine
def _slots(items):
out = {'new': [], 'return': [], 'wildcard': []}
for it in items:
out[it['slot']].append(it)
return out
def test_v11_item9_compose_matrix():
"""A1-A8 of the item 9 acceptance criteria on deterministic pools."""
d, _c, db_path = p3_env()
def env():
conn = _sq_conn(db_path)
_v11_wipe(conn)
conn.commit()
return conn
try:
# --- A1: 30 fresh / 10 returns / wildcards -> 25: 21/2/2 ----------
conn = env()
ids = _v11_ids(conn, 60)
_v11_activate(conn, ids[0:28]) # 28 fresh
_v11_stage_fresh(conn, ids[0:28]) # (all wild-eligible)
_v11_activate(conn, ids[28:38]) # 10 returns
_v11_stage_returns(conn, ids[28:38])
conn.commit(); conn.close()
recipe, items, engine = _v11_compose(db_path)
slots = _slots(items)
assert len(items) == 25, len(items)
assert (recipe['new'], recipe['return'], recipe['wildcard']) \
== (21, 2, 2), recipe
assert (len(slots['new']), len(slots['return']),
len(slots['wildcard'])) == (21, 2, 2)
# pinned order: new -> return -> wildcard
roles = [it['slot'] for it in items]
assert roles == ['new'] * 21 + ['return'] * 2 + ['wildcard'] * 2, \
roles[:2]
# fresh picks ordered points DESC (non-increasing)
pts = [engine.points(it['id']) for it in slots['new']]
assert all(a >= b for a, b in zip(pts, pts[1:])), pts
# --- A2a: 5 fresh / 20 returns / wildcards -> 5/18/2 ---------------
conn = env()
ids = _v11_ids(conn, 60)
_v11_activate(conn, ids[0:3])
_v11_stage_fresh(conn, ids[0:3]) # 3 fresh-only
_v11_activate(conn, ids[3:5])
_v11_stage_fresh(conn, ids[3:5]) # 2 fresh+wild
_v11_activate(conn, ids[5:25]) # 20 returns
_v11_stage_returns(conn, ids[5:25])
conn.commit(); conn.close()
recipe, items, _e = _v11_compose(db_path)
assert len(items) == 25, len(items)
# Wildcards are BY DEFINITION never-swiped (wild pool ⊆ fresh pool),
# so on a 5-fresh day the 2 wilds come from those 5: the deck reads
# 5 fresh-total (3 new + 2 wild) + 20 second looks = 25 — Glenn's
# "5 fresh listed, rest second looks". The spec's "5 fresh + 18
# returns + 2 wild" arithmetic assumed 7 fresh-eligible listings;
# with 5 the pool-honest fill is 20 (implementer-verified).
assert (recipe['new'], recipe['return'], recipe['wildcard']) \
== (3, 20, 2), recipe
# --- A2b: same but the wildcard pool is dry -> 5/20/0 --------------
conn = env()
ids = _v11_ids(conn, 60)
_v11_activate(conn, ids[0:5])
_v11_stage_fresh(conn, ids[0:5], seen=True) # fresh, no wilds
_v11_activate(conn, ids[5:25]) # 20 returns
_v11_stage_returns(conn, ids[5:25]) #
conn.commit(); conn.close()
recipe, items, _e = _v11_compose(db_path)
assert len(items) == 25, len(items)
assert (recipe['new'], recipe['return'], recipe['wildcard']) \
== (5, 20, 0), recipe
# --- A3: 23 fresh / 5 returns / wildcards -> 21/2/2 (the sign-off
# --- sentence shape) ----------------------------------------------
conn = env()
ids = _v11_ids(conn, 60)
_v11_activate(conn, ids[0:23])
_v11_stage_fresh(conn, ids[0:23])
_v11_activate(conn, ids[23:28]) # 5 returns
_v11_stage_returns(conn, ids[23:28])
conn.commit(); conn.close()
recipe, items, _e = _v11_compose(db_path)
slots = _slots(items)
assert len(items) == 25 and len(slots['new']) == 21 \
and len(slots['return']) == 2 \
and len(slots['wildcard']) == 2, recipe
# --- A4: 0 fresh / 12 returns (2 nope) -> 12 returns, <=2 nopes,
# --- LAST_TWO excl: second compose repeats nothing -----------------
conn = env()
ids = _v11_ids(conn, 60)
_v11_activate(conn, ids[0:12])
_v11_stage_returns(conn, ids[0:10], 'maybe')
_v11_stage_returns(conn, ids[10:12], 'nope') # 2 re-nope cands
conn.commit(); conn.close()
recipe, items, _e = _v11_compose(db_path)
slots = _slots(items)
assert len(items) == 12 and len(slots['new']) == 0 \
and len(slots['return']) == 12 \
and len(slots['wildcard']) == 0, recipe
n_nopes = sum(1 for it in slots['return']
if it['decision'] == 'nope')
assert n_nopes <= 2, n_nopes
first_ids = {it['id'] for it in items}
# second compose on the same pool: LAST_TWO bars the 12 just served
# and returns stay one-shot -> nothing to serve
recipe2, items2, _e = _v11_compose(db_path)
assert len(items2) == 0, items2
assert not ({it['id'] for it in items2} & first_ids)
# --- A5: 40 fresh / 0 returns -> 25 then the 15 leftover, no
# --- overlap, fresh ordered points DESC ----------------------------
conn = env()
ids = _v11_ids(conn, 60)
_v11_activate(conn, ids[0:40])
_v11_stage_fresh(conn, ids[0:40])
# spread scores so the points DESC order check is meaningful
for k, lid in enumerate(ids[0:40]):
conn.execute("UPDATE listings SET score=? WHERE id=?",
(40 - k, lid))
conn.commit(); conn.close()
recipe, items, engine = _v11_compose(db_path)
assert len(items) == 25, len(items)
assert recipe['return'] == 0, recipe
first_ids = {it['id'] for it in items}
slots1 = _slots(items)
pts = [engine.points(it['id']) for it in slots1['new']]
# scores unique DESC -> fresh-slot points non-increasing (wildcards
# sit pinned at the back and don't participate in that order)
assert pts == sorted(pts, reverse=True), pts
recipe2, items2, _e = _v11_compose(db_path)
slots2 = _slots(items2)
assert recipe2['return'] == 0, recipe2
assert len(items2) == 15, len(items2)
second_ids = {it['id'] for it in items2}
assert not (first_ids & second_ids) # zero overlap
# --- A6: 0/0/0 -> empty composed section (FE side = item 8) --------
conn = env()
conn.commit(); conn.close()
recipe, items, _e = _v11_compose(db_path)
assert items == [], items
assert (recipe['new'], recipe['return'], recipe['wildcard']) \
== (0, 0, 0), recipe
# --- A7: family cap — fill-heavy cruiser pool: fresh/reserved hold
# --- <=4, fill raises return slots to <=8 --------------------------
conn = env()
ids = _v11_ids(conn, 60)
_v11_activate(conn, ids[0:40], family='cruiser')
_v11_stage_fresh(conn, ids[0:10], seen=True) # 10 fresh cruiser
_v11_stage_returns(conn, ids[10:40], 'maybe') # 30 cruiser rets
conn.commit(); conn.close()
recipe, items, _e = _v11_compose(db_path)
slots = _slots(items)
fam = {}
for it in items:
fam[it['family']] = fam.get(it['family'], 0) + 1
assert fam.get('cruiser', 0) <= 8, fam
assert len(slots['new']) == 2, recipe # fresh stops at cap 4
assert len(slots['return']) == 6, recipe # 2 reserved + 4 fill
assert (recipe['new'], recipe['return']) == (2, 6), recipe
# --- A8: re-nope gate — <=2 nope returns total; a rested item never
# --- returns; gate can empty the reserved slots --------------------
conn = env()
ids = _v11_ids(conn, 60)
_v11_activate(conn, ids[0:10])
_v11_stage_returns(conn, ids[0:10], 'maybe') # 10 maybes
_v11_activate(conn, ids[10:15], family='gatefam', score=100)
_v11_stage_returns(conn, ids[10:15], 'nope') # 5 nope re-nopes
# family net positive: gate passes for gatefam's nope candidates
_v11_stage_support(conn, ids[30:40], family='gatefam') # 10 likes
_v11_activate(conn, ids[15:16], family='gatefam')
_v11_stage_returns(conn, ids[15:16], 'maybe',
rests=[ids[15]]) # rested: r2 nope
conn.commit(); conn.close()
recipe, items, _e = _v11_compose(db_path)
slots = _slots(items)
assert len(items) == 12, len(items) # 10 maybe + 2 nope
n_nopes = sum(1 for it in slots['return']
if it['decision'] == 'nope')
assert n_nopes == 2, n_nopes
assert all(it['id'] != ids[15] for it in slots['return']) # rested
# gate-block: low-score nope family, net NOT positive -> reserved
# slots skipped; fill still caps at 2 nopes (gate-free fill rule)
conn = env()
ids = _v11_ids(conn, 60)
_v11_activate(conn, ids[0:3], family='blockfam', score=1)
_v11_stage_returns(conn, ids[0:3], 'nope') # 3 gate-blocked
conn.commit(); conn.close()
recipe, items, _e = _v11_compose(db_path)
slots = _slots(items)
assert recipe['return'] == 2, recipe # fill cap only
assert all(it['decision'] == 'nope'
for it in slots['return']), items
finally:
shutil.rmtree(d, ignore_errors=True)
P3_API_TESTS = [
('p3: events seeding idempotent (from swipes)', test_p3_event_seeding_idempotent),
('p3: swipe round math + clear-then-re-decide', test_p3_round_math_and_clear),
@@ -1295,6 +1757,20 @@ P3_API_TESTS = [
if API_DEPS:
TESTS += P3_API_TESTS
V11_TESTS = [
('v1.1: item 5 — section counter keys off in-section events',
test_v11_item5_section_counter),
('v1.1: item 7 — stats fresh = active minus swiped',
test_v11_item7_stats_fresh),
('v1.1: item 8/6 — pool counts, 0/0/0 empty compose, dry forge note',
test_v11_item8_pool_and_dry),
('v1.1: item 9 — batch formula v2 compose matrix A1-A8',
test_v11_item9_compose_matrix),
]
if API_DEPS:
TESTS += V11_TESTS
B1_TESTS = [
('b1: guarded migrations (imgs + last_photo_idx, idempotent)',
test_b1_migration_guarded),

View File

@@ -33,7 +33,8 @@ header{height:calc(50px + env(safe-area-inset-top,0px));display:flex;align-items
.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}
.nophoto{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:repeating-linear-gradient(45deg,#141419 0 14px,#18181f 14px 28px);color:#55555f;font-size:13px;text-align:center;padding:24px;line-height:1.6}
.card .photo{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.card .photo{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;filter:drop-shadow(0 6px 24px rgba(0,0,0,.45))}
.phblur{position:absolute;inset:-18px;background-size:cover;background-position:center;background-repeat:no-repeat;filter:blur(22px) brightness(.55) saturate(1.1);transform:scale(1.08);pointer-events:none}
.card .grad{position:absolute;left:0;right:0;bottom:0;height:52%;background:linear-gradient(180deg,rgba(0,0,0,0) 0%,rgba(0,0,0,.55) 55%,rgba(0,0,0,.88) 100%)}
.card .info{position:absolute;left:16px;right:16px;bottom:14px;z-index:3}
.chips{display:flex;gap:6px;margin-bottom:8px;flex-wrap:wrap}
@@ -66,8 +67,9 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
.dgrab{flex:none;height:26px;display:flex;align-items:center;justify-content:center;background:#0f0f13;cursor:grab;touch-action:none}
.dgrab i{width:42px;height:5px;border-radius:3px;background:rgba(255,255,255,.3);display:block}
.dclose{position:absolute;top:38px;left:14px;width:36px;height:36px;border-radius:50%;background:rgba(0,0,0,.55);color:#fff;border:0;font-size:17px;z-index:5;cursor:pointer}
.dhero{position:relative;height:34%;min-height:190px;flex:none;background:#17171c;touch-action:none}
.dphoto{width:100%;height:100%;object-fit:cover;display:block}
.dhero{position:relative;height:34%;min-height:190px;flex:none;background:#17171c;touch-action:none;overflow:hidden}
.dblur{position:absolute;inset:-18px;background-size:cover;background-position:center;background-repeat:no-repeat;filter:blur(22px) brightness(.55) saturate(1.1);transform:scale(1.08);pointer-events:none}
.dphoto{width:100%;height:100%;object-fit:contain;display:block;filter:drop-shadow(0 6px 24px rgba(0,0,0,.45))}
.dphoto.ph{opacity:.25}
.dherograd{position:absolute;left:0;right:0;bottom:0;height:70px;background:linear-gradient(transparent,rgba(15,15,19,.95))}
.dbody{flex:1;overflow-y:auto;padding:14px 18px 20px}
@@ -95,6 +97,10 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
.empty{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}
.empty.on{display:flex}
.empty b{color:#fff;font-size:16px}
/* item 8: loud exhausted state — section mode only (legacy .empty stays) */
.empty2{position:absolute;inset:6px 14px 2px;display:none;flex-direction:column;align-items:center;justify-content:center;gap:10px;border:1px dashed #4a4a55;border-radius:18px;background:#141419;color:var(--mut);text-align:center;padding:32px;font-size:14px;min-height:220px;z-index:3}
.empty2.on{display:flex}
.empty2 b{color:#fff;font-size:22px;font-weight:800}
/* list screen */
.list{position:absolute;inset:0;display:none;flex-direction:column;background:var(--bg);z-index:50;padding-bottom:68px}
.list.on{display:flex}
@@ -210,6 +216,7 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
<div class="stage" id="stage">
<div class="empty" id="empty"><b>You're all caught up.</b>New bikes arrive nightly — next import 08:30.<br>↺ brings the last card back.</div>
<div class="empty2" id="empty2"><b>No more new bikes!</b>New bikes arrive nightly — next import 08:30.<br>↺ brings the last card back.</div>
<div class="report" id="report">
<b>Section complete.</b>
<div id="repCounts"></div>
@@ -217,6 +224,7 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
<div id="repLine2"></div>
<button class="rforge" id="btnForge">Forge next 25</button>
<div class="rstatus" id="forgeStatus"></div>
<div class="rcap" id="dryCap" style="display:none">Catalog fully reviewed — fresh listings arrive with the next 08:30 import; showing second looks</div>
<div class="rmode" id="modeRow">
<span id="modeOnd" class="on">on demand</span><i class="sep">⇄</i><span id="modeStr">strict</span>
<div class="rcap" id="strictCap" style="display:none">Waiting for the nightly read — next section after the agent runs.</div>
@@ -242,7 +250,7 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
<div class="detail" id="detail">
<div class="dgrab" id="dgrab"><i></i></div>
<button class="dclose" id="dclose">⌄</button>
<div class="dhero"><img class="dphoto" id="dphoto" alt=""><div class="dherograd"></div></div>
<div class="dhero"><div class="dblur" id="dblur"></div><img class="dphoto" id="dphoto" alt=""><div class="dherograd"></div></div>
<div class="dbody" id="dbody">
<div class="dtitle" id="dtitle"></div>
<div class="drow"><div class="dprice" id="dprice"></div><div class="dsub" id="dsub"></div></div>
@@ -319,6 +327,7 @@ nav{height:calc(68px + env(safe-area-inset-bottom,0px));display:flex;align-items
<div class="tstatus" id="runStatus"></div>
</div>
<div class="trow"><span>Forge:</span><span id="tOnd" class="on">on demand</span><i>⇄</i><span id="tStr">strict</span></div>
<div class="trow"><span>Why breakdown:</span><span id="tRubOff" class="on">off</span><i>⇄</i><span id="tRubOn">on</span></div>
<div class="tmuted" id="tLastRun"></div>
</div>
</div>
@@ -509,8 +518,10 @@ function segHTML(n,cur){
if(!n||n<2) return '';
return `<div class="segments">${segBars(n,cur)}</div>`;
}
function escAttr(s){ return String(s).replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/'/g,'&#39;'); }
function phwrapHTML(src){
return `<div class="phwrap">${src?`<img class="photo" src="${src}" alt="" draggable="false">`:`<div class="nophoto">Photo pending — thumbnail backfill queued</div>`}</div>`;
const img=src?`<div class="phblur" style="background-image:url('${escAttr(src)}')"></div><img class="photo" src="${escAttr(src)}" alt="" draggable="false">`:`<div class="nophoto">Photo pending — thumbnail backfill queued</div>`;
return `<div class="phwrap">${img}</div>`;
}
function attachPhError(entry){
const wrap=entry.el.querySelector('.phwrap');
@@ -646,6 +657,12 @@ async function loadSection(){
finally{ deckLoading=false; }
maybeRefill();
}
/* item 8: the deck can serve nothing at all (pool all-zero) -> loud empty */
function poolDead(){
return !!(section && section.pool
&& section.pool.fresh===0 && section.pool.returns===0
&& section.pool.wildcards===0);
}
function maybeRefill(){
if(legacyMode){
if(buffer.length<DEPTH&&deckCursor&&!deckLoaded) loadDeck();
@@ -653,23 +670,31 @@ function maybeRefill(){
return;
}
if(!pile.length&&!buffer.length&&!deckLoading){
if(section&&sectDecided>=sectTotal){
if(poolDead()){
// nothing to serve at all: the loud empty owns the stage (no report)
$('empty2').classList.add('on');
$('report').classList.remove('on');
$('empty').classList.remove('on');
}else if(section&&sectDecided>=sectTotal){
// locally exhausted (last POSTs may still be flushing — the report
// shows from localDecisions; a quiet resync freshens counts and the
// server's report flip, rate-limited so a failing last POST can't
// cause a resync loop)
$('report').classList.add('on');
$('empty').classList.remove('on');
$('empty2').classList.remove('on');
if(!section.exhausted&&Date.now()-lastResyncAt>2000){
lastResyncAt=Date.now();
loadSection();
}
}else if(section){
$('empty').classList.remove('on'); $('report').classList.remove('on');
$('empty2').classList.remove('on');
}
}else{
$('empty').classList.remove('on');
$('report').classList.remove('on');
$('empty2').classList.remove('on');
}
}
@@ -681,7 +706,7 @@ function commit(el,dir){
const act= dir==='maybe'?'maybe':dir;
setDecision(t.d.id, act, (!legacyMode&&section&&!section.exhausted)?section.section.id:null,
nPhotos(t.d)>1?(t.cur||0):null); // B1: photo on screen at strike
sectDecided++;
sectDecided=Math.min(sectTotal, sectDecided+1); // clamp: never past the total
paintSect();
flyOut(el,dir);
fillPile(); relayer();
@@ -717,6 +742,7 @@ function undo(){
preloadPhotos();
$('empty').classList.remove('on');
$('report').classList.remove('on');
$('empty2').classList.remove('on');
}
$('btnLike').onclick=()=>{ if(pile[0]) commit(pile[0].el,'like'); };
$('btnNope').onclick=()=>{ if(pile[0]) commit(pile[0].el,'nope'); };
@@ -751,27 +777,34 @@ function upH(e){
else if(dy<-140) commit(el,'maybe');
else { el.style.transform=''; setStamps(el,0,0,0); if(!moved && e.type==='pointerup' && isTop(el)) tapZone(pile[0],e); }
}
/* §11.2/§11.3/§11.4 tap zones: sides flip (clamped), center = fullscreen.
The old tap-anywhere -> dossier gesture is retired (ⓘ stays the door). */
/* §11.4 v1.1 tap zones: sides flip (clamped), CENTER = dossier (bike data
first — the old center-tap→fullscreen and tap-anywhere→dossier gestures
are retired). The deck dossier remembers its pile entry so a viewer
opened from its hero walks back to it on Esc. */
function tapZone(entry,e){
const n=nPhotos(entry.d);
if(n<1 || !entry.d.img) return;
const r=stage.getBoundingClientRect();
const rel=e.clientX-r.left, w=r.width||360;
if(rel>=w/3 && rel<=w*2/3) openViewer(entry.d, entry.cur||0, {type:'card',entry});
else flipCard(entry, rel<w/3?-1:1);
if(rel>=w/3 && rel<=w*2/3){
dEntry=entry; // live pile entry (cur photo index)
openDetail(entry.d,{type:'deck'});
}else{
flipCard(entry, rel<w/3?-1:1); // no-ops on single/no-photo cards
}
}
/* ---------- docs/mockup core: fullscreen dossier ---------- */
let dCtx=null;
let dData=null; // B1: dossier payload (hero -> viewer)
let dEntry=null; // v1.1: pile entry when opened from the deck
function openDetail(data,ctx){
dCtx=ctx||null;
dData=data;
dEntry=null; // only tapZone re-sets it (deck path)
const ph=$('dphoto');
if(data.img){ ph.src=data.img; ph.classList.remove('ph'); }
else { ph.removeAttribute('src'); ph.classList.add('ph'); }
ph.onerror=()=>{ ph.removeAttribute('src'); ph.classList.add('ph'); };
const blur=$('dblur');
if(data.img){ ph.src=data.img; ph.classList.remove('ph'); blur.style.backgroundImage='url("'+data.img+'")'; }
else { ph.removeAttribute('src'); ph.classList.add('ph'); blur.style.backgroundImage='none'; }
ph.onerror=()=>{ ph.removeAttribute('src'); ph.classList.add('ph'); blur.style.backgroundImage='none'; };
$('dtitle').textContent=data.title||'';
$('dprice').textContent=priceFor(data);
$('dsub').textContent=subFor(data);
@@ -794,7 +827,9 @@ function openDetail(data,ctx){
$('detail').classList.add('on'); $('dback').classList.add('on');
$('dbody').scrollTop=0;
}
/* P3 dossier rank block: gauge + points + strongest ± lines + audit footer */
/* P3 dossier rank block: gauge + points% minimal; the full "why" breakdown
and the audit footer render only when prefs.rubric_debug === 'on' (§10.5). */
function rubricOn(){ return !!(section&&section.prefs&&section.prefs.rubric_debug==='on'); }
function fillRank(data){
if(!data||data.tank==null||data.tank.value==null){
$('drank').style.display='none';
@@ -802,24 +837,30 @@ function fillRank(data){
}
$('drank').style.display='flex';
$('drankTank').innerHTML=tankSVG(data.tank,true);
$('dpts').textContent=data.tank.value+'/100';
const lines=(data.points_breakdown||[]).slice()
.sort((a,b)=>Math.abs(b.value)-Math.abs(a.value)).slice(0,4);
$('dlines').innerHTML=lines.map(l=>{
const lbl= l.source==='agent'?('agent: '+l.label):l.label;
const n= l.value>=0?(' +'+l.value):(' '+l.value);
return `<div class="${l.value>=0?'pos':'neg'}">· ${lbl}${n}</div>`;
}).join('');
const ri= section&&section.read_info;
$('dfoot').textContent= ri?`from ${ri.events} strikes · read ${relTime(ri.profile_at)}`:'';
// list/matches payloads carry no breakdown — fill it on the quiet
if(!data.points_breakdown&&data.id&&!legacyMode){
getJSON('/api/listing/'+data.id).then(full=>{
if(full&&full.points_breakdown&&dCtx) fillRank(full);
});
$('dpts').textContent=(data.tank.value|0)+'%';
if(rubricOn()){
const lines=(data.points_breakdown||[]).slice()
.sort((a,b)=>Math.abs(b.value)-Math.abs(a.value)).slice(0,4);
$('dlines').innerHTML=lines.map(l=>{
const lbl= l.source==='agent'?('agent: '+l.label):l.label;
const n= l.value>=0?(' +'+l.value):(' '+l.value);
return `<div class="${l.value>=0?'pos':'neg'}">· ${lbl}${n}</div>`;
}).join('');
const ri= section&&section.read_info;
$('dfoot').textContent= ri?`from ${ri.events} strikes · read ${relTime(ri.profile_at)}`:'';
// list/matches payloads carry no breakdown — fill it on the quiet
if(!data.points_breakdown&&data.id&&!legacyMode){
getJSON('/api/listing/'+data.id).then(full=>{
if(full&&full.points_breakdown&&dCtx) fillRank(full);
});
}
}else{
// minimal display: gauge + % only; skip the quiet enrichment fetch
$('dlines').innerHTML='';
$('dfoot').textContent='';
}
}
function closeDetail(){ const d=$('detail'); d.style.transition=''; d.style.transform=''; d.classList.remove('on'); $('dback').classList.remove('on'); dCtx=null; }
function closeDetail(){ const d=$('detail'); d.style.transition=''; d.style.transform=''; d.classList.remove('on'); $('dback').classList.remove('on'); dCtx=null; dEntry=null; }
$('dclose').onclick=closeDetail;
$('dclose').addEventListener('pointerdown',e=>e.stopPropagation());
/* pull-down-to-close (grabber bar + photo) */
@@ -829,10 +870,12 @@ function dMoveH(e){ if(dDragY===null) return; const dy=Math.max(0,e.clientY-dDra
function dEndH(e){ if(dDragY===null) return; const dy=Math.max(0,e.clientY-dDragY); dDragY=null;
if(dy>110){ closeDetail(); }
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 photo 0 */
/* B1 §11.3: a tap on the dossier HERO opens the fullscreen viewer at
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. */
if(e.type==='pointerup' && dy<=6 && e.currentTarget&&e.currentTarget.classList
&& e.currentTarget.classList.contains('dhero') && dData&&dData.img){
openViewer(dData,0,{type:'dossier'});
openViewer(dData,0,{type:'dossier', backToDetail:dEntry});
} } }
[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){
@@ -881,6 +924,19 @@ function closeViewer(){
v.style.transition=''; v.style.transform='';
vCtx=null; vPtrs.clear(); vPinch=null; vDrag=null;
}
/* v1.1 walk-back chain: when the viewer was reached from the deck dossier
hero, Esc returns to the dossier (photo 0) instead of the deck. */
function vWalkBack(){
const back=vCtx&&vCtx.back;
if(back&&back.backToDetail){
const item=vCtx.item;
closeViewer();
openDetail(item, back.backToDetail);
dEntry=back.backToDetail.entry||null; // keep the chain repeatable
} else {
closeViewer();
}
}
$('vback').addEventListener('click',closeViewer);
$('vclose').onclick=closeViewer;
$('vclose').addEventListener('pointerdown',e=>e.stopPropagation());
@@ -1127,7 +1183,8 @@ let badgeFired=false;
async function loadStats(){
const res=await getJSON('/api/stats');
if(!res) return;
$('pill').innerHTML=`<b>${res.live}</b> live`+(res.new>0?` · <b>${res.new}</b> new`:'');
const fresh=typeof res.fresh==='number'?res.fresh:null; // old API: no segment
$('pill').innerHTML=`<b>${res.live}</b> live${fresh!=null?` · <b>${fresh}</b> fresh`:''}`+(res.new>0?` · <b>${res.new}</b> new`:'');
$('lsub').innerHTML=`${res.live} active · `+(res.new>0?`<b style="color:#fff">${res.new} new</b>`:res.new+' new')+' since your last visit';
if(!badgeFired){
badgeFired=true;
@@ -1140,7 +1197,7 @@ let sectDecided=0, sectTotal=0;
function paintSect(){
const t=$('sect');
if(legacyMode||!section){ t.textContent=''; return; }
t.textContent=`${sectDecided}/${sectTotal}`;
t.textContent=`${Math.min(sectDecided,sectTotal)}/${sectTotal}`; // clamp: never paints past the total
t.classList.toggle('hot',sectDecided>=sectTotal);
}
function paintMode(){
@@ -1156,14 +1213,20 @@ function paintMode(){
}
function updateSectionUI(body){
sectTotal=body.progress.total;
// item 6: the dry-catalog caption rides every hydrate (legacy API -> absent)
$('dryCap').style.display= dryLabel(body)?'':'none';
let decided=0;
for(const it of (body.items||[])){
const local=localDecisions.get(it.id);
if(local===undefined? it.decision!=null : local!=null) decided++;
// item 5: server truth = decided DURING this section (an in-section
// event), never the lifetime decision a second look wears into it;
// local intent wins while a swipe's POST is in flight
if(local===undefined? !!it.decided_this_section : local!=null) decided++;
}
sectDecided=decided;
paintSect();
paintMode();
paintRubricMode();
const c=body.counts||{};
$('repCounts').innerHTML=`♥ ${c.likes||0} · ★ ${c.maybes||0} · ✕ ${c.nopes||0}`;
const hits=[];
@@ -1177,6 +1240,28 @@ async function setMode(m){
}
$('modeOnd').onclick=()=>setMode('ondemand');
$('modeStr').onclick=()=>setMode('strict');
function paintRubricMode(){
const on=rubricOn();
$('tRubOff').classList.toggle('on',!on);
$('tRubOn').classList.toggle('on',on);
}
async function setRubricDebug(m){
const res=await fetch('/api/prefs',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({key:'rubric_debug',value:m})}).catch(()=>null);
if(res&&res.ok){
if(section){ section.prefs=section.prefs||{}; section.prefs.rubric_debug=m; }
paintRubricMode();
if(!legacyMode) loadSection(); // repaint any dossier already open
}
}
$('tRubOff').onclick=()=>setRubricDebug('off');
$('tRubOn').onclick=()=>setRubricDebug('on');
/* item 6: dry catalog — a forged batch with zero fresh cards is labeled,
never silent (BACKLOG "Dry-catalog messaging"). */
const DRY_MSG='Catalog fully reviewed — fresh listings arrive with the next 08:30 import; showing second looks';
function dryLabel(body){
return !!(body && body.recipe && body.recipe.new===0
&& body.items && body.items.length>0);
}
$('btnForge').onclick=async()=>{
if(forgeBusy||!section) return;
forgeBusy=true;
@@ -1186,8 +1271,10 @@ $('btnForge').onclick=async()=>{
const res=await fetch('/api/section/forge',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});
const body=await res.json();
if(res.ok){
$('forgeStatus').textContent= body.note&&body.note.indexOf('fallback')>=0
?'Agent offline — forging on the last read.':'';
$('forgeStatus').textContent= dryLabel(body)
?DRY_MSG
:(body.note&&body.note.indexOf('fallback')>=0
?'Agent offline — forging on the last read.':'');
section=body;
buffer.length=0;
const live=new Set([...pile.map(c=>c.d.id),...hist.map(h=>h.id)]);
@@ -1196,6 +1283,12 @@ $('btnForge').onclick=async()=>{
fillPile();
updateSectionUI(body);
if(pile.length){ $('report').classList.remove('on'); }
// item 8: a zero-item forge on a fully drained catalog -> empty2,
// no lone Forge button inviting a wasted agent run
if((body.items||[]).length===0 && poolDead()){
$('report').classList.remove('on');
$('empty2').classList.add('on');
}
}else{
$('forgeStatus').textContent= body.detail||'Forge failed';
paintMode();
@@ -1260,13 +1353,28 @@ document.querySelectorAll('.tab').forEach(t=>t.onclick=()=>{
else if(name==='trends') fetchTrends();
});
/* ---------- desktop keyboard arrows (DESIGN.md: v1 frontend) ---------- */
/* ---------- v1.1 keyboard map (BACKLOG "Shortcuts"): ← nope · → like ·
↑ maybe · ↓ undo · Backspace = undo alias (kept for muscle memory) ·
Esc closes the top open sheet (viewer → dossier → deck). Arrows act only
on the deck; text-input focus and open sheets swallow them; arrow-key
defaults are prevented so no page scroll can fire. -------------------- */
document.addEventListener('keydown',e=>{
if(e.target.tagName==='INPUT'||$('detail').classList.contains('on')||$('viewer').classList.contains('on')) return;
if(e.key==='ArrowRight'){ if(pile[0]) commit(pile[0].el,'like'); }
else if(e.key==='ArrowLeft'){ if(pile[0]) commit(pile[0].el,'nope'); }
else if(e.key==='ArrowUp'){ if(pile[0]) commit(pile[0].el,'maybe'); }
else if(e.key==='Backspace'){ undo(); }
const t=e.target;
if(t && (t.tagName==='INPUT'||t.tagName==='TEXTAREA'||t.tagName==='SELECT'||t.isContentEditable)) return;
const k=e.key;
if(k==='Escape'){
if($('viewer').classList.contains('on')) vWalkBack(); // viewer → dossier (when reached from it) → deck
else if($('detail').classList.contains('on')) closeDetail();
return; // Esc never forges or navigates tabs
}
if(k==='ArrowDown'){ e.preventDefault(); undo(); return; }
if(k==='Backspace'){ undo(); return; }
if(k==='ArrowLeft'||k==='ArrowRight'||k==='ArrowUp'){
e.preventDefault();
if($('detail').classList.contains('on')||$('viewer').classList.contains('on')) return;
const el=pile[0]&&pile[0].el;
if(el) commit(el, k==='ArrowLeft'?'nope':k==='ArrowRight'?'like':'maybe');
}
});
/* ---------- boot ---------- */

View File

@@ -162,9 +162,9 @@ Semantics:
- Round = prior events for that listing + 1, assigned at write time. Rounds cap at 2 for engine influence (any later events weigh as round 2; v1 returns never produce rounds >2 by design).
- **Migration seeding:** when `swipe_events` is empty and `swipes` has rows → insert one round-1 event per swipe row (created_at copied). Only-when-empty, hence idempotent.
- **Sections:** at most ONE `open` section at a time. The deck = that section's `section_items` in `position` order, filtered to items undecided at read. Exhausted = no item undecided → `status='report'`. Forge = close current + open new. First-ever read composes a cold section (rubric-weighted, w=0).
- **Returns eligibility (v1 contract):** a verdict exists (like/maybe/nope in `swipes`); listing `active`; NOT in either of the previous two sections; no round≥2 `nope` ever (rested); not already returned once (round cap). Selection prefers maybe > like > nope; nope candidates must be "surprising" (points ≥55 or net-positive family). Max 5 returns per section, ≤2 of them nopes.
- **Returns eligibility (v1.1 contract, amends the frozen ≤5 rule):** a verdict exists (like/maybe/nope in `swipes`); listing `active`; NOT in either of the previous two sections; no round≥2 `nope` ever (rested); not already returned once (round cap). Selection prefers maybe > like > nope; nope candidates must be "surprising" (points ≥55 or net-positive family) for the RESERVED slots only. Every batch carries ≥2 returns whenever eligible stock exists and fills the remainder up to 25 when fresh < 23; ≤2 nope-verdict returns per batch; fill returns relax the per-family cap from 4 to 8 (fill slots only).
- **`points` is computed, not stored** (deterministic from events + profile; a cache is allowed only if it never changes semantics).
- **prefs:** `forge_mode` ('ondemand' default | 'strict'). Existing keys unchanged.
- **prefs:** `forge_mode` ('ondemand' default | 'strict') · `rubric_debug` ('off' default | 'on' — dossier "why" breakdown visibility; v1.1). Existing keys unchanged.
- **Legacy deck semantics:** `/api/deck` (cursor paging; 7-day maybe re-admit) stays as a read-only fallback for debugging; sections are the production flow.
## B1 additions — frozen 2026-11-10 (photo experience v2)

View File

@@ -26,7 +26,7 @@ Deterministic, explainable, pure-Python. Learning reads `swipe_events` only.
**Score.** `taste_raw` = Σ shrunk weights over the listing's values; `taste_norm` = percentile rank among active listings (0–100). Blend: `w = min(0.85, N/60)` where N = total events; `points = clip( round( (1−w)·rubric + w·taste_norm + agent_adj ), 0, 100 )`. `agent_adj` = Σ profile adjustments (clamped ±10 per listing). Breakdown for the dossier: rubric share · top 3 ± taste features · agent lines — all source-labeled.
**Section recipe.** 25 cards = 2 wildcards + ≤5 returns + remainder new (points DESC). Constraints: ≤4 per family per section; ≥3 price bands when the pool allows; shortfalls fill from new.
**Section recipe.** Every batch targets 25 cards = fresh first (up to 23 slots) + ≥2 second looks whenever eligible stock exists + the 2 wildcard slots (wildcards draw from the fresh pool). When fresh < the remainder, second looks fill up to 25 (family cap relaxes to 8 for fill returns only); leftover fresh rolls to the next batch; fresh/return shortfalls are never padded — a drained pool yields a short (or empty) section. Constraints: ≤4 per family per section for fresh + reserved returns; ≥3 price bands when the pool allows.
**Wildcards.** Candidates: active, unseen, not in the last two sections. Exclusions: families with ≥3 cumulative nopes and net-negative weight. Prefer: different family AND different price band than the section's top new items. Score = `0.5·points + 0.5·novelty` (novelty = distance from the liked-profile centroid). Picks: 2 per section.