Spaces:
Running
Running
Complete P1 schedule loop: seed day, live capacity, templates, API tests.
Browse files- .gitignore +2 -0
- app/routers/agent.py +32 -53
- app/routers/plan.py +90 -69
- app/schedule_math.py +31 -0
- app/schedule_reschedule.py +48 -1
- app/schedule_risk.py +73 -0
- app/schedule_templates.py +32 -0
- docs/SCHEDULE.md +3 -0
- frontend/src/api.ts +4 -0
- frontend/src/components/BlockSheet.tsx +51 -8
- frontend/src/pages/Plan.tsx +31 -6
- static/assets/index-CsRld2Dr.js +0 -0
- static/assets/index-CsRld2Dr.js.map +0 -0
- static/assets/index-D3LLeLlA.js +0 -0
- static/assets/index-D3LLeLlA.js.map +0 -0
- static/index.html +1 -1
- static/sw.js +1 -1
- tests/test_schedule_api.py +95 -0
.gitignore
CHANGED
|
@@ -7,3 +7,5 @@ data/
|
|
| 7 |
frontend/node_modules/
|
| 8 |
frontend/dist/
|
| 9 |
*.log
|
|
|
|
|
|
|
|
|
| 7 |
frontend/node_modules/
|
| 8 |
frontend/dist/
|
| 9 |
*.log
|
| 10 |
+
commands.md
|
| 11 |
+
_tmp_*.txt
|
app/routers/agent.py
CHANGED
|
@@ -14,6 +14,7 @@ from fastapi import APIRouter, Depends, Request, status
|
|
| 14 |
from app.deps import require_login
|
| 15 |
from app.models import ApiEnvelope, err, ok
|
| 16 |
from app.schedule_math import capacity_hint, trigger_operators
|
|
|
|
| 17 |
from app.schedule_store import DayPlanPut
|
| 18 |
|
| 19 |
router = APIRouter(prefix="/api/agent", tags=["agent"])
|
|
@@ -48,62 +49,40 @@ def agent_context(
|
|
| 48 |
|
| 49 |
now = datetime.now(timezone.utc)
|
| 50 |
since = now - timedelta(hours=48)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
risk_tags = {
|
| 55 |
-
"urge",
|
| 56 |
-
"court",
|
| 57 |
-
"comparison",
|
| 58 |
-
"corn",
|
| 59 |
-
"daydream",
|
| 60 |
-
"bully",
|
| 61 |
-
"family",
|
| 62 |
-
"shame",
|
| 63 |
-
"rerun",
|
| 64 |
-
"home",
|
| 65 |
-
"spain",
|
| 66 |
-
"build",
|
| 67 |
-
}
|
| 68 |
entries_48h = []
|
| 69 |
-
tags_1h: list[str] = []
|
| 70 |
-
triggers_y: list[str] = []
|
| 71 |
for entry in entry_store._load():
|
| 72 |
ts = entry.ts if entry.ts.tzinfo else entry.ts.replace(tzinfo=timezone.utc)
|
| 73 |
if ts < since:
|
| 74 |
continue
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
if y_daily.court == "court":
|
| 98 |
-
triggers_y.append("court")
|
| 99 |
-
if y_daily.corn_sessions >= 2:
|
| 100 |
-
triggers_y.append("corn")
|
| 101 |
-
if y_daily.daydream == "fc":
|
| 102 |
-
triggers_y.append("daydream")
|
| 103 |
-
triggers_y = sorted(set(triggers_y))
|
| 104 |
-
|
| 105 |
risk_score = float(len(tags_1h))
|
| 106 |
-
last_hour_high =
|
|
|
|
|
|
|
|
|
|
| 107 |
cap = capacity_hint(
|
| 108 |
risk_1h_score=risk_score,
|
| 109 |
triggers_yesterday=triggers_y,
|
|
@@ -111,10 +90,10 @@ def agent_context(
|
|
| 111 |
last_hour_high=last_hour_high,
|
| 112 |
)
|
| 113 |
ops = trigger_operators(risk_1h_tags=tags_1h, triggers_yesterday=triggers_y)
|
| 114 |
-
pending = sum(
|
| 115 |
-
1 for e in entry_store._load() if e.result.value == "pending"
|
| 116 |
-
)
|
| 117 |
priors = store.load_priors()
|
|
|
|
|
|
|
| 118 |
|
| 119 |
return ok(
|
| 120 |
{
|
|
|
|
| 14 |
from app.deps import require_login
|
| 15 |
from app.models import ApiEnvelope, err, ok
|
| 16 |
from app.schedule_math import capacity_hint, trigger_operators
|
| 17 |
+
from app.schedule_risk import risk_from_stores
|
| 18 |
from app.schedule_store import DayPlanPut
|
| 19 |
|
| 20 |
router = APIRouter(prefix="/api/agent", tags=["agent"])
|
|
|
|
| 49 |
|
| 50 |
now = datetime.now(timezone.utc)
|
| 51 |
since = now - timedelta(hours=48)
|
| 52 |
+
|
| 53 |
+
risk_tags_extra = {"home", "spain", "build"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
entries_48h = []
|
|
|
|
|
|
|
| 55 |
for entry in entry_store._load():
|
| 56 |
ts = entry.ts if entry.ts.tzinfo else entry.ts.replace(tzinfo=timezone.utc)
|
| 57 |
if ts < since:
|
| 58 |
continue
|
| 59 |
+
entries_48h.append(
|
| 60 |
+
{
|
| 61 |
+
"id": entry.id,
|
| 62 |
+
"ts": entry.ts.isoformat(),
|
| 63 |
+
"tags": entry.tags,
|
| 64 |
+
"emotions": entry.emotions,
|
| 65 |
+
"intensity": entry.intensity,
|
| 66 |
+
"remedy": entry.remedy,
|
| 67 |
+
"result": entry.result.value,
|
| 68 |
+
"happened": entry.happened[:280],
|
| 69 |
+
}
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
risk = risk_from_stores(entry_store, daily_store, now=now, target_day=target)
|
| 73 |
+
# Keep agent context tags slightly broader for Spain/home signals.
|
| 74 |
+
tags_1h = sorted(set(risk["risk_1h_tags"]))
|
| 75 |
+
for entry in entry_store._load():
|
| 76 |
+
ts = entry.ts if entry.ts.tzinfo else entry.ts.replace(tzinfo=timezone.utc)
|
| 77 |
+
if ts < now - timedelta(hours=1):
|
| 78 |
+
continue
|
| 79 |
+
hit = sorted((set(entry.tags) | set(entry.emotions)) & risk_tags_extra)
|
| 80 |
+
tags_1h = sorted(set(tags_1h) | set(hit))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
risk_score = float(len(tags_1h))
|
| 82 |
+
last_hour_high = risk["last_hour_high"] or bool(
|
| 83 |
+
{"urge", "court", "corn", "rerun"} & set(tags_1h)
|
| 84 |
+
)
|
| 85 |
+
triggers_y = risk["triggers_yesterday"]
|
| 86 |
cap = capacity_hint(
|
| 87 |
risk_1h_score=risk_score,
|
| 88 |
triggers_yesterday=triggers_y,
|
|
|
|
| 90 |
last_hour_high=last_hour_high,
|
| 91 |
)
|
| 92 |
ops = trigger_operators(risk_1h_tags=tags_1h, triggers_yesterday=triggers_y)
|
| 93 |
+
pending = sum(1 for e in entry_store._load() if e.result.value == "pending")
|
|
|
|
|
|
|
| 94 |
priors = store.load_priors()
|
| 95 |
+
y_daily = daily_store.get(target - timedelta(days=1))
|
| 96 |
+
t_daily = daily_store.get(target)
|
| 97 |
|
| 98 |
return ok(
|
| 99 |
{
|
app/routers/plan.py
CHANGED
|
@@ -5,15 +5,17 @@ Session-authenticated; mirrors the app envelope pattern.
|
|
| 5 |
|
| 6 |
from __future__ import annotations
|
| 7 |
|
| 8 |
-
from datetime import date
|
| 9 |
from typing import Any
|
| 10 |
|
| 11 |
from fastapi import APIRouter, Depends, Request, status
|
| 12 |
-
from pydantic import BaseModel
|
| 13 |
|
| 14 |
from app.deps import require_login
|
| 15 |
from app.models import ApiEnvelope, err, ok
|
| 16 |
from app.schedule_math import capacity_hint, trigger_operators
|
|
|
|
|
|
|
| 17 |
from app.schedule_store import BlockCreate, BlockFeedback, BlockPatch, DayPlanPut
|
| 18 |
|
| 19 |
router = APIRouter(tags=["plan"], dependencies=[Depends(require_login)])
|
|
@@ -25,7 +27,7 @@ class RescheduleBody(BaseModel):
|
|
| 25 |
|
| 26 |
|
| 27 |
class FeedbackBody(BlockFeedback):
|
| 28 |
-
block_id: str
|
| 29 |
date: str | None = None
|
| 30 |
|
| 31 |
|
|
@@ -33,58 +35,42 @@ def _store(request: Request):
|
|
| 33 |
return request.app.state.schedule_store
|
| 34 |
|
| 35 |
|
| 36 |
-
def
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
"
|
| 44 |
-
"
|
| 45 |
-
"
|
| 46 |
-
"
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
"
|
| 50 |
-
"
|
| 51 |
-
"rerun",
|
| 52 |
-
}
|
| 53 |
-
tags_1h: list[str] = []
|
| 54 |
-
triggers_y: list[str] = []
|
| 55 |
-
for entry in request.app.state.entry_store._load():
|
| 56 |
-
ts = entry.ts
|
| 57 |
-
if ts.tzinfo is None:
|
| 58 |
-
ts = ts.replace(tzinfo=timezone.utc)
|
| 59 |
-
entry_tags = set(entry.tags) | set(entry.emotions)
|
| 60 |
-
hit = sorted(entry_tags & risk_tags)
|
| 61 |
-
if ts >= hour_ago:
|
| 62 |
-
tags_1h.extend(hit)
|
| 63 |
-
if entry.ts.date().isoformat() == yesterday:
|
| 64 |
-
triggers_y.extend(hit)
|
| 65 |
-
try:
|
| 66 |
-
y_daily = request.app.state.daily_store.get(date.fromisoformat(yesterday))
|
| 67 |
-
if y_daily:
|
| 68 |
-
if y_daily.court == "court":
|
| 69 |
-
triggers_y.append("court")
|
| 70 |
-
if y_daily.corn_sessions >= 2:
|
| 71 |
-
triggers_y.append("corn")
|
| 72 |
-
if y_daily.daydream == "fc":
|
| 73 |
-
triggers_y.append("daydream")
|
| 74 |
-
except Exception: # noqa: BLE001
|
| 75 |
-
pass
|
| 76 |
-
tags_1h = sorted(set(tags_1h))
|
| 77 |
-
triggers_y = sorted(set(triggers_y))
|
| 78 |
-
score = float(len(tags_1h))
|
| 79 |
-
last_hour_high = bool(
|
| 80 |
-
{"urge", "court", "corn", "rerun"} & set(tags_1h)
|
| 81 |
)
|
| 82 |
-
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
|
| 85 |
@router.get("/api/plan/{day}", response_model=ApiEnvelope)
|
| 86 |
def get_plan(request: Request, day: date) -> dict[str, Any]:
|
| 87 |
-
return ok(
|
| 88 |
|
| 89 |
|
| 90 |
@router.put("/api/plan/{day}", response_model=ApiEnvelope)
|
|
@@ -92,7 +78,7 @@ def put_plan(request: Request, day: date, body: DayPlanPut) -> object:
|
|
| 92 |
try:
|
| 93 |
put = body.model_copy(update={"source": body.source or "user"})
|
| 94 |
_store(request).save_plan(day.isoformat(), put)
|
| 95 |
-
return ok(
|
| 96 |
except ValueError as exc:
|
| 97 |
return err("validation_error", str(exc), status.HTTP_422_UNPROCESSABLE_ENTITY)
|
| 98 |
|
|
@@ -101,7 +87,7 @@ def put_plan(request: Request, day: date, body: DayPlanPut) -> object:
|
|
| 101 |
def add_block(request: Request, day: date, body: BlockCreate) -> object:
|
| 102 |
try:
|
| 103 |
_store(request).add_block(day.isoformat(), body)
|
| 104 |
-
return ok(
|
| 105 |
except ValueError as exc:
|
| 106 |
return err("validation_error", str(exc), status.HTTP_422_UNPROCESSABLE_ENTITY)
|
| 107 |
|
|
@@ -115,7 +101,7 @@ def patch_block(
|
|
| 115 |
) -> object:
|
| 116 |
try:
|
| 117 |
_store(request).patch_block(day.isoformat(), block_id, body)
|
| 118 |
-
return ok(
|
| 119 |
except KeyError:
|
| 120 |
return err("not_found", "Block not found", status.HTTP_404_NOT_FOUND)
|
| 121 |
except ValueError as exc:
|
|
@@ -126,7 +112,7 @@ def patch_block(
|
|
| 126 |
def delete_block(request: Request, day: date, block_id: str) -> object:
|
| 127 |
try:
|
| 128 |
_store(request).delete_block(day.isoformat(), block_id)
|
| 129 |
-
return ok(
|
| 130 |
except KeyError:
|
| 131 |
return err("not_found", "Block not found", status.HTTP_404_NOT_FOUND)
|
| 132 |
|
|
@@ -144,7 +130,7 @@ def post_feedback(
|
|
| 144 |
return ok(
|
| 145 |
{
|
| 146 |
"feedback": stored.model_dump(mode="json"),
|
| 147 |
-
"plan":
|
| 148 |
"priors": list(_store(request).load_priors().values()),
|
| 149 |
}
|
| 150 |
)
|
|
@@ -152,6 +138,42 @@ def post_feedback(
|
|
| 152 |
return err("not_found", "Block not found", status.HTTP_404_NOT_FOUND)
|
| 153 |
|
| 154 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
@router.get("/api/schedule/priors", response_model=ApiEnvelope)
|
| 156 |
def get_priors(request: Request) -> dict[str, Any]:
|
| 157 |
kinds = _store(request).load_priors()
|
|
@@ -171,29 +193,28 @@ def get_health(request: Request, day: date) -> dict[str, Any]:
|
|
| 171 |
@router.post("/api/plan/{day}/reschedule", response_model=ApiEnvelope)
|
| 172 |
def reschedule(request: Request, day: date, body: RescheduleBody | None = None) -> object:
|
| 173 |
payload = body or RescheduleBody()
|
| 174 |
-
|
| 175 |
-
cap = capacity_hint(
|
| 176 |
-
risk_1h_score=risk,
|
| 177 |
-
triggers_yesterday=triggers,
|
| 178 |
-
yesterday_trigger=len(triggers) > 0,
|
| 179 |
-
last_hour_high=last_hour_high,
|
| 180 |
-
)
|
| 181 |
-
ops = trigger_operators(risk_1h_tags=tags, triggers_yesterday=triggers)
|
| 182 |
try:
|
| 183 |
result = request.app.state.reschedule_service.reschedule(
|
| 184 |
day.isoformat(),
|
| 185 |
reason=payload.reason,
|
| 186 |
force=payload.force,
|
| 187 |
-
risk_score=
|
| 188 |
-
capacity_hint=
|
| 189 |
priors_md=_store(request).priors_table(),
|
| 190 |
context_notes=(
|
| 191 |
-
f"risk_tags={
|
| 192 |
-
f"
|
|
|
|
| 193 |
),
|
| 194 |
)
|
| 195 |
-
result["operators"] =
|
| 196 |
-
result["capacity_hint"] =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
return ok(result)
|
| 198 |
except PermissionError as exc:
|
| 199 |
return err("rate_limited", str(exc), status.HTTP_429_TOO_MANY_REQUESTS)
|
|
|
|
| 5 |
|
| 6 |
from __future__ import annotations
|
| 7 |
|
| 8 |
+
from datetime import date
|
| 9 |
from typing import Any
|
| 10 |
|
| 11 |
from fastapi import APIRouter, Depends, Request, status
|
| 12 |
+
from pydantic import BaseModel
|
| 13 |
|
| 14 |
from app.deps import require_login
|
| 15 |
from app.models import ApiEnvelope, err, ok
|
| 16 |
from app.schedule_math import capacity_hint, trigger_operators
|
| 17 |
+
from app.schedule_reschedule import seed_starter_blocks
|
| 18 |
+
from app.schedule_risk import risk_from_stores
|
| 19 |
from app.schedule_store import BlockCreate, BlockFeedback, BlockPatch, DayPlanPut
|
| 20 |
|
| 21 |
router = APIRouter(tags=["plan"], dependencies=[Depends(require_login)])
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
class FeedbackBody(BlockFeedback):
|
| 30 |
+
block_id: str = ""
|
| 31 |
date: str | None = None
|
| 32 |
|
| 33 |
|
|
|
|
| 35 |
return request.app.state.schedule_store
|
| 36 |
|
| 37 |
|
| 38 |
+
def _risk_bundle(request: Request, target: date | None = None) -> dict[str, Any]:
|
| 39 |
+
risk = risk_from_stores(
|
| 40 |
+
request.app.state.entry_store,
|
| 41 |
+
request.app.state.daily_store,
|
| 42 |
+
target_day=target,
|
| 43 |
+
)
|
| 44 |
+
cap = capacity_hint(
|
| 45 |
+
risk_1h_score=risk["risk_1h_score"],
|
| 46 |
+
triggers_yesterday=risk["triggers_yesterday"],
|
| 47 |
+
yesterday_trigger=risk["yesterday_trigger"],
|
| 48 |
+
last_hour_high=risk["last_hour_high"],
|
| 49 |
+
)
|
| 50 |
+
ops = trigger_operators(
|
| 51 |
+
risk_1h_tags=risk["risk_1h_tags"],
|
| 52 |
+
triggers_yesterday=risk["triggers_yesterday"],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
)
|
| 54 |
+
return {**risk, "capacity_hint": cap, "operators": ops}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _enrich_plan(request: Request, day: date) -> dict[str, Any]:
|
| 58 |
+
data = _store(request).plan_with_feedback(day.isoformat())
|
| 59 |
+
bundle = _risk_bundle(request, day)
|
| 60 |
+
data["capacity_hint"] = bundle["capacity_hint"]
|
| 61 |
+
data["operators"] = bundle["operators"]
|
| 62 |
+
data["risk_1h"] = {
|
| 63 |
+
"score": bundle["risk_1h_score"],
|
| 64 |
+
"tags": bundle["risk_1h_tags"],
|
| 65 |
+
"high": bundle["last_hour_high"],
|
| 66 |
+
}
|
| 67 |
+
data["triggers_yesterday"] = bundle["triggers_yesterday"]
|
| 68 |
+
return data
|
| 69 |
|
| 70 |
|
| 71 |
@router.get("/api/plan/{day}", response_model=ApiEnvelope)
|
| 72 |
def get_plan(request: Request, day: date) -> dict[str, Any]:
|
| 73 |
+
return ok(_enrich_plan(request, day))
|
| 74 |
|
| 75 |
|
| 76 |
@router.put("/api/plan/{day}", response_model=ApiEnvelope)
|
|
|
|
| 78 |
try:
|
| 79 |
put = body.model_copy(update={"source": body.source or "user"})
|
| 80 |
_store(request).save_plan(day.isoformat(), put)
|
| 81 |
+
return ok(_enrich_plan(request, day))
|
| 82 |
except ValueError as exc:
|
| 83 |
return err("validation_error", str(exc), status.HTTP_422_UNPROCESSABLE_ENTITY)
|
| 84 |
|
|
|
|
| 87 |
def add_block(request: Request, day: date, body: BlockCreate) -> object:
|
| 88 |
try:
|
| 89 |
_store(request).add_block(day.isoformat(), body)
|
| 90 |
+
return ok(_enrich_plan(request, day))
|
| 91 |
except ValueError as exc:
|
| 92 |
return err("validation_error", str(exc), status.HTTP_422_UNPROCESSABLE_ENTITY)
|
| 93 |
|
|
|
|
| 101 |
) -> object:
|
| 102 |
try:
|
| 103 |
_store(request).patch_block(day.isoformat(), block_id, body)
|
| 104 |
+
return ok(_enrich_plan(request, day))
|
| 105 |
except KeyError:
|
| 106 |
return err("not_found", "Block not found", status.HTTP_404_NOT_FOUND)
|
| 107 |
except ValueError as exc:
|
|
|
|
| 112 |
def delete_block(request: Request, day: date, block_id: str) -> object:
|
| 113 |
try:
|
| 114 |
_store(request).delete_block(day.isoformat(), block_id)
|
| 115 |
+
return ok(_enrich_plan(request, day))
|
| 116 |
except KeyError:
|
| 117 |
return err("not_found", "Block not found", status.HTTP_404_NOT_FOUND)
|
| 118 |
|
|
|
|
| 130 |
return ok(
|
| 131 |
{
|
| 132 |
"feedback": stored.model_dump(mode="json"),
|
| 133 |
+
"plan": _enrich_plan(request, day),
|
| 134 |
"priors": list(_store(request).load_priors().values()),
|
| 135 |
}
|
| 136 |
)
|
|
|
|
| 138 |
return err("not_found", "Block not found", status.HTTP_404_NOT_FOUND)
|
| 139 |
|
| 140 |
|
| 141 |
+
@router.post("/api/plan/{day}/seed", response_model=ApiEnvelope)
|
| 142 |
+
def seed_plan(request: Request, day: date) -> object:
|
| 143 |
+
"""Fill an empty day from templates under live capacity (P0 locked)."""
|
| 144 |
+
|
| 145 |
+
store = _store(request)
|
| 146 |
+
existing = store.get_plan(day.isoformat())
|
| 147 |
+
if existing.blocks:
|
| 148 |
+
return err(
|
| 149 |
+
"validation_error",
|
| 150 |
+
"Day already has blocks — clear or reschedule instead",
|
| 151 |
+
status.HTTP_422_UNPROCESSABLE_ENTITY,
|
| 152 |
+
)
|
| 153 |
+
bundle = _risk_bundle(request, day)
|
| 154 |
+
blocks = seed_starter_blocks(
|
| 155 |
+
day.isoformat(),
|
| 156 |
+
capacity_hint=bundle["capacity_hint"],
|
| 157 |
+
max_blocks=request.app.state.settings.schedule_max_blocks,
|
| 158 |
+
)
|
| 159 |
+
try:
|
| 160 |
+
store.save_plan(
|
| 161 |
+
day.isoformat(),
|
| 162 |
+
DayPlanPut(
|
| 163 |
+
blocks=blocks,
|
| 164 |
+
source="rules",
|
| 165 |
+
capacity_hint=bundle["capacity_hint"],
|
| 166 |
+
notes="seed",
|
| 167 |
+
force_p0_move=True,
|
| 168 |
+
),
|
| 169 |
+
)
|
| 170 |
+
data = _enrich_plan(request, day)
|
| 171 |
+
data["seeded"] = True
|
| 172 |
+
return ok(data)
|
| 173 |
+
except ValueError as exc:
|
| 174 |
+
return err("validation_error", str(exc), status.HTTP_422_UNPROCESSABLE_ENTITY)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
@router.get("/api/schedule/priors", response_model=ApiEnvelope)
|
| 178 |
def get_priors(request: Request) -> dict[str, Any]:
|
| 179 |
kinds = _store(request).load_priors()
|
|
|
|
| 193 |
@router.post("/api/plan/{day}/reschedule", response_model=ApiEnvelope)
|
| 194 |
def reschedule(request: Request, day: date, body: RescheduleBody | None = None) -> object:
|
| 195 |
payload = body or RescheduleBody()
|
| 196 |
+
bundle = _risk_bundle(request, day)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
try:
|
| 198 |
result = request.app.state.reschedule_service.reschedule(
|
| 199 |
day.isoformat(),
|
| 200 |
reason=payload.reason,
|
| 201 |
force=payload.force,
|
| 202 |
+
risk_score=bundle["risk_1h_score"],
|
| 203 |
+
capacity_hint=bundle["capacity_hint"],
|
| 204 |
priors_md=_store(request).priors_table(),
|
| 205 |
context_notes=(
|
| 206 |
+
f"risk_tags={bundle['risk_1h_tags']}; "
|
| 207 |
+
f"triggers_y={bundle['triggers_yesterday']}; "
|
| 208 |
+
f"operators={bundle['operators']}"
|
| 209 |
),
|
| 210 |
)
|
| 211 |
+
result["operators"] = bundle["operators"]
|
| 212 |
+
result["capacity_hint"] = bundle["capacity_hint"]
|
| 213 |
+
if "plan" in result:
|
| 214 |
+
plan = result["plan"]
|
| 215 |
+
if isinstance(plan, dict):
|
| 216 |
+
plan["capacity_hint"] = bundle["capacity_hint"]
|
| 217 |
+
plan["operators"] = bundle["operators"]
|
| 218 |
return ok(result)
|
| 219 |
except PermissionError as exc:
|
| 220 |
return err("rate_limited", str(exc), status.HTTP_429_TOO_MANY_REQUESTS)
|
app/schedule_math.py
CHANGED
|
@@ -225,6 +225,37 @@ def validate_blocks(
|
|
| 225 |
return errors
|
| 226 |
|
| 227 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
def capacity_hint(
|
| 229 |
*,
|
| 230 |
risk_1h_score: float,
|
|
|
|
| 225 |
return errors
|
| 226 |
|
| 227 |
|
| 228 |
+
def ev_score(
|
| 229 |
+
*,
|
| 230 |
+
p_done: float,
|
| 231 |
+
utility: float,
|
| 232 |
+
information: float = 0.0,
|
| 233 |
+
fun: float = 0.0,
|
| 234 |
+
d_hat_min: float = 30.0,
|
| 235 |
+
cost: float = 0.0,
|
| 236 |
+
fse: float = 0.0,
|
| 237 |
+
gamma: float = 0.25,
|
| 238 |
+
eta: float = 0.35,
|
| 239 |
+
lambda_t: float = 0.01,
|
| 240 |
+
lambda_m: float = 0.15,
|
| 241 |
+
lambda_f: float = 0.4,
|
| 242 |
+
raise_eta: bool = False,
|
| 243 |
+
raise_lambda_f: bool = False,
|
| 244 |
+
) -> float:
|
| 245 |
+
"""Locked EV formula (operators may raise η / λ_f; no δ / H / PERMA terms)."""
|
| 246 |
+
|
| 247 |
+
eta_eff = eta * (1.35 if raise_eta else 1.0)
|
| 248 |
+
lf_eff = lambda_f * (1.4 if raise_lambda_f else 1.0)
|
| 249 |
+
return (
|
| 250 |
+
p_done * utility
|
| 251 |
+
+ gamma * information
|
| 252 |
+
+ eta_eff * fun
|
| 253 |
+
- lambda_t * d_hat_min
|
| 254 |
+
- lambda_m * cost
|
| 255 |
+
- lf_eff * fse
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
def capacity_hint(
|
| 260 |
*,
|
| 261 |
risk_1h_score: float,
|
app/schedule_reschedule.py
CHANGED
|
@@ -16,7 +16,12 @@ import httpx
|
|
| 16 |
from app.config import Settings
|
| 17 |
from app.schedule_math import minutes_between, parse_hhmm, trigger_operators
|
| 18 |
from app.schedule_store import DayPlanPut, ScheduledBlock, ScheduleStore
|
| 19 |
-
from app.schedule_templates import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
|
| 22 |
def _hhmm(minutes: int) -> str:
|
|
@@ -24,6 +29,45 @@ def _hhmm(minutes: int) -> str:
|
|
| 24 |
return f"{minutes // 60:02d}:{minutes % 60:02d}"
|
| 25 |
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
def rules_backup_reschedule(
|
| 28 |
plan_blocks: list[dict[str, Any]],
|
| 29 |
*,
|
|
@@ -36,6 +80,9 @@ def rules_backup_reschedule(
|
|
| 36 |
) -> list[ScheduledBlock]:
|
| 37 |
"""Deterministic reschedule: keep P0, drop/shrink P2, optional stabilize/fun."""
|
| 38 |
|
|
|
|
|
|
|
|
|
|
| 39 |
kept: list[dict[str, Any]] = []
|
| 40 |
for block in plan_blocks:
|
| 41 |
if block.get("priority") == "P0" or block.get("locked"):
|
|
|
|
| 16 |
from app.config import Settings
|
| 17 |
from app.schedule_math import minutes_between, parse_hhmm, trigger_operators
|
| 18 |
from app.schedule_store import DayPlanPut, ScheduledBlock, ScheduleStore
|
| 19 |
+
from app.schedule_templates import (
|
| 20 |
+
KIND_LABELS,
|
| 21 |
+
SEED_SLOTS,
|
| 22 |
+
seed_template_ids,
|
| 23 |
+
template_by_id,
|
| 24 |
+
)
|
| 25 |
|
| 26 |
|
| 27 |
def _hhmm(minutes: int) -> str:
|
|
|
|
| 29 |
return f"{minutes // 60:02d}:{minutes % 60:02d}"
|
| 30 |
|
| 31 |
|
| 32 |
+
def seed_starter_blocks(
|
| 33 |
+
day: str,
|
| 34 |
+
*,
|
| 35 |
+
capacity_hint: float,
|
| 36 |
+
max_blocks: int = 7,
|
| 37 |
+
) -> list[ScheduledBlock]:
|
| 38 |
+
"""Build a thin starter day from templates (P0 locked; capacity cuts P2)."""
|
| 39 |
+
|
| 40 |
+
slot_map = {tid: (start, end) for tid, start, end in SEED_SLOTS}
|
| 41 |
+
out: list[ScheduledBlock] = []
|
| 42 |
+
for tid in seed_template_ids(capacity_hint=capacity_hint):
|
| 43 |
+
if len(out) >= max_blocks:
|
| 44 |
+
break
|
| 45 |
+
tmpl = template_by_id(tid)
|
| 46 |
+
if not tmpl:
|
| 47 |
+
continue
|
| 48 |
+
start, end = slot_map.get(tid, ("10:00", "10:30"))
|
| 49 |
+
planned = max(1, minutes_between(start, end))
|
| 50 |
+
out.append(
|
| 51 |
+
ScheduledBlock(
|
| 52 |
+
date=day,
|
| 53 |
+
start=start,
|
| 54 |
+
end=end,
|
| 55 |
+
title=str(tmpl["title"]),
|
| 56 |
+
kind=tmpl["kind"],
|
| 57 |
+
intent=tmpl["intent"],
|
| 58 |
+
priority=tmpl["priority"],
|
| 59 |
+
planned_min=planned,
|
| 60 |
+
status="planned",
|
| 61 |
+
source="rules",
|
| 62 |
+
locked=bool(tmpl.get("locked") or tmpl.get("priority") == "P0"),
|
| 63 |
+
notes="seed",
|
| 64 |
+
version_added=1,
|
| 65 |
+
)
|
| 66 |
+
)
|
| 67 |
+
out.sort(key=lambda b: b.start)
|
| 68 |
+
return out
|
| 69 |
+
|
| 70 |
+
|
| 71 |
def rules_backup_reschedule(
|
| 72 |
plan_blocks: list[dict[str, Any]],
|
| 73 |
*,
|
|
|
|
| 80 |
) -> list[ScheduledBlock]:
|
| 81 |
"""Deterministic reschedule: keep P0, drop/shrink P2, optional stabilize/fun."""
|
| 82 |
|
| 83 |
+
if not plan_blocks:
|
| 84 |
+
return seed_starter_blocks(day, capacity_hint=capacity_hint, max_blocks=max_blocks)
|
| 85 |
+
|
| 86 |
kept: list[dict[str, Any]] = []
|
| 87 |
for block in plan_blocks:
|
| 88 |
if block.get("priority") == "P0" or block.get("locked"):
|
app/schedule_risk.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Derive schedule risk signals from entries + daily check-ins.
|
| 2 |
+
|
| 3 |
+
Shared by human plan routes and agent context — server-owned, not LLM.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
from datetime import date, datetime, timedelta, timezone
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
RISK_TAGS = frozenset(
|
| 12 |
+
{
|
| 13 |
+
"urge",
|
| 14 |
+
"court",
|
| 15 |
+
"comparison",
|
| 16 |
+
"corn",
|
| 17 |
+
"daydream",
|
| 18 |
+
"bully",
|
| 19 |
+
"family",
|
| 20 |
+
"shame",
|
| 21 |
+
"rerun",
|
| 22 |
+
}
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
LAST_HOUR_HIGH_TAGS = frozenset({"urge", "court", "corn", "rerun"})
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def risk_from_stores(
|
| 29 |
+
entry_store: Any,
|
| 30 |
+
daily_store: Any,
|
| 31 |
+
*,
|
| 32 |
+
now: datetime | None = None,
|
| 33 |
+
target_day: date | None = None,
|
| 34 |
+
) -> dict[str, Any]:
|
| 35 |
+
"""Return risk_1h, triggers_yesterday, and last_hour_high flags."""
|
| 36 |
+
|
| 37 |
+
now = now or datetime.now(timezone.utc)
|
| 38 |
+
target = target_day or now.date()
|
| 39 |
+
hour_ago = now - timedelta(hours=1)
|
| 40 |
+
yesterday = (target - timedelta(days=1)).isoformat()
|
| 41 |
+
|
| 42 |
+
tags_1h: list[str] = []
|
| 43 |
+
triggers_y: list[str] = []
|
| 44 |
+
for entry in entry_store._load():
|
| 45 |
+
ts = entry.ts
|
| 46 |
+
if ts.tzinfo is None:
|
| 47 |
+
ts = ts.replace(tzinfo=timezone.utc)
|
| 48 |
+
entry_tags = set(entry.tags) | set(entry.emotions)
|
| 49 |
+
hit = sorted(entry_tags & RISK_TAGS)
|
| 50 |
+
if ts >= hour_ago:
|
| 51 |
+
tags_1h.extend(hit)
|
| 52 |
+
if entry.ts.date().isoformat() == yesterday:
|
| 53 |
+
triggers_y.extend(hit)
|
| 54 |
+
|
| 55 |
+
y_daily = daily_store.get(date.fromisoformat(yesterday))
|
| 56 |
+
if y_daily:
|
| 57 |
+
if y_daily.court == "court":
|
| 58 |
+
triggers_y.append("court")
|
| 59 |
+
if y_daily.corn_sessions >= 2:
|
| 60 |
+
triggers_y.append("corn")
|
| 61 |
+
if y_daily.daydream == "fc":
|
| 62 |
+
triggers_y.append("daydream")
|
| 63 |
+
|
| 64 |
+
tags_1h = sorted(set(tags_1h))
|
| 65 |
+
triggers_y = sorted(set(triggers_y))
|
| 66 |
+
last_hour_high = bool(LAST_HOUR_HIGH_TAGS & set(tags_1h))
|
| 67 |
+
return {
|
| 68 |
+
"risk_1h_score": float(len(tags_1h)),
|
| 69 |
+
"risk_1h_tags": tags_1h,
|
| 70 |
+
"triggers_yesterday": triggers_y,
|
| 71 |
+
"yesterday_trigger": len(triggers_y) > 0,
|
| 72 |
+
"last_hour_high": last_hour_high,
|
| 73 |
+
}
|
app/schedule_templates.py
CHANGED
|
@@ -190,3 +190,35 @@ KIND_LABELS: dict[str, str] = {
|
|
| 190 |
|
| 191 |
def list_templates() -> list[dict[str, Any]]:
|
| 192 |
return list(TEMPLATES)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
def list_templates() -> list[dict[str, Any]]:
|
| 192 |
return list(TEMPLATES)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def template_by_id(template_id: str) -> dict[str, Any] | None:
|
| 196 |
+
for row in TEMPLATES:
|
| 197 |
+
if row["id"] == template_id:
|
| 198 |
+
return dict(row)
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# Default clock slots for empty-day seed (P0 locked first).
|
| 203 |
+
SEED_SLOTS: list[tuple[str, str, str]] = [
|
| 204 |
+
("earn_one_ship", "09:00", "09:45"),
|
| 205 |
+
("food_outside", "12:30", "13:15"),
|
| 206 |
+
("stabilize_10", "15:00", "15:15"),
|
| 207 |
+
("walk_new_route", "16:30", "16:50"),
|
| 208 |
+
("sleep_wind", "22:00", "22:45"),
|
| 209 |
+
]
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def seed_template_ids(*, capacity_hint: float) -> list[str]:
|
| 213 |
+
"""Pick starter template ids under capacity (P0 always; cut P2 when low)."""
|
| 214 |
+
|
| 215 |
+
ids = ["food_outside", "sleep_wind"]
|
| 216 |
+
if capacity_hint >= 0.45:
|
| 217 |
+
ids.insert(0, "earn_one_ship")
|
| 218 |
+
if capacity_hint < 0.55:
|
| 219 |
+
ids.append("stabilize_10")
|
| 220 |
+
if capacity_hint >= 0.4:
|
| 221 |
+
ids.append("walk_new_route")
|
| 222 |
+
# Preserve SEED_SLOTS order
|
| 223 |
+
order = {tid: i for i, (tid, _, _) in enumerate(SEED_SLOTS)}
|
| 224 |
+
return sorted(set(ids), key=lambda t: order.get(t, 99))
|
docs/SCHEDULE.md
CHANGED
|
@@ -77,11 +77,14 @@ LLM must not invent `p_helped`, rank, or %.
|
|
| 77 |
- `GET/PUT /api/plan/{date}`
|
| 78 |
- `POST/PATCH/DELETE /api/plan/{date}/blocks[/{id}]`
|
| 79 |
- `POST /api/plan/{date}/blocks/{id}/feedback`
|
|
|
|
| 80 |
- `GET /api/schedule/priors`
|
| 81 |
- `GET /api/schedule/templates`
|
| 82 |
- `POST /api/plan/{date}/reschedule` `{ "reason", "force" }`
|
| 83 |
- `GET /api/plan/{date}/health`
|
| 84 |
|
|
|
|
|
|
|
| 85 |
## Agent API
|
| 86 |
|
| 87 |
Set Space secret `AGENT_TOKEN`.
|
|
|
|
| 77 |
- `GET/PUT /api/plan/{date}`
|
| 78 |
- `POST/PATCH/DELETE /api/plan/{date}/blocks[/{id}]`
|
| 79 |
- `POST /api/plan/{date}/blocks/{id}/feedback`
|
| 80 |
+
- `POST /api/plan/{date}/seed` — empty day → template starter (P0 locked; capacity cuts)
|
| 81 |
- `GET /api/schedule/priors`
|
| 82 |
- `GET /api/schedule/templates`
|
| 83 |
- `POST /api/plan/{date}/reschedule` `{ "reason", "force" }`
|
| 84 |
- `GET /api/plan/{date}/health`
|
| 85 |
|
| 86 |
+
`GET /api/plan/{date}` overlays live `capacity_hint`, `operators`, `risk_1h`, `triggers_yesterday`.
|
| 87 |
+
|
| 88 |
## Agent API
|
| 89 |
|
| 90 |
Set Space secret `AGENT_TOKEN`.
|
frontend/src/api.ts
CHANGED
|
@@ -489,3 +489,7 @@ export function reschedulePlan(
|
|
| 489 |
body: JSON.stringify(payload),
|
| 490 |
});
|
| 491 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 489 |
body: JSON.stringify(payload),
|
| 490 |
});
|
| 491 |
}
|
| 492 |
+
|
| 493 |
+
export function seedPlan(day: string): Promise<DayPlanView> {
|
| 494 |
+
return api(`/api/plan/${day}/seed`, { method: "POST", body: "{}" });
|
| 495 |
+
}
|
frontend/src/components/BlockSheet.tsx
CHANGED
|
@@ -4,8 +4,10 @@ import { useEffect, useState } from "preact/hooks";
|
|
| 4 |
import {
|
| 5 |
addPlanBlock,
|
| 6 |
deletePlanBlock,
|
|
|
|
| 7 |
postBlockFeedback,
|
| 8 |
type ScheduledBlock,
|
|
|
|
| 9 |
type TaskKind,
|
| 10 |
} from "../api";
|
| 11 |
import { Button } from "./Button";
|
|
@@ -27,6 +29,14 @@ const KIND_OPTIONS: { value: TaskKind; label: string }[] = [
|
|
| 27 |
{ value: "other", label: "Other" },
|
| 28 |
];
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
type Props = {
|
| 31 |
open: boolean;
|
| 32 |
day: string;
|
|
@@ -48,6 +58,7 @@ export function BlockSheet({ open, day, block, mode, onClose, onChanged }: Props
|
|
| 48 |
const [note, setNote] = useState("");
|
| 49 |
const [money, setMoney] = useState("");
|
| 50 |
const [busy, setBusy] = useState(false);
|
|
|
|
| 51 |
|
| 52 |
const [title, setTitle] = useState("New block");
|
| 53 |
const [kind, setKind] = useState<TaskKind>("other");
|
|
@@ -58,6 +69,11 @@ export function BlockSheet({ open, day, block, mode, onClose, onChanged }: Props
|
|
| 58 |
|
| 59 |
useEffect(() => {
|
| 60 |
if (!open) return;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
if (mode === "view" && block) {
|
| 62 |
setActualMin(block.planned_min || 30);
|
| 63 |
setDid("done");
|
|
@@ -79,6 +95,21 @@ export function BlockSheet({ open, day, block, mode, onClose, onChanged }: Props
|
|
| 79 |
}
|
| 80 |
}, [open, mode, block?.id]);
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
const saveFeedback = async () => {
|
| 83 |
if (!block) return;
|
| 84 |
setBusy(true);
|
|
@@ -157,6 +188,22 @@ export function BlockSheet({ open, day, block, mode, onClose, onChanged }: Props
|
|
| 157 |
>
|
| 158 |
{mode === "create" ? (
|
| 159 |
<div class="stack">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
<label class="field-label">
|
| 161 |
Title
|
| 162 |
<input class="field-input" value={title} onInput={(e) => setTitle((e.target as HTMLInputElement).value)} />
|
|
@@ -255,22 +302,18 @@ export function BlockSheet({ open, day, block, mode, onClose, onChanged }: Props
|
|
| 255 |
)}
|
| 256 |
<span class="field-label">Energy after</span>
|
| 257 |
<div class="segment-row">
|
| 258 |
-
{[
|
| 259 |
-
[-2, "Worse"],
|
| 260 |
-
[0, "Same"],
|
| 261 |
-
[2, "Better"],
|
| 262 |
-
].map(([v, label]) => (
|
| 263 |
<Pressable
|
| 264 |
key={String(v)}
|
| 265 |
className="segment"
|
| 266 |
ariaPressed={energy === v}
|
| 267 |
-
onClick={() => setEnergy(
|
| 268 |
>
|
| 269 |
-
{
|
| 270 |
</Pressable>
|
| 271 |
))}
|
| 272 |
</div>
|
| 273 |
-
{
|
| 274 |
<>
|
| 275 |
<span class="field-label">Would repeat?</span>
|
| 276 |
<div class="segment-row">
|
|
|
|
| 4 |
import {
|
| 5 |
addPlanBlock,
|
| 6 |
deletePlanBlock,
|
| 7 |
+
getScheduleTemplates,
|
| 8 |
postBlockFeedback,
|
| 9 |
type ScheduledBlock,
|
| 10 |
+
type ScheduleTemplate,
|
| 11 |
type TaskKind,
|
| 12 |
} from "../api";
|
| 13 |
import { Button } from "./Button";
|
|
|
|
| 29 |
{ value: "other", label: "Other" },
|
| 30 |
];
|
| 31 |
|
| 32 |
+
function addMinutes(hhmm: string, mins: number): string {
|
| 33 |
+
const [h, m] = hhmm.split(":").map(Number);
|
| 34 |
+
const total = h * 60 + m + mins;
|
| 35 |
+
const nh = Math.floor(((total % (24 * 60)) + 24 * 60) % (24 * 60) / 60);
|
| 36 |
+
const nm = ((total % (24 * 60)) + 24 * 60) % (24 * 60) % 60;
|
| 37 |
+
return `${String(nh).padStart(2, "0")}:${String(nm).padStart(2, "0")}`;
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
type Props = {
|
| 41 |
open: boolean;
|
| 42 |
day: string;
|
|
|
|
| 58 |
const [note, setNote] = useState("");
|
| 59 |
const [money, setMoney] = useState("");
|
| 60 |
const [busy, setBusy] = useState(false);
|
| 61 |
+
const [templates, setTemplates] = useState<ScheduleTemplate[]>([]);
|
| 62 |
|
| 63 |
const [title, setTitle] = useState("New block");
|
| 64 |
const [kind, setKind] = useState<TaskKind>("other");
|
|
|
|
| 69 |
|
| 70 |
useEffect(() => {
|
| 71 |
if (!open) return;
|
| 72 |
+
if (mode === "create") {
|
| 73 |
+
void getScheduleTemplates()
|
| 74 |
+
.then((r) => setTemplates(r.items || []))
|
| 75 |
+
.catch(() => setTemplates([]));
|
| 76 |
+
}
|
| 77 |
if (mode === "view" && block) {
|
| 78 |
setActualMin(block.planned_min || 30);
|
| 79 |
setDid("done");
|
|
|
|
| 95 |
}
|
| 96 |
}, [open, mode, block?.id]);
|
| 97 |
|
| 98 |
+
const applyTemplate = (tmpl: ScheduleTemplate) => {
|
| 99 |
+
setTitle(tmpl.title);
|
| 100 |
+
setKind(tmpl.kind);
|
| 101 |
+
setPriority((tmpl.priority as "P0" | "P1" | "P2") || "P2");
|
| 102 |
+
setIntent(
|
| 103 |
+
(tmpl.intent as ScheduledBlock["intent"]) ||
|
| 104 |
+
(tmpl.kind === "explore"
|
| 105 |
+
? "explore"
|
| 106 |
+
: tmpl.kind === "restore_fun"
|
| 107 |
+
? "restore_fun"
|
| 108 |
+
: "duty"),
|
| 109 |
+
);
|
| 110 |
+
setEnd(addMinutes(start, tmpl.default_min || 30));
|
| 111 |
+
};
|
| 112 |
+
|
| 113 |
const saveFeedback = async () => {
|
| 114 |
if (!block) return;
|
| 115 |
setBusy(true);
|
|
|
|
| 188 |
>
|
| 189 |
{mode === "create" ? (
|
| 190 |
<div class="stack">
|
| 191 |
+
{templates.length > 0 && (
|
| 192 |
+
<>
|
| 193 |
+
<span class="field-label">From template</span>
|
| 194 |
+
<div class="choice-list">
|
| 195 |
+
{templates.slice(0, 8).map((tmpl) => (
|
| 196 |
+
<Pressable
|
| 197 |
+
key={tmpl.id}
|
| 198 |
+
className="choice-item"
|
| 199 |
+
onClick={() => applyTemplate(tmpl)}
|
| 200 |
+
>
|
| 201 |
+
{tmpl.title}
|
| 202 |
+
</Pressable>
|
| 203 |
+
))}
|
| 204 |
+
</div>
|
| 205 |
+
</>
|
| 206 |
+
)}
|
| 207 |
<label class="field-label">
|
| 208 |
Title
|
| 209 |
<input class="field-input" value={title} onInput={(e) => setTitle((e.target as HTMLInputElement).value)} />
|
|
|
|
| 302 |
)}
|
| 303 |
<span class="field-label">Energy after</span>
|
| 304 |
<div class="segment-row">
|
| 305 |
+
{([-2, -1, 0, 1, 2] as const).map((v) => (
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
<Pressable
|
| 307 |
key={String(v)}
|
| 308 |
className="segment"
|
| 309 |
ariaPressed={energy === v}
|
| 310 |
+
onClick={() => setEnergy(v)}
|
| 311 |
>
|
| 312 |
+
{v > 0 ? `+${v}` : String(v)}
|
| 313 |
</Pressable>
|
| 314 |
))}
|
| 315 |
</div>
|
| 316 |
+
{did !== "skipped" && (
|
| 317 |
<>
|
| 318 |
<span class="field-label">Would repeat?</span>
|
| 319 |
<div class="segment-row">
|
frontend/src/pages/Plan.tsx
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
/** Plan day view: iOS-like timeline, reschedule, add/complete blocks.
|
| 2 |
|
| 3 |
Nav IA: Home | Plan | (+) Log | Daily | Settings (History via Home).
|
| 4 |
*/
|
|
@@ -8,6 +8,7 @@ import { useEffect, useState } from "preact/hooks";
|
|
| 8 |
import {
|
| 9 |
getPlan,
|
| 10 |
reschedulePlan,
|
|
|
|
| 11 |
type DayPlanView,
|
| 12 |
type ScheduledBlock,
|
| 13 |
} from "../api";
|
|
@@ -17,6 +18,7 @@ import { Pressable } from "../components/Pressable";
|
|
| 17 |
import { Timeline } from "../components/Timeline";
|
| 18 |
import { useToast } from "../components/Toast";
|
| 19 |
import { isoDate } from "../dates";
|
|
|
|
| 20 |
|
| 21 |
function shiftDay(day: string, delta: number): string {
|
| 22 |
const d = new Date(`${day}T00:00:00`);
|
|
@@ -49,8 +51,13 @@ export function Plan({ initialDate }: { initialDate?: string }) {
|
|
| 49 |
}
|
| 50 |
};
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
useEffect(() => {
|
| 53 |
void load(day);
|
|
|
|
| 54 |
}, [day]);
|
| 55 |
|
| 56 |
const openBlock = (block: ScheduledBlock) => {
|
|
@@ -65,8 +72,20 @@ export function Plan({ initialDate }: { initialDate?: string }) {
|
|
| 65 |
setSheetOpen(true);
|
| 66 |
};
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
const onReschedule = async () => {
|
| 69 |
-
if (!confirm("Reschedule the rest of this day?
|
| 70 |
setBusy(true);
|
| 71 |
try {
|
| 72 |
const result = await reschedulePlan(day, { reason: "user", force: true });
|
|
@@ -81,6 +100,7 @@ export function Plan({ initialDate }: { initialDate?: string }) {
|
|
| 81 |
|
| 82 |
const capacity = plan?.capacity_hint ?? 1;
|
| 83 |
const health = plan?.health;
|
|
|
|
| 84 |
|
| 85 |
return (
|
| 86 |
<div class="app-shell">
|
|
@@ -126,14 +146,19 @@ export function Plan({ initialDate }: { initialDate?: string }) {
|
|
| 126 |
</Button>
|
| 127 |
</div>
|
| 128 |
|
| 129 |
-
{
|
| 130 |
<section class="surface-card empty-card stack">
|
| 131 |
-
<p>No blocks yet.
|
| 132 |
-
<Button onClick={
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
</section>
|
| 134 |
) : (
|
| 135 |
<section class="surface-card timeline-card">
|
| 136 |
-
<Timeline blocks={plan.blocks} onSelect={openBlock} />
|
| 137 |
</section>
|
| 138 |
)}
|
| 139 |
</main>
|
|
|
|
| 1 |
+
/** Plan day view: iOS-like timeline, seed, reschedule, add/complete blocks.
|
| 2 |
|
| 3 |
Nav IA: Home | Plan | (+) Log | Daily | Settings (History via Home).
|
| 4 |
*/
|
|
|
|
| 8 |
import {
|
| 9 |
getPlan,
|
| 10 |
reschedulePlan,
|
| 11 |
+
seedPlan,
|
| 12 |
type DayPlanView,
|
| 13 |
type ScheduledBlock,
|
| 14 |
} from "../api";
|
|
|
|
| 18 |
import { Timeline } from "../components/Timeline";
|
| 19 |
import { useToast } from "../components/Toast";
|
| 20 |
import { isoDate } from "../dates";
|
| 21 |
+
import { navigate } from "../router";
|
| 22 |
|
| 23 |
function shiftDay(day: string, delta: number): string {
|
| 24 |
const d = new Date(`${day}T00:00:00`);
|
|
|
|
| 51 |
}
|
| 52 |
};
|
| 53 |
|
| 54 |
+
useEffect(() => {
|
| 55 |
+
if (initialDate && initialDate !== day) setDay(initialDate);
|
| 56 |
+
}, [initialDate]);
|
| 57 |
+
|
| 58 |
useEffect(() => {
|
| 59 |
void load(day);
|
| 60 |
+
navigate(`/plan/${day}`);
|
| 61 |
}, [day]);
|
| 62 |
|
| 63 |
const openBlock = (block: ScheduledBlock) => {
|
|
|
|
| 72 |
setSheetOpen(true);
|
| 73 |
};
|
| 74 |
|
| 75 |
+
const onSeed = async () => {
|
| 76 |
+
setBusy(true);
|
| 77 |
+
try {
|
| 78 |
+
setPlan(await seedPlan(day));
|
| 79 |
+
toast.show("Starter day added");
|
| 80 |
+
} catch (e) {
|
| 81 |
+
toast.show(e instanceof Error ? e.message : "Seed failed", "error");
|
| 82 |
+
} finally {
|
| 83 |
+
setBusy(false);
|
| 84 |
+
}
|
| 85 |
+
};
|
| 86 |
+
|
| 87 |
const onReschedule = async () => {
|
| 88 |
+
if (!confirm("Reschedule the rest of this day? Locked blocks stay put.")) return;
|
| 89 |
setBusy(true);
|
| 90 |
try {
|
| 91 |
const result = await reschedulePlan(day, { reason: "user", force: true });
|
|
|
|
| 100 |
|
| 101 |
const capacity = plan?.capacity_hint ?? 1;
|
| 102 |
const health = plan?.health;
|
| 103 |
+
const empty = !plan?.blocks.length;
|
| 104 |
|
| 105 |
return (
|
| 106 |
<div class="app-shell">
|
|
|
|
| 146 |
</Button>
|
| 147 |
</div>
|
| 148 |
|
| 149 |
+
{empty ? (
|
| 150 |
<section class="surface-card empty-card stack">
|
| 151 |
+
<p>No blocks yet. Seed a light starter day, or add one block.</p>
|
| 152 |
+
<Button disabled={busy} onClick={onSeed}>
|
| 153 |
+
Seed starter day
|
| 154 |
+
</Button>
|
| 155 |
+
<Button className="btn-secondary" disabled={busy} onClick={openCreate}>
|
| 156 |
+
Add block
|
| 157 |
+
</Button>
|
| 158 |
</section>
|
| 159 |
) : (
|
| 160 |
<section class="surface-card timeline-card">
|
| 161 |
+
<Timeline blocks={plan!.blocks} onSelect={openBlock} />
|
| 162 |
</section>
|
| 163 |
)}
|
| 164 |
</main>
|
static/assets/index-CsRld2Dr.js
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
static/assets/index-CsRld2Dr.js.map
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
static/assets/index-D3LLeLlA.js
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
static/assets/index-D3LLeLlA.js.map
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
static/index.html
CHANGED
|
@@ -20,7 +20,7 @@
|
|
| 20 |
<link rel="manifest" href="/manifest.webmanifest" />
|
| 21 |
<link rel="apple-touch-icon" href="/icons/icon-192.png" />
|
| 22 |
<title>Habit Journal</title>
|
| 23 |
-
<script type="module" crossorigin src="/assets/index-
|
| 24 |
<link rel="stylesheet" crossorigin href="/assets/index-6RturTFo.css">
|
| 25 |
</head>
|
| 26 |
<body>
|
|
|
|
| 20 |
<link rel="manifest" href="/manifest.webmanifest" />
|
| 21 |
<link rel="apple-touch-icon" href="/icons/icon-192.png" />
|
| 22 |
<title>Habit Journal</title>
|
| 23 |
+
<script type="module" crossorigin src="/assets/index-CsRld2Dr.js"></script>
|
| 24 |
<link rel="stylesheet" crossorigin href="/assets/index-6RturTFo.css">
|
| 25 |
</head>
|
| 26 |
<body>
|
static/sw.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
|
| 2 |
const CACHE = "habit-journal-v3";
|
| 3 |
-
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-
|
| 4 |
self.addEventListener("install", event => event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(SHELL)).then(() => self.skipWaiting())));
|
| 5 |
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())));
|
| 6 |
self.addEventListener("fetch", event => {
|
|
|
|
| 1 |
|
| 2 |
const CACHE = "habit-journal-v3";
|
| 3 |
+
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-CsRld2Dr.js","/assets/index-CsRld2Dr.js.map"];
|
| 4 |
self.addEventListener("install", event => event.waitUntil(caches.open(CACHE).then(cache => cache.addAll(SHELL)).then(() => self.skipWaiting())));
|
| 5 |
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())));
|
| 6 |
self.addEventListener("fetch", event => {
|
tests/test_schedule_api.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""API smoke tests for plan seed, feedback priors, agent auth, rules reschedule."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import pytest
|
| 8 |
+
from fastapi.testclient import TestClient
|
| 9 |
+
|
| 10 |
+
from app.config import get_settings
|
| 11 |
+
from app.schedule_math import ev_score
|
| 12 |
+
from app.schedule_reschedule import seed_starter_blocks
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.fixture()
|
| 16 |
+
def client(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> TestClient:
|
| 17 |
+
monkeypatch.setenv("DATA_ROOT", str(tmp_path / "data"))
|
| 18 |
+
monkeypatch.setenv("AGENT_TOKEN", "test-agent-token")
|
| 19 |
+
monkeypatch.setenv("APP_SECRET_KEY", "test-secret-key")
|
| 20 |
+
monkeypatch.setenv("APP_PASSWORD", "test-password")
|
| 21 |
+
monkeypatch.setenv("ENV", "dev")
|
| 22 |
+
get_settings.cache_clear()
|
| 23 |
+
from app.main import create_app
|
| 24 |
+
|
| 25 |
+
c = TestClient(create_app())
|
| 26 |
+
assert c.post("/api/auth/login", json={"password": "test-password"}).status_code == 200
|
| 27 |
+
return c
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_ev_score_locked_formula() -> None:
|
| 31 |
+
base = ev_score(p_done=0.8, utility=1.0, fun=0.5, d_hat_min=30, fse=0.2)
|
| 32 |
+
raised = ev_score(
|
| 33 |
+
p_done=0.8,
|
| 34 |
+
utility=1.0,
|
| 35 |
+
fun=0.5,
|
| 36 |
+
d_hat_min=30,
|
| 37 |
+
fse=0.2,
|
| 38 |
+
raise_eta=True,
|
| 39 |
+
raise_lambda_f=True,
|
| 40 |
+
)
|
| 41 |
+
assert isinstance(base, float) and isinstance(raised, float)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_seed_starter_keeps_p0() -> None:
|
| 45 |
+
blocks = seed_starter_blocks("2026-07-19", capacity_hint=0.8)
|
| 46 |
+
kinds = {b.kind for b in blocks}
|
| 47 |
+
assert "food_out" in kinds and "sleep_window" in kinds
|
| 48 |
+
assert all(b.locked for b in blocks if b.priority == "P0")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_plan_seed_and_feedback_priors(client: TestClient) -> None:
|
| 52 |
+
day = "2026-07-19"
|
| 53 |
+
r = client.post(f"/api/plan/{day}/seed")
|
| 54 |
+
assert r.status_code == 200, r.text
|
| 55 |
+
plan = r.json()["data"]
|
| 56 |
+
assert plan["blocks"]
|
| 57 |
+
assert "capacity_hint" in plan
|
| 58 |
+
bid = plan["blocks"][0]["id"]
|
| 59 |
+
fb = client.post(
|
| 60 |
+
f"/api/plan/{day}/blocks/{bid}/feedback",
|
| 61 |
+
json={
|
| 62 |
+
"did": "done",
|
| 63 |
+
"actual_min": 20,
|
| 64 |
+
"quality": 4,
|
| 65 |
+
"fun": 3,
|
| 66 |
+
"energy_after": 1,
|
| 67 |
+
"would_repeat": "yes",
|
| 68 |
+
},
|
| 69 |
+
)
|
| 70 |
+
assert fb.status_code == 200, fb.text
|
| 71 |
+
priors = client.get("/api/schedule/priors").json()["data"]["kinds"]
|
| 72 |
+
assert any(p.get("n", 0) >= 1 for p in priors)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_agent_requires_token(client: TestClient) -> None:
|
| 76 |
+
bare = TestClient(client.app)
|
| 77 |
+
r = bare.get("/api/agent/context?day=2026-07-19")
|
| 78 |
+
assert r.status_code in (401, 403)
|
| 79 |
+
ok = bare.get(
|
| 80 |
+
"/api/agent/context?day=2026-07-19",
|
| 81 |
+
headers={"Authorization": "Bearer test-agent-token"},
|
| 82 |
+
)
|
| 83 |
+
assert ok.status_code == 200
|
| 84 |
+
assert ok.json()["data"]["constraints"]["scope"] == "P1_thin_loop"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_reschedule_rules_source(client: TestClient) -> None:
|
| 88 |
+
day = "2026-07-20"
|
| 89 |
+
client.post(f"/api/plan/{day}/seed")
|
| 90 |
+
r = client.post(f"/api/plan/{day}/reschedule", json={"reason": "test", "force": True})
|
| 91 |
+
assert r.status_code == 200, r.text
|
| 92 |
+
body = r.json()["data"]
|
| 93 |
+
assert body["source"] in ("rules", "openrouter")
|
| 94 |
+
p0 = [b for b in body["plan"]["blocks"] if b["priority"] == "P0"]
|
| 95 |
+
assert p0
|