Something can happen because time passed, and land somewhere worth reading

Nothing in LLeMbas ever happened on its own. Every reply was downstream of
somebody pressing Send, and the one exception -- jobs.wake, waking a chat when a
background job finishes -- was downstream of a command they had run. PLAN.md
never listed scheduling as unbuilt because services/chat.py:618 had recorded it
as a decision: "a scheduler is a whole new concern for a single-worker
application". This is that concern, taken on deliberately, plus the two places
its output goes.

Reports first, because it is useful with no scheduling at all. A report is not a
Chat with one Message in it: it has no turns and no reply, it is read top to
bottom, and it must be writable with no chat behind it -- being the fallback for
a run whose own chat has gone. As a Chat it would need a sidebar row per daily
report, a title that regenerates itself, a composer to suppress and a bubble with
a rewind button around something that is not a turn. The section's character is
enforced by absence: nothing under reports/ includes the composer or renders
chat/_message.html, so there is no sse-connect anywhere and nothing on those
pages *can* start a generation. The test reads that off the OpenAPI schema, not
by walking app.routes -- this FastAPI keeps an included router wrapped rather
than flattening it, so the walk finds nothing and the assertion passes for the
wrong reason.

rule.py is pure, total, and was finished before anything called it. No session,
no wall clock, nothing that raises: validate clamps what it recognises, drops
what it does not, and answers {} for prose -- at which point the caller shows the
manual form. It had to be that way because the compile step's output is model
output that becomes a *timer*, which is the sharpest case of hard rule 6 here.
The invariant, pinned: anything validate accepts has a computable next
occurrence. A schedule that can never fire looks exactly like a working one on
every screen it appears on.

Wall-clock and elapsed time are kept apart because they mean different things.
at.times are wall-clock in the owner's zone, so 15:00 stays 15:00 across a
daylight-saving change -- that is what "every Monday at 3PM" means. every is
elapsed real time, so six hours stays six hours across a 23- or 25-hour day --
that is what a timer means. Conflating them gets one of the two wrong twice a
year. A time inside the spring-forward gap fires at the first minute that exists;
left to zoneinfo's own resolution it lands an hour away wearing a wall-clock time
that did not happen, and a daily 02:30 report vanishing once a year on a machine
nobody watches is the failure this file is arranged around.

The ticker claims and commits *before* it fires. The other order is a hot loop: a
firing that raises is retried every tick for ever against whatever it was that
failed, and the only symptom is load. Its blanket except is copied from the
terminal reaper for a sharper reason -- a ticker that dies on one bad row stops
every schedule on the instance and says nothing at all. No request fails, no
reply errors, no dot appears. The reports simply stop.

Three rules that look like bugs from outside: a firing arriving while the chat is
still answering queues rather than starting a second reply, and past max_queued
is skipped with the reason on the row; Run now does not advance next_fire_at, or
testing a schedule silently consumes the run it was testing; resuming recomputes
from now, or a schedule paused for a month fires the instant it comes back, once
per occurrence it missed. Catching up lives in the sweep and not in a startup
hook, because a suspended host and a long stall reproduce "its time passed while
nothing was running" with no restart to hang one on.

services/wake.py is the lock discipline extracted rather than copied. A finished
job and a due schedule are the same problem, and both depend on there being no
await between the running_for check and the writes; two lock dictionaries for one
invariant is how one of them drifts. jobs.wake is now a caller that supplies
wording, and _completion_text stayed exactly where it was because tool.background
quotes its opening sentence.

A scheduled run has no reader, so ask_user is withdrawn from resolve_tools rather
than merely discouraged in core.unattended -- a rule living only in a system
message is one a page the model just read can argue with, and a parked question
holds the reply for the whole approval_timeout with nobody to answer it. For the
same reason a task chat may not be an agent chat in v1: Manual, Edit and Plan all
stop to ask on RISK_EXECUTE, so the only two outcomes would be unattended
execution and a reply that stalls. That deserves its own pass.

Messages is bounded in the request and unbounded on disk. Only the latest chunk
is sent; everything else stays exactly where it was written. Nothing is folded
into text and nothing is deleted -- the visible conversation is identical either
way, so destroying the older rows would buy only disk, against being irreversible
and losing every attachment and tool call in the range, and it would contradict
the rule compaction already holds. should_compact refuses this kind for the
matching reason: two mechanisms narrowing one transcript is how a summary ends up
summarising a summary. The history route is the mirror of thread_tail and keeps
its four properties; the fifth is its own, that prepending moves the scroll
position, so app.js records scrollHeight before the swap and adds the difference
back after.

