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
co-authored by Claude Opus 5
parent 178742501d
commit 9ddc0a2103
63 changed files with 6773 additions and 67 deletions
+190 -3
View File
@@ -32,9 +32,10 @@ from typing import Any
from sqlalchemy import select
from sqlalchemy.orm import Session as DBSession
from lembas.db.models import AUTHOR_MODEL, Chat, User
from lembas.db.models import AUTHOR_MODEL, KIND_TASK, SOURCE_CHAT, Chat, User
from lembas.db.session import session_scope
from lembas.services import prompts as prompts_service
from lembas.services import reports as reports_service
from lembas.services import scratch as scratch_service
from lembas.services import search as search_service
from lembas.services import settings_store
@@ -119,6 +120,16 @@ FAMILY_AGENT = "agent"
# the whole cost of this one is somewhere else.
FAMILY_IMAGE = "image"
# Filing a finished piece of work where the reader will find it later.
# Deliberately not part of `notes`, and the line is the one a note already
# draws from the other side: a note is something to be found again *by the
# model*, searched for mid-conversation and edited when it turns out to be
# wrong. A report is addressed to a person, read once, and never answered --
# so it is the destination for work nobody was watching, which is exactly what
# a note is not. Narrowing notes off must not take it away, and turning it on
# must not hand out the notebook.
FAMILY_REPORT = "report"
# The built-in families, in the order they are offered.
FAMILIES = (
FAMILY_SEARCH,
@@ -130,6 +141,7 @@ FAMILIES = (
FAMILY_SCRATCH,
FAMILY_ASK,
FAMILY_IMAGE,
FAMILY_REPORT,
FAMILY_AGENT,
)
@@ -670,6 +682,93 @@ async def _run_memory_forget(context: ToolContext, args: dict[str, Any]) -> Tool
)
# --- Reports -----------------------------------------------------------------
async def _run_report_write(context: ToolContext, args: dict[str, Any]) -> ToolOutcome:
title = str(args.get("title") or "").strip()
body = str(args.get("body") or "").strip()
summary = str(args.get("summary") or "").strip()
if not body:
return ToolOutcome(
"A report needs a body. Write what you found, not a note saying you found it.",
{"name": "report_write", "status": "error", "error": "Empty body."},
)
with session_scope() as db:
user = db.get(User, context.owner_id)
if user is None:
return ToolOutcome(
"That report could not be filed.",
{"name": "report_write", "status": "error", "error": "No such owner."},
)
report = reports_service.create(
db,
owner=user,
title=title,
body=body,
summary=summary,
source=SOURCE_CHAT,
source_id=context.chat_id or "",
model_id=context.model_id or "",
)
return ToolOutcome(
f"Filed report {report.id} — {report.title!r}. "
"The reader will find it under Reports; they cannot reply to it there.",
{
"name": "report_write",
"query": report.title,
"status": "ok",
"results": [{"title": report.title, "id": report.id}],
},
)
async def _run_report_search(context: ToolContext, args: dict[str, Any]) -> ToolOutcome:
query = str(args.get("query") or "").strip()
with session_scope() as db:
user = db.get(User, context.owner_id)
found = (
reports_service.search(db, user, query, limit=8)
if query
else reports_service.recent(db, user, limit=8)
)
event = {
"name": "report_search",
"query": query,
"status": "ok",
"results": [{"title": r.title, "id": r.id} for r in found],
}
if not found:
return ToolOutcome("There are no reports matching that.", event)
lines = ["Reports:"]
for report in found:
when = report.created_at.strftime("%Y-%m-%d %H:%M")
lines.append(
f"\n[{report.id}] {when} — {report.title}\n{reports_service.snippet(report)}"
)
lines.append("\nUse report_get with an id to read one in full.")
return ToolOutcome("\n".join(lines), event)
async def _run_report_get(context: ToolContext, args: dict[str, Any]) -> ToolOutcome:
with session_scope() as db:
user = db.get(User, context.owner_id)
report = reports_service.get(db, str(args.get("id") or ""), user)
if report is None:
return ToolOutcome(
"There is no such report.",
{"name": "report_get", "status": "error", "error": "Not found."},
)
when = report.created_at.strftime("%Y-%m-%d %H:%M")
return ToolOutcome(
f"{report.title}\nFiled {when}\n\n{report.body}",
{
"name": "report_get",
"query": report.title,
"status": "ok",
"results": [{"title": report.title, "id": report.id}],
},
)
# --- Skills ------------------------------------------------------------------
async def _run_skill_get(context: ToolContext, args: dict[str, Any]) -> ToolOutcome:
name = str(args.get("name") or "").strip()
@@ -971,6 +1070,73 @@ REGISTRY: dict[str, ToolDef] = {
run=_run_memory_forget,
risk=RISK_WRITE,
),
ToolDef(
name="report_write",
family=FAMILY_REPORT,
description=(
"File a report: a finished piece of work, written for the person "
"to read later. Use this when you have been asked for one, and "
"when you finish a long piece of work whose result is worth "
"keeping — an investigation, a summary of what you found, an "
"account of what you changed. A report is read on its own, away "
"from this conversation and possibly long after it, and THE "
"READER CANNOT REPLY TO IT. So write it whole: say what you were "
"asked, what you found and what you conclude, and do not refer "
"to 'the above' or ask a question at the end."
),
parameters=_object(
{
"title": {
**_STRING,
"description": (
"One line naming what this is about, as it will appear "
"in a list of dozens. 'Build failures this week', not "
"'Report' or 'Results'."
),
},
"body": {
**_STRING,
"description": (
"The report itself, in Markdown. Headings and lists are "
"rendered. This is the whole of what the reader gets, so "
"it should stand on its own with no further context."
),
},
"summary": {
**_STRING,
"description": (
"One sentence for the list page, so the report can be "
"triaged without opening it. Say the finding, not the "
"subject: 'Three tests fail on ARM only', not 'About the "
"test failures'. Omit it and the first line of the body "
"is used instead."
),
},
},
["title", "body"],
),
run=_run_report_write,
risk=RISK_WRITE,
),
ToolDef(
name="report_search",
family=FAMILY_REPORT,
description=(
"Search reports filed earlier, yours and the reader's. With no "
"query, returns the most recent. Worth doing before writing a "
"recurring report, so this week's can say what changed since last "
"week's rather than repeating it."
),
parameters=_object({"query": _STRING}, []),
run=_run_report_search,
),
ToolDef(
name="report_get",
family=FAMILY_REPORT,
description="Read one report in full, by the id a search returned.",
parameters=_object({"id": _STRING}, ["id"]),
run=_run_report_get,
),
ToolDef(
name="skill_get",
family=FAMILY_SKILLS,
@@ -1153,12 +1319,23 @@ def _family_allowed(
# the shape `resolve_tools` already refuses for `skill_get` with an
# empty library. `settings_store.images_ready` answers all three.
return bool(allowed.get("tools.image") and images)
if gate in (FAMILY_CUSTOM, FAMILY_MCP, FAMILY_ASK, FAMILY_AGENT, FAMILY_SCRATCH):
if gate in (
FAMILY_CUSTOM,
FAMILY_MCP,
FAMILY_ASK,
FAMILY_AGENT,
FAMILY_SCRATCH,
FAMILY_REPORT,
):
# Deliberately without `library.use`: an HTTP endpoint an administrator
# wrote has nothing to do with this person's own documents and notes,
# and requiring the library permission for it would be a coincidence of
# naming rather than a rule. The same goes for being asked a question,
# and for a pad that belongs to this chat and goes nowhere else.
# for a pad that belongs to this chat and goes nowhere else, and for
# filing a report -- which is addressed to the reader rather than kept
# for the model, and is the fallback destination for scheduled work, so
# gating it behind the library would switch that off for anyone whose
# instance does not use one.
return bool(allowed.get(f"tools.{gate}"))
return bool(allowed.get(f"tools.{gate}") and allowed.get("library.use"))
@@ -1293,6 +1470,16 @@ def resolve_tools(db: DBSession, chat: Chat, user: User | None) -> ToolSet:
off = scoped_off(chat)
empty_library = not skills_service.count_enabled(db, user, exclude=scoped_skills_off(chat))
# A scheduled task runs with nobody present, so `ask_user` cannot work here:
# it pauses the reply and waits for a POST that will never come, until
# `approval_timeout` expires -- a run that silently does nothing for fifteen
# minutes and then gives up. Withdrawn from the offered set rather than
# merely discouraged in `core.unattended`, because a rule living only in a
# system message is one a page the model just read can argue with. The
# fragment is the half that stops it *planning* around a tool it has not got.
if chat is not None and chat.kind == KIND_TASK:
off = off | {FAMILY_ASK}
return ToolSet(
tuple(
tool