Spaces:
Sleeping
Sleeping
Ship Plan timeline with thick feedback, priors, and P1 Seligman scope lock.
Browse filesFiles changed (28)
- README.md+6-2
- app/config.py+7
- app/main.py+14-1
- app/paths.py+23-1
- app/routers/agent.pyAdded+170
- app/routers/plan.pyAdded+201
- app/schedule_math.pyAdded+338
- app/schedule_reschedule.pyAdded+358
- app/schedule_store.pyAdded+422
- app/schedule_templates.pyAdded+192
- docs/SCHEDULE.mdAdded+138
- frontend/src/api.ts+165
- frontend/src/components/BlockSheet.tsxAdded+336
- frontend/src/components/TabBar.tsx+8-15
- frontend/src/components/Timeline.tsxAdded+103
- frontend/src/main.tsx+2
- frontend/src/pages/Home.tsx+85-3
- frontend/src/pages/Plan.tsxAdded+151
- frontend/src/router.tsx+3
- frontend/src/styles/app.css+101
- static/assets/index-DNPW78XL.css → static/assets/index-6RturTFo.cssRenamed+1-1
- static/assets/index-B-lUWqRt.jsDeleted
- static/assets/index-B-lUWqRt.js.mapDeleted
- static/assets/index-D3LLeLlA.jsAdded
- static/assets/index-D3LLeLlA.js.mapAdded
- static/index.html+2-2
- static/sw.js+1-1
- tests/test_schedule_math.pyAdded+117
32 unmodified lines3334353637383940414232 unmodified lines- `SESSION_MAX_AGE_SEC`: signed-session lifetime (default `604800`)- `LOGIN_RATE_LIMIT`: login attempts per window (default `10`)- `LOGIN_RATE_WINDOW_SEC`: login window in seconds (default `900`)Additional coach-related variables are documented in `docs/BACKEND.md`.## Frontend (F0–F1)```textcd frontend32 unmodified lines333435363738394041424344454632 unmodified lines- `SESSION_MAX_AGE_SEC`: signed-session lifetime (default `604800`)- `LOGIN_RATE_LIMIT`: login attempts per window (default `10`)- `LOGIN_RATE_WINDOW_SEC`: login window in seconds (default `900`)- `AGENT_TOKEN`: optional Bearer token for Cursor agent plan pull/push- `RESCHEDULE_MIN_GAP_MIN`: cooldown between auto-reschedules (default `90`)Coach and schedule details: `docs/BACKEND.md`, `docs/SCHEDULE.md`.## FrontendNav: **Home | Plan | (+) Log | Daily | Settings** (History via Home).```textcd frontend
43 unmodified lines44454647484943 unmodified lineslogin_rate_window_sec: int = 900max_body_bytes: int = 65536@propertydef is_prod(self) -> bool:"""Return whether production-only security behavior is enabled."""43 unmodified lines4445464748495051525354555643 unmodified lineslogin_rate_window_sec: int = 900max_body_bytes: int = 65536agent_token: str | None = Nonereschedule_min_gap_min: int = 90schedule_day_start: str = "06:00"schedule_day_end: str = "23:00"schedule_timezone: str = "Africa/Dar_es_Salaam"schedule_max_blocks: int = 7@propertydef is_prod(self) -> bool:"""Return whether production-only security behavior is enabled."""
20 unmodified lines212223242526272862 unmodified lines91929394959614 unmodified lines11111211311411511649 unmodified lines16616716816917017120 unmodified linesfrom app.coach_service import CoachServicefrom app.models import errfrom app.paths import Pathsfrom app.routers import auth, coach, daily, debug, entries, export, health, statsfrom app.routers import settings as settings_routerfrom app.store_config import ConfigStorefrom app.store_daily import DailyStorefrom app.store_entries import EntryStore62 unmodified linestrace_store = TraceStore(paths, trace_limit=settings.coach_trace_limit)trace_store.ensure_brief()coach_service = CoachService(settings, entry_store, daily_store, trace_store)@asynccontextmanagerasync def lifespan(_app: FastAPI) -> AsyncIterator[None]:14 unmodified linesapp.state.daily_store = daily_storeapp.state.trace_store = trace_storeapp.state.coach_service = coach_serviceapp.add_middleware(BodySizeMiddleware, max_bytes=settings.max_body_bytes)app.add_middleware(49 unmodified linesapp.include_router(debug.router)app.include_router(export.router)app.include_router(settings_router.router)static_dir = Path("static")if static_dir.is_dir():20 unmodified lines2122232425262728293062 unmodified lines9394959697989910010110210310410514 unmodified lines12012112212312412512612749 unmodified lines17717817918018118218318420 unmodified linesfrom app.coach_service import CoachServicefrom app.models import errfrom app.paths import Pathsfrom app.routers import agent, auth, coach, daily, debug, entries, export, health, plan, statsfrom app.routers import settings as settings_routerfrom app.schedule_reschedule import RescheduleServicefrom app.schedule_store import ScheduleStorefrom app.store_config import ConfigStorefrom app.store_daily import DailyStorefrom app.store_entries import EntryStore62 unmodified linestrace_store = TraceStore(paths, trace_limit=settings.coach_trace_limit)trace_store.ensure_brief()coach_service = CoachService(settings, entry_store, daily_store, trace_store)schedule_store = ScheduleStore(paths,shrink_k=settings.stats_shrink_k,max_blocks=settings.schedule_max_blocks,)schedule_store.recompute_and_save_priors()reschedule_service = RescheduleService(settings, schedule_store)@asynccontextmanagerasync def lifespan(_app: FastAPI) -> AsyncIterator[None]:14 unmodified linesapp.state.daily_store = daily_storeapp.state.trace_store = trace_storeapp.state.coach_service = coach_serviceapp.state.schedule_store = schedule_storeapp.state.reschedule_service = reschedule_serviceapp.add_middleware(BodySizeMiddleware, max_bytes=settings.max_body_bytes)app.add_middleware(49 unmodified linesapp.include_router(debug.router)app.include_router(export.router)app.include_router(settings_router.router)app.include_router(plan.router)app.include_router(agent.router)static_dir = Path("static")if static_dir.is_dir():
35 unmodified lines36373839404142434435 unmodified linesdef coach_brief(self) -> Path:return self.root / "coach_brief.md"def ensure(self) -> None:"""Create the data directory and initial empty JSONL files."""self.root.mkdir(parents=True, exist_ok=True)for path in (self.entries, self.daily, self.traces):path.touch(exist_ok=True)35 unmodified lines3637383940414243444546474849505152535455565758596061626364656635 unmodified linesdef coach_brief(self) -> Path:return self.root / "coach_brief.md"@propertydef schedule_dir(self) -> Path:return self.root / "schedule"@propertydef schedule_priors(self) -> Path:return self.schedule_dir / "priors.json"@propertydef schedule_feedback(self) -> Path:return self.schedule_dir / "feedback.jsonl"@propertydef schedule_meta(self) -> Path:return self.schedule_dir / "meta.json"def plan_path(self, day: str) -> Path:"""Return the JSON path for one calendar day's plan."""return self.schedule_dir / f"plan-{day}.json"def ensure(self) -> None:"""Create the data directory and initial empty JSONL files."""self.root.mkdir(parents=True, exist_ok=True)self.schedule_dir.mkdir(parents=True, exist_ok=True)for path in (self.entries, self.daily, self.traces, self.schedule_feedback):path.touch(exist_ok=True)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""Agent (Cursor) schedule endpoints using Bearer AGENT_TOKEN or session.
GET context packs priors, risks, and constraints; PUT replaces the day plan."""
from __future__ import annotations
import hmacfrom datetime import date, datetime, timedelta, timezonefrom typing import Any
from fastapi import APIRouter, Depends, Request, status
from app.deps import require_loginfrom app.models import ApiEnvelope, err, okfrom app.schedule_math import capacity_hint, trigger_operatorsfrom app.schedule_store import DayPlanPut
router = APIRouter(prefix="/api/agent", tags=["agent"])
def require_agent_or_login(request: Request) -> str: """Allow AGENT_TOKEN bearer or a valid human session."""
settings = request.app.state.settings auth = request.headers.get("authorization") or "" if auth.lower().startswith("bearer ") and settings.agent_token: token = auth[7:].strip() if hmac.compare_digest(token, settings.agent_token): return "agent" # Fall back to session login require_login(request) return "session"
@router.get("/context", response_model=ApiEnvelope)def agent_context( request: Request, day: date | None = None, _auth: str = Depends(require_agent_or_login),) -> dict[str, Any]: settings = request.app.state.settings target = day or datetime.now(timezone.utc).date() day_s = target.isoformat() store = request.app.state.schedule_store entry_store = request.app.state.entry_store daily_store = request.app.state.daily_store
now = datetime.now(timezone.utc) since = now - timedelta(hours=48) hour_ago = now - timedelta(hours=1) yesterday = (target - timedelta(days=1)).isoformat()
risk_tags = { "urge", "court", "comparison", "corn", "daydream", "bully", "family", "shame", "rerun", "home", "spain", "build", } entries_48h = [] tags_1h: list[str] = [] triggers_y: list[str] = [] for entry in entry_store._load(): ts = entry.ts if entry.ts.tzinfo else entry.ts.replace(tzinfo=timezone.utc) if ts < since: continue item = { "id": entry.id, "ts": entry.ts.isoformat(), "tags": entry.tags, "emotions": entry.emotions, "intensity": entry.intensity, "remedy": entry.remedy, "result": entry.result.value, "happened": entry.happened[:280], } entries_48h.append(item) hit = sorted((set(entry.tags) | set(entry.emotions)) & risk_tags) if ts >= hour_ago: tags_1h.extend(hit) if entry.ts.date().isoformat() == yesterday: triggers_y.extend(hit)
tags_1h = sorted(set(tags_1h)) triggers_y = sorted(set(triggers_y)) y_daily = daily_store.get(date.fromisoformat(yesterday)) t_daily = daily_store.get(target) if y_daily: if y_daily.court == "court": triggers_y.append("court") if y_daily.corn_sessions >= 2: triggers_y.append("corn") if y_daily.daydream == "fc": triggers_y.append("daydream") triggers_y = sorted(set(triggers_y))
risk_score = float(len(tags_1h)) last_hour_high = bool({"urge", "court", "corn", "rerun"} & set(tags_1h)) cap = capacity_hint( risk_1h_score=risk_score, triggers_yesterday=triggers_y, yesterday_trigger=len(triggers_y) > 0, last_hour_high=last_hour_high, ) ops = trigger_operators(risk_1h_tags=tags_1h, triggers_yesterday=triggers_y) pending = sum( 1 for e in entry_store._load() if e.result.value == "pending" ) priors = store.load_priors()
return ok( { "date": day_s, "timezone": settings.schedule_timezone, "now": now.isoformat(), "daily_yesterday": y_daily.model_dump(mode="json") if y_daily else None, "daily_today": t_daily.model_dump(mode="json") if t_daily else None, "entries_last_48h": entries_48h, "risk_1h": {"score": risk_score, "tags": tags_1h, "high": last_hour_high}, "triggers_yesterday": triggers_y, "capacity_hint": cap, "operators": ops, "priors": list(priors.values()), "server_priors_markdown": store.priors_table(), "current_plan": store.plan_with_feedback(day_s), "pending_entries_count": pending, "templates": store.templates(), "constraints": { "max_blocks": settings.schedule_max_blocks, "must_include_explore_or_restore": True, "p0_locked": True, "pad_with_d_hat": True, "day_start": settings.schedule_day_start, "day_end": settings.schedule_day_end, "scope": "P1_thin_loop", "no_perma_fields": True, "ev_formula_locked": True, "schedule_does_not_replace_daily_or_log": True, }, "formulas": ( "EV=P(done)*U+γ*I+η*Fun-λt*d_hat-λm*cost-λf*FSE (locked; no δ/H/PERMA). " "d_hat=(n/(n+m))*mean_actual+(m/(n+m))*prior. " "On trigger_day: raise λ_f and η; P0 only overrides. " "Escape≠explore. Server owns p_helped/rank/picks from logs." ), } )
@router.put("/plan/{day}", response_model=ApiEnvelope)def agent_put_plan( request: Request, day: date, body: DayPlanPut, _auth: str = Depends(require_agent_or_login),) -> object: put = body.model_copy(update={"source": body.source or "cursor"}) try: request.app.state.schedule_store.save_plan(day.isoformat(), put) return ok(request.app.state.schedule_store.plan_with_feedback(day.isoformat())) except ValueError as exc: return err("validation_error", str(exc), status.HTTP_422_UNPROCESSABLE_ENTITY)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201"""Human schedule/plan routes: CRUD, feedback, priors, templates, reschedule.
Session-authenticated; mirrors the app envelope pattern."""
from __future__ import annotations
from datetime import date, datetime, timedelta, timezonefrom typing import Any
from fastapi import APIRouter, Depends, Request, statusfrom pydantic import BaseModel, Field
from app.deps import require_loginfrom app.models import ApiEnvelope, err, okfrom app.schedule_math import capacity_hint, trigger_operatorsfrom app.schedule_store import BlockCreate, BlockFeedback, BlockPatch, DayPlanPut
router = APIRouter(tags=["plan"], dependencies=[Depends(require_login)])
class RescheduleBody(BaseModel): reason: str = "user" force: bool = False
class FeedbackBody(BlockFeedback): block_id: str date: str | None = None
def _store(request: Request): return request.app.state.schedule_store
def _risk_from_entries(request: Request) -> tuple[float, list[str], list[str]]: """Derive risk_1h and yesterday triggers from recent entries + daily."""
now = datetime.now(timezone.utc) hour_ago = now - timedelta(hours=1) yesterday = (now.date() - timedelta(days=1)).isoformat() risk_tags = { "urge", "court", "comparison", "corn", "daydream", "bully", "family", "shame", "rerun", } tags_1h: list[str] = [] triggers_y: list[str] = [] for entry in request.app.state.entry_store._load(): ts = entry.ts if ts.tzinfo is None: ts = ts.replace(tzinfo=timezone.utc) entry_tags = set(entry.tags) | set(entry.emotions) hit = sorted(entry_tags & risk_tags) if ts >= hour_ago: tags_1h.extend(hit) if entry.ts.date().isoformat() == yesterday: triggers_y.extend(hit) try: y_daily = request.app.state.daily_store.get(date.fromisoformat(yesterday)) if y_daily: if y_daily.court == "court": triggers_y.append("court") if y_daily.corn_sessions >= 2: triggers_y.append("corn") if y_daily.daydream == "fc": triggers_y.append("daydream") except Exception: # noqa: BLE001 pass tags_1h = sorted(set(tags_1h)) triggers_y = sorted(set(triggers_y)) score = float(len(tags_1h)) last_hour_high = bool( {"urge", "court", "corn", "rerun"} & set(tags_1h) ) return score, tags_1h, triggers_y, last_hour_high
@router.get("/api/plan/{day}", response_model=ApiEnvelope)def get_plan(request: Request, day: date) -> dict[str, Any]: return ok(_store(request).plan_with_feedback(day.isoformat()))
@router.put("/api/plan/{day}", response_model=ApiEnvelope)def put_plan(request: Request, day: date, body: DayPlanPut) -> object: try: put = body.model_copy(update={"source": body.source or "user"}) _store(request).save_plan(day.isoformat(), put) return ok(_store(request).plan_with_feedback(day.isoformat())) except ValueError as exc: return err("validation_error", str(exc), status.HTTP_422_UNPROCESSABLE_ENTITY)
@router.post("/api/plan/{day}/blocks", response_model=ApiEnvelope)def add_block(request: Request, day: date, body: BlockCreate) -> object: try: _store(request).add_block(day.isoformat(), body) return ok(_store(request).plan_with_feedback(day.isoformat())) except ValueError as exc: return err("validation_error", str(exc), status.HTTP_422_UNPROCESSABLE_ENTITY)
@router.patch("/api/plan/{day}/blocks/{block_id}", response_model=ApiEnvelope)def patch_block( request: Request, day: date, block_id: str, body: BlockPatch,) -> object: try: _store(request).patch_block(day.isoformat(), block_id, body) return ok(_store(request).plan_with_feedback(day.isoformat())) except KeyError: return err("not_found", "Block not found", status.HTTP_404_NOT_FOUND) except ValueError as exc: return err("validation_error", str(exc), status.HTTP_422_UNPROCESSABLE_ENTITY)
@router.delete("/api/plan/{day}/blocks/{block_id}", response_model=ApiEnvelope)def delete_block(request: Request, day: date, block_id: str) -> object: try: _store(request).delete_block(day.isoformat(), block_id) return ok(_store(request).plan_with_feedback(day.isoformat())) except KeyError: return err("not_found", "Block not found", status.HTTP_404_NOT_FOUND)
@router.post("/api/plan/{day}/blocks/{block_id}/feedback", response_model=ApiEnvelope)def post_feedback( request: Request, day: date, block_id: str, body: FeedbackBody,) -> object: fb = body.model_copy(update={"block_id": block_id, "date": day.isoformat()}) try: stored, _plan = _store(request).submit_feedback(day.isoformat(), fb) return ok( { "feedback": stored.model_dump(mode="json"), "plan": _store(request).plan_with_feedback(day.isoformat()), "priors": list(_store(request).load_priors().values()), } ) except KeyError: return err("not_found", "Block not found", status.HTTP_404_NOT_FOUND)
@router.get("/api/schedule/priors", response_model=ApiEnvelope)def get_priors(request: Request) -> dict[str, Any]: kinds = _store(request).load_priors() return ok({"kinds": list(kinds.values()), "markdown": _store(request).priors_table()})
@router.get("/api/schedule/templates", response_model=ApiEnvelope)def get_templates(request: Request) -> dict[str, Any]: return ok({"items": _store(request).templates()})
@router.get("/api/plan/{day}/health", response_model=ApiEnvelope)def get_health(request: Request, day: date) -> dict[str, Any]: return ok(_store(request).health(day.isoformat()))
@router.post("/api/plan/{day}/reschedule", response_model=ApiEnvelope)def reschedule(request: Request, day: date, body: RescheduleBody | None = None) -> object: payload = body or RescheduleBody() risk, tags, triggers, last_hour_high = _risk_from_entries(request) cap = capacity_hint( risk_1h_score=risk, triggers_yesterday=triggers, yesterday_trigger=len(triggers) > 0, last_hour_high=last_hour_high, ) ops = trigger_operators(risk_1h_tags=tags, triggers_yesterday=triggers) try: result = request.app.state.reschedule_service.reschedule( day.isoformat(), reason=payload.reason, force=payload.force, risk_score=risk, capacity_hint=cap, priors_md=_store(request).priors_table(), context_notes=( f"risk_tags={tags}; triggers_y={triggers}; " f"operators={ops}" ), ) result["operators"] = ops result["capacity_hint"] = cap return ok(result) except PermissionError as exc: return err("rate_limited", str(exc), status.HTTP_429_TOO_MANY_REQUESTS) except ValueError as exc: return err("validation_error", str(exc), status.HTTP_422_UNPROCESSABLE_ENTITY)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338"""Pure schedule math: duration shrinkage, slip, completion rates, EV score.
Server-owned — LLM must never invent these statistics.
P1 scope lock (do not expand):- EV stays exactly: EV = P(done)*U + γ*I + η*Fun − λt*d_hat − λm*cost − λf*FSE- No PERMA, no ωE_i, no δ_i, no H=S+C+V in code.- Hedonic δ is not a v1 term; learn later via would_repeat + falling fun.- Seligman = operators on a trigger day: raise λ_f and η; only P0 overrides.- Escape (porn/court/rerun binge) ≠ explore/restore_fun.- Family contact is often FSE load, not a pillar to maximize."""
from __future__ import annotations
from collections import defaultdictfrom typing import Any
# Default planned minutes by kind when no samples exist yet.PRIOR_DEFAULT_MIN: dict[str, float] = { "earn_ship": 45, "admin_spain": 30, "body_care": 20, "move_out": 15, "boundary": 10, "food_out": 45, "stabilize": 15, "explore": 25, "restore_fun": 30, "sleep_window": 45, "other": 30,}
# Escape / FSE tags — never treat as fun or explore intent.ESCAPE_FSE_TAGS = frozenset( {"urge", "corn", "court", "rerun", "daydream", "bully", "shame", "family"})
def is_strong_feedback(fb: dict[str, Any]) -> bool: """Strong iff done|partial with actual_min, quality, and fun present."""
did = fb.get("did") return ( did in ("done", "partial") and fb.get("actual_min") is not None and fb.get("quality") is not None and fb.get("fun") is not None )
def d_hat( mean_actual: float | None, n: int, prior_default: float, *, m: float = 3.0,) -> float: """Shrinkage duration estimate: (n/(n+m))*mean + (m/(n+m))*prior."""
if n <= 0 or mean_actual is None: return float(prior_default) weight = n / (n + m) return weight * float(mean_actual) + (1.0 - weight) * float(prior_default)
def p_done_rate(n_done: int, n: int, *, alpha: float = 1.0, beta: float = 1.0) -> float: """Smoothed completion rate (N_done + α) / (N + α + β)."""
return (n_done + alpha) / (n + alpha + beta) if (n + alpha + beta) else 0.5
def mean_or_none(values: list[float]) -> float | None: return sum(values) / len(values) if values else None
def recompute_priors( feedback: list[dict[str, Any]], blocks_by_id: dict[str, dict[str, Any]], *, shrink_k: float = 3.0,) -> dict[str, dict[str, Any]]: """Rebuild per-kind priors from strong feedback samples.
EV ranking (documented for schedule generators / OR prompts): EV ≈ P_done * U + γ * I + η * Fun_bar - λt * d_hat - λm * cost - λf * fse_load High I when n_k is low or variance is high (explore kinds). """
by_kind: dict[str, list[dict[str, Any]]] = defaultdict(list) for fb in feedback: if not (fb.get("strong") or is_strong_feedback(fb)): continue block = blocks_by_id.get(str(fb.get("block_id") or "")) kind = (block or {}).get("kind") or fb.get("kind") or "other" by_kind[str(kind)].append(fb)
out: dict[str, dict[str, Any]] = {} for kind, samples in by_kind.items(): actuals = [float(s["actual_min"]) for s in samples if s.get("actual_min") is not None] qualities = [float(s["quality"]) for s in samples if s.get("quality") is not None] funs = [float(s["fun"]) for s in samples if s.get("fun") is not None] energies = [ float(s["energy_after"]) for s in samples if s.get("energy_after") is not None ] slips: list[float] = [] for s in samples: block = blocks_by_id.get(str(s.get("block_id") or "")) planned = (block or {}).get("planned_min") if planned is not None and s.get("actual_min") is not None: slips.append(float(s["actual_min"]) - float(planned)) n = len(samples) n_done = sum(1 for s in samples if s.get("did") == "done") mean_actual = mean_or_none(actuals) prior = PRIOR_DEFAULT_MIN.get(kind, 30.0) repeats = [ 1.0 if s.get("would_repeat") == "yes" else 0.0 for s in samples if s.get("would_repeat") in ("yes", "no", "maybe") ] out[kind] = { "kind": kind, "n": n, "mean_actual": mean_actual, "d_hat": d_hat(mean_actual, n, prior, m=shrink_k), "mean_quality": mean_or_none(qualities), "mean_fun": mean_or_none(funs), "mean_energy": mean_or_none(energies), "p_done": p_done_rate(n_done, n), "mean_slip": mean_or_none(slips), "repeat_score": mean_or_none(repeats) or 0.0, } # Ensure defaults exist for known kinds with no samples. for kind, prior in PRIOR_DEFAULT_MIN.items(): if kind not in out: out[kind] = { "kind": kind, "n": 0, "mean_actual": None, "d_hat": float(prior), "mean_quality": None, "mean_fun": None, "mean_energy": None, "p_done": 0.5, "mean_slip": None, "repeat_score": 0.0, } return out
def minutes_between(start: str, end: str) -> int: """Compute end-start in minutes for HH:MM strings."""
sh, sm = map(int, start.split(":")) eh, em = map(int, end.split(":")) return (eh * 60 + em) - (sh * 60 + sm)
def parse_hhmm(value: str) -> int: h, m = map(int, value.split(":")) return h * 60 + m
def overlaps(a_start: str, a_end: str, b_start: str, b_end: str) -> bool: a0, a1 = parse_hhmm(a_start), parse_hhmm(a_end) b0, b1 = parse_hhmm(b_start), parse_hhmm(b_end) return a0 < b1 and b0 < a1
def validate_blocks( blocks: list[dict[str, Any]], *, max_blocks: int = 7, previous_p0: list[dict[str, Any]] | None = None, allow_p0_move: bool = False,) -> list[str]: """Return validation error strings (empty if valid)."""
errors: list[str] = [] if len(blocks) > max_blocks: errors.append(f"max_blocks exceeded ({len(blocks)} > {max_blocks})") for block in blocks: start = str(block.get("start") or "") end = str(block.get("end") or "") try: span = minutes_between(start, end) except Exception: # noqa: BLE001 errors.append(f"invalid time on block {block.get('id')}") continue if span <= 0: errors.append(f"end must be after start for {block.get('id')}") planned = int(block.get("planned_min") or 0) if planned and abs(planned - span) > 1: errors.append( f"planned_min mismatch for {block.get('id')}: {planned} vs {span}" ) for i, a in enumerate(blocks): for b in blocks[i + 1 :]: if overlaps( str(a.get("start")), str(a.get("end")), str(b.get("start")), str(b.get("end")), ): errors.append( f"overlap between {a.get('id')} and {b.get('id')}" ) if previous_p0 and not allow_p0_move: prev = { str(b.get("id")): b for b in previous_p0 if b.get("priority") == "P0" or b.get("locked") } for block in blocks: bid = str(block.get("id") or "") if bid in prev: old = prev[bid] if old.get("start") != block.get("start") or old.get("end") != block.get( "end" ): errors.append(f"P0/locked block {bid} cannot be moved") return errors
def capacity_hint( *, risk_1h_score: float, triggers_yesterday: list[str], yesterday_trigger: bool | None = None, last_hour_high: bool | None = None,) -> float: """Soft capacity 0..1. Trigger day / last-hour FSE cut C_today; P0 still allowed.
On trigger days, callers should also raise λ_f and η in ranking/reschedule prompts (operators only — EV formula unchanged). """
y_trig = ( bool(yesterday_trigger) if yesterday_trigger is not None else len(triggers_yesterday) > 0 ) hour_high = ( bool(last_hour_high) if last_hour_high is not None else risk_1h_score >= 1.0 ) penalty = min( 0.65, 0.15 * risk_1h_score + 0.08 * len(triggers_yesterday) + (0.12 if y_trig else 0.0) + (0.15 if hour_high else 0.0), ) return max(0.25, 1.0 - penalty)
def trigger_operators( *, risk_1h_tags: list[str], triggers_yesterday: list[str],) -> dict[str, Any]: """Seligman-as-operators payload for reschedule / agent context (not new math)."""
escape_hit = bool(ESCAPE_FSE_TAGS & set(risk_1h_tags + triggers_yesterday)) trigger_day = len(triggers_yesterday) > 0 or escape_hit return { "trigger_day": trigger_day, "raise_lambda_f": trigger_day, "raise_eta": trigger_day, "p0_only_overrides": True, "escape_is_not_explore": True, "fun_must_yield_data_or_skill": True, "no_family_relationship_optimization": True, "ev_formula_locked": True, }
def plan_health( blocks: list[dict[str, Any]], feedback: list[dict[str, Any]],) -> dict[str, Any]: """Health ≈ (strong_fb/planned) * p0_done_rate * explore_flag."""
planned = [b for b in blocks if b.get("status") != "cancelled"] planned_count = max(1, len(planned)) fb_by_block = {str(f.get("block_id")): f for f in feedback} strong = sum( 1 for b in planned if is_strong_feedback(fb_by_block.get(str(b.get("id")), {})) or fb_by_block.get(str(b.get("id")), {}).get("strong") ) p0 = [b for b in planned if b.get("priority") == "P0"] p0_done = sum( 1 for b in p0 if fb_by_block.get(str(b.get("id")), {}).get("did") == "done" or b.get("status") == "done" ) p0_rate = (p0_done / len(p0)) if p0 else 1.0 explore_done = any( b.get("intent") in ("explore", "restore_fun") and ( b.get("status") in ("done", "partial") or fb_by_block.get(str(b.get("id")), {}).get("did") in ("done", "partial") ) for b in planned ) score = (strong / planned_count) * p0_rate * (1.0 if explore_done else 0.0) return { "score": round(score, 3), "strong_feedback_count": strong, "planned_count": len(planned), "p0_done_rate": round(p0_rate, 3), "explore_or_restore_done": explore_done, }
def priors_markdown(priors: dict[str, dict[str, Any]]) -> str: """Compact SERVER_PRIORS table for LLM prompts."""
lines = [ "SERVER_PRIORS (do not invent numbers)", "kind | n | d_hat | p_done | fun_bar | repeat", ] for kind in sorted(priors.keys()): row = priors[kind] fun = row.get("mean_fun") fun_s = f"{fun:.2f}" if isinstance(fun, (int, float)) else "n/a" lines.append( f"{kind} | {row.get('n', 0)} | {row.get('d_hat', 0):.0f} | " f"{row.get('p_done', 0):.2f} | {fun_s} | {row.get('repeat_score', 0):.2f}" ) return "\n".join(lines)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358"""Reschedule day plans via OpenRouter or deterministic rules backup.
P0/locked blocks stay put; P2 shrinks under load; explore/restore inserted when thin."""
from __future__ import annotations
import jsonimport refrom datetime import datetime, timezonefrom typing import Anyfrom uuid import uuid4
import httpx
from app.config import Settingsfrom app.schedule_math import minutes_between, parse_hhmm, trigger_operatorsfrom app.schedule_store import DayPlanPut, ScheduledBlock, ScheduleStorefrom app.schedule_templates import KIND_LABELS
def _hhmm(minutes: int) -> str: minutes = max(0, min(24 * 60 - 1, minutes)) return f"{minutes // 60:02d}:{minutes % 60:02d}"
def rules_backup_reschedule( plan_blocks: list[dict[str, Any]], *, day: str, risk_score: float, capacity_hint: float, day_start: str = "06:00", day_end: str = "23:00", max_blocks: int = 7,) -> list[ScheduledBlock]: """Deterministic reschedule: keep P0, drop/shrink P2, optional stabilize/fun."""
kept: list[dict[str, Any]] = [] for block in plan_blocks: if block.get("priority") == "P0" or block.get("locked"): item = dict(block) item["status"] = item.get("status") or "planned" item["source"] = "rules" kept.append(item) elif block.get("priority") == "P1": item = dict(block) item["source"] = "rules" kept.append(item) elif block.get("priority") == "P2" and capacity_hint >= 0.55: # Shrink long P2 blocks start = parse_hhmm(str(block["start"])) end = parse_hhmm(str(block["end"])) span = max(10, min(end - start, 25)) item = dict(block) item["end"] = _hhmm(start + span) item["planned_min"] = span item["source"] = "rules" kept.append(item)
# Fill gaps with stabilize if risk high if risk_score >= 1.0 or capacity_hint < 0.55: occupied = [(parse_hhmm(b["start"]), parse_hhmm(b["end"])) for b in kept] cursor = parse_hhmm(day_start) + 60 end_limit = parse_hhmm(day_end) - 30 placed = False while cursor + 15 <= end_limit and not placed: clash = any(s < cursor + 15 and cursor < e for s, e in occupied) if not clash: kept.append( { "id": str(uuid4()), "date": day, "start": _hhmm(cursor), "end": _hhmm(cursor + 15), "title": "Stabilize: walk/move 10m", "kind": "stabilize", "intent": "measure", "priority": "P1", "planned_min": 15, "status": "planned", "source": "rules", "locked": False, "notes": "rules backup", "version_added": 1, } ) placed = True cursor += 30
has_explore = any( b.get("intent") in ("explore", "restore_fun") for b in kept ) if not has_explore and capacity_hint >= 0.4 and len(kept) < max_blocks: start_m = parse_hhmm(day_start) + 4 * 60 end_m = start_m + 25 occupied = [(parse_hhmm(b["start"]), parse_hhmm(b["end"])) for b in kept] while any(s < end_m and start_m < e for s, e in occupied) and end_m < parse_hhmm(day_end): start_m += 30 end_m = start_m + 25 if end_m <= parse_hhmm(day_end): kept.append( { "id": str(uuid4()), "date": day, "start": _hhmm(start_m), "end": _hhmm(end_m), "title": "Fun recharge / try something new", "kind": "restore_fun", "intent": "restore_fun", "priority": "P2", "planned_min": 25, "status": "planned", "source": "rules", "locked": False, "notes": "rules explore pad", "version_added": 1, } )
kept.sort(key=lambda b: b["start"]) # Deduplicate overlaps by preferring P0 then P1 final: list[dict[str, Any]] = [] for block in kept: if len(final) >= max_blocks: break clash = False for existing in final: if parse_hhmm(existing["start"]) < parse_hhmm(block["end"]) and parse_hhmm( block["start"] ) < parse_hhmm(existing["end"]): clash = True break if not clash: final.append(block) return [ScheduledBlock.model_validate(b) for b in final]
class RescheduleService: """OpenRouter reschedule with rules fallback."""
def __init__(self, settings: Settings, store: ScheduleStore) -> None: self.settings = settings self.store = store
def can_reschedule(self, *, force: bool = False) -> tuple[bool, str | None]: meta = self.store.get_meta() last = meta.get("last_reschedule_at") if force or not last: return True, None try: ts = datetime.fromisoformat(str(last).replace("Z", "+00:00")) except ValueError: return True, None gap = (datetime.now(timezone.utc) - ts).total_seconds() / 60.0 if gap < self.settings.reschedule_min_gap_min: return False, f"Reschedule cooldown ({int(self.settings.reschedule_min_gap_min - gap)}m left)" return True, None
def call_openrouter(self, messages: list[dict[str, str]]) -> str | None: if not self.settings.openrouter_api_key: return None url = f"{self.settings.openrouter_base_url.rstrip('/')}/chat/completions" headers = { "Authorization": f"Bearer {self.settings.openrouter_api_key}", "Content-Type": "application/json", "X-Title": "Habit Journal", } body = { "model": self.settings.openrouter_model, "messages": messages, "temperature": 0.25, "max_tokens": 1200, } try: with httpx.Client(timeout=self.settings.coach_timeout_sec) as client: response = client.post(url, headers=headers, json=body) if response.status_code >= 400: return None content = ( response.json() .get("choices", [{}])[0] .get("message", {}) .get("content") ) return str(content) if content else None except Exception: # noqa: BLE001 return None
def parse_blocks_json(self, raw: str, day: str) -> list[ScheduledBlock] | None: text = raw.strip() if text.startswith("```"): text = re.sub(r"^```(?:json)?\s*", "", text) text = re.sub(r"\s*```$", "", text) try: payload = json.loads(text) except json.JSONDecodeError: match = re.search(r"\{[\s\S]*\}", text) if not match: return None try: payload = json.loads(match.group(0)) except json.JSONDecodeError: return None blocks_raw = payload.get("blocks") if not isinstance(blocks_raw, list): return None blocks: list[ScheduledBlock] = [] for item in blocks_raw: try: data = dict(item) data["date"] = day data.setdefault("id", str(uuid4())) data.setdefault("status", "planned") data.setdefault("source", "openrouter") if not data.get("planned_min"): data["planned_min"] = max( 1, minutes_between(str(data["start"]), str(data["end"])) ) if data.get("priority") == "P0": data["locked"] = True blocks.append(ScheduledBlock.model_validate(data)) except Exception: # noqa: BLE001 continue return blocks or None
def reschedule( self, day: str, *, reason: str = "user", force: bool = False, risk_score: float = 0.0, capacity_hint: float = 0.7, priors_md: str = "", context_notes: str = "", ) -> dict[str, Any]: ok, msg = self.can_reschedule(force=force) if not ok: raise PermissionError(msg or "cooldown")
plan = self.store.get_plan(day) locked = [b.model_dump() for b in plan.blocks if b.priority == "P0" or b.locked] source = "rules" blocks: list[ScheduledBlock] | None = None raw = None
ops = trigger_operators( risk_1h_tags=[], triggers_yesterday=[], ) # Prefer operators passed via context_notes when present; else derive from risk. trigger_day = risk_score >= 1.0 or "triggers_y=" in context_notes if "raise_lambda_f" in context_notes or trigger_day: ops = { **ops, "trigger_day": trigger_day, "raise_lambda_f": trigger_day, "raise_eta": trigger_day, } system = ( "Checklist schedule coach. JSON only: " '{"version_notes":"","blocks":[{"id":"...","start":"HH:MM","end":"HH:MM",' '"title":"...","kind":"...","intent":"duty|explore|restore_fun|measure",' '"priority":"P0|P1|P2","planned_min":N,"locked":false,"notes":""}]}. ' "EV is server-owned — never invent p_done, d_hat, or %. " "P0/locked (sleep, food, visa/admin deadlines) stay at the same times — " "never silent-move. Escape (porn/court/rerun binge) is NOT explore/fun. " "On trigger_day: raise FSE weight and fun weight; only P0 overrides cuts. " "Explore/restore must yield data or skill contact, not escape. " "Do not schedule family/relationship optimization tasks. " "Include ≥1 explore/restore_fun if capacity allows; cut P2 when overload. " "Max 7 blocks. No pep talk, no guilt, no duty maximizer tone. " "Schedule does not replace Daily check-in or Log entries." ) user = json.dumps( { "date": day, "reason": reason, "capacity_hint": capacity_hint, "risk_score": risk_score, "operators": ops, "locked_p0": locked, "current_blocks": [b.model_dump(mode="json") for b in plan.blocks], "SERVER_PRIORS": priors_md, "notes": context_notes, "kind_labels": KIND_LABELS, "day_window": [ self.settings.schedule_day_start, self.settings.schedule_day_end, ], }, ensure_ascii=False, ) if self.settings.openrouter_api_key: raw = self.call_openrouter( [ {"role": "system", "content": system}, {"role": "user", "content": user}, ] ) if raw: blocks = self.parse_blocks_json(raw, day) if blocks: source = "openrouter"
if blocks is None: blocks = rules_backup_reschedule( [b.model_dump() for b in plan.blocks], day=day, risk_score=risk_score, capacity_hint=capacity_hint, day_start=self.settings.schedule_day_start, day_end=self.settings.schedule_day_end, max_blocks=self.settings.schedule_max_blocks, ) source = "rules"
# Preserve P0 times from previous plan by id/title prev_p0 = { b.id: b for b in plan.blocks if b.priority == "P0" or b.locked } fixed: list[ScheduledBlock] = [] for block in blocks: if block.id in prev_p0: old = prev_p0[block.id] fixed.append( block.model_copy( update={ "start": old.start, "end": old.end, "planned_min": old.planned_min, "locked": True, "priority": "P0" if old.priority == "P0" else block.priority, } ) ) else: fixed.append(block)
saved = self.store.save_plan( day, DayPlanPut( blocks=fixed, source=source, capacity_hint=capacity_hint, notes=f"reschedule:{reason}", force_p0_move=False, ), bump_version=True, ) self.store.set_meta(last_reschedule_at=datetime.now(timezone.utc).isoformat()) return { "plan": self.store.plan_with_feedback(day), "source": source, "raw_model": raw, "version": saved.version, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422"""Persist day plans, block feedback, and learned schedule priors.
JSON files under DATA_ROOT/schedule/; feedback is append-only JSONL."""
from __future__ import annotations
import jsonfrom datetime import date, datetime, timezonefrom typing import Any, Literalfrom uuid import uuid4
from pydantic import BaseModel, ConfigDict, Field, field_validator
from app.fsutil import append_jsonl, atomic_write_text, file_lock, read_json, read_jsonlfrom app.paths import Pathsfrom app.schedule_math import ( PRIOR_DEFAULT_MIN, is_strong_feedback, minutes_between, plan_health, priors_markdown, recompute_priors, validate_blocks,)from app.schedule_templates import KIND_LABELS, list_templates
TaskKind = Literal[ "earn_ship", "admin_spain", "body_care", "move_out", "boundary", "food_out", "stabilize", "explore", "restore_fun", "sleep_window", "other",]Priority = Literal["P0", "P1", "P2"]Intent = Literal["duty", "explore", "restore_fun", "measure"]BlockStatus = Literal["planned", "done", "partial", "skipped", "moved", "cancelled"]Did = Literal["done", "partial", "skipped"]WouldRepeat = Literal["yes", "no", "maybe"]SkipReason = Literal["time", "fear", "fse", "locks", "boring", "urge", "other"]PlanSource = Literal["cursor", "openrouter", "user", "rules"]
def utc_now() -> datetime: return datetime.now(timezone.utc)
class ScheduledBlock(BaseModel): """One timed block on a day plan."""
model_config = ConfigDict(extra="ignore")
id: str = Field(default_factory=lambda: str(uuid4())) date: str start: str end: str title: str = Field(min_length=1, max_length=200) kind: TaskKind = "other" intent: Intent = "duty" priority: Priority = "P2" planned_min: int = Field(ge=1, le=24 * 60) status: BlockStatus = "planned" source: PlanSource | str = "user" locked: bool = False notes: str = "" version_added: int = 1
@field_validator("start", "end") @classmethod def _hhmm(cls, value: str) -> str: parts = value.split(":") if len(parts) != 2: raise ValueError("time must be HH:MM") h, m = int(parts[0]), int(parts[1]) if not (0 <= h <= 23 and 0 <= m <= 59): raise ValueError("invalid time") return f"{h:02d}:{m:02d}"
class BlockFeedback(BaseModel): """Thick feedback for one block."""
model_config = ConfigDict(extra="ignore")
block_id: str date: str did: Did actual_min: int | None = Field(default=None, ge=0, le=24 * 60) quality: int | None = Field(default=None, ge=1, le=5) fun: int | None = Field(default=None, ge=1, le=5) energy_after: int | None = Field(default=None, ge=-2, le=2) money_amount: float | None = None money_currency: str = "TZS" would_repeat: WouldRepeat | None = None skip_reason: SkipReason | None = None note: str = "" strong: bool = False ts: datetime = Field(default_factory=utc_now)
def with_strong_flag(self) -> "BlockFeedback": payload = self.model_dump() strong = is_strong_feedback(payload) return self.model_copy(update={"strong": strong})
class DayPlan(BaseModel): """Versioned day schedule."""
model_config = ConfigDict(extra="ignore")
date: str version: int = 1 source: PlanSource | str = "user" blocks: list[ScheduledBlock] = Field(default_factory=list) capacity_hint: float = Field(default=1.0, ge=0.0, le=1.0) notes: str = "" updated_at: datetime = Field(default_factory=utc_now) parent_version: int | None = None
class BlockCreate(BaseModel): """Payload for adding one block."""
model_config = ConfigDict(extra="forbid")
start: str end: str title: str = Field(min_length=1, max_length=200) kind: TaskKind = "other" intent: Intent = "duty" priority: Priority = "P2" planned_min: int | None = None locked: bool | None = None notes: str = ""
class BlockPatch(BaseModel): """Partial block update."""
model_config = ConfigDict(extra="forbid")
start: str | None = None end: str | None = None title: str | None = Field(default=None, min_length=1, max_length=200) kind: TaskKind | None = None intent: Intent | None = None priority: Priority | None = None planned_min: int | None = Field(default=None, ge=1, le=24 * 60) status: BlockStatus | None = None locked: bool | None = None notes: str | None = None
class DayPlanPut(BaseModel): """Replace/create a day plan."""
model_config = ConfigDict(extra="ignore")
blocks: list[ScheduledBlock] source: PlanSource | str = "user" capacity_hint: float | None = Field(default=None, ge=0.0, le=1.0) notes: str = "" force_p0_move: bool = False
class ScheduleStore: """Read and mutate schedule plans and priors."""
def __init__(self, paths: Paths, *, shrink_k: float = 3.0, max_blocks: int = 7) -> None: self.paths = paths self.shrink_k = shrink_k self.max_blocks = max_blocks self.paths.schedule_dir.mkdir(parents=True, exist_ok=True)
def empty_plan(self, day: str) -> DayPlan: return DayPlan(date=day, blocks=[], source="user")
def get_plan(self, day: str) -> DayPlan: path = self.paths.plan_path(day) raw = read_json(path) if raw is None: return self.empty_plan(day) return DayPlan.model_validate(raw)
def save_plan( self, day: str, put: DayPlanPut, *, bump_version: bool = True, ) -> DayPlan: current = self.get_plan(day) blocks = [] for block in put.blocks: data = block.model_dump() data["date"] = day if not data.get("planned_min"): data["planned_min"] = max(1, minutes_between(data["start"], data["end"])) if data.get("priority") == "P0" and put.source in ("openrouter", "rules", "cursor"): data["locked"] = True if data.get("locked") is None else data["locked"] blocks.append(ScheduledBlock.model_validate(data))
errors = validate_blocks( [b.model_dump() for b in blocks], max_blocks=self.max_blocks, previous_p0=[b.model_dump() for b in current.blocks], allow_p0_move=put.force_p0_move or put.source == "user", ) if errors: raise ValueError("; ".join(errors))
version = current.version + 1 if bump_version and current.blocks else max(1, current.version) if not current.blocks and not bump_version: version = 1 plan = DayPlan( date=day, version=version, source=put.source, blocks=blocks, capacity_hint=put.capacity_hint if put.capacity_hint is not None else current.capacity_hint, notes=put.notes, updated_at=utc_now(), parent_version=current.version if current.blocks else None, ) self._write_plan(plan) return plan
def _write_plan(self, plan: DayPlan) -> None: path = self.paths.plan_path(plan.date) payload = json.dumps(plan.model_dump(mode="json"), ensure_ascii=False, indent=2) with file_lock(path): atomic_write_text(path, payload + "\n")
def add_block(self, day: str, body: BlockCreate) -> DayPlan: plan = self.get_plan(day) planned = body.planned_min or max(1, minutes_between(body.start, body.end)) locked = body.locked if body.locked is not None else body.priority == "P0" block = ScheduledBlock( date=day, start=body.start, end=body.end, title=body.title, kind=body.kind, intent=body.intent, priority=body.priority, planned_min=planned, locked=locked, notes=body.notes, source="user", version_added=plan.version, ) blocks = list(plan.blocks) + [block] return self.save_plan( day, DayPlanPut( blocks=blocks, source="user", capacity_hint=plan.capacity_hint, notes=plan.notes, force_p0_move=True, ), bump_version=False, )
def patch_block(self, day: str, block_id: str, patch: BlockPatch) -> DayPlan: plan = self.get_plan(day) found = False blocks: list[ScheduledBlock] = [] for block in plan.blocks: if block.id != block_id: blocks.append(block) continue found = True data = block.model_dump() data.update(patch.model_dump(exclude_unset=True)) if patch.start is not None or patch.end is not None: data["planned_min"] = patch.planned_min or max( 1, minutes_between(data["start"], data["end"]) ) blocks.append(ScheduledBlock.model_validate(data)) if not found: raise KeyError(block_id) return self.save_plan( day, DayPlanPut( blocks=blocks, source="user", capacity_hint=plan.capacity_hint, notes=plan.notes, force_p0_move=True, ), bump_version=False, )
def delete_block(self, day: str, block_id: str) -> DayPlan: plan = self.get_plan(day) blocks = [b for b in plan.blocks if b.id != block_id] if len(blocks) == len(plan.blocks): raise KeyError(block_id) return self.save_plan( day, DayPlanPut( blocks=blocks, source="user", capacity_hint=plan.capacity_hint, notes=plan.notes, force_p0_move=True, ), bump_version=False, )
def list_feedback(self, day: str | None = None) -> list[dict[str, Any]]: rows = read_jsonl(self.paths.schedule_feedback) if day is None: return rows return [r for r in rows if r.get("date") == day]
def feedback_for_plan(self, day: str) -> list[dict[str, Any]]: return self.list_feedback(day)
def submit_feedback(self, day: str, fb: BlockFeedback) -> tuple[BlockFeedback, DayPlan]: plan = self.get_plan(day) block = next((b for b in plan.blocks if b.id == fb.block_id), None) if block is None: raise KeyError(fb.block_id) stored = fb.model_copy(update={"date": day}).with_strong_flag() append_jsonl(self.paths.schedule_feedback, stored.model_dump(mode="json"))
status_map = {"done": "done", "partial": "partial", "skipped": "skipped"} patched = self.patch_block( day, fb.block_id, BlockPatch(status=status_map[fb.did]), # type: ignore[arg-type] ) self.recompute_and_save_priors() return stored, patched
def load_priors(self) -> dict[str, dict[str, Any]]: raw = read_json(self.paths.schedule_priors) if raw and isinstance(raw.get("kinds"), dict): return raw["kinds"] # Seed defaults kinds = { k: { "kind": k, "n": 0, "mean_actual": None, "d_hat": float(v), "mean_quality": None, "mean_fun": None, "mean_energy": None, "p_done": 0.5, "mean_slip": None, "repeat_score": 0.0, } for k, v in PRIOR_DEFAULT_MIN.items() } return kinds
def recompute_and_save_priors(self) -> dict[str, dict[str, Any]]: feedback = self.list_feedback() blocks_by_id: dict[str, dict[str, Any]] = {} # Load blocks from feedback dates dates = {str(f.get("date")) for f in feedback if f.get("date")} for day in dates: for block in self.get_plan(day).blocks: blocks_by_id[block.id] = block.model_dump() kinds = recompute_priors(feedback, blocks_by_id, shrink_k=self.shrink_k) payload = { "updated_at": utc_now().isoformat(), "kinds": kinds, "kind_labels": KIND_LABELS, } text = json.dumps(payload, ensure_ascii=False, indent=2) + "\n" with file_lock(self.paths.schedule_priors): atomic_write_text(self.paths.schedule_priors, text) return kinds
def get_meta(self) -> dict[str, Any]: return read_json(self.paths.schedule_meta) or {}
def set_meta(self, **kwargs: Any) -> dict[str, Any]: meta = self.get_meta() meta.update(kwargs) text = json.dumps(meta, ensure_ascii=False, indent=2) + "\n" with file_lock(self.paths.schedule_meta): atomic_write_text(self.paths.schedule_meta, text) return meta
def health(self, day: str) -> dict[str, Any]: plan = self.get_plan(day) return plan_health( [b.model_dump() for b in plan.blocks], self.feedback_for_plan(day), )
def plan_with_feedback(self, day: str) -> dict[str, Any]: plan = self.get_plan(day) feedback = self.feedback_for_plan(day) by_block = {str(f.get("block_id")): f for f in feedback} blocks = [] for block in plan.blocks: item = block.model_dump(mode="json") item["feedback"] = by_block.get(block.id) item["label"] = KIND_LABELS.get(block.kind, block.kind) blocks.append(item) data = plan.model_dump(mode="json") data["blocks"] = blocks data["health"] = self.health(day) return data
def templates(self) -> list[dict[str, Any]]: return list_templates()
def priors_table(self) -> str: return priors_markdown(self.load_priors())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192"""Built-in schedule templates: duty, explore, and restore_fun menus.
Escape (porn binge, family courtroom) is NOT explore."""
from __future__ import annotations
from typing import Any
# Each template: default_min, kind, intent, utility U, fse_load, default priority.TEMPLATES: list[dict[str, Any]] = [ { "id": "earn_one_ship", "title": "Earn one ship", "kind": "earn_ship", "intent": "duty", "priority": "P1", "default_min": 45, "utility": 0.9, "fse_load": 0.2, "label": "Work / earn", }, { "id": "admin_task", "title": "Trip / admin task", "kind": "admin_spain", "intent": "duty", "priority": "P0", "default_min": 30, "utility": 0.85, "fse_load": 0.3, "label": "Trip / admin", "locked": True, }, { "id": "body_room", "title": "Body or room care", "kind": "body_care", "intent": "duty", "priority": "P2", "default_min": 20, "utility": 0.55, "fse_load": 0.1, "label": "Body or room", }, { "id": "move_out_line", "title": "Move-out one line", "kind": "move_out", "intent": "duty", "priority": "P1", "default_min": 15, "utility": 0.7, "fse_load": 0.25, "label": "Move-out step", }, { "id": "food_outside", "title": "Food outside", "kind": "food_out", "intent": "duty", "priority": "P0", "default_min": 45, "utility": 0.8, "fse_load": 0.15, "label": "Food", "locked": True, }, { "id": "boundary_5m", "title": "Boundary practice 5m", "kind": "boundary", "intent": "duty", "priority": "P2", "default_min": 10, "utility": 0.5, "fse_load": 0.2, "label": "Boundary practice", }, { "id": "walk_new_route", "title": "Timed walk new route 20m", "kind": "explore", "intent": "explore", "priority": "P2", "default_min": 20, "utility": 0.45, "fse_load": 0.05, "label": "Try something new", "measure": "rate urge/mood after", }, { "id": "music_album", "title": "Music full album + fun rating", "kind": "restore_fun", "intent": "restore_fun", "priority": "P2", "default_min": 40, "utility": 0.4, "fse_load": 0.05, "label": "Fun recharge", }, { "id": "cook_simple", "title": "Cook simple meal", "kind": "explore", "intent": "explore", "priority": "P2", "default_min": 35, "utility": 0.5, "fse_load": 0.1, "label": "Try something new", "money_optional": True, }, { "id": "photo_challenge", "title": "Photo challenge 20 shots", "kind": "explore", "intent": "explore", "priority": "P2", "default_min": 25, "utility": 0.45, "fse_load": 0.05, "label": "Try something new", }, { "id": "spanish_15", "title": "Spanish 15m light practice", "kind": "explore", "intent": "explore", "priority": "P2", "default_min": 15, "utility": 0.55, "fse_load": 0.1, "label": "Try something new", }, { "id": "cafe_45", "title": "Cafe 45m + short journal", "kind": "restore_fun", "intent": "restore_fun", "priority": "P2", "default_min": 45, "utility": 0.5, "fse_load": 0.1, "label": "Fun recharge", "money_optional": True, }, { "id": "stabilize_10", "title": "Stabilize: walk/move 10m", "kind": "stabilize", "intent": "measure", "priority": "P1", "default_min": 10, "utility": 0.6, "fse_load": 0.0, "label": "Stabilize / reset", "measure": "after urge", }, { "id": "sleep_wind", "title": "Sleep wind-down", "kind": "sleep_window", "intent": "duty", "priority": "P0", "default_min": 45, "utility": 0.85, "fse_load": 0.0, "label": "Sleep wind-down", "locked": True, },]
KIND_LABELS: dict[str, str] = { "earn_ship": "Work / earn", "admin_spain": "Trip / admin", "body_care": "Body or room", "move_out": "Move-out step", "food_out": "Food", "stabilize": "Stabilize / reset", "explore": "Try something new", "restore_fun": "Fun recharge", "boundary": "Boundary practice", "sleep_window": "Sleep wind-down", "other": "Other",}
def list_templates() -> list[dict[str, Any]]: return list(TEMPLATES)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138# Schedule / time-tracking
Additive Habit Journal feature: iOS-like day plan, thick block feedback, learned duration priors, Cursor agent pull/push, and OpenRouter/rules reschedule.
## P1 scope lock (hard)
Ship only: **day timeline + thick feedback (<20s) + priors/duration learning + yesterday-trigger / last-hour capacity cut.**
Do **not** implement as code:
- full PERMA- ωEᵢ, δᵢ, or H=S+C+V- hedonic δ as an explicit v1 term (learn later via would_repeat + falling fun)- split feedback into Meaning vs Flow / “meaningful?” / “in the zone?”- family/relationship tasks as a pillar to maximize- schedule as a substitute for Daily or Log
### EV stays owned (no rewrite)
```EV = P(done)*U + γ*I + η*Fun − λt*d_hat − λm*cost − λf*FSE```
Seligman = **operators**, not a new religion:
- trigger day → raise λ_f and η; only P0 overrides cuts- escape (porn / court / rerun binge) ≠ fun/explore- fun/explore should yield data or skill contact
### Feedback fields (v1 — no extras)
`did` · `actual_min` · `quality` 1–5 · `fun` 1–5 · `energy_after` −2…+2 · `would_repeat` · `skip_reason` · money optional.
Later mapping from data only: quality+would_repeat ≈ meaning; fun+energy ≈ recovery. Do not ask PERMA questions in UI.
### Premortems (fail the PR if present)
Planning-as-avoidance · no feedback · OR thrash · overfull FSE day · schedule theater · guilt / duty-maximizer copy.
### P0 never silent-reschedule
Sleep, food, Spain/visa deadlines stay locked at their times.
## Nav IA (chosen)
`Home | Plan | (+) Log | Daily | Settings`
- Center FAB stays **Log** (one tap from every main screen).- **History** remains at `#/history` and is reachable from Home (“See all” / History chip).
## Data
Under `DATA_ROOT/schedule/`:
| Path | Purpose ||------|---------|| `plan-YYYY-MM-DD.json` | Versioned day plan || `feedback.jsonl` | Block feedback rows || `priors.json` | Per-kind `d_hat`, `p_done`, fun, slip || `meta.json` | Last reschedule timestamp |
## Math (server-owned)
```d_hat = (n/(n+m)) * mean_actual + (m/(n+m)) * prior_defaultslip = actual_min - planned_minp_done ≈ (N_done + α) / (N + α + β)C_today cut if yesterday_trigger or last-hour urge/court/corn/rerun (P0 still allowed)health = (strong_feedback / planned) * p0_done_rate * (1 if explore/fun done else 0)```
Strong feedback = `did` in done|partial **and** actual_min, quality, fun present. LLM must not invent `p_helped`, rank, or %.
## Human API (session cookie)
- `GET/PUT /api/plan/{date}`- `POST/PATCH/DELETE /api/plan/{date}/blocks[/{id}]`- `POST /api/plan/{date}/blocks/{id}/feedback`- `GET /api/schedule/priors`- `GET /api/schedule/templates`- `POST /api/plan/{date}/reschedule` `{ "reason", "force" }`- `GET /api/plan/{date}/health`
## Agent API
Set Space secret `AGENT_TOKEN`.
```bash# Pull contextcurl -s -H "Authorization: Bearer $AGENT_TOKEN" \ "https://YOUR_SPACE/api/agent/context?day=2026-07-19"
# Push plancurl -s -X PUT -H "Authorization: Bearer $AGENT_TOKEN" \ -H "Content-Type: application/json" \ -d '{"source":"cursor","blocks":[{"date":"2026-07-19","start":"09:00","end":"09:45","title":"Earn one ship","kind":"earn_ship","intent":"duty","priority":"P1","planned_min":45,"status":"planned","locked":false,"notes":"","version_added":1,"source":"cursor"}]}' \ "https://YOUR_SPACE/api/agent/plan/2026-07-19"```
### Agent contract (one line)
Implement thin schedule loop + thick feedback + trigger capacity cuts. Seligman validates recovery and anti-duty-only design; do not expand the equation or feedback fields.
### Steps
1. `GET /api/agent/context?day=`2. Build ≤ `max_blocks`, pad with `d_hat`, keep P0 locked, ≥1 explore/restore unless capacity very low3. `PUT /api/agent/plan/{date}`4. User completes blocks on phone (thick feedback)5. Optional `POST /api/plan/{date}/reschedule` when missed/risk
Context includes `operators` and `capacity_hint`.
## Env
```AGENT_TOKEN=...OPENROUTER_API_KEY=... # optional; rules backup if missingRESCHEDULE_MIN_GAP_MIN=90SCHEDULE_DAY_START=06:00SCHEDULE_DAY_END=23:00TZ / SCHEDULE_TIMEZONE=Africa/Dar_es_Salaam```
## UI map
| Route | Role ||-------|------|| `#/plan` | Day timeline 06:00–23:00, now line, colored blocks || Block sheet | Complete with did / minutes / quality / fun (no PERMA Qs) || Home | Next 1–2 blocks + overdue feedback banner |
## Reschedule
- OpenRouter returns JSON blocks; P0 times preserved.- Without API key / parse fail → `rules_backup_reschedule`.- Cooldown `RESCHEDULE_MIN_GAP_MIN` unless `force`.323 unmodified lines324325326323 unmodified linesif (!res.ok) throw new ApiError({ code: "request_failed", message: "Export failed" });return res.blob();}323 unmodified lines324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491323 unmodified linesif (!res.ok) throw new ApiError({ code: "request_failed", message: "Export failed" });return res.blob();}/* —— Schedule / Plan —— */export type TaskKind =| "earn_ship"| "admin_spain"| "body_care"| "move_out"| "boundary"| "food_out"| "stabilize"| "explore"| "restore_fun"| "sleep_window"| "other";export type ScheduledBlock = {id: string;date: string;start: string;end: string;title: string;kind: TaskKind;intent: "duty" | "explore" | "restore_fun" | "measure";priority: "P0" | "P1" | "P2";planned_min: number;status: "planned" | "done" | "partial" | "skipped" | "moved" | "cancelled";source: string;locked: boolean;notes: string;version_added: number;label?: string;feedback?: BlockFeedback | null;};export type BlockFeedback = {block_id: string;date: string;did: "done" | "partial" | "skipped";actual_min: number | null;quality: number | null;fun: number | null;energy_after: number | null;money_amount: number | null;money_currency: string;would_repeat: "yes" | "no" | "maybe" | null;skip_reason: string | null;note: string;strong: boolean;ts: string;};export type DayPlanView = {date: string;version: number;source: string;blocks: ScheduledBlock[];capacity_hint: number;notes: string;updated_at: string;parent_version: number | null;health?: {score: number;strong_feedback_count: number;planned_count: number;p0_done_rate: number;explore_or_restore_done: boolean;};};export type ScheduleTemplate = {id: string;title: string;kind: TaskKind;intent: string;priority: string;default_min: number;label: string;};export function getPlan(day: string): Promise<DayPlanView> {return api(`/api/plan/${day}`);}export function putPlan(day: string,payload: {blocks: Partial<ScheduledBlock>[];source?: string;notes?: string;capacity_hint?: number;force_p0_move?: boolean;},): Promise<DayPlanView> {return api(`/api/plan/${day}`, {method: "PUT",body: JSON.stringify(payload),});}export function addPlanBlock(day: string,payload: {start: string;end: string;title: string;kind: TaskKind;intent: ScheduledBlock["intent"];priority: ScheduledBlock["priority"];planned_min?: number;locked?: boolean;notes?: string;},): Promise<DayPlanView> {return api(`/api/plan/${day}/blocks`, {method: "POST",body: JSON.stringify(payload),});}export function patchPlanBlock(day: string,id: string,payload: Partial<ScheduledBlock>,): Promise<DayPlanView> {return api(`/api/plan/${day}/blocks/${encodeURIComponent(id)}`, {method: "PATCH",body: JSON.stringify(payload),});}export function deletePlanBlock(day: string, id: string): Promise<DayPlanView> {return api(`/api/plan/${day}/blocks/${encodeURIComponent(id)}`, {method: "DELETE",});}export function postBlockFeedback(day: string,id: string,payload: Partial<BlockFeedback> & { did: BlockFeedback["did"] },): Promise<{ feedback: BlockFeedback; plan: DayPlanView }> {return api(`/api/plan/${day}/blocks/${encodeURIComponent(id)}/feedback`, {method: "POST",body: JSON.stringify(payload),});}export function getScheduleTemplates(): Promise<{ items: ScheduleTemplate[] }> {return api("/api/schedule/templates");}export function getSchedulePriors(): Promise<{ kinds: Array<Record<string, unknown>>; markdown: string }> {return api("/api/schedule/priors");}export function reschedulePlan(day: string,payload: { reason?: string; force?: boolean } = {},): Promise<{ plan: DayPlanView; source: string; version: number }> {return api(`/api/plan/${day}/reschedule`, {method: "POST",body: JSON.stringify(payload),});}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336/** Block detail + thick feedback sheet for schedule blocks. */
import { useEffect, useState } from "preact/hooks";import { addPlanBlock, deletePlanBlock, postBlockFeedback, type ScheduledBlock, type TaskKind,} from "../api";import { Button } from "./Button";import { Pressable } from "./Pressable";import { Sheet } from "./Sheet";import { useToast } from "./Toast";
const KIND_OPTIONS: { value: TaskKind; label: string }[] = [ { value: "earn_ship", label: "Work / earn" }, { value: "admin_spain", label: "Trip / admin" }, { value: "body_care", label: "Body or room" }, { value: "move_out", label: "Move-out step" }, { value: "food_out", label: "Food" }, { value: "stabilize", label: "Stabilize / reset" }, { value: "explore", label: "Try something new" }, { value: "restore_fun", label: "Fun recharge" }, { value: "boundary", label: "Boundary practice" }, { value: "sleep_window", label: "Sleep wind-down" }, { value: "other", label: "Other" },];
type Props = { open: boolean; day: string; block: ScheduledBlock | null; mode: "view" | "create"; onClose: () => void; onChanged: () => void;};
export function BlockSheet({ open, day, block, mode, onClose, onChanged }: Props) { const toast = useToast(); const [did, setDid] = useState<"done" | "partial" | "skipped">("done"); const [actualMin, setActualMin] = useState(30); const [quality, setQuality] = useState(3); const [fun, setFun] = useState(3); const [energy, setEnergy] = useState(0); const [wouldRepeat, setWouldRepeat] = useState<"yes" | "no" | "maybe" | "">(""); const [skipReason, setSkipReason] = useState(""); const [note, setNote] = useState(""); const [money, setMoney] = useState(""); const [busy, setBusy] = useState(false);
const [title, setTitle] = useState("New block"); const [kind, setKind] = useState<TaskKind>("other"); const [start, setStart] = useState("09:00"); const [end, setEnd] = useState("09:30"); const [priority, setPriority] = useState<"P0" | "P1" | "P2">("P2"); const [intent, setIntent] = useState<ScheduledBlock["intent"]>("duty");
useEffect(() => { if (!open) return; if (mode === "view" && block) { setActualMin(block.planned_min || 30); setDid("done"); setQuality(3); setFun(3); setEnergy(0); setWouldRepeat(""); setSkipReason(""); setNote(""); setMoney(""); } if (mode === "create") { setTitle("New block"); setKind("other"); setStart("09:00"); setEnd("09:30"); setPriority("P2"); setIntent("duty"); } }, [open, mode, block?.id]);
const saveFeedback = async () => { if (!block) return; setBusy(true); try { await postBlockFeedback(day, block.id, { did, actual_min: did === "skipped" ? null : actualMin, quality: did === "skipped" ? null : quality, fun: did === "skipped" ? null : fun, energy_after: energy, money_amount: money ? Number(money) : null, would_repeat: wouldRepeat || null, skip_reason: did === "skipped" ? skipReason || "other" : null, note, }); toast.show("Saved"); onChanged(); onClose(); } catch (e) { toast.show(e instanceof Error ? e.message : "Save failed", "error"); } finally { setBusy(false); } };
const createBlock = async () => { setBusy(true); try { await addPlanBlock(day, { title, kind, start, end, priority, intent: kind === "explore" ? "explore" : kind === "restore_fun" ? "restore_fun" : kind === "stabilize" ? "measure" : intent, locked: priority === "P0", }); toast.show("Block added"); onChanged(); onClose(); } catch (e) { toast.show(e instanceof Error ? e.message : "Could not add", "error"); } finally { setBusy(false); } };
const removeBlock = async () => { if (!block || !confirm("Remove this block?")) return; setBusy(true); try { await deletePlanBlock(day, block.id); toast.show("Removed"); onChanged(); onClose(); } catch (e) { toast.show(e instanceof Error ? e.message : "Delete failed", "error"); } finally { setBusy(false); } };
return ( <Sheet open={open} tall title={mode === "create" ? "Add block" : block?.title || "Block"} onClose={onClose} > {mode === "create" ? ( <div class="stack"> <label class="field-label"> Title <input class="field-input" value={title} onInput={(e) => setTitle((e.target as HTMLInputElement).value)} /> </label> <span class="field-label">Type</span> <div class="choice-list"> {KIND_OPTIONS.map((opt) => ( <Pressable key={opt.value} className="choice-item" ariaPressed={kind === opt.value} onClick={() => setKind(opt.value)} > {opt.label} </Pressable> ))} </div> <div class="plan-time-row"> <label class="field-label"> Start <input class="field-input" type="time" value={start} onInput={(e) => setStart((e.target as HTMLInputElement).value)} /> </label> <label class="field-label"> End <input class="field-input" type="time" value={end} onInput={(e) => setEnd((e.target as HTMLInputElement).value)} /> </label> </div> <span class="field-label">Priority</span> <div class="segment-row"> {(["P0", "P1", "P2"] as const).map((p) => ( <Pressable key={p} className="segment" ariaPressed={priority === p} onClick={() => setPriority(p)}> {p === "P0" ? "Locked" : p === "P1" ? "Important" : "Flex"} </Pressable> ))} </div> <div class="resolve-sticky"> <Button className="btn-large" disabled={busy} onClick={createBlock}> {busy ? "Saving…" : "Add block"} </Button> </div> </div> ) : block ? ( <div class="stack"> <p class="meta-line"> {block.start}–{block.end} · {block.label || block.kind} ·{" "} {block.priority === "P0" ? "Locked" : block.priority} {block.locked ? " · locked" : ""} </p> <span class="section-title">How did it go?</span> <div class="segment-row"> {([ ["done", "Done"], ["partial", "Partial"], ["skipped", "Skipped"], ] as const).map(([value, label]) => ( <Pressable key={value} className="segment" ariaPressed={did === value} onClick={() => setDid(value)} > {label} </Pressable> ))} </div> {did !== "skipped" && ( <> <label class="field-label"> Actual minutes <input class="field-input" type="number" min={0} max={24 * 60} value={actualMin} onInput={(e) => setActualMin(Number((e.target as HTMLInputElement).value))} /> </label> <span class="field-label">Quality</span> <div class="segment-row"> {[1, 2, 3, 4, 5].map((n) => ( <Pressable key={n} className="segment" ariaPressed={quality === n} onClick={() => setQuality(n)}> {n} </Pressable> ))} </div> <span class="field-label">Fun</span> <div class="segment-row"> {[1, 2, 3, 4, 5].map((n) => ( <Pressable key={n} className="segment" ariaPressed={fun === n} onClick={() => setFun(n)}> {n} </Pressable> ))} </div> </> )} <span class="field-label">Energy after</span> <div class="segment-row"> {[ [-2, "Worse"], [0, "Same"], [2, "Better"], ].map(([v, label]) => ( <Pressable key={String(v)} className="segment" ariaPressed={energy === v} onClick={() => setEnergy(Number(v))} > {label} </Pressable> ))} </div> {(block.intent === "explore" || block.intent === "restore_fun") && did !== "skipped" && ( <> <span class="field-label">Would repeat?</span> <div class="segment-row"> {(["yes", "maybe", "no"] as const).map((v) => ( <Pressable key={v} className="segment" ariaPressed={wouldRepeat === v} onClick={() => setWouldRepeat(v)} > {v} </Pressable> ))} </div> </> )} {did === "skipped" && ( <> <span class="field-label">Why skipped?</span> <div class="segment-row"> {["time", "fear", "urge", "boring", "other"].map((v) => ( <Pressable key={v} className="segment" ariaPressed={skipReason === v} onClick={() => setSkipReason(v)} > {v} </Pressable> ))} </div> </> )} <label class="field-label"> Money (optional, TZS) <input class="field-input" inputMode="decimal" value={money} onInput={(e) => setMoney((e.target as HTMLInputElement).value)} /> </label> <label class="field-label"> Note <input class="field-input" value={note} onInput={(e) => setNote((e.target as HTMLInputElement).value)} /> </label> <div class="resolve-sticky stack"> <Button className="btn-large" disabled={busy} onClick={saveFeedback}> {busy ? "Saving…" : "Save feedback"} </Button> <Button className="btn-secondary" disabled={busy} onClick={removeBlock}> Remove block </Button> </div> </div> ) : null} </Sheet> );}123456789101112131415162 unmodified lines1920212223242540 unmodified lines6667686970717273747576/** Bottom nav: Home | History | gold FAB Log | Daily | Settings. */import {CalendarDays,History,House,Plus,Settings,} from "lucide-preact";import { Pressable } from "./Pressable";import { navigate, type Route } from "../router";type TabName = "home" | "history" | "daily" | "settings";const TABS: {name: TabName;2 unmodified linesIcon: typeof House;}[] = [{ name: "home", label: "Home", path: "/", Icon: House },{ name: "history", label: "History", path: "/history", Icon: History },{ name: "daily", label: "Daily", path: "/daily", Icon: CalendarDays },{ name: "settings", label: "Settings", path: "/settings", Icon: Settings },];40 unmodified lines})}</div><PressableclassName="tab-fab"ariaLabel="Log"onClick={() => navigate("/log")}><Plus size={28} strokeWidth={2.5} color="#202020" aria-hidden="true" /></Pressable></nav>123456789101112132 unmodified lines1617181920212240 unmodified lines63646566676869/** Bottom nav: Home | Plan | gold FAB Log | Daily | Settings.History stays reachable from Home (“See all”). Log FAB remains one tap.*/import { CalendarClock, CalendarDays, House, Plus, Settings } from "lucide-preact";import { Pressable } from "./Pressable";import { navigate, type Route } from "../router";type TabName = "home" | "plan" | "daily" | "settings";const TABS: {name: TabName;2 unmodified linesIcon: typeof House;}[] = [{ name: "home", label: "Home", path: "/", Icon: House },{ name: "plan", label: "Plan", path: "/plan", Icon: CalendarClock },{ name: "daily", label: "Daily", path: "/daily", Icon: CalendarDays },{ name: "settings", label: "Settings", path: "/settings", Icon: Settings },];40 unmodified lines})}</div><Pressable className="tab-fab" ariaLabel="Log" onClick={() => navigate("/log")}><Plus size={28} strokeWidth={2.5} color="#202020" aria-hidden="true" /></Pressable></nav>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103/** iOS-like day timeline: hour grid, now line, colored blocks. */
import type { ScheduledBlock } from "../api";
const DAY_START = 6;const DAY_END = 23;const HOUR_PX = 64;
export function parseMinutes(hhmm: string): number { const [h, m] = hhmm.split(":").map(Number); return h * 60 + m;}
export function timelineMetrics() { const startMin = DAY_START * 60; const endMin = DAY_END * 60; return { startMin, endMin, hourPx: HOUR_PX, totalPx: ((endMin - startMin) / 60) * HOUR_PX, };}
function blockClass(block: ScheduledBlock): string { const parts = ["timeline-block"]; if (block.priority === "P0" || block.locked) parts.push("p0"); else if (block.intent === "explore") parts.push("explore"); else if (block.intent === "restore_fun") parts.push("restore"); else if (block.kind === "stabilize") parts.push("stabilize"); else if (block.priority === "P1") parts.push("duty"); else parts.push("flex"); if (block.status === "done" || block.status === "partial") parts.push("done"); if (block.status === "skipped" || block.status === "cancelled") parts.push("skipped"); return parts.join(" ");}
type Props = { blocks: ScheduledBlock[]; onSelect: (block: ScheduledBlock) => void; now?: Date;};
export function Timeline({ blocks, onSelect, now = new Date() }: Props) { const { startMin, endMin, hourPx, totalPx } = timelineMetrics(); const hours: number[] = []; for (let h = DAY_START; h <= DAY_END; h += 1) hours.push(h);
const nowMin = now.getHours() * 60 + now.getMinutes(); const showNow = nowMin >= startMin && nowMin <= endMin; const nowTop = ((nowMin - startMin) / 60) * hourPx;
return ( <div class="timeline" style={{ height: `${totalPx}px` }}> <div class="timeline-gutter" aria-hidden="true"> {hours.map((h) => ( <div key={h} class="timeline-hour-label" style={{ top: `${((h * 60 - startMin) / 60) * hourPx}px` }} > {`${String(h).padStart(2, "0")}:00`} </div> ))} </div> <div class="timeline-canvas"> {hours.map((h) => ( <div key={h} class="timeline-hour-line" style={{ top: `${((h * 60 - startMin) / 60) * hourPx}px` }} /> ))} {showNow && ( <div class="timeline-now" style={{ top: `${nowTop}px` }}> <span class="timeline-now-dot" /> </div> )} {blocks.map((block) => { const start = Math.max(parseMinutes(block.start), startMin); const end = Math.min(parseMinutes(block.end), endMin); if (end <= start) return null; const top = ((start - startMin) / 60) * hourPx; const height = Math.max(28, ((end - start) / 60) * hourPx - 4); return ( <button key={block.id} type="button" class={blockClass(block)} style={{ top: `${top}px`, height: `${height}px` }} onClick={() => onSelect(block)} > <strong>{block.title}</strong> <span> {block.start}–{block.end} · {block.planned_min}m </span> </button> ); })} </div> </div> );}9 unmodified lines10111213141555 unmodified lines7172737475769 unmodified linesimport { History } from "./pages/History";import { EntryDetail } from "./pages/EntryDetail";import { Daily } from "./pages/Daily";import { Stats } from "./pages/Stats";import { Remedies } from "./pages/Remedies";import { Coach } from "./pages/Coach";55 unmodified lineselse if (route.name === "history") page = <History />;else if (route.name === "entry") page = <EntryDetail id={route.id} />;else if (route.name === "daily") page = <Daily />;else if (route.name === "stats") page = <Stats />;else if (route.name === "coach") page = <Coach />;else if (route.name === "remedies") page = <Remedies />;9 unmodified lines1011121314151655 unmodified lines727374757677789 unmodified linesimport { History } from "./pages/History";import { EntryDetail } from "./pages/EntryDetail";import { Daily } from "./pages/Daily";import { Plan } from "./pages/Plan";import { Stats } from "./pages/Stats";import { Remedies } from "./pages/Remedies";import { Coach } from "./pages/Coach";55 unmodified lineselse if (route.name === "history") page = <History />;else if (route.name === "entry") page = <EntryDetail id={route.id} />;else if (route.name === "daily") page = <Daily />;else if (route.name === "plan") page = <Plan initialDate={route.date} />;else if (route.name === "stats") page = <Stats />;else if (route.name === "coach") page = <Coach />;else if (route.name === "remedies") page = <Remedies />;
2 unmodified lines3456789101112136 unmodified lines2021222324252627282930313233348 unmodified lines43444546474849503 unmodified lines54555657585974 unmodified lines13413513613713813942 unmodified lines18218318418518618718832 unmodified lines2212222232242252262 unmodified linesimport { ChevronRight, Clock3 } from "lucide-preact";import { useEffect, useState } from "preact/hooks";import {listDaily,listEntries,type DailyRangeData,type DailyRow,type Entry,} from "../api";import { Pressable } from "../components/Pressable";import { usePendingResolve } from "../components/PendingResolve";6 unmodified linesconst WEEK_MAX = 42; // 6 pts × 7 daysexport function Home() {const { openResolve, refreshPendingSignal } = usePendingResolve();const [pending, setPending] = useState<Entry[]>([]);const [week, setWeek] = useState<DailyRangeData | null>(null);const [recent, setRecent] = useState<Entry[]>([]);const [entryDays, setEntryDays] = useState<Set<string>>(new Set());const load = async () => {const weekDays = mondaySundayWeek(new Date());try {const pendingData = await listEntries({ result: "pending", limit: 50 });setPending(pendingData.items);8 unmodified linestry {const recentData = await listEntries({ limit: 8 });setRecent(recentData.items);setEntryDays(new Set(recentData.items.map((e) => entryLocalDate(e.ts))));// Fill more dates for week strip completenessconst range = await listEntries({start: weekDays[0],end: weekDays[6],3 unmodified lines} catch {setRecent([]);}};useEffect(() => {74 unmodified lines</Pressable>) : null}{/* 4. Hero score card */}<section class="hero-score-card surface-card" aria-label="Week points"><div class="hero-score-copy">42 unmodified lines{/* 6. Recent entries */}<section class="stack recent-section" aria-label="Recent entries"><h2 class="section-title">Recent</h2>{!recent.length ? (<p class="muted">No entries yet.</p>) : (32 unmodified lines{/* 7. Quick actions */}<section class="quick-actions" aria-label="Quick actions"><Pressable className="quick-chip" onClick={() => navigate("/history")}>History</Pressable>2 unmodified lines34567891011121314156 unmodified lines22232425262728293031323334353637383940414243448 unmodified lines5354555657583 unmodified lines62636465666768697071727374757677787980818283848586878874 unmodified lines16316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021142 unmodified lines25425525625725825926026126226326426526626732 unmodified lines3003013023033043053063073082 unmodified linesimport { ChevronRight, Clock3 } from "lucide-preact";import { useEffect, useState } from "preact/hooks";import {getPlan,listDaily,listEntries,type DailyRangeData,type DailyRow,type Entry,type ScheduledBlock,} from "../api";import { Pressable } from "../components/Pressable";import { usePendingResolve } from "../components/PendingResolve";6 unmodified linesconst WEEK_MAX = 42; // 6 pts × 7 daysfunction parseMin(hhmm: string): number {const [h, m] = hhmm.split(":").map(Number);return h * 60 + m;}export function Home() {const { openResolve, refreshPendingSignal } = usePendingResolve();const [pending, setPending] = useState<Entry[]>([]);const [week, setWeek] = useState<DailyRangeData | null>(null);const [recent, setRecent] = useState<Entry[]>([]);const [entryDays, setEntryDays] = useState<Set<string>>(new Set());const [nextBlocks, setNextBlocks] = useState<ScheduledBlock[]>([]);const [overdue, setOverdue] = useState<ScheduledBlock | null>(null);const load = async () => {const weekDays = mondaySundayWeek(new Date());const todayIso = isoDate(new Date());try {const pendingData = await listEntries({ result: "pending", limit: 50 });setPending(pendingData.items);8 unmodified linestry {const recentData = await listEntries({ limit: 8 });setRecent(recentData.items);const range = await listEntries({start: weekDays[0],end: weekDays[6],3 unmodified lines} catch {setRecent([]);}try {const plan = await getPlan(todayIso);const now = new Date();const nowMin = now.getHours() * 60 + now.getMinutes();const upcoming = plan.blocks.filter((b) => b.status === "planned" && parseMin(b.end) >= nowMin).sort((a, b) => parseMin(a.start) - parseMin(b.start)).slice(0, 2);setNextBlocks(upcoming);const overdueBlock =plan.blocks.find((b) =>b.status === "planned" &&parseMin(b.end) < nowMin &&!b.feedback,) || null;setOverdue(overdueBlock);} catch {setNextBlocks([]);setOverdue(null);}};useEffect(() => {74 unmodified lines</Pressable>) : null}{overdue && (<PressableclassName="tip-card"onClick={() => navigate("/plan")}ariaLabel={`Finish feedback for ${overdue.title}`}><p>Finish feedback for: <strong>{overdue.title}</strong></p></Pressable>)}<section class="surface-card form-card stack" aria-label="Today's plan"><div class="week-progress-row"><h2 class="section-title" style={{ margin: 0 }}>Today’s plan</h2><Pressable className="chip-btn" onClick={() => navigate("/plan")}>Open</Pressable></div>{!nextBlocks.length ? (<p class="muted">No upcoming blocks. Open Plan to add one.</p>) : (<div class="stack">{nextBlocks.map((b) => (<Pressablekey={b.id}className="entry-row"onClick={() => navigate("/plan")}><span class="entry-row-main"><span class="entry-preview">{b.title}</span><time>{b.start}–{b.end}</time></span></Pressable>))}</div>)}</section>{/* 4. Hero score card */}<section class="hero-score-card surface-card" aria-label="Week points"><div class="hero-score-copy">42 unmodified lines{/* 6. Recent entries */}<section class="stack recent-section" aria-label="Recent entries"><div class="week-progress-row"><h2 class="section-title" style={{ margin: 0 }}>Recent</h2><Pressable className="chip-btn" onClick={() => navigate("/history")}>See all</Pressable></div>{!recent.length ? (<p class="muted">No entries yet.</p>) : (32 unmodified lines{/* 7. Quick actions */}<section class="quick-actions" aria-label="Quick actions"><Pressable className="quick-chip" onClick={() => navigate("/plan")}>Plan</Pressable><Pressable className="quick-chip" onClick={() => navigate("/history")}>History</Pressable>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151/** Plan day view: iOS-like timeline, reschedule, add/complete blocks.
Nav IA: Home | Plan | (+) Log | Daily | Settings (History via Home).*/
import { ChevronLeft, ChevronRight } from "lucide-preact";import { useEffect, useState } from "preact/hooks";import { getPlan, reschedulePlan, type DayPlanView, type ScheduledBlock,} from "../api";import { BlockSheet } from "../components/BlockSheet";import { Button } from "../components/Button";import { Pressable } from "../components/Pressable";import { Timeline } from "../components/Timeline";import { useToast } from "../components/Toast";import { isoDate } from "../dates";
function shiftDay(day: string, delta: number): string { const d = new Date(`${day}T00:00:00`); d.setDate(d.getDate() + delta); return isoDate(d);}
function friendly(day: string): string { return new Date(`${day}T00:00:00`).toLocaleDateString(undefined, { weekday: "short", month: "short", day: "numeric", });}
export function Plan({ initialDate }: { initialDate?: string }) { const toast = useToast(); const [day, setDay] = useState(initialDate || isoDate(new Date())); const [plan, setPlan] = useState<DayPlanView | null>(null); const [busy, setBusy] = useState(false); const [selected, setSelected] = useState<ScheduledBlock | null>(null); const [sheetMode, setSheetMode] = useState<"view" | "create">("view"); const [sheetOpen, setSheetOpen] = useState(false);
const load = async (date: string) => { try { setPlan(await getPlan(date)); } catch { setPlan(null); } };
useEffect(() => { void load(day); }, [day]);
const openBlock = (block: ScheduledBlock) => { setSelected(block); setSheetMode("view"); setSheetOpen(true); };
const openCreate = () => { setSelected(null); setSheetMode("create"); setSheetOpen(true); };
const onReschedule = async () => { if (!confirm("Reschedule the rest of this day? Must-do blocks stay put.")) return; setBusy(true); try { const result = await reschedulePlan(day, { reason: "user", force: true }); setPlan(result.plan); toast.show(result.source === "rules" ? "Rescheduled (rules)" : "Rescheduled"); } catch (e) { toast.show(e instanceof Error ? e.message : "Reschedule failed", "error"); } finally { setBusy(false); } };
const capacity = plan?.capacity_hint ?? 1; const health = plan?.health;
return ( <div class="app-shell"> <header class="top-bar material-bar plan-header"> <div class="plan-day-nav"> <Pressable className="icon-btn" ariaLabel="Previous day" onClick={() => setDay(shiftDay(day, -1))}> <ChevronLeft size={22} /> </Pressable> <div> <h1 class="page-title">Plan</h1> <span class="daily-date">{friendly(day)}</span> </div> <Pressable className="icon-btn" ariaLabel="Next day" onClick={() => setDay(shiftDay(day, 1))}> <ChevronRight size={22} /> </Pressable> </div> <Pressable className="chip-btn" onClick={() => setDay(isoDate(new Date()))}> Today </Pressable> </header>
<main class="page stack plan-page"> <div class="plan-meta-row"> <span class="caption">Capacity {Math.round(capacity * 100)}%</span> {health && ( <span class="caption"> Health {Math.round(health.score * 100)}% · v{plan?.version ?? 1} </span> )} </div> {capacity < 0.55 && ( <div class="tip-card" role="status"> <p>High load risk — lighter plan recommended.</p> </div> )}
<div class="plan-actions"> <Button className="btn-secondary" disabled={busy} onClick={openCreate}> + Block </Button> <Button className="btn-secondary" disabled={busy} onClick={onReschedule}> Reschedule </Button> </div>
{!plan?.blocks.length ? ( <section class="surface-card empty-card stack"> <p>No blocks yet. Add one, or Reschedule for a starter plan.</p> <Button onClick={openCreate}>Add block</Button> </section> ) : ( <section class="surface-card timeline-card"> <Timeline blocks={plan.blocks} onSelect={openBlock} /> </section> )} </main>
<BlockSheet open={sheetOpen} day={day} block={selected} mode={sheetMode} onClose={() => setSheetOpen(false)} onChanged={() => void load(day)} /> </div> );}8 unmodified lines9101112131410 unmodified lines2526272829308 unmodified lines| { name: "history" }| { name: "entry"; id: string }| { name: "daily" }| { name: "stats" }| { name: "coach" }| { name: "remedies" }10 unmodified linesif (path === "/history") return { name: "history" };if (path.startsWith("/entry/")) return { name: "entry", id: decodeURIComponent(path.slice(7)) };if (path === "/daily") return { name: "daily" };if (path === "/stats") return { name: "stats" };if (path === "/coach") return { name: "coach" };if (path === "/remedies") return { name: "remedies" };8 unmodified lines910111213141510 unmodified lines26272829303132338 unmodified lines| { name: "history" }| { name: "entry"; id: string }| { name: "daily" }| { name: "plan"; date?: string }| { name: "stats" }| { name: "coach" }| { name: "remedies" }10 unmodified linesif (path === "/history") return { name: "history" };if (path.startsWith("/entry/")) return { name: "entry", id: decodeURIComponent(path.slice(7)) };if (path === "/daily") return { name: "daily" };if (path === "/plan") return { name: "plan" };if (path.startsWith("/plan/")) return { name: "plan", date: decodeURIComponent(path.slice(6)) };if (path === "/stats") return { name: "stats" };if (path === "/coach") return { name: "coach" };if (path === "/remedies") return { name: "remedies" };
937 unmodified lines938939940941942943937 unmodified linesbackground: linear-gradient(to top, var(--bg) 70%, transparent);}@keyframes card-in {from { opacity: 0; transform: translateY(8px); }to { opacity: 1; transform: translateY(0); }937 unmodified lines938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044937 unmodified linesbackground: linear-gradient(to top, var(--bg) 70%, transparent);}/* Plan timeline */.plan-header { flex-wrap: wrap; gap: 0.5rem; }.plan-day-nav { display: flex; align-items: center; gap: 0.35rem; }.icon-btn {width: 44px;height: 44px;display: grid;place-items: center;border-radius: 999px;color: var(--text);}.chip-btn {min-height: 36px;padding: 0 0.85rem;border-radius: 999px;background: var(--accent-soft);color: var(--text);font-weight: 600;font-size: 13px;}.plan-meta-row { display: flex; justify-content: space-between; gap: 0.75rem; }.caption { font-size: 13px; color: var(--text-secondary); }.plan-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 0.6rem; }.timeline-card { padding: 12px 8px 12px 0; overflow: hidden; }.timeline {position: relative;display: grid;grid-template-columns: 56px 1fr;}.timeline-gutter { position: relative; }.timeline-hour-label {position: absolute;right: 8px;transform: translateY(-50%);font-size: 11px;color: var(--text-tertiary);}.timeline-canvas { position: relative; border-left: 1px solid var(--separator); }.timeline-hour-line {position: absolute;left: 0;right: 0;height: 1px;background: var(--separator);}.timeline-now {position: absolute;left: 0;right: 0;height: 2px;background: var(--accent);z-index: 3;}.timeline-now-dot {position: absolute;left: -5px;top: -4px;width: 10px;height: 10px;border-radius: 999px;background: var(--accent);}.timeline-block {position: absolute;left: 8px;right: 8px;z-index: 2;display: flex;flex-direction: column;align-items: flex-start;justify-content: center;gap: 0.1rem;padding: 6px 10px;border-radius: 12px;border: 1px solid transparent;text-align: left;overflow: hidden;}.timeline-block strong { font-size: 13px; font-weight: 600; }.timeline-block span { font-size: 11px; opacity: 0.85; }.timeline-block.duty { background: #e8eef3; color: #243447; }.timeline-block.explore { background: #e5f3ea; color: #1f4d32; }.timeline-block.restore { background: #f3e8f0; color: #4a2f45; }.timeline-block.stabilize { background: #f7ecd8; color: #5a4418; }.timeline-block.flex { background: var(--surface-secondary); color: var(--text); }.timeline-block.p0 { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }.timeline-block.done { opacity: 0.55; }.timeline-block.skipped { opacity: 0.4; text-decoration: line-through; }.plan-time-row { display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; }.btn-secondary {min-height: var(--btn-h);width: 100%;border-radius: 999px;background: var(--card);border: 1px solid var(--separator);color: var(--text);font-weight: 600;}.meta-line { margin: 0; color: var(--text-secondary); font-size: 14px; }.empty-card { text-align: center; }@keyframes card-in {from { opacity: 0; transform: translateY(8px); }to { opacity: 1; transform: translateY(0); }
1:root{color-scheme:light;--bg: #ebe7e0;--bg-elevated: #f1eee8;--card: #f8f6f2;--surface: #f8f6f2;--surface-solid: #f8f6f2;--surface-secondary: #f1eee8;--text: #202020;--text-secondary: #666666;--text-tertiary: #9a9a9a;--separator: rgba(32, 32, 32, .08);--accent: #e8a317;--accent-soft: rgba(232, 163, 23, .16);--ok: #2f6b3c;--ok-bg: #e4f0e6;--warn: #8a6a10;--warn-bg: #f5ebcc;--danger: #8b3a34;--danger-bg: #f0e0de;--pending-bg: #faf3e3;--pending-border: #e8a317;--scrim: rgba(32, 32, 32, .35);--shadow: 0 8px 24px rgba(32, 32, 32, .06);--radius: 20px;--pad: 1.25rem;--hit: 44px;--btn-h: 56px;--fab-size: 60px;--tab-h: 76px;--font: "Plus Jakarta Sans", system-ui, -apple-system, "Segoe UI", sans-serif;--safe-top: env(safe-area-inset-top, 0px);--safe-bottom: env(safe-area-inset-bottom, 0px);font:400 16px/1.47 var(--font);background:var(--bg);color:var(--text);letter-spacing:0}@media(prefers-contrast:more){:root{--separator: rgba(32, 32, 32, .28);--text-secondary: #444444;--shadow: none}}*,*:before,*:after{box-sizing:border-box}html,body,#app{min-height:100%;margin:0}body{background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}button,input,textarea,select{font:inherit;color:inherit}button{cursor:pointer;border:none;background:none}a{color:var(--accent);text-decoration:none}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}img{max-width:100%}.material-bar{background:#f8f6f2eb;border-bottom:1px solid var(--separator)}.sheet-material{background:var(--card);border-radius:20px 20px 0 0;box-shadow:0 -8px 40px #2020201f}.surface-card{background:var(--card);border:1px solid var(--separator);border-radius:var(--radius);box-shadow:var(--shadow)}@media(prefers-reduced-transparency:reduce){.material-bar,.sheet-material,.surface-card{backdrop-filter:none;-webkit-backdrop-filter:none;background:var(--surface-solid)}}@media(prefers-contrast:more){.material-bar,.sheet-material,.surface-card{border-color:#20202047;box-shadow:none}}.app-shell{min-height:100dvh;display:flex;flex-direction:column;background:var(--bg)}.top-bar{position:sticky;top:0;z-index:20;display:flex;align-items:center;gap:.75rem;min-height:calc(var(--hit) + var(--safe-top));padding:calc(.5rem + var(--safe-top)) var(--pad) .75rem}.top-bar h1,.page-title{margin:0;font-size:28px;font-weight:700;letter-spacing:-.02em;line-height:1.1}.page{flex:1;width:min(40rem,100%);margin:0 auto;padding:1.25rem var(--pad) calc(1.5rem + var(--safe-bottom) + var(--tab-h) + .75rem)}.home-page{gap:16px;animation:card-in .18s ease both}.stack{display:flex;flex-direction:column;gap:16px}.field-label{display:block;margin-bottom:.4rem;color:var(--text-secondary);font-size:13px;font-weight:500}.field-input,.field-textarea{width:100%;min-height:var(--hit);padding:.85rem 1rem;border-radius:16px;border:1px solid var(--separator);background:var(--card);color:var(--text)}.field-textarea{min-height:7rem;resize:vertical;line-height:1.47}.muted{color:var(--text-secondary)}.tertiary{color:var(--text-tertiary)}.error-text{color:var(--danger);font-size:.9rem}.chip-row{display:flex;flex-wrap:wrap;gap:.5rem}.chip{min-height:var(--hit);padding:0 .95rem;border-radius:999px;border:1px solid var(--separator);background:var(--card);color:var(--text-secondary);font-weight:500;display:inline-flex;align-items:center;gap:.35rem}.chip[aria-pressed=true]{border-color:var(--accent);background:var(--accent-soft);color:var(--text)}.chip.result-worked[aria-pressed=true]{border-color:var(--ok);background:var(--ok-bg);color:var(--ok)}.chip.result-partial[aria-pressed=true]{border-color:var(--warn);background:var(--warn-bg);color:var(--warn)}.chip.result-failed[aria-pressed=true]{border-color:var(--danger);background:var(--danger-bg);color:var(--danger)}.chip.result-pending[aria-pressed=true]{border-color:var(--pending-border);background:var(--pending-bg);color:var(--accent)}.slider-wrap{display:grid;gap:.5rem}.slider-wrap input[type=range]{width:100%;accent-color:var(--accent)}.more-block{border-top:1px solid var(--separator);padding-top:1rem}.login-page{min-height:100dvh;display:grid;place-items:center;padding:var(--pad);padding-top:calc(var(--pad) + var(--safe-top));padding-bottom:calc(var(--pad) + var(--safe-bottom));background:var(--bg)}.login-card{width:min(22rem,100%);padding:1.5rem}.login-card h1{margin:0 0 .35rem;font-size:32px;font-weight:700;letter-spacing:-.02em;line-height:1.1}.toast-host{position:fixed;left:0;right:0;top:calc(.75rem + var(--safe-top));z-index:50;display:flex;justify-content:center;pointer-events:none;padding:0 var(--pad)}.toast{pointer-events:auto;max-width:24rem;width:100%;padding:.85rem 1rem;border-radius:16px;background:var(--card);border:1px solid var(--separator);box-shadow:var(--shadow);color:var(--text);font-weight:500}.toast.error{border-color:var(--danger);background:var(--danger-bg)}.pressable{touch-action:manipulation;-webkit-tap-highlight-color:transparent;transform-origin:center}.btn{display:inline-flex;align-items:center;justify-content:center;min-height:var(--btn-h);padding:0 1.25rem;border-radius:999px;font-weight:600}.btn:disabled{opacity:.4;pointer-events:none}.btn-primary{background:var(--accent);color:#202020}.btn-secondary{background:var(--card);border:1px solid var(--separator);color:var(--text)}.btn-destructive{background:var(--danger-bg);color:var(--danger);border:1px solid rgba(139,58,52,.25)}.btn-plain{color:var(--text-secondary);min-height:var(--hit);padding:0 .35rem;justify-content:flex-start;font-weight:500}.btn-large{min-height:var(--btn-h);width:100%;font-size:1.0625rem}.tab-bar{position:fixed;left:0;right:0;bottom:0;z-index:30;min-height:calc(var(--tab-h) + var(--safe-bottom));padding-bottom:var(--safe-bottom);background:var(--card);border-top:1px solid var(--separator)}.tab-bar-inner{display:grid;grid-template-columns:1fr 1fr 60px 1fr 1fr;align-items:stretch;min-height:var(--tab-h);padding:0 .35rem}.tab-item{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.2rem;min-height:var(--tab-h);color:var(--text-tertiary);font-size:11px;font-weight:500;letter-spacing:.01em}.tab-item.active{color:var(--text);font-weight:600}.tab-item.active svg{color:var(--accent)}.tab-fab-slot{width:var(--fab-size)}.tab-fab{position:absolute;left:50%;top:-10px;transform:translate(-50%);width:var(--fab-size);height:var(--fab-size);border-radius:999px;background:var(--accent);box-shadow:0 10px 24px #e8a31759;display:grid;place-items:center}.home-greeting{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem}.greeting-title{margin:0;font-size:32px;font-weight:700;letter-spacing:-.02em;line-height:1.1}.greeting-sub{margin:.35rem 0 0;color:var(--text-secondary);font-size:15px}.avatar-circle{width:48px;height:48px;border-radius:999px;background:var(--accent-soft);color:var(--text);display:grid;place-items:center;font-weight:700;font-size:14px;flex-shrink:0}.week-calendar{display:grid;grid-template-columns:repeat(7,1fr);gap:.35rem}.week-cal-cell{display:grid;justify-items:center;gap:.25rem;padding:.55rem .2rem;border-radius:16px;background:transparent}.week-cal-cell.today{background:var(--accent);color:#202020}.week-cal-label{font-size:11px;font-weight:600;color:inherit;opacity:.7}.week-cal-num{font-size:15px;font-weight:700}.week-cal-dot{width:6px;height:6px;border-radius:999px;background:transparent}.week-cal-cell.filled .week-cal-dot{background:var(--accent)}.week-cal-cell.today.filled .week-cal-dot,.week-cal-cell.today .week-cal-dot{background:#202020}.pending-banner-card{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:.75rem;min-height:100px;padding:.75rem 1rem;border-radius:var(--radius);background:var(--pending-bg);border:1.5px solid var(--pending-border);text-align:left;box-shadow:var(--shadow)}.pending-illu{width:88px;height:auto}.pending-copy{display:grid;gap:.15rem}.pending-copy strong{font-size:18px;font-weight:600}.pending-copy span{color:var(--text-secondary);font-size:14px}.hero-score-card{display:grid;grid-template-columns:1fr 38%;align-items:center;gap:.5rem;padding:18px;overflow:hidden}.hero-score-label{color:var(--text-secondary);font-size:14px;font-weight:500}.hero-score-value{margin:.15rem 0;font-size:54px;font-weight:700;letter-spacing:-.03em;line-height:1}.hero-score-sub{margin:0;color:var(--text-secondary);font-size:14px}.hero-illu{width:100%;height:auto;justify-self:end}.week-progress-card{display:grid;grid-template-columns:1fr auto;gap:.75rem;align-items:center;padding:16px 18px}.week-progress-row{display:flex;justify-content:space-between;gap:.75rem;margin-bottom:.45rem;color:var(--text-secondary);font-size:14px}.week-progress-row strong{color:var(--text);font-size:18px}.progress-track{height:8px;border-radius:999px;background:var(--surface-secondary);overflow:hidden;margin-top:.35rem}.progress-fill{height:100%;border-radius:inherit;background:var(--accent)}.scores-illu{width:72px;height:auto}.section-title{margin:0;font-size:20px;font-weight:600}.entry-list{display:grid;gap:.65rem}.entry-row{display:grid;grid-template-columns:auto 1fr;gap:.75rem;align-items:start;padding:16px;min-height:var(--hit);text-align:left;border-radius:var(--radius);background:var(--card);border:1px solid var(--separator);box-shadow:var(--shadow)}.entry-row.pending-row{background:var(--pending-bg);border-color:var(--pending-border)}.entry-row-main{display:grid;gap:.25rem;min-width:0}.entry-preview{color:var(--text);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}.entry-row time{color:var(--text-tertiary);font-size:13px}.result-chip{display:inline-flex;align-items:center;gap:.25rem;padding:.3rem .55rem;border-radius:999px;font-size:12px;font-weight:600;text-transform:capitalize;white-space:nowrap}.result-chip.result-worked{background:var(--ok-bg);color:var(--ok)}.result-chip.result-partial{background:var(--warn-bg);color:var(--warn)}.result-chip.result-failed{background:var(--danger-bg);color:var(--danger)}.result-chip.result-pending{background:var(--pending-bg);color:var(--accent);border:1px solid var(--pending-border)}.quick-actions{display:flex;flex-wrap:wrap;gap:.5rem}.quick-chip{min-height:40px;padding:0 1rem;border-radius:999px;background:var(--surface-secondary);color:var(--text);font-weight:500;font-size:14px}.search-field{position:relative;display:block}.search-field svg{position:absolute;left:.9rem;top:50%;transform:translateY(-50%);color:var(--text-tertiary);pointer-events:none}.search-input{padding-left:2.4rem}.empty-state{padding:2rem 1.25rem;text-align:center;display:grid;gap:.75rem;justify-items:center}.detail-card,.form-card,.stats-card,.settings-card,.coach-result,.score-card{padding:16px 18px}.detail-snippet{margin:0;font-size:18px;font-weight:600;line-height:1.35}.meta-grid{display:grid;gap:.75rem}.section-head{display:flex;align-items:center;justify-content:space-between}.linkish{display:inline-flex;align-items:center;gap:.15rem;color:var(--accent);font-weight:600;font-size:14px;background:none;border:none;padding:0}.pending-focus{border:1.5px solid var(--pending-border);background:var(--pending-bg)}.resolve-snippet{padding:1rem}.resolve-activity{margin:0 0 .35rem;font-size:13px}.resolve-sticky{position:sticky;bottom:0;padding-top:.5rem;padding-bottom:.25rem;background:linear-gradient(transparent,var(--card) 28%)}.sheet-tall{max-height:85dvh!important}.gate-loading{min-height:100dvh;display:grid;place-items:center;color:var(--text-secondary);background:var(--bg)}.top-action{margin-left:auto;min-width:var(--hit);min-height:var(--hit);color:var(--accent);font-weight:600}.sheet-layer{position:fixed;top:0;right:0;bottom:0;left:0;z-index:100}.sheet-scrim{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:100%;background:#202020;opacity:0}.sheet-panel{position:absolute;left:0;right:0;bottom:0;max-height:min(82dvh,44rem);overflow:auto;padding-bottom:var(--safe-bottom);will-change:transform}.sheet-handle-zone{position:sticky;top:0;z-index:1;display:grid;justify-items:center;gap:.45rem;padding:.5rem var(--pad) .75rem;background:inherit;touch-action:none;-webkit-user-select:none;user-select:none}.sheet-handle{width:2.25rem;height:.3rem;border-radius:99px;background:var(--text-tertiary)}.sheet-handle-zone h2{margin:0;font-size:20px;font-weight:600}.sheet-content{padding:0 var(--pad) 1.25rem}.menu-list{display:grid}.menu-row{min-height:3.25rem;width:100%;text-align:left;border-bottom:1px solid var(--separator);color:var(--text)}.destructive-text{color:var(--danger)}.result-label{font-size:.75rem;font-weight:600;text-transform:capitalize}.result-worked{color:var(--ok)}.result-partial{color:var(--warn)}.result-failed{color:var(--danger)}.result-pending{color:var(--accent)}.detail-card p,.coach-text{margin:0;white-space:pre-wrap}.result-heading,.status-row,.score-card,.toggle-row{display:flex;align-items:center;justify-content:space-between;gap:.75rem}.source-badge{padding:.2rem .55rem;border-radius:99px;font-size:.75rem;font-weight:700}.source-badge.rules{background:var(--warn-bg);color:var(--warn)}.source-badge.model{background:var(--accent-soft);color:#8a6408}.flags{color:var(--text-tertiary);font-size:.68rem;text-align:right}.pick-list{display:grid;overflow:hidden;border-radius:var(--radius);background:var(--surface-secondary)}.pick-row{display:flex;justify-content:space-between;gap:.75rem;min-height:3rem;padding:.65rem .85rem;text-align:left;border-bottom:1px solid var(--separator)}.pick-row span:last-child{white-space:nowrap;font-size:.75rem}.disclaimer{font-size:.8rem;text-align:center}.coach-input{min-height:9rem}.segment-row{display:flex;flex-wrap:wrap;gap:.4rem}.segment{min-width:var(--hit);min-height:var(--hit);padding:0 .75rem;border:1px solid var(--separator);border-radius:999px;color:var(--text-secondary);background:var(--card)}.segment[aria-pressed=true]{border-color:var(--accent);background:var(--accent-soft);color:var(--text);font-weight:600}.toggle-row{min-height:var(--hit)}.toggle-row input{width:1.4rem;height:1.4rem;accent-color:var(--accent)}.score-card>div{display:grid}.score-card strong,.score-readout{font-size:1.5rem;font-weight:700}.stats-card{display:grid;gap:.85rem}.outcome-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:.5rem}.outcome-grid div{display:grid;text-align:center;gap:.2rem}.outcome-grid strong,.large-number{font-size:1.5rem}.stat-row{display:grid;gap:.35rem}.stat-row>div:first-child{display:flex;justify-content:space-between;gap:.5rem}.bar-track{height:.35rem;border-radius:99px;background:var(--surface-secondary);overflow:hidden}.bar-track span{display:block;height:100%;border-radius:inherit;background:var(--accent)}.install-steps{margin:0;padding-left:1.4rem;display:grid;gap:.5rem}.daily-header{justify-content:space-between;align-items:center}.daily-date{font-size:13px;color:var(--text-secondary)}.daily-points{font-size:1.35rem;font-weight:700;color:var(--warn)}.tip-card{position:relative;display:flex;align-items:flex-start;gap:.5rem;padding:12px 44px 12px 16px;border-radius:var(--radius);background:var(--accent-soft);font-size:14px;color:var(--text-secondary)}.tip-card p{margin:0}.tip-dismiss{position:absolute;top:6px;right:6px;display:grid;place-items:center;width:32px;height:32px;border-radius:999px;color:var(--text-secondary)}.choice-list{display:grid;gap:.5rem}.choice-item{min-height:var(--hit);padding:.7rem 1rem;text-align:left;border:1px solid var(--separator);border-radius:14px;background:var(--card);color:var(--text-secondary);font-size:15px}.choice-item[aria-pressed=true]{border-color:var(--accent);background:var(--accent-soft);color:var(--text);font-weight:600}.stepper-row{display:flex;align-items:center;gap:1rem}.stepper-btn{width:48px;height:48px;border-radius:999px;border:1px solid var(--separator);background:var(--card);font-size:1.4rem;line-height:1}.stepper-btn[disabled]{opacity:.4}.stepper-value{min-width:2.5rem;text-align:center;font-size:1.6rem;font-weight:700}.points-breakdown{list-style:none;margin:0;padding:0;display:grid;gap:.5rem}.points-breakdown li{display:flex;justify-content:space-between;gap:.75rem;font-size:14px}.points-breakdown li.missed{color:var(--text-tertiary)}.points-breakdown .points-pts{font-weight:700}.points-breakdown li.earned .points-pts{color:var(--ok)}.how-points{padding:14px 18px;font-size:14px;color:var(--text-secondary)}.how-points summary{cursor:pointer;font-weight:600;color:var(--text);min-height:var(--hit);display:flex;align-items:center}.how-points ul{margin:.5rem 0 0;padding-left:1.2rem;display:grid;gap:.4rem}.daily-sticky{position:sticky;bottom:0;padding:.5rem 0 .25rem;background:linear-gradient(to top,var(--bg) 70%,transparent)}@keyframes card-in{0%{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}@media(prefers-reduced-motion:reduce){.home-page,.surface-card,.entry-row,.pending-banner-card{animation:none!important;transition:opacity .2s ease}.toast{transition:opacity .2s ease}}@media(prefers-reduced-transparency:reduce){.sheet-scrim{background:#202020cc}}@media(prefers-contrast:more){.tab-bar,.pending-banner-card,.segment,.entry-row{border-color:#20202059}}1:root{color-scheme:light;--bg: #ebe7e0;--bg-elevated: #f1eee8;--card: #f8f6f2;--surface: #f8f6f2;--surface-solid: #f8f6f2;--surface-secondary: #f1eee8;--text: #202020;--text-secondary: #666666;--text-tertiary: #9a9a9a;--separator: rgba(32, 32, 32, .08);--accent: #e8a317;--accent-soft: rgba(232, 163, 23, .16);--ok: #2f6b3c;--ok-bg: #e4f0e6;--warn: #8a6a10;--warn-bg: #f5ebcc;--danger: #8b3a34;--danger-bg: #f0e0de;--pending-bg: #faf3e3;--pending-border: #e8a317;--scrim: rgba(32, 32, 32, .35);--shadow: 0 8px 24px rgba(32, 32, 32, .06);--radius: 20px;--pad: 1.25rem;--hit: 44px;--btn-h: 56px;--fab-size: 60px;--tab-h: 76px;--font: "Plus Jakarta Sans", system-ui, -apple-system, "Segoe UI", sans-serif;--safe-top: env(safe-area-inset-top, 0px);--safe-bottom: env(safe-area-inset-bottom, 0px);font:400 16px/1.47 var(--font);background:var(--bg);color:var(--text);letter-spacing:0}@media(prefers-contrast:more){:root{--separator: rgba(32, 32, 32, .28);--text-secondary: #444444;--shadow: none}}*,*:before,*:after{box-sizing:border-box}html,body,#app{min-height:100%;margin:0}body{background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}button,input,textarea,select{font:inherit;color:inherit}button{cursor:pointer;border:none;background:none}a{color:var(--accent);text-decoration:none}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}img{max-width:100%}.material-bar{background:#f8f6f2eb;border-bottom:1px solid var(--separator)}.sheet-material{background:var(--card);border-radius:20px 20px 0 0;box-shadow:0 -8px 40px #2020201f}.surface-card{background:var(--card);border:1px solid var(--separator);border-radius:var(--radius);box-shadow:var(--shadow)}@media(prefers-reduced-transparency:reduce){.material-bar,.sheet-material,.surface-card{backdrop-filter:none;-webkit-backdrop-filter:none;background:var(--surface-solid)}}@media(prefers-contrast:more){.material-bar,.sheet-material,.surface-card{border-color:#20202047;box-shadow:none}}.app-shell{min-height:100dvh;display:flex;flex-direction:column;background:var(--bg)}.top-bar{position:sticky;top:0;z-index:20;display:flex;align-items:center;gap:.75rem;min-height:calc(var(--hit) + var(--safe-top));padding:calc(.5rem + var(--safe-top)) var(--pad) .75rem}.top-bar h1,.page-title{margin:0;font-size:28px;font-weight:700;letter-spacing:-.02em;line-height:1.1}.page{flex:1;width:min(40rem,100%);margin:0 auto;padding:1.25rem var(--pad) calc(1.5rem + var(--safe-bottom) + var(--tab-h) + .75rem)}.home-page{gap:16px;animation:card-in .18s ease both}.stack{display:flex;flex-direction:column;gap:16px}.field-label{display:block;margin-bottom:.4rem;color:var(--text-secondary);font-size:13px;font-weight:500}.field-input,.field-textarea{width:100%;min-height:var(--hit);padding:.85rem 1rem;border-radius:16px;border:1px solid var(--separator);background:var(--card);color:var(--text)}.field-textarea{min-height:7rem;resize:vertical;line-height:1.47}.muted{color:var(--text-secondary)}.tertiary{color:var(--text-tertiary)}.error-text{color:var(--danger);font-size:.9rem}.chip-row{display:flex;flex-wrap:wrap;gap:.5rem}.chip{min-height:var(--hit);padding:0 .95rem;border-radius:999px;border:1px solid var(--separator);background:var(--card);color:var(--text-secondary);font-weight:500;display:inline-flex;align-items:center;gap:.35rem}.chip[aria-pressed=true]{border-color:var(--accent);background:var(--accent-soft);color:var(--text)}.chip.result-worked[aria-pressed=true]{border-color:var(--ok);background:var(--ok-bg);color:var(--ok)}.chip.result-partial[aria-pressed=true]{border-color:var(--warn);background:var(--warn-bg);color:var(--warn)}.chip.result-failed[aria-pressed=true]{border-color:var(--danger);background:var(--danger-bg);color:var(--danger)}.chip.result-pending[aria-pressed=true]{border-color:var(--pending-border);background:var(--pending-bg);color:var(--accent)}.slider-wrap{display:grid;gap:.5rem}.slider-wrap input[type=range]{width:100%;accent-color:var(--accent)}.more-block{border-top:1px solid var(--separator);padding-top:1rem}.login-page{min-height:100dvh;display:grid;place-items:center;padding:var(--pad);padding-top:calc(var(--pad) + var(--safe-top));padding-bottom:calc(var(--pad) + var(--safe-bottom));background:var(--bg)}.login-card{width:min(22rem,100%);padding:1.5rem}.login-card h1{margin:0 0 .35rem;font-size:32px;font-weight:700;letter-spacing:-.02em;line-height:1.1}.toast-host{position:fixed;left:0;right:0;top:calc(.75rem + var(--safe-top));z-index:50;display:flex;justify-content:center;pointer-events:none;padding:0 var(--pad)}.toast{pointer-events:auto;max-width:24rem;width:100%;padding:.85rem 1rem;border-radius:16px;background:var(--card);border:1px solid var(--separator);box-shadow:var(--shadow);color:var(--text);font-weight:500}.toast.error{border-color:var(--danger);background:var(--danger-bg)}.pressable{touch-action:manipulation;-webkit-tap-highlight-color:transparent;transform-origin:center}.btn{display:inline-flex;align-items:center;justify-content:center;min-height:var(--btn-h);padding:0 1.25rem;border-radius:999px;font-weight:600}.btn:disabled{opacity:.4;pointer-events:none}.btn-primary{background:var(--accent);color:#202020}.btn-secondary{background:var(--card);border:1px solid var(--separator);color:var(--text)}.btn-destructive{background:var(--danger-bg);color:var(--danger);border:1px solid rgba(139,58,52,.25)}.btn-plain{color:var(--text-secondary);min-height:var(--hit);padding:0 .35rem;justify-content:flex-start;font-weight:500}.btn-large{min-height:var(--btn-h);width:100%;font-size:1.0625rem}.tab-bar{position:fixed;left:0;right:0;bottom:0;z-index:30;min-height:calc(var(--tab-h) + var(--safe-bottom));padding-bottom:var(--safe-bottom);background:var(--card);border-top:1px solid var(--separator)}.tab-bar-inner{display:grid;grid-template-columns:1fr 1fr 60px 1fr 1fr;align-items:stretch;min-height:var(--tab-h);padding:0 .35rem}.tab-item{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.2rem;min-height:var(--tab-h);color:var(--text-tertiary);font-size:11px;font-weight:500;letter-spacing:.01em}.tab-item.active{color:var(--text);font-weight:600}.tab-item.active svg{color:var(--accent)}.tab-fab-slot{width:var(--fab-size)}.tab-fab{position:absolute;left:50%;top:-10px;transform:translate(-50%);width:var(--fab-size);height:var(--fab-size);border-radius:999px;background:var(--accent);box-shadow:0 10px 24px #e8a31759;display:grid;place-items:center}.home-greeting{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem}.greeting-title{margin:0;font-size:32px;font-weight:700;letter-spacing:-.02em;line-height:1.1}.greeting-sub{margin:.35rem 0 0;color:var(--text-secondary);font-size:15px}.avatar-circle{width:48px;height:48px;border-radius:999px;background:var(--accent-soft);color:var(--text);display:grid;place-items:center;font-weight:700;font-size:14px;flex-shrink:0}.week-calendar{display:grid;grid-template-columns:repeat(7,1fr);gap:.35rem}.week-cal-cell{display:grid;justify-items:center;gap:.25rem;padding:.55rem .2rem;border-radius:16px;background:transparent}.week-cal-cell.today{background:var(--accent);color:#202020}.week-cal-label{font-size:11px;font-weight:600;color:inherit;opacity:.7}.week-cal-num{font-size:15px;font-weight:700}.week-cal-dot{width:6px;height:6px;border-radius:999px;background:transparent}.week-cal-cell.filled .week-cal-dot{background:var(--accent)}.week-cal-cell.today.filled .week-cal-dot,.week-cal-cell.today .week-cal-dot{background:#202020}.pending-banner-card{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:.75rem;min-height:100px;padding:.75rem 1rem;border-radius:var(--radius);background:var(--pending-bg);border:1.5px solid var(--pending-border);text-align:left;box-shadow:var(--shadow)}.pending-illu{width:88px;height:auto}.pending-copy{display:grid;gap:.15rem}.pending-copy strong{font-size:18px;font-weight:600}.pending-copy span{color:var(--text-secondary);font-size:14px}.hero-score-card{display:grid;grid-template-columns:1fr 38%;align-items:center;gap:.5rem;padding:18px;overflow:hidden}.hero-score-label{color:var(--text-secondary);font-size:14px;font-weight:500}.hero-score-value{margin:.15rem 0;font-size:54px;font-weight:700;letter-spacing:-.03em;line-height:1}.hero-score-sub{margin:0;color:var(--text-secondary);font-size:14px}.hero-illu{width:100%;height:auto;justify-self:end}.week-progress-card{display:grid;grid-template-columns:1fr auto;gap:.75rem;align-items:center;padding:16px 18px}.week-progress-row{display:flex;justify-content:space-between;gap:.75rem;margin-bottom:.45rem;color:var(--text-secondary);font-size:14px}.week-progress-row strong{color:var(--text);font-size:18px}.progress-track{height:8px;border-radius:999px;background:var(--surface-secondary);overflow:hidden;margin-top:.35rem}.progress-fill{height:100%;border-radius:inherit;background:var(--accent)}.scores-illu{width:72px;height:auto}.section-title{margin:0;font-size:20px;font-weight:600}.entry-list{display:grid;gap:.65rem}.entry-row{display:grid;grid-template-columns:auto 1fr;gap:.75rem;align-items:start;padding:16px;min-height:var(--hit);text-align:left;border-radius:var(--radius);background:var(--card);border:1px solid var(--separator);box-shadow:var(--shadow)}.entry-row.pending-row{background:var(--pending-bg);border-color:var(--pending-border)}.entry-row-main{display:grid;gap:.25rem;min-width:0}.entry-preview{color:var(--text);overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}.entry-row time{color:var(--text-tertiary);font-size:13px}.result-chip{display:inline-flex;align-items:center;gap:.25rem;padding:.3rem .55rem;border-radius:999px;font-size:12px;font-weight:600;text-transform:capitalize;white-space:nowrap}.result-chip.result-worked{background:var(--ok-bg);color:var(--ok)}.result-chip.result-partial{background:var(--warn-bg);color:var(--warn)}.result-chip.result-failed{background:var(--danger-bg);color:var(--danger)}.result-chip.result-pending{background:var(--pending-bg);color:var(--accent);border:1px solid var(--pending-border)}.quick-actions{display:flex;flex-wrap:wrap;gap:.5rem}.quick-chip{min-height:40px;padding:0 1rem;border-radius:999px;background:var(--surface-secondary);color:var(--text);font-weight:500;font-size:14px}.search-field{position:relative;display:block}.search-field svg{position:absolute;left:.9rem;top:50%;transform:translateY(-50%);color:var(--text-tertiary);pointer-events:none}.search-input{padding-left:2.4rem}.empty-state{padding:2rem 1.25rem;text-align:center;display:grid;gap:.75rem;justify-items:center}.detail-card,.form-card,.stats-card,.settings-card,.coach-result,.score-card{padding:16px 18px}.detail-snippet{margin:0;font-size:18px;font-weight:600;line-height:1.35}.meta-grid{display:grid;gap:.75rem}.section-head{display:flex;align-items:center;justify-content:space-between}.linkish{display:inline-flex;align-items:center;gap:.15rem;color:var(--accent);font-weight:600;font-size:14px;background:none;border:none;padding:0}.pending-focus{border:1.5px solid var(--pending-border);background:var(--pending-bg)}.resolve-snippet{padding:1rem}.resolve-activity{margin:0 0 .35rem;font-size:13px}.resolve-sticky{position:sticky;bottom:0;padding-top:.5rem;padding-bottom:.25rem;background:linear-gradient(transparent,var(--card) 28%)}.sheet-tall{max-height:85dvh!important}.gate-loading{min-height:100dvh;display:grid;place-items:center;color:var(--text-secondary);background:var(--bg)}.top-action{margin-left:auto;min-width:var(--hit);min-height:var(--hit);color:var(--accent);font-weight:600}.sheet-layer{position:fixed;top:0;right:0;bottom:0;left:0;z-index:100}.sheet-scrim{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:100%;background:#202020;opacity:0}.sheet-panel{position:absolute;left:0;right:0;bottom:0;max-height:min(82dvh,44rem);overflow:auto;padding-bottom:var(--safe-bottom);will-change:transform}.sheet-handle-zone{position:sticky;top:0;z-index:1;display:grid;justify-items:center;gap:.45rem;padding:.5rem var(--pad) .75rem;background:inherit;touch-action:none;-webkit-user-select:none;user-select:none}.sheet-handle{width:2.25rem;height:.3rem;border-radius:99px;background:var(--text-tertiary)}.sheet-handle-zone h2{margin:0;font-size:20px;font-weight:600}.sheet-content{padding:0 var(--pad) 1.25rem}.menu-list{display:grid}.menu-row{min-height:3.25rem;width:100%;text-align:left;border-bottom:1px solid var(--separator);color:var(--text)}.destructive-text{color:var(--danger)}.result-label{font-size:.75rem;font-weight:600;text-transform:capitalize}.result-worked{color:var(--ok)}.result-partial{color:var(--warn)}.result-failed{color:var(--danger)}.result-pending{color:var(--accent)}.detail-card p,.coach-text{margin:0;white-space:pre-wrap}.result-heading,.status-row,.score-card,.toggle-row{display:flex;align-items:center;justify-content:space-between;gap:.75rem}.source-badge{padding:.2rem .55rem;border-radius:99px;font-size:.75rem;font-weight:700}.source-badge.rules{background:var(--warn-bg);color:var(--warn)}.source-badge.model{background:var(--accent-soft);color:#8a6408}.flags{color:var(--text-tertiary);font-size:.68rem;text-align:right}.pick-list{display:grid;overflow:hidden;border-radius:var(--radius);background:var(--surface-secondary)}.pick-row{display:flex;justify-content:space-between;gap:.75rem;min-height:3rem;padding:.65rem .85rem;text-align:left;border-bottom:1px solid var(--separator)}.pick-row span:last-child{white-space:nowrap;font-size:.75rem}.disclaimer{font-size:.8rem;text-align:center}.coach-input{min-height:9rem}.segment-row{display:flex;flex-wrap:wrap;gap:.4rem}.segment{min-width:var(--hit);min-height:var(--hit);padding:0 .75rem;border:1px solid var(--separator);border-radius:999px;color:var(--text-secondary);background:var(--card)}.segment[aria-pressed=true]{border-color:var(--accent);background:var(--accent-soft);color:var(--text);font-weight:600}.toggle-row{min-height:var(--hit)}.toggle-row input{width:1.4rem;height:1.4rem;accent-color:var(--accent)}.score-card>div{display:grid}.score-card strong,.score-readout{font-size:1.5rem;font-weight:700}.stats-card{display:grid;gap:.85rem}.outcome-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:.5rem}.outcome-grid div{display:grid;text-align:center;gap:.2rem}.outcome-grid strong,.large-number{font-size:1.5rem}.stat-row{display:grid;gap:.35rem}.stat-row>div:first-child{display:flex;justify-content:space-between;gap:.5rem}.bar-track{height:.35rem;border-radius:99px;background:var(--surface-secondary);overflow:hidden}.bar-track span{display:block;height:100%;border-radius:inherit;background:var(--accent)}.install-steps{margin:0;padding-left:1.4rem;display:grid;gap:.5rem}.daily-header{justify-content:space-between;align-items:center}.daily-date{font-size:13px;color:var(--text-secondary)}.daily-points{font-size:1.35rem;font-weight:700;color:var(--warn)}.tip-card{position:relative;display:flex;align-items:flex-start;gap:.5rem;padding:12px 44px 12px 16px;border-radius:var(--radius);background:var(--accent-soft);font-size:14px;color:var(--text-secondary)}.tip-card p{margin:0}.tip-dismiss{position:absolute;top:6px;right:6px;display:grid;place-items:center;width:32px;height:32px;border-radius:999px;color:var(--text-secondary)}.choice-list{display:grid;gap:.5rem}.choice-item{min-height:var(--hit);padding:.7rem 1rem;text-align:left;border:1px solid var(--separator);border-radius:14px;background:var(--card);color:var(--text-secondary);font-size:15px}.choice-item[aria-pressed=true]{border-color:var(--accent);background:var(--accent-soft);color:var(--text);font-weight:600}.stepper-row{display:flex;align-items:center;gap:1rem}.stepper-btn{width:48px;height:48px;border-radius:999px;border:1px solid var(--separator);background:var(--card);font-size:1.4rem;line-height:1}.stepper-btn[disabled]{opacity:.4}.stepper-value{min-width:2.5rem;text-align:center;font-size:1.6rem;font-weight:700}.points-breakdown{list-style:none;margin:0;padding:0;display:grid;gap:.5rem}.points-breakdown li{display:flex;justify-content:space-between;gap:.75rem;font-size:14px}.points-breakdown li.missed{color:var(--text-tertiary)}.points-breakdown .points-pts{font-weight:700}.points-breakdown li.earned .points-pts{color:var(--ok)}.how-points{padding:14px 18px;font-size:14px;color:var(--text-secondary)}.how-points summary{cursor:pointer;font-weight:600;color:var(--text);min-height:var(--hit);display:flex;align-items:center}.how-points ul{margin:.5rem 0 0;padding-left:1.2rem;display:grid;gap:.4rem}.daily-sticky{position:sticky;bottom:0;padding:.5rem 0 .25rem;background:linear-gradient(to top,var(--bg) 70%,transparent)}.plan-header{flex-wrap:wrap;gap:.5rem}.plan-day-nav{display:flex;align-items:center;gap:.35rem}.icon-btn{width:44px;height:44px;display:grid;place-items:center;border-radius:999px;color:var(--text)}.chip-btn{min-height:36px;padding:0 .85rem;border-radius:999px;background:var(--accent-soft);color:var(--text);font-weight:600;font-size:13px}.plan-meta-row{display:flex;justify-content:space-between;gap:.75rem}.caption{font-size:13px;color:var(--text-secondary)}.plan-actions{display:grid;grid-template-columns:1fr 1fr;gap:.6rem}.timeline-card{padding:12px 8px 12px 0;overflow:hidden}.timeline{position:relative;display:grid;grid-template-columns:56px 1fr}.timeline-gutter{position:relative}.timeline-hour-label{position:absolute;right:8px;transform:translateY(-50%);font-size:11px;color:var(--text-tertiary)}.timeline-canvas{position:relative;border-left:1px solid var(--separator)}.timeline-hour-line{position:absolute;left:0;right:0;height:1px;background:var(--separator)}.timeline-now{position:absolute;left:0;right:0;height:2px;background:var(--accent);z-index:3}.timeline-now-dot{position:absolute;left:-5px;top:-4px;width:10px;height:10px;border-radius:999px;background:var(--accent)}.timeline-block{position:absolute;left:8px;right:8px;z-index:2;display:flex;flex-direction:column;align-items:flex-start;justify-content:center;gap:.1rem;padding:6px 10px;border-radius:12px;border:1px solid transparent;text-align:left;overflow:hidden}.timeline-block strong{font-size:13px;font-weight:600}.timeline-block span{font-size:11px;opacity:.85}.timeline-block.duty{background:#e8eef3;color:#243447}.timeline-block.explore{background:#e5f3ea;color:#1f4d32}.timeline-block.restore{background:#f3e8f0;color:#4a2f45}.timeline-block.stabilize{background:#f7ecd8;color:#5a4418}.timeline-block.flex{background:var(--surface-secondary);color:var(--text)}.timeline-block.p0{border-color:var(--accent);box-shadow:inset 0 0 0 1px var(--accent)}.timeline-block.done{opacity:.55}.timeline-block.skipped{opacity:.4;text-decoration:line-through}.plan-time-row{display:grid;grid-template-columns:1fr 1fr;gap:.75rem}.btn-secondary{min-height:var(--btn-h);width:100%;border-radius:999px;background:var(--card);border:1px solid var(--separator);color:var(--text);font-weight:600}.meta-line{margin:0;color:var(--text-secondary);font-size:14px}.empty-card{text-align:center}@keyframes card-in{0%{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}@media(prefers-reduced-motion:reduce){.home-page,.surface-card,.entry-row,.pending-banner-card{animation:none!important;transition:opacity .2s ease}.toast{transition:opacity .2s ease}}@media(prefers-reduced-transparency:reduce){.sheet-scrim{background:#202020cc}}@media(prefers-contrast:more){.tab-bar,.pending-banner-card,.segment,.entry-row{border-color:#20202059}}
19 unmodified lines202122232425262719 unmodified lines<link rel="manifest" href="/manifest.webmanifest" /><link rel="apple-touch-icon" href="/icons/icon-192.png" /><title>Habit Journal</title><script type="module" crossorigin src="/assets/index-B-lUWqRt.js"></script><link rel="stylesheet" crossorigin href="/assets/index-DNPW78XL.css"></head><body><div id="app"></div>19 unmodified lines202122232425262719 unmodified lines<link rel="manifest" href="/manifest.webmanifest" /><link rel="apple-touch-icon" href="/icons/icon-192.png" /><title>Habit Journal</title><script type="module" crossorigin src="/assets/index-D3LLeLlA.js"></script><link rel="stylesheet" crossorigin href="/assets/index-6RturTFo.css"></head><body><div id="app"></div>
123456const CACHE = "habit-journal-v3";const SHELL = ["/","/index.html","/manifest.webmanifest","/icons/icon-192.png","/icons/icon-512.png","/illustrations/hero-home.svg","/illustrations/pending.svg","/illustrations/scores.svg","/illustrations/coach.svg","/illustrations/empty.svg","/assets/index-DNPW78XL.css","/assets/index-B-lUWqRt.js","/assets/index-B-lUWqRt.js.map"];self.addEventListener("install", event => event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(SHELL)).then(() => self.skipWaiting())));self.addEventListener("activate", event => event.waitUntil(caches.keys().then(keys => Promise.all(keys.filter(key => key !== CACHE).map(key => caches.delete(key)))).then(() => self.clients.claim())));self.addEventListener("fetch", event => {123456const CACHE = "habit-journal-v3";const SHELL = ["/","/index.html","/manifest.webmanifest","/icons/icon-192.png","/icons/icon-512.png","/illustrations/hero-home.svg","/illustrations/pending.svg","/illustrations/scores.svg","/illustrations/coach.svg","/illustrations/empty.svg","/assets/index-6RturTFo.css","/assets/index-D3LLeLlA.js","/assets/index-D3LLeLlA.js.map"];self.addEventListener("install", event => event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(SHELL)).then(() => self.skipWaiting())));self.addEventListener("activate", event => event.waitUntil(caches.keys().then(keys => Promise.all(keys.filter(key => key !== CACHE).map(key => caches.delete(key)))).then(() => self.clients.claim())));self.addEventListener("fetch", event => {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117"""Unit tests for schedule math: d_hat, overlaps, P0 lock, strong feedback."""
from app.schedule_math import ( d_hat, is_strong_feedback, overlaps, recompute_priors, validate_blocks,)from app.schedule_reschedule import rules_backup_reschedule
def test_d_hat_shrinkage() -> None: # n=3, mean=40, prior=30, m=3 → 0.5*40 + 0.5*30 = 35 assert abs(d_hat(40.0, 3, 30.0, m=3) - 35.0) < 1e-9 assert d_hat(None, 0, 45.0, m=3) == 45.0
def test_strong_feedback() -> None: assert is_strong_feedback( {"did": "done", "actual_min": 20, "quality": 4, "fun": 3} ) assert not is_strong_feedback({"did": "skipped", "actual_min": 20, "quality": 4, "fun": 3}) assert not is_strong_feedback({"did": "done", "actual_min": None, "quality": 4, "fun": 3})
def test_overlap_and_p0_lock() -> None: assert overlaps("09:00", "10:00", "09:30", "10:30") assert not overlaps("09:00", "10:00", "10:00", "11:00") blocks = [ { "id": "a", "start": "09:00", "end": "10:00", "planned_min": 60, "priority": "P0", "locked": True, } ] prev = [{"id": "a", "start": "09:00", "end": "10:00", "priority": "P0", "locked": True}] moved = [ { "id": "a", "start": "11:00", "end": "12:00", "planned_min": 60, "priority": "P0", "locked": True, } ] assert validate_blocks(moved, previous_p0=prev, allow_p0_move=False) assert not validate_blocks(blocks, previous_p0=prev, allow_p0_move=False)
def test_recompute_priors() -> None: blocks = { "b1": {"id": "b1", "kind": "earn_ship", "planned_min": 45}, } feedback = [ { "block_id": "b1", "did": "done", "actual_min": 50, "quality": 4, "fun": 2, "strong": True, "would_repeat": "yes", } ] priors = recompute_priors(feedback, blocks, shrink_k=3) assert priors["earn_ship"]["n"] == 1 assert priors["earn_ship"]["d_hat"] > 0
def test_rules_backup_keeps_p0() -> None: blocks = [ { "id": "p0", "date": "2026-07-19", "start": "08:00", "end": "08:30", "title": "Food", "kind": "food_out", "intent": "duty", "priority": "P0", "planned_min": 30, "status": "planned", "locked": True, "notes": "", "version_added": 1, "source": "user", }, { "id": "p2", "date": "2026-07-19", "start": "14:00", "end": "16:00", "title": "Flex", "kind": "other", "intent": "duty", "priority": "P2", "planned_min": 120, "status": "planned", "locked": False, "notes": "", "version_added": 1, "source": "user", }, ] out = rules_backup_reschedule( blocks, day="2026-07-19", risk_score=2.0, capacity_hint=0.4, ) p0 = next(b for b in out if b.id == "p0") assert p0.start == "08:00" and p0.end == "08:30"README.md+6-2
app/config.py+7
app/main.py+14-1
app/paths.py+23-1
app/routers/agent.pyAdded+170
app/routers/plan.pyAdded+201
app/schedule_math.pyAdded+338
app/schedule_reschedule.pyAdded+358
app/schedule_store.pyAdded+422
app/schedule_templates.pyAdded+192
docs/SCHEDULE.mdAdded+138
frontend/src/api.ts+165
frontend/src/components/BlockSheet.tsxAdded+336
frontend/src/components/TabBar.tsx+8-15
frontend/src/components/Timeline.tsxAdded+103
frontend/src/main.tsx+2
frontend/src/pages/Home.tsx+85-3
frontend/src/pages/Plan.tsxAdded+151
frontend/src/router.tsx+3
frontend/src/styles/app.css+101
static/assets/index-DNPW78XL.css → static/assets/index-6RturTFo.cssRenamed+1-1
static/assets/index-B-lUWqRt.jsDeleted
static/assets/index-B-lUWqRt.js.mapDeleted
static/assets/index-D3LLeLlA.jsAdded
static/assets/index-D3LLeLlA.js.mapAdded
static/index.html+2-2
static/sw.js+1-1
tests/test_schedule_math.pyAdded+117