An empty Chat.kind meant "both sides of the switch" and had been read as "no
filter" since there were only two of them. The sidebar passes "" precisely when
agent chats are switched off -- so the moment a third kind existed, every task
chat and every Messages conversation appeared in somebody's ordinary chat list,
on exactly the instances whose owners would never think to look. KINDS stays the
two-sided fork, because set_sidebar_kind validates against it and a third entry
there makes the tree filterable to a side with no button to leave it; ALL_KINDS
is what a row may be. Both narrowings are pinned, because they are two
implementations of one rule and only one of them is SQL.

Per-user timezone had to exist for any of this: harness.py:179 was telling every
reader the *server's* idea of the date, which is survivable while the answer is
prose and stops being survivable the moment somebody says "every Monday at 3" and
something has to work out when that is.

Three things were caught by a test being wrong rather than by the code being
wrong. The task-chat "no composer" assertions were passing against a page
rendering its no-models-configured branch. A permission test asserted the same
thing twice because the administrator bypasses every permission. And every
Messages test passed with default_model never called, because none of them
configured a model -- so the pair it returns was being assigned straight to
model_id, and SQLite refuses a tuple in a String column. The fixtures now say why
they exist.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-08-05 21:31:36 +02:00
parent 178742501d
commit 9ddc0a2103
63 changed files with 6773 additions and 67 deletions
+218
View File
@@ -0,0 +1,218 @@
"""Turning "remind me every Monday to check the build" into a schedule.
One request, once, when a schedule is created. It does two things a person
should not have to do by hand: work out the recurrence, and rewrite the
description into something that reads sensibly with **no conversation around
it** — because that is how it will be read, days later, by a model that was not
present when it was typed.
Three rules hold this up:
- **The rule goes through `rule.validate` and nothing else.** That function is
total and clamping, and this is the reason it had to be: what arrives here is
model output that becomes a *timer*. There is one normaliser, shared with the
manual form, so there cannot be two ideas of what a legal schedule is.
- **A compile that fails is not an error.** It hands back what it could work out
and the caller shows the manual form with the reader's own words in it. A
model that answers in prose must never quietly produce a schedule that never
fires.
- **Clearing `task.schedule_compile` switches off the compiling, not the
feature.** That is what makes "an empty override means off" safe here, and it
is only safe because the manual form exists. `task.compact` set the precedent
that clearing a fragment kills a feature, so this one says otherwise in its
own hint.
Deliberately no `response_format`. Several local endpoints reject unknown
parameters outright, and this is exactly the `apply_effort` lesson: a request
that 400s here would be the compile silently switching itself off.
"""
from __future__ import annotations
import json
import logging
import re
from dataclasses import dataclass, field
from datetime import UTC, datetime
from lembas.db.models import TARGET_CHAT, TARGETS, Chat, User
from lembas.services.llm.openai_client import Endpoint, LLMError, complete
from lembas.services.reasoning import strip_reasoning
from lembas.services.schedule import clock
from lembas.services.schedule import rule as rule_service
log = logging.getLogger(__name__)
# Enough for a small model that thinks before answering. The title lesson
# applies: too small is not a shorter answer, it is no answer, because the
# thinking consumes the budget and content comes back empty.
MAX_TOKENS = 900
MAX_REQUEST_CHARS = 2000
_FENCE = re.compile(r"```(?:json)?\s*(.*?)```", re.DOTALL)
@dataclass(frozen=True)
class Compiled:
"""What the compile worked out. `ok` is False when the reader must finish
the job by hand -- the fields are still filled in as far as they went."""
ok: bool = False
title: str = ""
instruction: str = ""
target: str = TARGET_CHAT
rule: dict = field(default_factory=dict)
reason: str = ""
def _payload(raw: str) -> dict:
"""The first JSON object in a reply, however it was wrapped.
Lenient for the reason `tools.parse_arguments` is: a small model sends
something close to the shape rather than the shape, and refusing it costs a
whole round trip to end up showing the manual form anyway.
"""
text = (raw or "").strip()
fenced = _FENCE.search(text)
if fenced:
text = fenced.group(1).strip()
if not text.startswith("{"):
start, end = text.find("{"), text.rfind("}")
if start == -1 or end <= start:
return {}
text = text[start : end + 1]
try:
parsed = json.loads(text)
except (ValueError, TypeError):
return {}
return parsed if isinstance(parsed, dict) else {}
def render_prompt(template: str, *, request: str, user: User | None) -> str:
"""Fill the fragment in. Separate so a test can read what was asked."""
from lembas.services import prompts as prompts_service
zone = clock.zone_for(user)
now = datetime.now(tz=UTC).astimezone(zone)
return prompts_service.substitute(
template,
{
"request": request[:MAX_REQUEST_CHARS],
"now": now.strftime("%A %-d %B %Y, %H:%M"),
"timezone": clock.name_for(user) or str(clock.server_zone()),
"targets": ", ".join(TARGETS),
},
)
async def compile_request(
endpoint: Endpoint,
model_id: str,
request: str,
*,
template: str,
user: User | None = None,
) -> Compiled:
"""Work a plain-language request into a schedule.
Never raises. Every failure -- a cleared fragment, an endpoint that is down,
prose instead of JSON, a rule that normalises to nothing -- comes back as
`ok=False` with whatever was salvageable, and the route shows the manual form.
"""
plain = (request or "").strip()
if not plain:
return Compiled(reason="Say what you want to happen.")
if not template.strip():
# An administrator cleared the fragment. That switches off the
# *compiling*: the reader fills the form in themselves, with their own
# words already in it.
return Compiled(instruction=plain, title=plain[:80], reason="")
prompt = render_prompt(template, request=plain, user=user)
body = {
"model": model_id,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": MAX_TOKENS,
"temperature": 0.2,
}
try:
raw = await complete(endpoint, body)
except LLMError as exc:
log.info("schedule compile failed: %s", exc)
return Compiled(
instruction=plain,
title=plain[:80],
reason="The model could not be reached, so fill this in yourself.",
)
# A model that thinks inline puts its reasoning in `content`, which is the
# field `complete` hands back verbatim -- the same trap auto-titling hit.
answered, _ = strip_reasoning(raw)
payload = _payload(answered)
if not payload:
return Compiled(
instruction=plain,
title=plain[:80],
reason="The model did not answer with a schedule, so fill this in yourself.",
)
raw_rule = payload.get("schedule") or payload.get("rule") or {}
if isinstance(raw_rule, dict):
# A model asked for "every six hours" writes `{"every": {"hours": 6}}`
# and nothing else, which is the natural reading and cannot fire: a
# timer measures from a start, and `rule.py` has no clock to invent one.
# Filled in here, exactly as the manual form's `_rule_from_form` does,
# so the two paths agree about what a startless timer means. A model
# that puts `start` at the top level instead is read the same way rather
# than being told its schedule means nothing.
raw_rule = dict(raw_rule)
if raw_rule.get("every") and not raw_rule.get("start"):
raw_rule["start"] = payload.get("start") or datetime.now(tz=UTC).isoformat()
clean = rule_service.validate(raw_rule)
title = str(payload.get("title") or "").strip() or plain[:80]
instruction = str(payload.get("instruction") or "").strip() or plain
target = str(payload.get("target") or TARGET_CHAT)
if target not in TARGETS:
target = TARGET_CHAT
if not clean:
return Compiled(
title=title,
instruction=instruction,
target=target,
reason="The model could not work out when this should run — say when below.",
)
if rule_service.next_after(clean, datetime.now(tz=UTC), zone=clock.zone_for(user)) is None:
# Normalised, but with nothing left to fire. Refused for the same reason
# `schedules.create` refuses it: a schedule that can never run looks
# exactly like a working one on every screen it appears on.
return Compiled(
title=title,
instruction=instruction,
target=target,
rule=clean,
reason="That time has already passed — say when it should run.",
)
return Compiled(ok=True, title=title, instruction=instruction, target=target, rule=clean)
def endpoint_for(db, user: User) -> tuple[Endpoint, str] | None:
"""A connection and model to compile with, or None if there is none.
Built on a throwaway `Chat` that is never added to a session, exactly as
`agent/draft.py` does: `resolve_endpoint` reads `model_id` and
`connection_id` and nothing else, so it works unchanged and did not have to
learn what a compile is.
"""
from lembas.services import chat as chat_service
models = chat_service.available_models(db, user)
if not models:
return None
chosen = next((m for m in models if m.pinned), models[0])
stand_in = Chat(user_id=user.id, model_id=chosen.model_id, connection_id=chosen.connection_id)
try:
return chat_service.resolve_endpoint(db, stand_in)
except LLMError:
return None