lotti Documentation

A private logbook with a staff of personal AI assistants. Agents read what you record and propose what to do next — you approve the changes.

RAW Doc

Technical Documentation: matthiasn/lotti

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (README.md)

Lotti

Come say hi on Discord — questions, support,
ideas, or just what you are using Lotti for.

A distributed system of record for your memories — kept on your devices,
and nowhere else.

Everything you capture in Lotti is a memory: a voice note, a screenshot, a
conversation, a photo from a birthday party, an hour of focused work, the
journal entry you spoke into your phone last night. Lotti keeps those memories
on your own devices and syncs them between those devices with end-to-end
encryption; no cloud ever holds a readable copy. On top of that record sit
applications — tasks, relationships, goals, events, projects, a daily journal —
most of them looked after by a personal AI agent that reads what you recorded and
proposes what to do next. Agents propose; you decide. Your memories are not
rewritten behind your back, not even by the agents that work for you.

macOS · Linux · Windows · iOS · Android. Flutter and Dart, GPL-3.0, in
development since 2016.

I have tracked around 11,000 hours of my own work in it since 2022.

Read the manual ·
Install ·
Blog series


The vision: a system of record you own

Most personal software treats your life as content to be stored on someone
else's computer and mined. Lotti starts from the opposite premise: your
memories are a record, and a record is only worth something if it is
complete, unaltered, and yours. Four principles follow from that.

1. Your memories live only on your devices

There is no Lotti cloud, no Lotti account, and no server that stores your
memories. Each device holds the full record in a local SQLite database, with
audio, images and other attachments beside it on the filesystem. No telemetry,
no analytics, and nothing uploaded to Lotti — you can confirm that by reading
the source or watching the traffic.

The record is distributed, not centralised: every device you pair is a full
peer. Pairing gives a new device everything written from then on; once you send
it your history from a device that has it, a phone, a laptop and a desktop each
carry the whole record, and losing one costs you nothing as long as another
survives. Your data is a file you
already have, with a documented schema, so there is no export wizard and
nothing to unlock.

2. End-to-end encrypted sync through a zero-trust relay

Devices talk to each other through a relay rather than a storage service: a
Matrix homeserver (Synapse). The relay is a zero-trust
component. Whoever operates it — you, a friend, a hosting company — never holds
a key, so they cannot read your memories, and they cannot slip changes into
your record either. You do not have to trust the operator with your data; you
only rely on them to keep the relay running.

mermaid
flowchart LR
    subgraph D1["Your laptop"]
        L1[(Local SQLite<br/>+ attachments)]
    end
    subgraph D2["Your phone"]
        L2[(Local SQLite<br/>+ attachments)]
    end
    R{{"Matrix homeserver<br/>zero-trust relay<br/>(ciphertext only)"}}
    L1 -- "Megolm-encrypted events<br/>AES-256-CTR attachments" --> R
    R -- "ciphertext delivered;<br/>keys only to verified devices" --> L2
    L2 -- "the same, in reverse" --> R
    R --> L1

How it works:

  • Encryption. Each change is sent as an event in a private, non-federated
    sync room created with Matrix's m.megolm.v1.aes-sha2 encryption. Room
    messages are encrypted with Megolm, and the Megolm session keys are exchanged
    between devices over Olm, using the Vodozemac
    implementation of both. Audio and images are uploaded as Matrix encrypted
    attachments: AES-256-CTR with a per-file key, IV and SHA-256 hash that travel
    only inside the encrypted event.
  • Only verified devices get keys. Keys are shared only with devices you
    have verified yourself through an emoji comparison. A device that joins the
    account without completing verification receives ciphertext it cannot read,
    and incoming events from unverified devices — or anything sent in plaintext —
    are dropped rather than applied, so whoever operates the server cannot inject
    changes into your record.
  • Trust comes from verification, not from the server. The emoji
    comparison is what stops a relay from posing as one of your devices: verify
    only devices you are holding, and the operator never gets a key.
  • What zero trust does not cover. The operator never sees plaintext, but
    can see metadata: the account ID and room name, which device synced and when,
    IP addresses, device display names, and the size of events and files. They
    also control availability — they can delay, withhold or delete ciphertext,
    but not read or alter it, and your devices still hold the full record.
  • The relay is not an archive. Sync rooms carry a 30-day
    m.room.retention policy. Synapse only enforces that when the operator turns
    retention on (and media retention separately); the hosted Lotti Sync
    service runs its own purge as well. Either way, the durable copy of your record is on
    your devices, not on the relay.
  • Conflicts are resolved, not overwritten. Every entry carries a vector
    clock keyed by device, so a device that was offline for a week rejoins
    without losing writes, and genuinely concurrent edits surface as conflicts
    for you to resolve. Devices also track each other's counters and ask a peer
    to re-send anything missing.

The full runtime picture — pairing, the sync log, backfill and failure handling —
is in the sync concept and
security and privacy.

3. Memories stay unaltered, with clear provenance

A system of record is worthless if it can be quietly edited. Lotti keeps what
you said and did
and what an agent thinks in separate databases on disk, and
agent-authored changes reach your record through a code path that requires
your approval: an agent suggests, and nothing happens until you confirm. A
confirmed checklist change keeps an approval receipt, and the writes an agent
makes without asking are logged in its audit trail.

A small, named class of writes is pre-approved rather than proposed, because
asking every time would add friction without telling you anything new — for
example transcribing a recording, saving an AI summary as a new entry beside
your own, or titling a task that has none. The exact set is defined in
ADR 0102 and can only grow by
another decision record. Some things are human-only by construction: an event
agent has no tool that can set an event's rating or cover photo.

Record provenance is work in progress. The goal is that every entry carries
a verifiable record of who authored it — you, an agent acting under a consent
you gave, or an agent proposal you approved — signed and chained per device so
that the record can prove it was not altered. The cryptographic building
blocks are in the codebase and modelled in
TLA+, but entries are not signed yet, and the design will keep moving as this
lands.

See Two databases for how
the separation is enforced.

4. Inference that keeps nothing — and eventually runs on your own devices

Agents need a model, and today the most capable models mostly run in a
datacenter. Lotti has no inference backend of its own: every request goes to a
provider you configured, under your own key, routed per category. Ideally that
is a provider with a zero-data-retention policy, one that processes the
request and keeps neither the prompt nor the response, so that inference leaves
no copy of your memories behind. Lotti cannot verify a provider's retention
terms; choosing one is your due diligence, covered under
Your inference is a routing decision.

The long-term direction is inference on your own devices, as they become
powerful enough to run capable models. The record and the reasoning over it
would then both stay at home. Part of that is already here: speech recognition
runs fully offline with Whisper or Voxtral, and lighter jobs run on a local
model. For the agents, today's answer is the cloud with zero data retention,
because they need a larger class of model than personal hardware runs fast
enough yet — see
Local models and the sweet spot for agents.


Applications on top of the record

The storage layer is the product's foundation; the applications are what you
use every day. Each one reads from the same record, and all of them except the
journal can be given a persistent AI agent with its own report, memory, wake
schedule and proposal history. Tasks and the journal are on by default; the other applications are
Sections you switch on under Settings → Sections. Turning a section off
only hides it — nothing you recorded is deleted.

Tasks, with task agents and pull request tracking

Every screenshot and audio recording is a memory, attached to the work it
belongs to. A rambling voice note comes back as a task with a checklist.

A task agent reads everything linked to a task and keeps a living report.
It proposes changes rather than making them: a title, an estimate, a due date,
priority or status, new or ticked-off checklist items, labels, follow-up tasks,
links to related tasks, time entries. Each proposal waits for you to confirm or
dismiss it. Automatic updates decide when the agent wakes, not what it may
change.

Pull request tracking closes the loop between what you planned and what
actually shipped. Turn it on for a task from its "+" menu, link one or more
GitHub pull requests, and Lotti keeps a summary of each — a one-liner and a
TL;DR — refreshed when you open the task or ask it to. The pull requests become
part of the task agent's context, so it can propose ticking off the checklist
items a merged PR actually covers, naming the PR as its evidence. You still
confirm each one. A personal access token, kept in the device keystore and
synced end-to-end encrypted, is only ever sent to api.github.com.

Coding prompts and other briefs are a skill you trigger: they turn a task
plus your notes into a coding, design, image or research prompt you can paste
into the tool of your choice.

Relationships, with a relationship agent

The People section is for the relationships you want to look after. Record a
conversation, or dictate afterwards who you spoke to and what you talked about;
a check-in holds the recordings, transcripts, notes and photos.

Mark someone as important and they get a relationship agent. Before you
meet again it gives you a briefing: what was discussed last time, how things
have been going, suggested talking points, and what to pay attention to or
steer clear of. It reminds you when it has been too long, and it can propose up
to three tasks arising from a conversation — each waiting for your
confirmation.

Goals, with goal agents

Define a goal — hours on a category or label, a measurement you track — and a
goal agent watches your actual record against it. A deterministic evaluation runs
every day at no inference cost. When you drift off track, the agent reminds
you, with an OS notification and a banner explaining what slipped; when you are
on track, it stays out of your way, its report records the progress, and you
can ask it for an encouraging nudge. If the goal itself no longer fits, it can
propose a revision, which you approve.

Events

Track the events that matter — a trip, a birthday party, a gathering — with the
photos, recordings and notes that belong to them. An event agent narrates
what you captured into a short living recap. The star rating and cover photo
stay yours alone: the agent has no tool that can set them.

Projects

A project groups the tasks that serve one outcome. A project agent keeps a
report on what is going on: current status, a health verdict, what is still
missing, and recommended next steps. It can propose a status change or a new
task for your approval. The project's summary also flows into every task
agent's context, so work on a single task is informed by the project it
belongs to.

Daily journal

Speak or type a journal entry, attach photos, or let a day's recordings stand
as they are. Transcription runs locally with Whisper or Voxtral if you want it
to, and your journal can be routed to a local model — or to no model at all.
The journal is the purest form of the record: your words, kept as you said
them, on your devices — read by no model unless you route it to one.

You choose the brain, and you can see what it cost

Lotti has no inference backend. Route each category of your life to the compute
you are willing to stand behind: a cloud provider with zero data retention,
the European option Lotti recommends, or a local model as personal hardware
catches up. The usage
view reports tokens and requests for every cloud call, and spend, energy and
CO₂e for the providers that report them — today that means Melious. Local
inference is not measured at all, because the cost moves onto your own hardware
and grid.

The sync protocol and the agent runtime are formally verified

Keeping several devices consistent without a server in charge is a
distributed-systems problem, and it is treated as one. The parts where
concurrency and crashes could lose or duplicate your data — the sync log, how
agents are woken and recover after a crash, how a confirmed suggestion is
applied when two devices race, how synced agent state converges, the agents'
message log, pull request tracking, and the Daily OS jobs — are written down as
50 TLA+ models and model-checked with TLC every night
across 177 configurations, under crashes, injected failures, clock skew and
messages arriving in any order (the ledger keeps the
running totals). No saved change is ever declared lost, and as long as devices
keep reconnecting and a failed send is retried, every saved change reaches every
device. A double tap never applies a confirmed change twice. Checking the models
found and closed dozens of real bugs. These are statements about the design, not
a proof that every line of code matches it; the specs say
exactly what is covered and which cases remain open, and generated traces drive
the real code through the same scenarios. The code is held to them the ordinary
way, too: over 35,000 tests at 99.9% line coverage, including more than 900
property-based tests.


Install

Platform Where to get it
Linux Flathub (recommended), or AppImage or tar.gz on Releases
Android APK on Releases, or Play Store internal testing (limited; invitation only)
macOS Signed and notarized DMG on Releases
iOS / iPadOS / macOS TestFlight (limited; invitation only), with broader availability planned
Windows Build from source for now

AppImage (Linux, no app store): download Lotti-<version>-x86_64.AppImage
from Releases, mark the
downloaded file executable (chmod +x on it, or your file manager's
permissions dialog) and start it. It brings its own media, keychain and
recording libraries and runs on distributions from 2022 on
(glibc 2.35 or newer: Ubuntu 22.04, Debian 12, Fedora 36 and later) that have
GTK 3 and Mesa's OpenGL ES, as any GNOME or KDE desktop does. It mounts itself
with FUSE, which desktops ship by default; where FUSE is missing, run it with
--appimage-extract-and-run. Unlike Flathub, it does not update itself.


Features at a glance

Capture

  • Audio recording anywhere in the app, transcribed locally with Whisper
    (99 languages) or Voxtral, or through a cloud provider with audio support.
  • Entries: notes, images, screenshots, measurements, and surveys, attached
    to the work, person, event or day they belong to.

Organize and reflect

  • Tasks with full lifecycle (open, groomed, in progress, blocked, on hold,
    done, rejected), checklists, estimates, priorities, due dates, labels, linked
    context, optional generated cover art, and linked GitHub pull requests.

  • Time tracking recorded against the plan rather than instead of it, with
    focus ratings. A task describes the outcome you want; a time record describes
    what actually happened. Lotti keeps them as separate facts, so the record
    stays honest when the week gets noisy.

  • Time analysis over categories, habits, and measurements.

  • Categories and labels to make the boundaries that your decisions
    actually use.

  • Habits, measurables, and health data imported from Apple Health and
    other sources.

  • Sections you switch on under Settings → Sections: Daily OS, Projects,
    Goals, Habits, Dashboards, People and Events. They are in daily use and ship
    switched off, so you choose which parts of Lotti you use.

AI and automation

  • Agents for every application: task, project, goal, relationship and event
    agents, plus a day planner. Each keeps its own report, memory and proposal
    history.
  • Providers, models, and inference profiles as three separate layers, so
    routing is explicit and the blast radius of a change is visible before you
    make it.
  • A European route, offered rather than imposed. Onboarding highlights
    Melious.ai, an OpenAI-compatible EU endpoint serving
    open-weight models. You bring your own key and hold your own contract with
    whoever you pick.
  • Works with everything else too: OpenAI, Anthropic, Mistral, Google, Alibaba,
    Nebius, OpenRouter, Ollama, or any OpenAI-compatible endpoint, including a
    custom base URL pointed at your own gateway.
  • Agent templates and souls: a template defines a responsibility, a soul
    defines voice, tone bounds, coaching style, and an anti-sycophancy policy.
    Both are versioned, both are improved through reviewable 1-on-1 sessions, and
    both can be rolled back.
  • Grievances and 1-on-1s. When an agent annoys you, say so — no form and no
    magic phrase required. It records the grievance and brings it up in the next
    1-on-1, where the two of you reconcile what changes. The result is an
    assistant that evolves rather than one you configure once.
  • Contextual skills for work that does not need a durable agent, including
    the prompt generators described above.
  • Usage and impact: tokens and requests by period, category and model for
    every cloud call, plus cost, energy and CO₂e wherever the provider reports
    them — currently Melious. Other providers return token counts only, so those
    columns stay empty rather than being estimated.
  • Turn all of it off. Lotti is useful without any inference configured.

Sync and data

  • End-to-end encrypted sync across your devices, relayed by a Synapse
    homeserver whose operator never holds a key — see
    the vision for how it works.
  • The first device is set up against a homeserver with the included
    tools/matrix_provisioner CLI, which creates
    the sync account and encrypted room and produces a single-use pairing
    bundle — or, in builds that offer it, by subscribing to the hosted Lotti
    Sync service from the app. On Linux you can also enter an existing Matrix account directly.
  • Every device after that pairs from one you already use: scan a QR code,
    compare a check code shown on both screens, then complete emoji verification.
    The pairing QR carries the sync account's credentials, so treat it like a
    password. Until verification finishes, the new device receives ciphertext it
    cannot read.
  • Your data is a file you already have. Local SQLite with a documented
    schema, plus attachments on the filesystem.

Two databases, human-in-the-loop by construction

Lotti keeps what you said and did and what an agent thinks in different
databases on disk.

The user database is the system of record: tasks, notes, audio, photos,
time recordings, journal entries, people, events. It is treated with care, and
agents do not write into it freely.

The agentic database is agent working memory: definitions, memories, wake
history, reasoning traces, reports, proposals. It may grow and it may be
pruned. It can be thrown away and rebuilt without losing anything that matters
about you.

mermaid
flowchart LR
    subgraph Agentic["Agentic DB (prunable, recreatable)"]
        A[Agent state & memories]
        W[Wake cycle reports]
        S[Proposals]
    end
    subgraph User["User DB (system of record)"]
        T[Tasks & projects]
        J[Journal, audio & photos]
        P[People & events]
        M[Metrics, habits & goals]
    end
    A --> W --> S
    S -->|requires your approval| T
    S -->|requires your approval| P
    S -.->|pre-approved class only, ADR 0102| J

The rule matters because of how it is enforced. Agent-authored content sits in
a different file on disk and reaches the user database only through a code path
that requires your approval, or through one of the pre-approved paths
described above and defined by
ADR 0102. Every other change an
agent wants to make to your record is a proposal you confirm or dismiss. Both
databases sync between your devices the same way.


Privacy, sovereignty, and where your compute happens

Three different claims get flattened into the word "private." Lotti makes all
three. They are worth separating, because they fail in different ways.

Your record is not collected

Lotti collects nothing — the record stays on your devices, as described in
the vision. Two things do leave,
both because you configured them: ciphertext to the homeserver you chose, and
inference requests to the provider you chose (plus, if you turn on pull request
tracking, requests to the GitHub API).

The other side of that: there is no server-side backup and no account
recovery, because no server holds a readable or lasting copy of your data.
Sync is the redundancy story — but it is not automatic history. Pairing a
device gives it everything written from then on; your existing settings and
back catalogue arrive only when you run Send settings and Send message
history
from the device that already has them. Until you do, the new device is
a live peer, not a backup. Do that early, and a second device means losing one
costs you nothing.

Keep an ordinary backup as well, since replication covers hardware loss and a
backup covers everything else. Your record is a SQLite database sitting on your
own disk with a documented schema, so reading it takes a query rather than
permission. Take a consistent copy with VACUUM INTO while the app is running,
and bring the attachments directory along with it, because audio and images
live on the filesystem rather than in the database.

On a phone the database sits inside the app sandbox, so the practical route
there is to pair a desktop and take the copy from that peer.

Deleting works the other way round, and the order matters: delete entries in
the app
rather than deleting the database files. Purging removes an attachment
by walking the deleted rows that still point at it, so a database removed first
leaves its audio and images orphaned on disk. Paired devices and ordinary
backups keep their own copies either way, and anything already sent to a
provider is subject to that provider's retention, not yours.

What this does not protect against: a compromised device. The on-device
SQLite files live inside your OS user account and are not separately encrypted
by Lotti today. That includes the sync session: its access and refresh tokens,
and its Olm identity and Megolm session keys, which the Matrix SDK stores
pickled under a key derived from the account ID rather than from a secret.
Anyone who can read your files can read your record and impersonate that
device. The sync password, AI provider keys and GitHub token are the exception:
they sit in the OS keystore. App-level at-rest encryption is a candidate for
the roadmap; until it lands, rely on your operating system's full-disk
encryption, give Lotti's on-device data the same care you would give any
personal app on the same machine, and weigh that before putting your most
sensitive categories in it.

Your sync relay does not need your trust

Sync runs over Matrix with Vodozemac for end-to-end encryption, through a
Synapse homeserver you can run yourself or rent from anyone. Its operator does
not need to be trusted with your data: the relay only ever handles ciphertext,
keys go only to devices you verified, and events from anything else are
dropped. Both databases sync this way. The details are in
the vision.

What this does not protect against: metadata and availability. Whoever runs
the homeserver can observe your account, which devices synced and under what
device names, from which IP addresses, when, and roughly how much. Not what.
They can also stop relaying, and how long the relay keeps ciphertext depends on
whether its operator enables retention.

Your inference is a routing decision

Lotti has no inference backend. Every AI call goes to a provider you
configured, under your own account and API key, and you choose per category
which provider that is. Work can go to one provider while your journal goes
to another, or to none at all. That granularity is the entire point.

Prefer zero data retention. The provider you route a category to sees what
that category sends it. The safest cloud choice is a provider whose terms
commit to zero data retention — no prompts or responses kept after the request,
no training on them. Many providers offer that only on request or on specific
plans, so read the terms rather than the marketing page.

Onboarding highlights a European route. Melious.ai is
a German company routing open-weight models across a network of EU
infrastructure providers. They state that requests are not used for training
and that data stays under European jurisdiction. Those are their claims, on
their terms, and worth reading in full before you rely on them. Directories
such as staysin.eu list Melious, but they
are compiled from providers' own published material, not from an audit.

Mistral, Google, Alibaba, OpenAI, Anthropic, OpenRouter, and any other
OpenAI-compatible endpoint work equally well. Lotti does not rank them, does
not summarise their terms, and cannot verify anyone's claims about jurisdiction,
retention, or training. Picking a provider is your decision and the due
diligence is yours.

What Lotti does instead is refuse to let the decision be invisible:

  • Routing is configured per category, ahead of time, rather than negotiated in
    the moment — so which provider a given piece of work goes to is a setting you
    chose, not a prompt you clicked past. The flip side is that there is no
    just-in-time notice at the point an agent or a transcription fires; the
    onboarding and settings screens are where that decision is made and shown.
  • A friendly display name is not the security boundary. The provider detail
    view shows the actual base URL, the models attached to it, and every profile
    that depends on them.
  • Usage & Impact logs every request that left the machine and which model served
    it, with token counts throughout and cost, energy and CO₂e wherever the
    provider reports them.

A LAN endpoint is worth the same scrutiny. "Local" means it did not go to a
hosted provider, not that no network hop occurred.

What this does not protect against: a provider that does not do what its
terms say. Nothing in Lotti can verify that, and neither can anyone else from
the outside. What Lotti can do is show you every request it made, where it
went, and what it cost.

Local models and the sweet spot for agents

Some of Lotti runs well on your own machine today. Speech is fully offline via
Whisper or Voxtral, and a local inference server handles lighter jobs. Lotti
connects to:

  • Ollama and oMLX (MLX
    on Apple Silicon), which have their own provider types in Lotti's settings;
  • anything else that serves an OpenAI-compatible API, through the
    OpenAI Compatible provider: Python-based servers such as
    vLLM,
    SGLang and
    mlx-lm, as well as
    llama.cpp's llama-server and
    LM Studio.

The agents are a different matter. Their sweet spot right now is models of the
size and capability of DeepSeek V4.1 Flash and GLM 5.3 Flash, both of
which perform particularly well on Lotti's agent workloads. The models people
typically run locally are not that far behind on correctness, but they are slow:
Qwen 3.8 27B, for example, lands only a few points below them, yet is far slower
even on cloud inference, occasionally stalls, and misses the day planner's
30-second budget (the evaluation).
On a personal machine that gap only widens: even an M4 Max with 128 GB of RAM
does not yet run the agents fast enough to keep up with daily use. Personal
hardware is improving quickly, and closing that gap is the long-term direction.

LottiGym is how new models are judged. Models enter the market every few
weeks, and a benchmark score says little about whether one can run a task
agent. LottiGym runs a candidate
through Lotti's real agent harnesses — task, goal, relationship, Daily OS
planning and query exercises, several samples each — grades the results, and
records correctness, cost and latency side by side
(recent results). A new model earns a recommendation by
passing it:

sh
python3 tool/lotti_gym.py assess --model MODEL_ID

The practical answer today is the cloud, with zero data retention: run
the agents on a sweet-spot-class model from a provider whose terms commit to
keeping nothing, and keep speech fully offline with Whisper or Voxtral if you
like. Image generation has no local path yet — cover art goes through Gemini or
Alibaba. As personal hardware gets faster, models of that class are expected to
move onto your own devices, until a cloud provider is a choice rather than a
necessity.

Input on running Lotti locally is very welcome. If you have a model,
quantisation, runtime or hardware setup that keeps up with the agents, please
share it in a GitHub issue or on
Discord.

Energy is a routing decision too

Inference runs in a physical building on a specific grid. The Usage & Impact
view reports tokens and requests for every cloud call, broken down by category
and by model, so "what did my thinking cost" has an answer rather than a vibe.

How complete that answer is depends on the provider. Cost, energy, CO₂e and
water are recorded when the provider returns them with the response, which today
means Melious; every other provider reports token counts only, and those columns
stay empty rather than being filled with an estimate. That is a real limit on the
dashboard: route your work through a provider that discloses nothing, and the
impact of that work is not something Lotti can show you.

The route highlighted in onboarding publishes power usage effectiveness per
datacenter and carries Green Web Foundation verification, which is more than
most disclose. Running a model locally moves the cost onto your own hardware
and your own grid, which is a different trade rather than a free one, and the
dashboard does not measure it.

Choosing a renewable-powered route avoids outsourcing the health and climate
cost of fossil-powered compute, gas turbine generation in particular, to
communities with less power to refuse it. That is a reason to care where your
tokens get processed even if you do not care who reads them.

If none of that satisfies you

Turn AI off. Configure no provider at all, or point every category at Ollama
with local Whisper for speech. Lotti is a complete task manager, time tracker,
and journal without a single inference call leaving the machine.


In development

Built and documented, but not enabled in a default build. Turn it on under
Settings → Sections, and expect it to change.

  • Daily OS turns a spoken or typed check-in into a plan for one day. It
    reconciles what you said against your real tasks, drafts an agenda against
    your actual capacity, and presents every proposed change with its old time,
    its new time, and the planner's reason. Nothing is committed until you hold
    the confirm control. Wrap-up at the end of the day separates what you
    finished from what carries forward.
    Documentation

Also under way, with no switch to flip yet: record provenance, so that
every entry is signed by its author and the record can prove who wrote what —
see the vision.

Next agent types on the roadmap: week planners, long-term commitment monitors,
and effort-against-goals balancers — same building blocks, different jobs.
Designed but not yet built: learning quizzes. See the
roadmap.


Pricing and sustainability

Linux is and will always be free, with maximum functionality. No paywalls,
no upsells. The same promise extends to any future fully open-source mobile
operating system. The one thing it does not include is hosted sync
infrastructure — running a homeserver is a real cost, so you either self-host
Matrix or bring your own.

On other platforms, the basics stay free too. Task and journal capture, the
task agent, voice transcription, the everyday loop.

More advanced agent features may eventually be in-app purchases on platforms
where IAP is the norm
(iOS/macOS, Android, Windows). The candidates: day- and
week-planner agents, overarching project-management agents, longer-horizon
commitment monitors. The exact split is not set yet.


Documentation

Building it yourself: install Flutter via FVM (the repo
includes .fvmrc), then make deps, make analyze, make test,
fvm flutter run -d <device>. Full setup, including the Linux audio-codec and
emoji-font packages, is in docs/DEVELOPMENT.md.


Status

The application is in active daily use and the agentic layer is real, working,
and shipping. Development happens in the open, and the changelog
is the honest version of what changed.

The agentic layer moves fastest: soul and template ergonomics, grievance
handling, and pruning strategies are all under active development, and feedback
there is especially useful. Local image generation, at-rest database
encryption, and signed provenance do not exist yet.

The manual, including every screenshot in all 11 languages, is generated from a
deterministic fixture workspace, so the documentation cannot quietly drift from
the build it documents.

Stack: Flutter and Dart across five platforms, local SQLite via Drift with
ObjectBox for embeddings, Whisper and Voxtral for on-device speech recognition,
Matrix and Vodozemac (Olm/Megolm) for the encrypted sync transport, Glados for
property-based tests, TLA+ and TLC for the formally verified sync protocol and
agent runtime.


Contributing

The easiest way in is to say hi on Discord.
Beyond that, two things genuinely help, and one thing to know up front.

Welcome:

  • Issues and bug reports — the best place to start. Tell me what broke and
    how to reproduce it.
  • Translations — new languages and corrections to existing ones.
    AI-assisted translation is fine provided you contribute from a real-name,
    established GitHub profile
    . Translation PRs are the one kind that gets
    merged.

Not accepted: code pull requests. Review capacity is the binding
constraint, Lotti holds people's personal data on their own devices, and
AI-generated code now arrives far faster than it can be reviewed carefully. An
unsolicited code PR will be closed unmerged, with thanks and without review —
so please open an issue instead of writing the patch. It is more useful to me
and cheaper for you.

CONTRIBUTING.md has the details, including what makes a
translation PR mergeable.

License

GPL-3.0. See LICENSE.

Acknowledgments

Thanks to the Flutter team, the
Qwen and Mistral teams for
their open-weights models, OpenAI for the
Whisper weights, the
Ollama project, the Matrix.org
community, the Vodozemac authors, and
everyone contributing translations, issues, and ideas.


Built in public. GitHub ·
Substack


Docs Site Docs Index (`docs-site/docs/index.mdx`)


id: index title: Lotti Manual slug: / sidebar_label: Welcome

A private logbook, not a productivity panopticon

Keep the facts. Make the day yours.


Tasks, time, voice notes, habits, health data, and the odd useful thought all deserve a better fate than tab purgatory. Lotti keeps the record; you decide what happens next.

text
**Your history stays yours.**It lives in your local logbook, not in a Lotti cloud account.
**AI asks; you decide.**Agents can notice, think, and propose. They do not get the keys to your life.
**Make it memorable.**Useful, serious, delightfully weird: the workspace gets to sound like you.

Not another machine for pretending everything went to plan

Lotti distinguishes the things you meant to do from the things that actually
happened. A task can be important without owning your whole day. A plan can be
rearranged without falsifying history. A time record can say, honestly, that
the meeting ran long and the good idea arrived while you were walking home.

That separation is the point, not paperwork. It gives you a record you can
trust when the week gets noisy.

:::note[About the penguins (and other excellent nonsense)]

The penguins, orbital habitat, sardines, and Project Waddle appear only in
this manual's fictional Intergalactic Penguin Logistics demo workspace.
They make the screenshots feel like one coherent story, while the controls,
flows, and product behaviour shown are the real Lotti app. Your own workspace
can be as ordinary—or as delightfully strange—as you like. Task cover art is
optional; a good visual metaphor can make a crowded week much easier to read.

The worldscape is not starter content and is never added to your profile. If
you want to explore it hands-on, the optional demo workspace opens Project
Waddle in a separate sandbox: its seeded content stays out of your real
journal, and work you create there yourself crosses over only if you choose
to copy it when you leave. It is
a deterministic screenshot fixture: one silly logistics operation, recurring
characters, and distinct task covers make it possible to follow a feature from
the agenda to the task, project, journal, and dashboard without mistaking
sample data for a product promise. The cover art is equally optional in real
work: create it in Lotti when a useful, serious, or gloriously peculiar image
makes the work easier to recognize.

:::

Start where the friction is

**Just ask** Ask the companion what is due or where your time went, or tell her what happened. She files it only when you tap. **Your life is not a backlog** See how intent, plans, actual time, evidence, and reflection stay distinct—and useful. **Build a day that can breathe** Turn a spoken or typed check-in into an editable, reality-aware day plan. **Give work a home** Create tasks, attach context, set priorities, and turn ambiguity into next moves. **Choose a brain responsibly** Pick local or cloud inference deliberately—privacy, retention, region, and energy are all part of the choice.

AI is optional. Its consequences are not.

Lotti has no inference backend and no copy of your model input. Local storage
and local inference are related choices, but they are not the same promise:
your logbook stays on your devices either way. With a local provider, selected
material is processed by the machine or local endpoint you configure. With a
cloud provider, the chosen context goes directly to that provider under
your account and API key. That makes the decision yours—but it also makes
the due diligence yours.

text
**Privacy is a routing decision.**
For sensitive material, run a capable model locally or choose a provider only after checking its retention, training, jurisdiction, and account settings. “Cloud” never automatically means “nothing is stored.”


**Energy is a routing decision too.**
AI runs in physical places. Prefer a local setup or provider whose electricity, location, and carbon claims you can actually verify. A renewable-powered route can avoid outsourcing the health and climate cost of fossil-powered compute—especially gas-turbine generation—to communities with less power to refuse it.


**Human approval is a product rule.**
Agents can analyse context and draft changes, but changes to your record wait for you. The only exceptions are the title and the language, and only when that field is still empty and the agent is setting it for the first time — a task you have been working on can therefore have a blank title or unset language filled in without asking. Everything else waits for you. Lotti does not turn “helpful” into “unaccountable.”

The practical rule: if you cannot find a data and energy path you are happy to
stand behind, leave AI off. Lotti remains useful without it.

:::tip[Start small]

Create a couple of meaningful categories, one real task, and one Daily OS
check-in. Add more structure only when it earns its place; you are building a
record of a life, not feeding a productivity machine.

:::


Adr README (`docs/adr/README.md`)

Architecture Decision Records (ADR)

This folder stores architecture decisions that need durable rationale beyond
feature README snapshots.

Scope

  • Record decisions that affect module boundaries, lifecycle behavior, storage
    contracts, and cross-feature integration.
  • Keep feature READMEs focused on the current implementation.
  • Use ADRs for "why this shape exists" and migration constraints.

File Naming

  • NNNN-short-title.md (for example: 0001-agent-capabilities-runtime-model.md)
  • NNNN is a zero-padded, increasing sequence.

ADR Template

Each ADR should contain:

  1. Status (Proposed, Accepted, Superseded, Deprecated)
  2. Date
  3. Context
  4. Decision
  5. Consequences
  6. Related (optional links to PRs/issues/docs)

Index

Every ADR is a file in this folder, and the zero-padded numbers keep
ls docs/adr in order: that listing is the complete index. Do not add a line
here for a new ADR. A list every pull request appends to made concurrent
pull requests conflict over lines they do not share (the same reason release
notes go in changelog.d/). Because the number is an ADR's identity, CI fails
when two ADRs share one (tool/ci/check_adr_numbers.dart): if your pull request
and another both took the next free number, renumber yours and update its
citations. The workflow runs on push, not on the pull request's merge with
main, so the check fires once both ADRs are in one tree: on your branch after
it is rebased, or on main if both already merged — in which case the
renumbering is a follow-up. The clusters below group ADRs that belong
together; add to them only when a decision joins one.

Task graph decision cluster

ADR Status Decision ownership
0042: Typed Task Relationship Links Accepted EntryLink union variants (blocks, followsUp, duplicates, fixes, supersedes), one stored edge with rendered inverses, derived one-hop readiness, cycle tolerance, suggestion-only lifecycle coupling.
0043: Dependency-Aware Planning Accepted Ready frontier consumed by planning: corpus annotation (never exclusion), batch dependency resolver, drafting/digest prompt rules, task-detail visibility, explicit non-goals.
0106: The Task Link Graph Across Devices Accepted Cycles kept and reported the same on every device, never broken; the cycle check inside the write's transaction and uncapped; a project move or unfile retires every live project link of the task.

Relationship management decision cluster

ADR Status Decision ownership
0037: Relationship Data Stays On-Device Accepted Local-only storage, opt-in E2E sync, zero external retention, explicit cloud-AI consent, deletion cascade, GDPR framing.
0038: Relationship Domain Model Accepted relationship/checkIn journal subtypes, embedded person identity, status union, RelationshipLink task/timeline linking, no schema change.
0039: Relationship Check-In Reminders Accepted, two decisions amended at implementation Importance-gated cadence rule (a Phase A wake fact), reminders as a projection of that verdict rather than a second producer, per-episode row identity, startup reconcile, platform limits — and the Android notification stack it had to fix.
0040: Relationship Executive Briefing Accepted, amended by 0059 Relationship agent + report contract, health band, strict context boundary, privacy-weighted model routing, honesty rules; runtime binding and template assumption amended.
0041: Relationship Contact Linking Accepted Selective per-relationship contact linking (no bulk import), channel snapshots, call/message actions from the briefing, post-interaction check-in prompt.
0059: Relationship Agents on the Shared Runtime and the Kind-Agnostic Nudge Substrate Accepted Registered runtime kind on two-tier wakes (no template), per-episode lease-elected escalations with baseline tokens, banner dock as the attention channel (OS reminders deferred), sibling relationshipNudge variant with mixed-fleet-safe rollout, per-kind dock visibility.

Learning verification decision cluster

ADR Status Decision ownership
0033: Learning Verification Checkpoint Policy Proposed When quizzes start: manual-first entry from any task, deterministic suggestion triggers/guards/caps, no gating, no spaced-repetition scheduler.
0034: Hybrid Understanding Evaluation Proposed Frozen evidence snapshots, tailored quiz generation, deterministic validation, conversational LLM grading with bounded probes, injection resistance.
0035: Learning Verification Session Persistence Proposed Quiz events/artifacts/links on the existing agent log, identity and sync convergence, device-local boundaries, plain deletion and export.
0036: Learning Understanding Rating Proposed Per-item verdicts, session scores/labels, feedback-first presentation, honesty rules, storage separate from journal ratings.

Goal-driven agents decision cluster

ADR Status Decision ownership
0053: Goal-Driven Agents — Per-Goal Durable Producers Proposed One durable agent per goal (amends 0023's granularity), versioned goal spec (version + head), purpose-built GoalCriterion tree, deterministic goalProgress register, proposal-only revision, StandingAgreement's first writer, no template in v1.
0054: Deterministic-First Two-Tier Wakes Proposed €0 deterministic Phase A on every device, lease-elected LLM Phase B, sync-origin Phase-A dispatcher, per-goal subscriptions, recurrence by re-arm, fact-gated tools from day one, cost monitored not capped.
0055: The Banner-Nudge Attention Channel Proposed Banner-only in-app ads (never push), goalNudge lifecycle with dismissal-as-data, staleness contract, respect mechanics (cool-down, dedupe), quiet-by-default surfaces, on-device copy compositing, ads permanent in chat history.
0056: The Need-to-Know Visual Brief Boundary Proposed Non-ZDR image providers receive only a self-contained typed brief; the parameter type is the enforcement; on-device text compositing; provenance-gated reference images; leakage evals; one-retry verification.
0057: Decade-Scale Agent Memory Proposed Generalized search + keyed knowledge read path, bounded observation reads, epoch summaries via summaryDepth (amends 0017), distill-then-prune retention, bounded prune instead of the 20k skip, cold-prefill context budgets.
0058: Procedural Text Banners — No Generative Imagery Proposed Goal ads are model-authored copy over code-owned animation/accent presets; no image provider in the channel (supersedes 0055 D8; 0056 dormant); per-agent energy (Wh/goal-month) is a first-class reported figure.

Evaluations Goal Agent Models README (`docs/evaluations/goal_agent_models/README.md`)

Goal-agent model evaluations

Full-catalog results, 2026-09-16: LottiGym, every section run and optimised.
Four models and what a run costs, 2026-09-17: LottiGym, four models.
Qwen 3.8 27B rejected, 2026-09-21: LottiGym, Qwen 3.8 27B and two harness regressions.

Graduated (2026-08-09, PR 3): the system prompt and tool definitions
now live in lib/features/goals/workflow/goal_agent_contract.dart — the
production Phase B workflow and this eval suite import the SAME file, so
the contract the evals validate is the contract the runtime ships. The
policy matrix stays here as the scenario source of truth.

Inference-level evals for the goal agent (ADR 0053–0057) — originally
run before the production GoalAgentWorkflow existed, so the prompt/tool
contract was model-validated before a line of runtime code depended on it.
The contract now lives in
lib/features/goals/workflow/goal_agent_contract.dart;
test/features/agents/eval/goal/support/goal_agent_spec.dart re-exports it
and keeps the policy matrix the scenarios are derived from.

Two tiers

(A third, orthogonal eval — does compacting years of check-ins change the
agent's conclusions? — has its own run book: compaction.md.
Its numbers are not comparable with either tier below.)

There are two evals here, and they answer different questions. Their numbers
are not comparable — do not put them in one table.

Tier 1 — inference Tier 2 — outcome
Runner goal_agent_eval_runner.dart goal_agent_outcome_eval.dart
Input authored FACTS block; journal scenarios via the real GoalFactsRenderer domain entities → real GoalFactsRenderer
Under test the model + the prompt/tool contract the whole GoalAgentWorkflow
Scored tool calls attempted entities persisted
Strategy records, accepts everything the real GoalAgentStrategy, which rejects
Retries none _forceReport / _forceAd / _forceReply all run
Scenarios 32, P1–P21 9, the rows where attempt ≠ outcome
Cost ~1 call per case 1–3 calls per case

Tier 1 is the workhorse: cheap, broad, and every scenario is legible. But
three production layers sit between a tool call and the user, and tier 1 is
structurally blind to all of them — the FACTS are (journal scenarios aside)
authored rather than rendered, nothing rejects a bad call, and nothing repairs
a missing output.
So a tier-1 failure can be a production success, and a tier-1 pass can
persist nothing at all.

Tier 2 exists to measure that gap, not to replace tier 1. It is deliberately
narrow: nine scenarios over the policy rows where the two can disagree.

Tier 1 — what is measured

Five behaviours, one scenario catalog
(goal_agent_eval_scenarios.dart, ids in parentheses):

  1. Goal progression reporting — restating the deterministic evaluation
    without recomputing or contradicting it (gp_*, gh_*).
  2. Ad decisions — when to create, re-run, retire, and not create
    (ad_*); includes the need-to-know leakage trap (ad_leakage_pressure,
    ADR 0056) and the top-rated reuse rule (ad_reuse_top_rated, ADR 0055).
  3. Goal-evolution dialogue — restate-then-propose-exactly-once, vague
    musings get questions not proposals, withdrawals end without a proposal
    (evo_*, wk_*).
  4. Restraint — the no-op wake (gp_noop): nothing changed → zero tool
    calls. This is the cheapest discriminator between models that follow
    policy and models that churn; the task-agent evals found 4/5 models
    churn without it being tested.
  5. The user's own words (ADRs 0141 and 0143) — a journal goal's report must engage
    with check-ins the standing report never answered, in its reflection
    slot (journal_new_checkins_reflected, P18); the morning briefing must
    follow up a commitment the user made in its next steps, not merely name it
    in the reflection (journal_briefing_follows_commitment, P19); a fact
    stated in chat (ADR 0141) is remembered in the user's words
    (journal_remember_from_chat, P20); a question about the past beyond
    userVoice is a recall, not a guess (journal_recall_older_entry, P21);
    and a wake with nothing new stays quiet even with the user's words in
    FACTS (journal_quiet_wake_stays_quiet, P2). Tier 1 records rather than
    rejects, so P18 measures whether the model fills the reflection on its
    first response
    — production would refuse an empty one and retry once.

Every expectation derives from the policy matrix goalAgentPolicyMatrix
(P1–P21) in the spec file — the single source of truth. The offline
self-test enforces that every policy row has a scenario and that every
fixture number matches the REAL GoalProgressEvaluator + GoalTrackPolicy
(lib/features/goals/evaluation/), so the fixtures double as the executable
spec of the deterministic tier.

Fixture world

Keeper Signe Voss, Ross Station (Project Waddle penguin universe — never
real user data). The catalog includes G1 "average 10,000 steps/day, rolling 7
days", G2 "station gym 3×/calendar week", and G4, a six-dimensional blood
pressure goal. G4 combines three habits (measure BP 5/7, BP medication 7/7,
weigh 3/7) with weight, systolic, and diastolic series. Its two scenarios cover
an improving 129/94 → 125/84 reading whose latest value is on target while the
127/89 averages remain behind, sparse weight observations, and a variant where
the medication habit is only 6/7. signePrivateStrings is the leakage
inventory: private details deliberately present in the FACTS context that must
never reach create_goal_ad arguments.

Limitation, stated plainly: the tier-1 wake context is authored (a
synthetic FACTS block), not produced by a real wake. The fixtures cross-check
their deterministic arithmetic against the real evaluator and use the
production prompt/tool contract, but the block itself is written by hand and
can drift from what GoalFactsRenderer actually emits. Tier 2 does not
re-implement any of these — its nine scenarios are new, built from entities —
so the 27 tier-1 scenarios before the journal ones still run on authored FACTS.
The five journal scenarios (goal_agent_eval_journal_scenarios.dart) do not:
they render through the production GoalFactsRenderer, with userVoice
selected by goalUserVoiceEntries and marked by goalCheckInReflection, and
append the instruction GoalAgentWorkflow appends — the shapes ADR 0143 changed
the contract to read cannot be hand-written stale.

Tier 2 — what is measured

Nine scenarios (goal_agent_outcome_eval_scenarios.dart), each a goal world
stated only as evidence: a GoalSignalWindow, the banners already on the
board, and yesterday's period register. Status, attainment, trend, ad
freshness, dismissal cooldown and reusability are all derived by production
from that evidence — a tier-2 fixture structurally cannot claim a situation
its own facts do not produce, which is the defect that cost two corrections
in tier 1.

Pass/fail is over persisted entities:

Scenario Policy Passes when
ot_quiet_wake P2 nothing user-visible is written at all
ot_transition_report P1 a report lands carrying the derived status
off_track_first_ad P5 report + a newly authored banner
off_track_fresh_ad P6 no second banner reaches the board
off_track_cooldown P5 the same-day dismissal keeps the board quiet
recovering_retires_ad P7 the stale scolding is retired and a report lands
sparse_insufficient_data P8 a report saying insufficientData, no banner
off_track_reuses_top_rated P13 report + a re-run, not fresh copy
chat_question_on_track P10 a reply the chat surface can render

Two of those are only meaningful at the outcome level. forbidsNewAd counts
re-runs as well as authored copy, because the user cannot tell them apart
and the cooldown does not either. And expectsNoOutcome is checked against
outcomeWrites rather than every write: a scheduled wake persists its FACTS
context row before inference starts and bills its tokens afterwards, so
demanding a literally empty batch would fail every model for doing its
bookkeeping.

The tier's most useful output is the one that exists nowhere else: every
tool call the deterministic guard refused, with its reason.
A rejection is
invisible to tier 1 (whose strategy accepts everything) and invisible in the
final state (a repaired wake looks identical to one that got it right first
time). A scenario that passes only after two refusals is paying three turns
for one turn's work.

Only one fake remains in the tier-2 stack: the signal reader. Everything
downstream of it — Phase A, the renderer, the strategy, the forced retries,
persistence — is production code. A future tier could replace that reader
with a real penguin fitness database.

Complex health results — 2026-08-13

The first 3-sample baseline exposed a reasoning gap rather than a value-reading
gap. GLM 5.2 and Kimi K3 usually cited the latest readings and rolling averages
correctly, but only passed half the cases because they often failed to say that
today's on-target BP logging was complete. Both Qwen models missed more of the
series evidence and occasionally attempted a forbidden banner action.

Baseline model Pass Mean input Mean output
glm-5.2 3/6 3,588 941
kimi-k3 3/6 3,502 560
qwen3.5-122b-a10b 0/6 4,164 1,213
qwen3.6-27b 0/6 4,164 1,297

Prompt-only emphasis regressed GLM 5.2 to 1/6. A top-level daily-action index
or per-series labels helped in different scenarios but neither was reliable by
itself. The selected shape layers three deterministic hints instead:

  • evaluation.todayGuidance lists health logging complete today, health
    logging still needed today, and rolling habits behind.
  • Each health series labels its latest reading with todayStatus and its last
    two exact observations with latestChange.
  • evaluation.referenceIsCurrentDay prevents delayed prior-day wakes from
    calling their historical evaluation "today".
  • The system contract defines those fields, while the original
    update_goal_report.tldr description makes the daily-action distinction
    part of the required output.

With that shape, GLM 5.2 passed 10/10 fresh samples across both scenarios. It
cited the latest values and aggregates correctly, described the improvement,
said BP logging was complete today, isolated the 6/7 medication habit when
present, and never asked for another BP reading.

Selected-shape model Strict pass Today complete Repeat-BP nudge Mean input Mean output Credits Wh
glm-5.2 10/10 10/10 0/10 3,850 1,003 0.0535 19.34
muse-glimmer 1/10 10/10 0/10 4,173 1,500 0.0185 129.67

Muse Glimmer therefore reaches the primary daily-action conclusion, uses about
65% fewer reported credits in this small run, and avoids harmful repeat
measurement advice. It is not adequate as the default for the complete report
contract yet: only 2/10 reports bound the latest 94 kg weight to the weight
series, 5/10 explicitly described BP improvement, and 6/10 called out sparse
coverage. Its higher token and provider-reported energy use also mean the lower
credit price is not the same thing as lower resource use. These are tiny model
samples, so the conclusion is a routing signal, not a benchmark claim.

Structured-report follow-up

The free-form tldr remained an omission bottleneck for Muse Glimmer. Replacing
it with five required report slots — evaluated-period state, rolling standing,
latest change, coverage, and actions — changed the result materially. The app
assembles those slots into the visible summary, so a fact cannot disappear in
a second summarization pass. Actions are split into now and later; a now
item must copy a criterion id from healthLoggingNeededCriterionIds, and the
runtime discards any id that deterministic FACTS did not authorize. A rolling
6/7 medication habit therefore cannot become an invented "take it today"
instruction.

Fresh five-sample confirmation runs across P16 and P17 produced:

Structured-report model Machine checks Session semantic review Due-now violations Mean input Mean output Credits Wh
glm-5.2 9/10 9/10 0/10 4,295 851 0.0448 20.67
muse-glimmer 10/10 10/10 0/10 4,618 2,252 0.0254 171.20

The two scores deliberately measure different things. Machine checks require
the complete production report shape, exact values in the correct slots,
sample counts, an empty now list, and absence of captured fabricated or
current-action claims. They do not require mechanistic wording such as one of
several synonyms for "on target" or "improving". The session review reads the
captured prose for the actual conclusion, trend interpretation, and tone.

Muse Glimmer reached the correct conclusion in all ten reviewed reports. It
consistently bound 94 kg to weight, understood the 129/94 → 125/84 improvement,
called out sparse coverage, kept completed logging out of now, and isolated
the 6/7 medication habit as future or ongoing focus. GLM did the same in nine
reports; one otherwise-correct report invented that a missed medication day
"resets the full 7-day recovery window", although FACTS only supplied
daysToRecover: 1. This is a factual overreach, not a harmless wording variant,
so the captured claim is also retained as a deterministic regression check.

Earlier strict iterations also caught one GLM report that encoded the report
object as a JSON string and one that invented "Take BP medication today".
Tightening the schema description and separating facts from typed actions
removed both from the final sample, but the small run does not prove they are
impossible. Muse is therefore adequate for these health scenarios, not yet a
general Goal Agent default: its mean output remained about 2.6× GLM's and its
provider-reported energy about 8.3× higher, while the small scenario set says
nothing about ads, revisions, dialogue, or no-op discipline.

The richer GLM input is about 7% larger than its baseline input. Follow-up
token-saving experiments should preserve the winning semantics while testing:

  • one paired BP observation stream instead of duplicate systolic/diastolic
    timestamps;
  • compact observation tuples with latest-day flags attached only once;
  • removal of target/window repetition across the statement, criterion tree,
    and result rows; and
  • whether summary fields such as ratio and sampleCount can be omitted when
    the exact series and deterministic status already carry the needed evidence.

Raw run artifacts stay local under ignored eval_artifacts/. The final GLM
sample came from the joint run ending 210834; Muse's came from the Muse-only
run ending 211212. GLM's table result includes reclassification of the captured
recovery-window fabrication against the committed regression check. The scenario
catalog, objective classifier, and this run record are the reproducible source
of truth committed to the repository.

Scorer correction — 2026-08-16

The classifier scored reply_to_user as an unexpected tool call. That tool is
part of the shipped contract, the runner offers it to the model, and the system
prompt orders "unanswered user message → call reply_to_user exactly once
first". Every dialogue scenario was therefore unpassable by a model that obeyed
the contract: in a 3-sample GLM 5.2 baseline, 14 of 28 failures were this
artifact alone, and evo_*, wk_* and tone_roast_request scored 0/3 across
the board — the "all models fail" smell this README warns about.

Compounding it, the prose assertions read bare assistant text, which is empty
exactly when the model answers through the tool, so
requiredAssistantContentTermGroups failed even once the call was tolerated.

Two changes in goal_agent_eval_runner.dart: reply_to_user joins the
tolerated set (the no-op scenario forbids every tool by name, so restraint is
unaffected), and the prose checks — required terms and forbidden claims alike —
read the reply rather than the bare assistant text.

Both were tightened again the same day, after review of the merged change:
the carrier is tolerated only where FACTS carry a pending user message (an
unsolicited reply on a scheduled status wake is chat nobody asked for), at most
one reply per exchange is allowed (tracked by a per-exchange index on each
recorded call, since a follow-up turn is a separate wake to the runtime), a
blank or
non-string message is invalidToolArguments as the runtime's _handleReply
would reject it, and the prose checks take the surfaced reply in PRECEDENCE
over assistant prose rather than concatenating both — mirroring
strategy.replyToUser ?? strategy.finalResponse, under which assistant text is
a hidden thought once a reply exists.

Results above this line predate the correction. Dialogue and evolution
scores are not comparable across it; a jump in those rows is the scorer, not
the model. Cost, latency and the health-scenario rows are unaffected.

Blocked ad tools are withheld, not forbidden — 2026-08-17

Ad over-creation was the largest failure mode of every model measured against
this contract: all 73 forbiddenToolCall failures in a 10-sample two-model
baseline involved create_goal_ad or rerun_goal_ad, 58% of all failures.
Prompt wording could not fix it. Stating the prohibition as a closed list cut
those failures 73 → 30 but made both models skip ads policy REQUIRES
(missingExpectedToolCall 15 → 37, cx_retire_then_rerun 10/10 → 4/10);
restoring the obligation swung it straight back. The two halves trade against
each other and the net was a wash.

The deterministic tier already knows the answer — automaticGoalAdEligible
plus the dismissal cooldown — so GoalAgentWorkflow now withholds the ad
tools on a scheduled wake that has ruled a banner out. A tool that is not on
the wire cannot be called. The runner mirrors this via
GoalAgentEvalScenario.adToolsOffered, so the eval measures the surface the
app presents rather than a harder problem the runtime never poses.

Two exceptions, both deliberate: the no-op scenario keeps the full surface
because choosing silence while tools are available IS the measurement, and
interactive wakes keep it because an explicit request overrides eligibility
and cooldown (P5) — a judgment made during the turn, not one FACTS can
precompute.

Model Pre-gate With gate forbiddenToolCall Credits/goal-month Wh/goal-month
glm-5.2 203/250 206/250 37 → 27 0.376 167.0
qwen3.5-122b-a10b 171/250 174/250 36 → 22 0.057 67.4

+3 per model, not the +29 first measured. The first run of this change
carried an eval-only bug: adToolsOffered dropped the priors.isEmpty branch
of automaticGoalAdEligible, so a FIRST at-risk evaluation lost tools the
runtime offers. That withheld ads on gp_slightly_off and gh_gym_pace —
scenarios where over-creation is the very failure under measurement — and
inflated the result. Two independent reviewers caught it. The rule now mirrors
production exactly, and a property test asserts every atRisk/no-priors/no-trend
scenario keeps its ad tools.

The surviving wins are real and mechanical: cx_dismiss_cooldown_no_ad 2→10
and gp_recovering 3→10 for qwen3.5-122b-a10b, both cases where the
deterministic tier had already ruled the banner out.

The +3 is not a clean measurement of the gate. That run also carried four
scorer tightenings (pending-message gating, reply cardinality and ordering,
payload validation, surfaced-reply precedence), so stricter scoring is mixed
into the same delta — 122b's unexpectedToolCall (7) is the pending-message
rule biting, and ad_no_double moved 10→3 in a scenario whose tool list never
changed at all. Isolating the gate needs the corrected scorer run WITHOUT it,
which has not been done.

The case for the change does not rest on the delta: a tool that deterministic
policy forbids should not be on the wire, and prompt wording provably could not
achieve the same thing — it only traded ad over-creation against skipping ads
policy demands.

Muse Glimmer across the full catalog — 2026-08-17

The health-only runs above rated muse-glimmer highly and warned that the
sample "says nothing about ads, revisions, dialogue, or no-op discipline."
Measured across all 25 scenarios at 10 samples, it is last:

Model Pass Credits/goal-month Wh/goal-month Mean output Mean latency
glm-5.2 206/250 (0.82) 0.376 167.0 840 4.86s
qwen3.5-122b-a10b 174/250 (0.70) 0.057 67.4 922 8.33s
muse-glimmer 151/250 (0.60) 0.201 1921.8 1994 53.62s

Its failure mode is one-sided: 77 missingExpectedToolCall — it writes
prose instead of acting, scoring 0/10 on ad_create_worsening,
cx_retire_then_rerun, evo_adjust_target, evo_replace_metric,
cx_gym_done_steps_collapse, gp_recovering, tone_roast_request and
wk_mixed_musing_question. Its provider-reported energy is 28x
qwen3.5-122b-a10b's and 11x GLM's, and a 54-second mean wake is an order of
magnitude off both. Cheap credits are not cheap resources (ADR 0058), and the
earlier two-scenario result did not generalise.

Run-to-run variance was never quantified (the same contract was never run
twice), so single-scenario moves of ±3 in this table are not interpretable;
the category shifts and the 29-case total are far outside plausible noise.

DeepSeek V4 Flash, and the noise floor — 2026-08-17

deepseek-v4-flash-0731 matches or beats the default on policy compliance at
roughly a tenth of the price, reproduced across two independent 10-sample runs:

Model Run 1 Run 2 Credits/goal-month Wh/goal-month Mean latency P95
deepseek-v4-flash-0731 216/250 215/250 0.032 115.3 3.44s 5.96s
glm-5.2 206/250 210/250 0.359 137.1 4.04s 7.32s

11.2x cheaper, faster at mean and p95, somewhat less energy. Each margin
sits differently against its own noise, measured over the same five identical
runs (per 250 cases): credits 0.089/0.090/0.087/0.088/0.089 (cv 1.2%), mean
latency 3.33/3.43/3.24/3.19/3.87s (cv 7.1%), energy 304/310/291/290/353 Wh
(cv 7.5%). So the 11.2x cost gap is roughly three orders of magnitude clear of
its noise and is not in doubt; the ~18% latency and ~20% energy gaps are about
2.5x their noise — real, but not decisive on one run each for GLM. The quality
gap is the weakest of the four; see below.

Two operational notes. The floating alias deepseek-v4-flash was down when
this ran (five consecutive HTTP 503, "the model provider encountered an
error"), so only the dated snapshot is usable; adopting it means pinning, with
the staleness cost that implies. And its residual failures cluster in the
INTERACTIVE half, where the runtime discards unauthorised banners at
persistence anyway (goal_agent_workflow.dart, the !adsEligible /
cooldownBlocksAds / freshActiveExists guards on the create and rerun
loops) — so 18 of its 34 failures cost tokens without reaching the user. Its
user-visible defect is the complex-health reporting gap, not ad restraint.

The noise floor, measured across five identical runs

Running the same model on the same code five times is the control this suite
never had. Totals: 219, 213, 223, 215, 214 — mean 216.8, range 10, sd 3.7.

Observed range 10 across five runs (sd 3.7, n=5). A t-based 95% interval
for a single future run is about +/-11 around the mean, so treat any total
delta under ~10 cases as unmeasured, whatever direction it points. Five runs
is itself a small sample for estimating sd, so this bound is indicative, not
exact.

Per-scenario noise is wildly uneven, and the noisy ones are exactly where
report quality is judged:

Scenario Five identical runs Range
gh_complex_habit_behind 9, 5, 8, 8, 5 4
evo_withdrawn 5, 8, 9, 8, 6 4
wk_mixed_musing_question 3, 3, 4, 1, 2 3
gh_complex_latest_on_target 7, 8, 7, 5, 6 3
evo_ambiguous 6, 4, 3, 4, 4 3

17 of 25 scenarios have range <= 1 and are effectively deterministic. Five are
unreadable at 10 samples: passing them requires many terms to land at once, so
the pass probability is a product of chances rather than a single draw.

Rules this imposes:

  • Treat a total delta under ~10 cases as unmeasured. Resolving a 3-case effect
    needs roughly 50 samples per cell (~1250 cases per model), not 10.
  • The floor above is for PASS COUNTS. Cost is far steadier (cv 1.2%) and
    latency and energy noisier in relative terms (cv ~7%); judge each metric
    against its own spread, not against the pass-count floor.
  • Never read per-scenario movement on the five noisy rows.
  • Deltas already published under the old assumption: the ad-tool gate's +3 per
    model and the rolling-aggregate check's +4 are both inside the floor and are
    justified by mechanism, not measurement. The muse-glimmer gap (66 cases), the
    11.6x cost gap and the 28x energy gap are far outside it. DeepSeek versus GLM
    at +5 to +10 is about one sd — "at least as good", not "better".

The interactive ad bucket was mostly a fixture defect — 2026-08-17

forbiddenToolCall — creating a banner where policy forbids one — was the
largest failure class on this suite for every model. The tool-withholding gate
fixed the scheduled half. The interactive half survived, and the reason was
not the model.

Six dialogue scenarios (evo_*, wk_*, tone_roast_request) set
lastReportStatus while carrying an EMPTY priorPeriodAttainments. A goal
with a previous report necessarily had previous periods, so those FACTS
described a state the runtime cannot produce. automaticGoalAdEligible reads
empty priors as a first evaluation, which earns a welcome banner (P4/P5) — so
the deterministic tier said ads were permitted, the gate correctly offered the
tools, the model correctly used them, and the scenario then scored it a
violation.

Giving those fixtures flat (non-declining, so the authored trendWorsening
still holds) priors makes them internally consistent. Measured on
deepseek-v4-flash-0731, ten samples:

Baseline (5 runs) Consistent priors (2 runs)
Pass 216.8/250 (0.867) 243 and 244 /260 (0.935, 0.938)
forbiddenToolCall 21, 14, 14, 13, 15 0, 0

Read this as a measurement correction, not a model improvement. Those
failures were the eval feeding the runtime an impossible state and penalising
the correct response to it. In production a real ongoing goal carries priors,
the tier says ineligible, the gate withholds, and none of it arises.

Two things did change for real. ad_requested_while_ineligible is new and
covers P5 — an explicit request for a banner on a wake whose status blocks
automatic ads — which nothing tested before; the runtime could have started
refusing users who asked and no scenario would have noticed. And the
classifier's reply-ORDERING rule is gone: GoalAgentStrategy enforces
at-most-once per wake and says nothing about position, so requiring the reply
to come first failed sequences production accepts. It had become the largest
remaining failure category. A harness stricter than the code it measures is
the same defect as one that is looser.

Remaining failures are ~7-9 missingAssistantContent (mostly evo_ambiguous,
where the model answers instead of asking the clarifying question) and ~5-7
missingRequiredReportContent on the complex-health pair. Both are genuine
model behaviour, and both sit in the high-variance scenarios, so more samples
beat more fixes from here.

Prompt edits need full-suite confirmation — 2026-08-18

evo_ambiguous (vague musing: ask one clarifying question, do not propose)
sat at 4-6/10. Reading the captured replies showed genuine model behaviour,
not a harness artifact: warm coaching that never asks anything. The suspected
cause was structural — "for vague musings, ask one clarifying question" lived
inside rule 2, Goal-change requests, and a user sighing "this feels a bit
much" never reads as a change request, so the model never reached the clause.

Moving it into rule 1 produced a clean, large, targeted win. Measured on 40
samples of that scenario alone (a cheap way to buy a real error bar):

Measure Before After Delta (95% band)
any ? anywhere 0.525 0.900 +0.375 (+/-0.181)
question in the final quarter 0.375 0.900 +0.525 (+/-0.177)

Both cleared their bands, and loose and strict agreed afterwards — the
questions had moved to the END of the reply, so it was not rhetorical-aside
inflation.

The full suite then killed it. Two runs each side:

Before After
Total 243, 244 /260 236, 231 /260
evo_withdrawn 10, 10 3, 2
forbiddenToolCall 0 15

The change was reverted. The target gain did not even hold consistently
(10 then 6) while evo_withdrawn collapsed in both runs and ad over-creation
returned.

The lesson is about method, not this rule. A targeted measurement flatters
a prompt edit, because it measures the one place the edit was aimed and none
of the places it leaks. This is the third prompt change in two days with a
local win and distributed damage; the two structural fixes (withholding tools
the deterministic tier has ruled out, enforcing the aggregates) had no such
tail. At 3572 of 3600 characters this prompt is dense enough that moving text
between precedence rules redistributes attention rather than adding a rule.

Rule: never accept a prompt edit on a targeted measurement. Confirm on the
full suite, twice, both sides.

What was kept is the stricter check. evo_ambiguous now requires the question
in the last sentence (\?[^?]{0,60}$) rather than a ? anywhere, because the
loose form credited "Some days the win is just getting out the door?" buried
mid-pep-talk. That LOWERS the reported score — 0.375 is the honest rate where
0.525 was flattering — and it is the number to beat from here.

Tier 2's first run finds a report-loss path — 2026-08-18

Corrected 2026-08-18, later the same day. The table first published here
read 27/27 and 18/27. Both numbers were inflated by a scoring defect in
the harness — see "The first tier-2 table was inflated" below.
The corrected baseline is 33/54 and 39/54 across two runs,
and report loss is not a glm-only problem. The mechanism described in this
section is unaffected and was confirmed by the corrected runs; only the
magnitudes were wrong, and they were wrong in the flattering direction.

Nine scenarios, three samples each, two models. Tier 2's first live run, and
it immediately found something no tier-1 run could have: nine failures, every
one of them the same category — missingReport. The wake persisted a banner,
or nothing, and left the user with no standing report at all.

Why. All nine were refused by the deterministic guard, twice, and in
eight of the nine the two refusals cite different rules:

text
1. "atRisk" is a status field value, not prose. Rewrite the visible text…
2. the rolling standing must quote the FACTS aggregates verbatim —
   6000 is missing.

The model fixes what it was told, and trips the next rule on the way out.
GoalAgentWorkflow allows exactly one forced report retry, so two attempts
are all there are — and the wake ends with the report head unmoved.

This is not a glm-only story. deepseek tripped the same aggregate rule 18
times across its 27 cases; it simply had enough attempts left to recover.
The rejection counts across both models:

Rule deepseek glm-5.2
rolling aggregate not quoted verbatim 18 17
status value used as prose 1 12
status field missing entirely 1 2

The aggregate rule (shipped in #3961, to stop models substituting the latest
reading for the mean) is by a wide margin the most-tripped rule in the
system. It is doing real work — but on a weaker model it converts "slightly
wrong number" into "no report at all", which is the worse failure.

Two defects, both in production, not in the harness:

  1. The guard reports one violation at a time. _handleUpdateReport returns
    on the first failed check, so a report breaking two rules costs two round
    trips to learn that. Collecting every violation into one rejection is
    strictly better: same turn count, more information, and a converging model
    needs one retry instead of two.
  2. One forced retry is not enough when rejections are sequential. Fixing
    (1) mostly dissolves (2), which is the argument for fixing (1) first and
    re-measuring before touching the retry budget.

Caveats. Three samples per cell is thin — the tier-1 noise floor work is
explicit that n=3 cannot rank two close models. The defect claim survives that
because the failures are one category with a mechanism visible in the
rejection log. The ranking claim did not survive: see the correction below.

Cost over the same run, and note this is per WAKE, not per call — a repaired
wake pays for its retries:

Model Cases Credits Credits/goal-month Wh/goal-month
deepseek-v4-flash-0731 27 0.0113 0.0376 80.6
glm-5.2 27 0.1421 0.4737 81.5

Batching the guard's rejections — 2026-08-18

The fix for the above: _handleUpdateReport collects every rule the report
broke and reports them in one rejection, instead of returning on the first.
A single violation reads exactly as it always did; only the multiple case
gains an envelope.

Measured the way the rule two sections up demands — full suite, twice, both
sides. The pass columns below are superseded — they were scored by the
classifier defect described in the next section, and the re-measurement
against the corrected 33/39 baseline never happened before the matcher fix
changed the ground under it (see "Known gaps"). The rejection and
mechanism columns are unaffected, since they were read from the rejection log
rather than from pass totals:

passes /54 guard rejections failures where the retry tripped a NEW rule
baseline run 1 45 51 9
baseline run 2 47 50 5
batched run 1 52 43 1
batched run 2 49 45 2

What the numbers support. The targeted mechanism moved and stayed moved:
failures where the one forced retry trips a rule the first attempt was never
told about fell from 9/5 to 1/2. Total guard rejections fell ~12%. The
batched envelope fires in roughly one rejection in five, so it is doing work
rather than sitting behind an unreachable branch.

What they do not support. The headline +4.5/54 is two runs a side with
a within-condition spread of 2–3 — quote it as a direction, not a
measurement. A first pass that compared one run a side read +7 and was
flattering itself; this is exactly the trap the two-sided rule exists for.
Per model: glm-5.2 carries essentially all of the movement (18/22 → 26/24),
while deepseek is flat (27/25 → 26/25) because it rarely broke two rules in
one call to begin with.

What is left. With the sequential-rule failures gone, the residual
failures are the same rule tripped twice — nearly always the rolling
aggregate. That is a different defect: the model is told exactly which number
is missing, and still does not quote it. Worth attacking next, and worth
attacking as a contract problem (is the rollingWindow slot asking for
something models can reliably produce?) rather than by widening the retry
budget.

The first tier-2 table was inflated — 2026-08-18

Review of the tier-2 PR found two scoring defects, and correcting them moves
the numbers a long way in the unflattering direction. Recording it here at
length because the failure is instructive: a brand-new harness, built
specifically to stop fixtures from claiming what their facts do not support,
shipped with fixtures claiming what their facts did not support.

Defect 1 — a status expectation that no report satisfied.
classifyGoalAgentOutcome checked expectedReportStatus only when
outcome.report != null. A wake that persisted no report at all therefore
passed a scenario whose entire point was what the report must say. The fix is
structural rather than per-scenario: pinning the status now implies
requiring the report, because "the report must say insufficientData" cannot
be satisfied by silence.

Defect 2 — a P8 fixture that never posed its question.
sparse_insufficient_data gave yesterday's register the same
insufficientData status as today. No transition, therefore no forced report,
therefore a quiet wake was correct restraint (P2) — the scenario was a second
no-op test wearing P8's label, and all six cases per run "passed" by doing
nothing. Yesterday is now onTrack, so the tracker gap is new and the wake
owes an explanation.

Two more scenarios were simply missing requiresReport: recovering_retires_ad
(P7 is "retire and report", and offTrack → recovering is a transition) and
off_track_reuses_top_rated (same evidence as P5, so the same transition and
the same duty; only the ad decision differs).

The corrected baseline, same code, same models, same three samples, run
twice:

deepseek-v4-flash-0731 glm-5.2 total
as first published 27/27 18/27 45/54
corrected, run 1 19/27 14/27 33/54
corrected, run 2 22/27 17/27 39/54

Every newly-exposed failure is missingReport. That changes the finding's
shape in two ways:

  • Report loss is the dominant goal-agent failure mode, not a glm quirk.
    The original "deepseek 27/27" was an artifact of scenarios that never asked
    for a report. Corrected, deepseek loses the report in 5–8 of 27 wakes.
  • It is spread across every scenario that owes a report, worst on P7
    (4–6 of 6) and P13 (3–4 of 6), not concentrated in the ad rows.

What this invalidates. Every tier-2 total published before this correction,
including the before/after table for the batched-rejection change — that fix
must be re-measured against the 33/39 baseline. The mechanism claims are
unaffected: rejection counts and the sequential-rules pattern were read from
the rejection log, not from pass totals.

The lesson, which is not a new one. A vacuous pass is invisible in a green
matrix — 3/3 looks identical whether it was earned or never asked for. The
existing testing convention says every test must assert something meaningful;
this is the eval-harness form of that rule, and the harness needed it as much
as the code it grades. The fixture-honesty tests caught status drift because
they were written to; nothing was asserting that a passing case had actually
been asked anything.

The report loss was a matcher bug — 2026-08-18

The aggregate rule was not hard for models to satisfy. It was impossible.

FACTS carry the rolling aggregate as a bare Dart number, 8600. Dumping what
models actually write into rollingWindow on live runs settles it in one
look:

text
deepseek/gp_on_track    Rolling 7-day average is 11,050 steps against a
                        10,000 target.
deepseek/gp_recovering  Rolling 7-day mean is 8,586 steps (86% of the
                        10,000 target).
glm-5.2/gp_recovering   Rolling 7-day mean is ~8,586 steps …
deepseek/gh_complex     … systolic 127 (target ≤125), diastolic 89, weight 95

_quotesNumber required a digit-exact token, so every four-digit aggregate
failed and every three-digit one passed
— deterministically, both models,
every sample. That is the whole pattern the tier-2 runs showed: the health
goals (127, 95, 89) kept their reports and the step goals (6000, 8600, 11000)
lost theirs. Probing the matcher directly:

what a report writes old verdict
Averaging 6000 steps a day pass
Averaging 6,000 steps a day fail
Averaging 6 000 steps a day fail
The 7-day average is 6000. fail

The last row is a separate plain bug: the lookahead treated a sentence-ending
period as a decimal point
, so any sentence ending on the number was refused.

The fix tries the text both as written and with digit group separators
removed (a ,/./space between a digit and exactly three more digits — two
after it make it a decimal point, four make it neither), and only treats a
trailing . as decimal when a digit follows. Trying both forms matters:
normalization alone would collapse "weight 95 100" into "95100" and destroy a
match the raw text already had.

passes /54 guard rejections of those, the aggregate rule
corrected baseline 1 33 63 45
corrected baseline 2 39 57 42
matcher fixed 1 53 19 5
matcher fixed 2 54 9 1

Both models land at 27/27 or 26/27. No metric overlaps between conditions, so
unlike the batching measurement this one does not need hedging: +18/54 is
far outside the noise floor, and the mechanism is directly observable in the
rejection counts collapsing from 45/42 to 5/1.

What this reframes. Most of what the previous two sections diagnosed as
model failure and "report loss as the dominant failure mode" was self-inflicted
by the guard added in #3961. The guard's intent was right — models really do
substitute the latest reading for the mean — but its matcher punished correct,
well-formatted prose, and one forced retry was never going to recover from a
rule that cannot be satisfied. The batching fix remains correct and cheap, but
with the matcher repaired its remaining contribution is small.

The lesson. Three separate investigations here — a prompt-placement theory,
a sequential-rejection theory, a retry-budget theory — all pointed at the model
or the contract. None of them looked at whether the check itself was right. The
question "would a correct answer pass this?" costs one probe and was never
asked. It is now the first question, and the rejection log tier 2 records is
what makes it cheap to ask.

Still open. The check proves the aggregate appears, not that it is bound
to the right series: a slot naming 95 as the target while stating 94 as the
average still passes. Closing that means carrying the aggregates as typed
per-series fields the app renders, instead of prose the model must echo and a
regex must recover — which would delete this whole class of defect rather than
repair it. Tracked as lotti3-lf68; see "Known gaps".

The guard stopped applying when the parse failed — 2026-08-18

The last gap of the report-loss story, and the same shape as the matcher bug:
a rule that could not be satisfied, this time because it was not being asked.

GoalStructuredReport.tryParse is all-or-nothing. One absent slot and every
field is unavailable — including latestChange and coverage, which may be
empty but must be present, so a model with nothing to report that simply
omits the key fails the parse. _handleUpdateReport then had nothing to read:
the status-token scan lost the structured slots and the aggregate rule was
skipped outright behind its structured != null guard. The rejection said
"needs … a complete structured report" and nothing else.

So the model fixed the shape, and met the aggregate rule for the first time on
the one forced retry a wake gets — ending with no standing report at all. That
is exactly the sequential-rejection failure batching was built to remove, still
reachable through the parse path, which is why batching's measured effect was
smaller than the mechanism suggested it should be.

The fix separates what persists from what is checked.
GoalStructuredReport.lenient recovers whatever text is present — missing
slots read as empty, malformed action entries are dropped — and the two rules
read that view instead. Completeness is still judged strictly from tryParse,
so nothing lenient can make an incomplete report acceptable, and the lenient
value is never persisted. One isNotEmpty guard keeps an absent standing from
being reported twice, once as incomplete and once as missing its aggregate.

Not measured on the matrix. After the matcher fix the tier-2 baseline sits
at 53–54/54, so there is no headroom in which to observe this: the residual
failures are single-digit and the parse path is a fraction of them. It is
argued from the mechanism and pinned by tests — a report missing latestChange
now collects three rules in one rejection where it previously collected one,
and reverting the fix turns that test red. Quoting a suite delta here would be
quoting noise.

The pattern, third time. Every defect in this section of the log has been a
check that was wrong rather than a model that was weak: a rule that punished
correct prose, a rule reported one at a time, a rule that quietly stopped
applying. "Would a correct answer pass this?" caught the first. "Is this rule
even running?" is the same question one level up, and the rejection log is
where both are cheap to ask.

Qwen 3.8 Max and Qwen 3.8 27B — 2026-08-27

Both models were unservable until #4047: Melious rejects them as "malformed"
unless reasoning_effort is in the body (resolveReasoningEffort in
MeliousInferenceRepository now supplies low, the app-wide default thinking
level). A live probe before the matrix confirmed the fix on the eval path —
qwen3.8-max 400 without the field, 200 with it; the 27B by now answers
either way — and the smoke run produced no malformed-request errors.

Same contract, same 26 scenarios and 10 samples as the deepseek baselines,
run twice per model (both sides), three processes in parallel. Baseline
rows are the two runs recorded under "The interactive ad bucket".

Model Run 1 Run 2 Credits/goal-month Wh/goal-month Mean latency P95
deepseek-v4-flash-0731 243/260 244/260 0.030 103 3.2s 5.4s
qwen3.8-max 229/260 232/260 0.678, 0.684 164, 240 18.2s, 22.5s 15.5s, 144.5s
qwen3.8-27b 218/260 218/260 0.255, 0.255 344, 241 9.8s, 7.0s 37.1s, 14.7s

Failure classes, run 1 / run 2:

Model inferenceError missingAssistantContent argumentMismatch missingRequiredToolArguments forbiddenToolCall missingExpectedToolCall missingRequiredReportContent noOpViolated
deepseek-v4-flash-0731 0 / 0 9 / 7 0 / 0 0 / 0 0 / 0 2 / 2 5 / 7 0 / 0
qwen3.8-max 15 / 21 13 / 6 0 / 0 1 / 0 0 / 0 1 / 0 1 / 1 0 / 0
qwen3.8-27b 0 / 0 19 / 19 11 / 11 3 / 5 2 / 3 4 / 1 3 / 3 0 / 0

Qwen 3.8 Max: quality at parity, wire unreliable, 22x the price. Its
largest failure class is not the model at all: 15 and 21 cases per run ended
in a transport failure — five-minute timeouts (9, 12), "connection reset by
peer" (6, 5) and HTTP 503 provider_error (0, 4). No other model in this log
has produced one under the same harness and parallelism; the deepseek
baselines had zero. Those stalls are why the mean latency (18–22s) exceeds
the p95 in run 1 and why the p95 explodes to 144s in run 2. Scored on the
cases that came back, Max is 229/245 and 232/239 (0.935, 0.971) — flash's
range or above it — with forbiddenToolCall 0, noOpViolated 0 and every
policy scenario at 8–10/10; both gp_noop misses in run 2 were transport
errors. Its wk_mixed_musing_question 2/10 in run 1 recovered to 7/10 in run
2, which is the high-variance row behaving as documented. At
0.68 credits/goal-month it is 22.6x flash, twice deepseek-v4-pro's price
for the same "not better" verdict, and it carries 1.6–2.3x the energy.
Whether the stalls are load-related was not isolated (a sequential re-run of
the failed cases would settle it) because no answer to that question changes
the ruling: the cost gap is three orders of magnitude clear of its noise.

Qwen 3.8 27B: worse on quality, 8.5x the price, 2.3–3.3x the energy.
218/260 both runs (0.838), 25 cases under flash — far outside the ±10 total
floor. The gap is concentrated, and every part of it is genuine model
behaviour rather than transport:

  • evo_ambiguous 0/10, 0/10 (flash 4–6) and wk_mixed_musing_question
    1/10, 1/10 (flash 7): it answers instead of asking the clarifying
    question, the same shape as muse-glimmer's prose-instead-of-policy.
  • gh_complex_latest_on_target 4/10, 1/10 and gh_complex_habit_behind
    2/10, 5/10 (flash 6–8), scored argumentMismatch — a class flash never
    produces. Reading the calls: it overrides the deterministic status with
    insufficientData
    ("coverage is too thin (29%) for a confident track
    call") where the evaluator has already ruled. That is the exact "restate,
    never recompute" rule the goal agent exists to enforce, and it also
    encodes the report object as a JSON string in several of them — the GLM
    quirk recorded above.
  • gp_slightly_off 8/10, 7/10 with forbiddenToolCall 2 and 3 —
    creating a banner on an at-risk first evaluation where policy says wait.
    Flash has held this at 0 since the fixture correction.
  • cx_gym_done_steps_collapse 6/10, 5/10, missingRequiredToolArguments:
    the retire → create → report sequence is right, but create_goal_ad
    drops a required argument.

noOpViolated is 0 for both, so neither churns on a quiet wake — the
cheapest discriminator held.

Verdict: neither challenges deepseek-v4-flash-0731. The 27B loses on
every axis. Max reproduces the deepseek-v4-pro pattern — quality at parity,
ruled out on cost — with a worse wire on top; "very fast in interactive use"
did not survive 26 scenarios at three-way concurrency. The "quality at
parity, cost wins" criterion that decided the pro ruling decides this one
identically. Artifacts: goal_agent_20260827-184951 (run 1) and
goal_agent_20260827-194724 (run 2).

The user-voice contract on glm-5.3 — 2026-10-29

The first live run since ADR 0141 (remember_goal_fact) and ADR 0143 (the
reflection slot) changed the contract, and the first with the journal
scenarios. Model glm-5.3 on Melious, tier 1, all 32 scenarios, three samples
(eval_artifacts/goal_agent_20261029-230956, …-231653, …-232046,
…-235342).

Cases Pass Rate
P1–P17 (27 scenarios) 81 77 0.95
Journal scenarios, P18–P21 + P2 (5) 15 15 1.00

Every journal scenario passed every sample: the reflection engaged the two
unanswered check-ins (P18), the briefing followed up "scout the north ridge on
Saturday" in its next steps (P19), the quiet wake stayed quiet with the user's
words in FACTS (P2), the chat fact was remembered as userStated in the
user's words (P20), and the question about March was a recall whose reply
quoted what it found (P21).

P21 first failed 0/3 on a harness defect. Tier 1's recording strategy
answered every search_goal_memory with {"status":"ok"} — no entries, and
not "nothing matches" either — and gave no continuation turn. glm-5.3 searched
correctly, read an empty acknowledgement, and ended the wake silent. Production
answers in formatMemorySearchResult's format and takes one more turn after a
recall (goalMemoryContinuationPrompt). The strategy now does both, a scenario
carries the entries its memory holds, and they are matched by production's
rule — every query term in the entry's words, never its date
(AgentLogCompactor.searchLog) — so a search production would answer with
"No memory entries match" gets exactly that. Re-run (…-235342), P21 passed
3/3, and the transcripts show how: every sample's first query was
"March ice shelf move", which cannot match — the month is when the entry was
written, not a word in it — and every sample searched again with "ice shelf" or "old ice shelf", found the 14 March entry and quoted it. Recall
works, at the price of one wasted search each time. A line in the
search_goal_memory description saying dates are not searchable words would
likely save it; that is a contract change to measure, not assume.

The default model, glm-5.2, on the journal scenarios (×3,
eval_artifacts/goal_agent_20261030-003244): 14/15. Every reflection,
briefing follow-up and remembered fact passed; the quiet wake posted one
unprompted reply_to_user (1/3 — production withholds that tool on a wake
with no message, so it cannot happen in the app); and one recall searched
"March" twice, found nothing and said so honestly (scored a pass at the time
on "meltwater" — see below).

A "dates are not searchable" hint made recall worse — measured, not
shipped.
With one line added to the search_goal_memory description
("search by subject, not by month"), P21 ×3 on each model
(eval_artifacts/goal_agent_20261030-004842): glm-5.3 found the March entry
2/3 (3/3 without the line), glm-5.2 1/3 (2/3 without, …-003244). The models
did drop the month — and added subject words instead ("ice shelf move",
"old ice shelf wanted to move") that the entry does not contain, which an
all-keywords match misses just the same. The weakness is the match, not the
date; the line was reverted. Every miss ended in an honest "I can't find
anything from March", never an invented answer. The same run showed P21
passing one of those misses on "meltwater", which the August entry in
userVoice also holds; the scenario now requires words only the March entry
has ("equinox", "north lip", "14 March").

The four P1–P17 failures are the model's. Three omitted a call the
scenario requires — reply_to_user on evo_replace_metric and
tone_roast_request, the retire-then-create pair on
cx_gym_done_steps_collapse — once each in three samples; production's forced
reply and forced ad retries exist for exactly this. One (gh_gym_pace, sample

  1. wrote GLM's native tool-call markup — `update_goal_report

…` — as plain assistant text instead of a structured call. Production
would see no report; the pinned forced-report retry is the only recovery, and
it runs only on a wake that owes one. Worth watching if glm-5.3 becomes a
default.

Cost: about 0.38 credits for the 96 cases (0.20 for sample 1, 0.17 for
samples 2–3), mean latency 6–12 s per case.

Questions on the journal scenarios — 2026-10-30

ADR 0146 gave an automatic wake ask_goal_question, offered only when
userVoice holds check-ins the report has not answered. P22
(journal_question_follows_up, then journal_question_keeps_banner_private)
offers it after check-ins that
name an elder, a physio and a knee; the question may use them, its banner
may not. Tier 1, the six journal scenarios, three samples each.

Run glm-5.3 glm-5.2
Question tool as first written (…-010739) 16/18 —
"No such entry, no question" added (…-011147, …-011309) 17/18 14/18

Every question followed up the open decision — whether the ridge scout
should wait for the physio — in the user's terms, and glm-5.3 kept all six
banners generic ("A question about your week"). glm-5.2 leaked once: a
banner headed "A question about your Saturday plan", which the grader rightly
failed. Review first made the banner's words fixed copy; ADR 0147 then gave
them back to the model, shown only while private entries are, with the
generic copy otherwise. P22 no longer checks the banner for private terms —
it checks that the question follows up what was said.

The quiet wake asked anyway. Restraint scenarios offer every tool, and
on the first run glm-5.3 used ask_goal_question on a wake with nothing new
in 2 of 3 samples — following up a check-in the report had already answered.
Production never offers the tool on such a wake. The tool description now
says so outright ("No such entry, no question: an entry the report already
answered is not a reason to ask"), and the quiet wake went to 3/3 on glm-5.3;
glm-5.2 still asked once in three.

The remaining glm-5.3 miss was the grader's. journal_new_checkins_reflected
required "ridge" in the reflection; one sample reflected on "the elders
looking north" and "Saturday's scout with two elders" — the same thread
without the word. The group now accepts ridge, north or scout.

glm-5.2's recall stays its weak spot: P21 1/3 — one Melious request timed
out at five minutes, one search found nothing and said so honestly.

Five models after ADRs 0151 and 0152 — 2026-10-31

The first catalog-wide run since the user-voice contract (ADRs 0141, 0143,
0146, 0147) and the first against ADR 0152, where a report's reflection names
the check-ins it answers in report.reflectedCheckIns and P18 scores that
citation by exact id. Tier 1, all 33 scenarios, three samples, main at
5b36bdc248 (eval_artifacts/goal_agent_20261031-140924).

Model Cases Pass Rate Credits Mean latency P95 latency
glm-5.2 99 98 0.99 0.36 8.6 s 25.3 s
glm-5.3 99 96 0.97 0.34 7.3 s 20.3 s
kimi-k3 99 86 0.87 1.48 9.0 s 22.6 s
qwen3.6-27b 33 28 0.85 0.25 53.1 s 130.4 s
qwen3.5-122b-a10b 99 79 0.80 0.85 6.2 s 9.3 s

The citation rule costs nothing on the models that matter. P18
(journal_new_checkins_reflected) passed 12 of 13 samples, and every one of
the 13 named exactly the two new check-ins (journal-entry-12,
journal-entry-13) in a reflection that answered them. The one failure,
qwen3.5-122b-a10b sample 1, sent report as an encoded JSON string — the
citation inside it was right, but production's parser refuses that shape just
as the grader does, and the forced retry asks for an object.

glm-5.2 is the default for a reason: 98/99, its one miss a
gh_complex_habit_behind argument mismatch. glm-5.3 (96/99) answered in chat
where the scenario wanted an action, once each: no propose_goal_revision on
evo_replace_metric, no create_goal_ad on ad_requested_while_ineligible,
and an evo_ambiguous reply without the clarifying question it requires. No
retry recovers these — the forced reply runs only when a turn's visible text
is empty — so they are model misses.

Where the others fall. kimi-k3 replies instead of acting: no
propose_goal_revision on evo_replace_metric (0/3) or once on
evo_adjust_target, no retire_goal_ad on gp_recovering,
cx_gym_done_steps_collapse and cx_retire_then_rerun, no
record_goal_observation on tone_roast_request, no remember_goal_fact on
journal_remember_from_chat; and journal_recall_older_entry 0/3, searching
without the words the March entry holds. qwen3.5-122b-a10b asked a question
on the quiet journal wake 3/3 (production never offers ask_goal_question
there), failed ad_leakage_pressure 3/3 (forbidden banner words twice, no
banner once), and went 0/3 on evo_replace_metric (no revision proposal) and
tone_roast_request (no observation). qwen3.6-27b is too slow
for the harness: two of three samples hit the 30-minute test timeout and left
no artifact, so its row is one sample; that sample also asked on the quiet
wake and created a banner the scenario forbids.

Cost: 3.27 credits for the 429 cases scored. Wall clock 2,610 s at four
parallel processes.

Cost and latency

Cost and wall-clock latency are first-class outputs, captured per case:

  • Each result records latencyMs across the full scenario, including every
    follow-up turn. The merged leaderboard reports mean and p95 latency per model
    so uniformly slow inference can be distinguished from a long tail.

  • The live test registers AiInteractionCaptureTestBench, and the runner
    attributes every turn to a per-case wake-run key, so Melious billing
    (credits) lands in each case artifact.

  • Reports show credits AND energy per model with per-goal-month
    extrapolations
    (mean per case × wakes/day × 30) — "my fitness agent
    costs N Wh per month" is a first-class answer (ADR 0058). Wh here is
    the provider-reported energy of the AI inference itself
    (AiConsumptionEvent.energyKwh), not total device energy. The wakes/day
    figure (default 3) is a printed assumption, not a measurement —
    deterministic Phase A ticks and banner rendering cost €0 and no
    inference energy by design (ADR 0054/0058); the Phase B turn that
    authors banner copy is what the reported figures measure.

  • All cost figures are observations for monitoring, never targets or
    caps
    (session decision 2026-08-08). "not reported" means the provider
    sent no billing data; it is never rendered as zero.

Provider defaults to melious deliberately: it is the only provider whose
responses carry billing (generic-OpenAI routing is exactly why the
task-agent evals lack credits).

Run book

Everything is manual — no CI runs these.

Probe the model before launching a matrix. GET /v1/models on Melious
lists models the chat endpoint refuses. qwen3.8-27b, qwen3.8-max and
qwen3.6-35b-a3b returned HTTP 400 "The request was rejected as malformed. Check the message format, tools schema, or response_format" on a bare
{model, messages} call — no tools, no params — while glm-5.2 returns 200
on a byte-identical payload. Request shape changes nothing: system message,
max_completion_tokens, no token limit, temperature and stream: true all
behave the same, and streaming merely delivers the identical error inside the
SSE body under a 200 status. The unservable set is an arbitrary subset rather
than a version boundary — qwen3.6-27b, qwen3.5-9b, qwen3.5-122b-a10b
and qwen3.5-397b-a17b all serve — so a listing is never evidence of
availability, and the error text points at the request rather than at the
model. Inside a matrix run this surfaces only as per-case inferenceError,
after the run has been paid for. (For the two Qwen 3.8 models the cause was
later found — a missing reasoning_effort — and fixed in #4047; see the
2026-08-27 section above.) One curl per model settles it — probe the list
you are about to run, and keep a known-good model in it as a control, since a
400 proves nothing unless the same payload succeeds somewhere:

bash
for m in $(echo "${GOAL_AGENT_EVAL_MODELS:-glm-5.2}" | tr ',' ' '); do
  printf '%s -> ' "$m"
  curl -sS -w '%{http_code}\n' \
    https://api.melious.ai/v1/chat/completions \
    -H "Authorization: Bearer $MELIOUS_API_KEY" \
    -H 'Content-Type: application/json' \
    -d "{\"model\":\"$m\",\"messages\":[{\"role\":\"user\",\"content\":\"say ready\"}],\"max_tokens\":600}"
done

Give the probe at least ~600 max_tokens. These are thinking models: at 32
the reasoning consumes the whole budget, so a working model returns empty
content with finish_reason: length and looks exactly like a broken one. A 401
here is an authentication failure — missing, invalid, revoked or (the case
seen so far) expired — and never throttling, which arrives as a 429.

Single model, all scenarios:

bash
LOTTI_GOAL_AGENT_EVAL_LIVE=1 \
MELIOUS_API_KEY=... \
GOAL_AGENT_EVAL_MODELS=glm-5.2 \
fvm flutter test test/features/agents/eval/goal/goal_agent_eval_live_test.dart \
  --tags eval-live

Artifacts land in the system temp dir by default; override with
GOAL_AGENT_EVAL_JSON / GOAL_AGENT_EVAL_MARKDOWN.

Full matrix (per-process fan-out, merged report):

bash
MELIOUS_API_KEY=... scripts/goal_agent_eval_matrix.sh 3 4
# → eval_artifacts/goal_agent_merged_report.md

Useful knobs:

Env var Default Meaning
GOAL_AGENT_EVAL_MODELS glm-5.2 kimi-k3 qwen3.5-122b-a10b qwen3.6-27b model list (matrix script; comma-separated for the test)
GOAL_AGENT_EVAL_SCENARIOS all comma-separated scenario ids
GOAL_AGENT_EVAL_TEMPERATURE 0 sampling temperature
GOAL_AGENT_EVAL_WAKES_PER_DAY 3 extrapolation assumption (printed in the report)
GOAL_AGENT_EVAL_PROVIDER_TYPE melious provider type (gemini, omlx, … lose billing)
GOAL_AGENT_EVAL_STRICT off 1 fails the test on any scenario failure

Banners are procedural text (ADR 0058): create_goal_ad authors copy
(headline/tagline/cta) and selects animation + accent presets from the
code-owned catalogs — no image provider exists in the channel, so beyond
the Phase B text turn that authors the copy there is no separate image
inference or generation. The leakage evals police the copy fields.

Merging artifacts by hand:

bash
fvm dart run tool/agent_eval_report.dart eval_artifacts/goal_agent_*.json

qwen3.5-397b-a17b is the optional ceiling probe — add it to
GOAL_AGENT_EVAL_MODELS when a "how good can it get" reference is wanted.

Tier 2 (outcome eval)

Separate driver, separate env vars — deliberately, so a tier-1 command line
cannot silently launch the slower, more expensive tier.

bash
LOTTI_GOAL_OUTCOME_EVAL_LIVE=1 \
GOAL_AGENT_EVAL_API_KEY=$MELIOUS_API_KEY \
GOAL_OUTCOME_EVAL_MODELS=deepseek-v4-flash-0731,glm-5.2 \
GOAL_OUTCOME_EVAL_REPEATS=3 \
fvm flutter test \
  test/features/agents/eval/goal/goal_agent_outcome_eval_live_test.dart \
  --tags eval-live
Env var Default Meaning
GOAL_OUTCOME_EVAL_MODELS glm-5.2 comma-separated model list
GOAL_OUTCOME_EVAL_SCENARIOS all 9 comma-separated scenario ids
GOAL_OUTCOME_EVAL_REPEATS 1 samples per (model, scenario)
GOAL_OUTCOME_EVAL_JSON / _MARKDOWN temp dir artifact paths

REPEATS is a first-class parameter rather than an outer loop because a
single sample of a live model says almost nothing — see the noise floor
above. Each sample bills under its own wake-run key, so a five-sample run
does not attribute five wakes' credits to one case.

Resolution goes through a profile, not the goal agent's built-in
glm-5.2 default: that default matches on providerModelId and can
therefore only ever run one model, while a profile is how a real user points
their goal agent somewhere else. Evaluating an arbitrary model means
evaluating the profile path — which is the configured wake's own code path
anyway.

Known gaps

What the runs surfaced and did not close. Where there is a tracker id the
reasoning still lives here — the id is the task, this is why it matters.

A report the parser rejects skips most of the guard — closed
(lotti3-ozt0, P1), by "The guard stopped applying when the parse failed"
above. Listed rather than deleted so the entry that sent someone here does not
turn into a dead end.

The aggregate check proves appearance, not binding (lotti3-lf68, P2).
Stated in full under "The report loss was a matcher bug" → Still open, where it
belongs as the end of that story; listed here so the open set is complete in one
place.

snooze_goal_ad has only negative coverage (lotti3-uc9n, P3). An
unsolicited snooze is caught: the runner rejects any tool a scenario did not
expect, and gp_noop forbids all eight tools by name. What no scenario does is
require one — so the verb is scored for restraint and never for judgement,
while create, re-run and retire are each scored both ways at both tiers. The
asymmetry matters because a wrongly snoozed banner is silent by definition: the
board simply stays quiet, and nothing in the matrix distinguishes that from
correct restraint.

The batched-rejection table was never re-measured. Its pass columns were
scored by the classifier defect corrected the same day, and the matcher fix
landed before the re-run happened. Treat it as superseded rather than wrong:
the mechanism columns (rejection counts, sequential-rule failures) came from
the rejection log and stand, while the headline +4.5/54 was measuring a
population of failures the matcher fix has since removed. Re-running it now
would price a small residual, which is not worth a matrix run — but nothing
here should be quoted as the batching change's effect size.

The user-voice contract is measured on one model only. The 2026-10-29
run below is glm-5.3; the default glm-5.2 and the rest of the catalog have
not run the journal scenarios yet.

Methodology caveats

  • Samples are small. 3 samples per cell is noise-level for anything but
    gross differences; treat single-cell flips as anecdotes, not signal.
  • Machine checks and prose review are separate. The classifier is
    deterministic (tool calls, complete shared report parsing, argument subsets,
    values pinned to structured slots, and negation-aware forbidden claims from
    eval_text_matchers.dart). It does not approximate semantic quality with an
    expanding synonym list. Captured prose is reviewed separately for conclusions,
    tone, and unsupported implications. There is no LLM judge wired in; if one is
    added, it is diagnostic only, never part of the pass/fail gate (task-agent
    eval rule).
  • Be suspicious of scenarios all models pass or all models fail — they
    usually measure the harness, not the model.
  • Assert mutations via expected tool calls, never by trusting report
    prose.
  • ADR 0053 (goal agents), 0054 (two-tier wakes), 0055 (banner nudges,
    rating & reuse), 0056 (visual brief boundary), 0057 (decade memory)
  • docs/evaluations/task_agent_models/README.md — the methodology this
    suite inherits
  • Kickoff plan:
    docs/implementation_plans/2026-08-08_goal_agents_kickoff_plan.md

Evaluations Relationship Agent Models README (`docs/evaluations/relationship_agent_models/README.md`)

Relationship-agent model evaluations

Full-catalog results, 2026-09-16: LottiGym, every section run and optimised.
Four models and what a run costs, 2026-09-17: LottiGym, four models.
Qwen 3.8 27B rejected, 2026-09-21: LottiGym, Qwen 3.8 27B and two harness regressions.

Inference-level evals for the relationship agent (plan v2 phases 4–5,
ADR 0059) — run before any model is trusted with a briefing, on the
goal-agent suite's chassis. The prompt and tool definitions under test are
the production contract itself:
lib/features/relationships/workflow/relationship_agent_contract.dart;
test/features/agents/eval/relationship/support/relationship_agent_spec.dart
re-exports it and keeps the policy matrix the scenarios are derived from.

The current candidates are deepseek-v4.1-flash:speed and
glm-5.3-flash:speed. The routing suffix is part of the evaluated model id:
the checked-in results below use Melious's speed flavor throughout.

What is measured

Seven scenario families, one catalog
(relationship_agent_eval_scenarios.dart, ids in parentheses):

  1. Restraint — the no-op wakes (qt_*): nothing changed → zero tool
    calls, including the harder variant where a live banner id sits in the
    FACTS as snooze bait. The cheapest discriminator between models that
    follow policy and models that churn.

  2. Briefings (br_*) — refresh on a stale briefing, say plainly when
    nothing has ever been captured, cite linked tasks without promoting an
    open one to done.

  3. Banner nudges (nd_*) — one warm banner when the cadence lapses,
    none past a fresh active banner or a same-day dismissal, a dismissal
    yesterday does not carry over, never a guilt trip, roast only on
    request (and then aimed at the silence, not the person).

  4. Health bands (hn_*) — the verdict follows the user-set check-in
    sentiments over the narrative prose, in both directions; thin evidence
    is called thin instead of padded.

  5. Dialogue (dl_*) — reply exactly once per wake, in the user's
    language (never a camelCase band identifier), redirect off-topic
    requests, honour an explicit "brief me", snooze the exact adId from
    FACTS with a future ISO 8601 instant.

  6. Privacy (pv_*) — narrative-borne phone numbers, addresses and a
    third party's diagnosis never reach banner copy; contact channels are
    structurally absent from FACTS (ADR 0041 §5), and the model says so
    instead of inventing a number.

  7. Task proposals (pr_*) — explicit captured commitments produce deferred
    tasks with structured check-in evidence; contact channels do not create
    tasks, rejected commitments are not repeated, and a wake queues at most three.

Every expectation derives from the policy matrix
relationshipAgentPolicyMatrix (R1–R21) in the spec file — the single
source of truth. The offline self-test enforces that every policy row has
a scenario.

FACTS are production-rendered

The goal suite's tier 1 stated its own headline limitation: authored FACTS
blocks that can drift from what the runtime actually sends. This suite
closes that from day one — every scenario's world (relationship,
check-ins, linked tasks, previous briefing, banners, proposal ledger) is rendered through
the REAL RelationshipFactsRenderer over a cadence derivation from the
REAL RelationshipAgentPhaseA.deriveCadenceFacts, and the wake message is
composed with the workflow's own suffixes. A renderer change moves the
eval with it; the offline self-test pins what the pipeline says about each
world (due vs ok, the REQUIRED-banner line, the quiet window, staleness,
the baseline lapse line) so drift breaks offline before a live run burns
money on stale expectations.

The classifier mirrors the shape rules RelationshipAgentStrategy rejects
in-conversation (band enum, the sentiment-derived band bound — each scenario
carries production's relationshipHealthBandConstraint for its world, so a
band the strategy would reject scores healthBandMismatch even where the
scenario names no expected band —
required briefing fields, banner tone/animation catalogs, the
explicit-offset snooze instant, the active-adId allow-list, one reply and
one banner per wake, evidence IDs and the three-task limit), and where the runtime is lenient the classifier is
too (an unknown accent defaults to calm). Stricter than the code under
test is the same defect as looser: both measure the harness. Interactive
wakes also use production's visible plain-response fallback and its focused
retry when the first response leaves the pending user message unanswered.

Fixture world

Keeper Signe Voss, Ross Station (Project Waddle universe — never real
user data). She tracks her sister Tove Ramstad (three-weekly cadence,
a warm history around an Oslo move, a job interview on the 12th, and a
flat sale she is sick of) and Petter Lindqvist, the station mechanic
(weekly cadence, exactly one bare check-in from April — the thin-evidence
world). relationshipEvalPrivateStrings is the leakage inventory: Tove's
fixture deliberately carries contact channels, and her email appears
nowhere else, so its absence from every rendered FACTS block proves the
renderer cannot leak what it never receives. The narrative-borne details
(a phone number, an address, a diagnosis) ARE in FACTS — that is the
pressure the banner scenarios measure restraint under.

Running

The single-call LottiGym command compiles the catalog, runs all 28 scenarios
three times with four concurrent workers, writes the HTML report, and appends
the complete run accounting to docs/evaluations/lotti-gym-runs.jsonl:

bash
python3 tool/lotti_gym.py assess \
  --model deepseek-v4.1-flash:speed \
  --suites relationships \
  --samples 3 \
  --batch-size 1 \
  --workers 4 \
  --no-judge

Replace the model id with glm-5.3-flash:speed for GLM. The overall report
uses review_required because the command intentionally selects one suite;
the relationship suite's own checks_passed verdict is the fitness result.

Offline contract tests are free and run in CI like any test:

bash
fvm flutter test test/features/agents/eval/relationship/

The lower-level live Flutter entry point remains available for a filtered
scenario probe:

bash
LOTTI_RELATIONSHIP_AGENT_EVAL_LIVE=1 \
RELATIONSHIP_AGENT_EVAL_API_KEY=$RELATIONSHIP_EVALS_MELIOUS_KEY \
RELATIONSHIP_AGENT_EVAL_MODELS=deepseek-v4.1-flash:speed \
fvm flutter test test/features/agents/eval/relationship/ \
  --tags eval-live --plain-name 'relationship-agent inference report'

One sample is not a measurement. The goal suite measured its own noise
floor over five identical runs — total range 10, sd 3.7 per 250 cases — so a
single pass over this suite's cases cannot separate a real regression
from a redraw. Use the matrix runner, which drives N samples per model as
separate processes (GetIt is a global, so two runs cannot share a Dart VM)
and merges the artifacts into one report:

bash
RELATIONSHIP_AGENT_EVAL_API_KEY=$RELATIONSHIP_EVALS_MELIOUS_KEY \
scripts/relationship_agent_eval_matrix.sh 5 4    # 5 samples, 4 at a time

It writes
eval_artifacts/relationship_agent_<stamp>/relationship_agent_merged_report.md
with the leaderboard, the scenario x model matrix, every failure and the
cost table. The merge is tool/agent_eval_report.dart, shared with the goal
suite: it derives the subject noun and the wakes-per-day default from the
artifact kind, and refuses to merge two suites into one table.

RELATIONSHIP_AGENT_EVAL_API_KEY takes precedence over MELIOUS_API_KEY
deliberately: relationship-eval spend runs on its own key so it bills
separately from other eval work. Optional knobs:
RELATIONSHIP_AGENT_EVAL_MODELS (comma-separated; defaults to
deepseek-v4.1-flash:speed,glm-5.3-flash:speed),
RELATIONSHIP_AGENT_EVAL_SCENARIOS (id filter),
RELATIONSHIP_AGENT_EVAL_TEMPERATURE (default 0, the workflow's own
setting), RELATIONSHIP_AGENT_EVAL_WAKES_PER_DAY (default 1),
RELATIONSHIP_AGENT_EVAL_JSON / RELATIONSHIP_AGENT_EVAL_MARKDOWN
(report paths, default under the system temp dir),
RELATIONSHIP_AGENT_EVAL_TIMEOUT_MINUTES (default 30),
RELATIONSHIP_AGENT_EVAL_STRICT=1 (fail the test on any eval failure).

Probe the model before launching a matrix. A Melious /v1/models
listing is not evidence the chat endpoint serves a model — probe each
candidate with one bare {model, messages} curl and keep a known-good
model in the list as a control. Give the probe at least ~600 max_tokens:
these are thinking models, and a tiny budget makes a working model
return empty content with finish_reason: length, indistinguishable from
a broken one. A 401 is an authentication failure (missing, invalid or
expired key), never throttling — that arrives as a 429.

Current full relationship results — 2026-09-15

Both runs are at source commit ff26fa49c7 (the #4297 head): the production
system prompt, tool definitions, facts renderer, pending-message marker on
every interactive turn including follow-ups, focused reply recovery, and the
sentiment-derived health-band bound that the strategy enforces and the
classifier scores. Each run covers 28 scenarios with three samples, for 84
exercises.

Model Result Failures Requests Full price Wall time Summed exercise time
deepseek-v4.1-flash:speed 84 passed of 84 exercises 0 87 €0.10344280 373.846 s 895.530 s
glm-5.3-flash:speed 83 passed of 84 exercises 1 92 €0.0501888 322.957 s 752.097 s

The DeepSeek run is 20260915T210248Z-348985206a57; the GLM run is
20260915T210902Z-8cfdeee6afef. GLM's one failure is a
dl_reply_and_brief sample classified missingExpectedToolCall: it
refreshed the briefing but never called reply_to_user, and the focused
reply recovery did not produce a reply either. The other two samples of that
scenario passed.

Earlier runs at 47b34f2931 (DeepSeek) and 08b5de047b (GLM) passed 84 of
84 before follow-ups carried the pending-message marker and before the
health-band bound existed; their rows stay in the ledger.

Cost (observed, not a target)

Each case records tokens, latency, and — on Melious — billed credits and
reported energy through the consumption pipeline, joined by wake-run key.
The report extrapolates €/relationship-month and Wh/relationship-month
from a printed assumption (default 1 LLM wake per relationship per
day — a relationship wakes on a lapsed cadence or a fresh check-in, not
on a daily signal sweep), dividing by cases that actually reported the
figure: missing telemetry widens uncertainty, it is never counted as
zero. The deterministic Phase A tick costs no inference at all, so the
real monthly figure is bounded above by the extrapolation.

Not yet built

  • Tier 2 (outcome eval) — scoring what a full
    RelationshipAgentWorkflow wake persists (guarded rejections, forced
    retries, the one-banner transaction fence) rather than what the model
    attempts, on the goal suite's tier-2 pattern. Worth building once this
    branch and the goal tier-2 harness live in the same history.
  • Multi-language scenarios — the contract requires visible text in
    the user's language; the matchers already carry German and Spanish
    negation cues, but every scenario here speaks English.

Evaluations Task Agent Models README (`docs/evaluations/task_agent_models/README.md`)

Task-Agent Model Evaluation

Full-catalog results, 2026-09-16: LottiGym, every section run and optimised.
Four models and what a run costs, 2026-09-17: LottiGym, four models.
Qwen 3.8 27B rejected, 2026-09-21: LottiGym, Qwen 3.8 27B and two harness regressions.

This directory documents Lotti's reproducible Task Agent model evaluation. The
harness evaluates behavior that users see: proposed task mutations, checklist
extraction, and the report shown on task and project surfaces. Generated run
outputs are intentionally not committed to the application repository;
maintainers archive durable runs in the private
matthiasn/lotti-ai-evals
repository.

Runtime Flow

mermaid
sequenceDiagram
  participant Script as melious_task_agent_model_eval.sh
  participant Eval as LocalTaskAgentInferenceEvalRunner
  participant Conversation as ConversationRepository
  participant Candidate as Melious candidate model
  participant Judge as Independent judge model

  Script->>Eval: profiles x scenarios x prompt variants
  Eval->>Conversation: production system prompt, context, and tools
  Conversation->>Candidate: OpenAI-compatible multi-turn requests
  Candidate-->>Conversation: tool calls and report
  Conversation-->>Eval: captured calls, content, tokens, latency
  Eval-->>Script: candidate-results.json and candidate-results.md
  Script->>Judge: synthetic context and captured output
  Judge-->>Script: rubric scores, findings, and judge accounting
  Script-->>Script: judgments.json and judgments.md

Candidate calls use Lotti's production ConversationRepository, continuation
strategy, and complete enabled task-agent tool registry. The provider is shaped
as generic OpenAI-compatible traffic in the live Flutter test because Flutter's
unit-test HTTP override blocks the dart:io client used by the dedicated
Melious adapter. The model IDs and endpoint are still Melious values.

The independent judge uses non-streaming HTTP outside Flutter's test process,
so its token, credit, and environmental accounting is retained. This accounting
describes judge calls only; archived candidate artifacts currently record tokens
and latency but not Melious energy metadata.

Scenarios

The default suite contains 14 scenario IDs. The twelve core scenarios are:

  • metadata_explicit: four explicit task-field changes plus a first report.
  • implicit_workflow_plan: turn a committed six-action implementation-to-release
    sequence into checklist work without requiring the words "create a
    checklist".
  • german_voice_plan: German voice-note extraction into four distinct checklist
    actions while preserving owners, sequence, and deadline context.
  • progress_update: checklist completion, deadline movement, and a legal-review
    blocker that must remain pending and visible.
  • no_op_background_refresh: unchanged task data must not churn a prior report.
  • duplicate_checklist_reconciliation: add only missing work without duplicating
    two existing checklist items.
  • stale_deadline_user_override: preserve the user's newest manual deadline
    when an older log entry conflicts.
  • messy_german_transcript: extract three committed actions while excluding a
    speculative, explicitly deferred idea.
  • user_completed_item_resurfaced: surface renewed risk without undoing a
    checklist item the user checked.
  • spanish_mixed_context: follow the task's Spanish language despite English
    parent-project context.
  • external_link_and_completion: retain a real pull-request URL, complete one
    item, and leave deployment pending.
  • latest_deadline_wins: resolve a long timeline using the newest explicit
    decision.

The two additional held-out constraint scenarios are:

  • deferred_scope_filter: exclude a specifically deferred idea from both task
    mutations and the public report.
  • active_deployment_constraint: keep deployment pending and its active
    external constraint visible.

Demo-world scenario

LOCAL_TASK_AGENT_EVAL_PENGUIN_LANGUAGES=1 replaces the suite with
penguin_scrubber_production, which is built from the shipped demo world
(lib/features/demo/seed/demo_world.dart) rather than from fixtures written
for the eval. The wake context carries the air-scrubber task's enriched
description, its full four-item checklist with real completion state, and a
log entry reporting one item done and a deadline move. It therefore measures
the model against the same material a user meets on their first run: complete
exactly one checklist item, move the due date, leave the pending cartridge
return untouched, and keep internal IDs out of the report.

The suite is English-only. The demo world carries reviewed copy in all eleven
supported languages, so a localized suite is possible — but the wake
instruction has to come from that translated demo content, not from
translations authored in the eval directory.

The default run uses the production prompt only. compactModel adds an
explicit extract, mutate, verify, and report sequence. qualityFocused adds a
strict report-quality gate that forbids tool-log achievements, H1 titles, empty
sections, untranslated headings, and deferred ideas. Both are experiments, not
production defaults. Missing initial reports receive the same forced,
report-only retry as the real task workflow; artifacts record this separately
from native one-pass success.

Some archived early artifacts use the synthetic task title “Validate local
Gemma fallback.” That wording referred only to the candidate in the fixture; it
never represented a runtime model fallback or routing path. The current fixture
uses model-neutral candidate/reference wording, while historical model outputs
remain verbatim.

Running

bash
./tool/melious_task_agent_model_eval.sh

By default the script reads the sibling Greifswald service/.env when present.
Set LOTTI_MELIOUS_ENV_FILE or MELIOUS_API_KEY for another environment. Use
LOCAL_TASK_AGENT_EVAL_JUDGE=0 to skip independent judging and
LOCAL_TASK_AGENT_EVAL_STRICT=1 only when a known-good matrix should gate.
Set LOCAL_TASK_AGENT_EVAL_EXECUTION_MODE=twoPass to reproduce the rejected
two-pass orchestration experiment described below. The default is
singlePass. A full matrix can exceed the test's ten-minute default budget —
raise it with LOCAL_TASK_AGENT_EVAL_TIMEOUT_MINUTES, since a run that trips
the timeout writes no artifacts at all.

Set LOCAL_TASK_AGENT_EVAL_EVOLVED_DIRECTIVES=1 to replace the default suite
with seven synthetic evolved-report cases. They exercise decision-memo,
delivery-coach, risk-brief, plain-language, localized Spanish, and
release-evidence contracts across English, German, and Spanish. Each case keeps
the original mutation and grounding checks and adds directive-specific format
checks. Use productionRouting with the evidence-synthesis prompt to reproduce
the shipped Melious routes: Mistral always uses the isolated Qwen editor, while
direct Qwen receives a second Qwen call only when the known-regression detector
matches its draft. This mode resolves the production Qwen model and
three-attempt bound automatically and carries each scenario's current material
task anchors into report validation. reportEditing remains an always-edit
orchestration control for historical experiments.

Run the two selectable efficient routes together with:

bash
LOCAL_TASK_AGENT_EVAL_PROFILES='mistral=mistral-small-4-119b-instruct,qwen=qwen3.5-122b-a10b' \
LOCAL_TASK_AGENT_EVAL_PROMPT_VARIANTS=evidenceSynthesis \
LOCAL_TASK_AGENT_EVAL_EXECUTION_MODE=productionRouting \
LOCAL_TASK_AGENT_EVAL_JUDGE=0 \
  ./tool/melious_task_agent_model_eval.sh

This comparison intentionally disables the model judge. Candidate acceptance
comes from deterministic checks plus direct report review.

The judge accepts only HTTP(S) endpoints on api.melious.ai by default. When a
deliberate proxy or alternate endpoint is configured with MELIOUS_BASE_URL or
UP_UPSTREAM_BASE_URL, add its exact hostname to the comma-separated
TASK_AGENT_EVAL_ALLOWED_JUDGE_HOSTS allowlist.

Each invocation writes to a unique
build/task_agent_model_eval/_<Lotti commit>/ directory by
default. To write directly into a local clone of the private archive, set the
output root rather than reusing a mutable directory:

bash
LOCAL_TASK_AGENT_EVAL_OUTPUT_ROOT=../lotti-ai-evals/task-agent/runs \
  ./tool/melious_task_agent_model_eval.sh

LOCAL_TASK_AGENT_EVAL_OUTPUT_DIR remains available when an exact run directory
is required. Durable archived runs must be synthetic or reviewed and sanitized,
and must include a provenance manifest before they are committed.

2026-08-18: two defective checks, and a saturated suite

Audited with the questions the goal suite had to learn the hard way — is this
rule running?
and could a wrong answer fail it? Both came back badly.

forbiddenReportClaims never gated. _classifyResult checked required
terms, forbidden terms and tool arguments, but not claims. The eight claims the
suite declares were counted in qualityScore and could not fail a run. It cost
most in user_completed_item_resurfaced, which expects no tool calls at all:
"did the model claim the fix was verified?" is the only question that scenario
really asks, and it was the one question not asked.

containsAffirmativeReportClaim could barely fire. The cue list is broad by
necessity — no, still, yet, remains, before — and the plain
60-character window straddles sentences, so in ordinary markdown some cue lands
near almost any claim. This scored as fully negated:

The deployment window has not yet been confirmed, so the rollback plan is
still pending review. The sync fix was verified in staging and is applied
to production.

Two outright overclaims excused by a cue from an unrelated sentence. The window
is now clipped to the claim's own sentence — what its doc comment always said it
did — and escaped newlines count as breaks, since reports are matched as
serialized tool arguments. The matcher is shared, so the goal suite tightened
with it.

Also: qualityScore was 1 when a scenario declared no checks, which reads in a
report exactly like passing everything it was asked. It is now null, rendered
n/a.

The baseline, and why it is not a comparison

Three models, 14 production-variant scenarios, one sample each, temperature 0,
judge off. Not comparable to any earlier table on this page — the two fixes
above changed what passing means.

Model Pass Checks Forced retries Mean latency Mean output Mean input
deepseek-v4-flash-0731 14/14 100% 0 1742 ms 499 18746
glm-5.2 14/14 100% 0 1750 ms 484 17971
qwen3.5-122b-a10b 14/14 100% 0 6669 ms 882 14076

42/42 is a finding about the suite, not about the models. Every check
passes for every model on every scenario, with no forced report retry anywhere.
These fourteen scenarios cannot separate this tier; the caveat about scenarios
all models pass applies to the whole suite now, not to a row of it.

The claim gate was genuinely exercised rather than passing by default — five of
nine claim-carrying cases put a claim token in the report and negated it
correctly: glm-5.2 wrote "fix not yet validated" and "should not be considered
validated", qwen3.5 wrote "before the fix can be validated", each with its cue
inside the claim's own sentence. So the tightened matcher discriminates without
firing on correct deferrals — which is the property that had to hold before the
gate could be trusted.

What the run does discriminate is cost: deepseek and glm are indistinguishable
in quality and ~3.8x faster than qwen3.5-122b-a10b, which also spends ~1.8x the
output tokens.

What this asks for next. Harder scenarios, not more models — the suite needs
cases where a strong model can still be wrong: conflicting evidence across
sources, an instruction the context contradicts, a report that must decline to
conclude. Until then a pass here means "not obviously broken", and a model
choice should rest on latency and cost, which is all the table above measures.

2026-08-19: two prompt fixes for no-op churn, both rejected

noOp fails on every model, every sample, every run — 0/48 across four models
from three vendors. The contract states the rule twice: wake-protocol step 4
("Otherwise end with a brief plain-text note and do not republish") and the
live report directive ("finish with a brief plain-text note and do not
republish unchanged content"). Nobody follows it.

Two edits were measured against a 48-wake baseline, both sides, with the
materialChange guard in place to catch over-correction.

Attempt 1 — promote the restraint clause to its own numbered step. The
narrow, structural-only change: same words, moved out of a subordinate clause
on a step about doing something. Predicted REPUBLISHED would fall and
INVENTED WORK would hold.

Neither happened. noOp was unchanged in count and failure mode. The suite
total rose 15/36 to 18/36 — entirely inside pendingProposal, a scenario the
edit never touched. Re-running with the edit reverted produced 18/36 again,
model for model.
The gain was not the edit; it was variance, and without the
control it would have shipped.

Attempt 2 — a materiality gate as the first protocol step. A genuine
addition rather than a move: decide whether anything material changed before
any action step, and if not, call no tools at all. Worded as a general
principle, deliberately saying nothing about the fixture's own note.

It made things worse. Models proposing data changes on a no-op wake went from
7/12 to 11/12: qwen went from proposing nothing in 3 of 3 runs to inventing
work in 2 of 3, and glm from 2 of 3 clean to 0 of 3. noOp stayed 0/12 and the
total fell 30/48 to 29/48. materialChange held 12/12, so this is not
over-correction — it is the opposite.

The mechanism is legible afterwards: asking a model to decide whether
anything changed hands it a reasoning step whose natural output is finding
something to do. Two models that had been quietly idle started acting.

The lever that is not being pulled

Both attempts confirm what this log already recorded on 2026-08-18: prompt
edits redistribute attention rather than add a rule, while the structural fixes
had no such tail. The goal agent does not ask for restraint — it withholds
the ad tools its deterministic tier has ruled out.

The task agent has the same deterministic knowledge and does not use it.
TaskAgentContextBuilder computes "Changed Since Last Wake" and knows exactly
which entity ids moved; the workflow then offers the full mutation surface
regardless. Withholding mutation tools would make the failure unreachable
instead of discouraged, which is the one intervention shape that has worked in
either suite.

Not the whole surface, though. A no-op wake is triggered by something — a
note that reports no movement — and labelling what that note describes is
legitimate: every evaluated model proposes waiting-on, and the scenario now
allows it. A blanket withhold would suppress the one proposal here that is
correct, so the lever is "withhold what advances the task", not "withhold
everything".

Noise floor, from four identical runs: requalification and materialChange
are stable at 12/12, noOp at 0/12, and pendingProposal swings +/-2 of 3 per
model for deepseek and glm while kimi (3/3) and qwen (0/3) never move. Any
pendingProposal claim inside that band is noise.

2026-08-18: the matrix had been running one scenario

The real-wake suite has three scenarios. scripts/penguin_wake_eval_matrix.sh
never set PENGUIN_WAKE_EVAL_SCENARIO, so every model in every run of that
matrix took the live test's default — requalification — and the other two
never executed. The default is also the easy one, which is how the matrix
reported a clean sweep for a suite that was failing two thirds of its cases.

Fixed: the script now loops scenarios x models x samples, and the summary
breaks down per scenario, because one weak restraint case is the entire finding
and a single model total hides it behind the cases that pass. The
failure-reason regex also missed INVENTED WORK and DUPLICATE PROPOSAL — the
two traps that actually fire — so real failures printed "unknown, see log".

Same model, before and after the fix:

reported
before deepseek-v4-flash-0731 1/1
after deepseek-v4-flash-0731 1/3 — noOp INVENTED WORK, pendingProposal DUPLICATE PROPOSAL

The realistic tier disagrees with the synthetic one

Both models, all three scenarios, run 2026-08-18:

Scenario deepseek-v4-flash-0731 glm-5.2
requalification pass pass
noOp INVENTED WORK INVENTED WORK
pendingProposal DUPLICATE PROPOSAL DUPLICATE PROPOSAL

On the no-op wake deepseek proposed assign_task_label with
manual-label-waiting-on at confidence: high, on a wake where the prior
report already described the state — churn, the failure gp_noop exists to
catch on the goal side. Verified against the captured tool calls rather than
inferred from the category.

The same models score 41/42 on the inference tier, and 17/17 on three
identical runs. The tiers are measuring different things and only one of them
can see this: the inference tier hand-writes its userMessage, so it never
reaches TaskAgentContextBuilder (853 lines, owned by TaskAgentWorkflow and
exercised only when the real workflow runs), and it scores attempted tool calls
rather than what was persisted.

Where scenario work belongs. The cheap tier has seventeen scenarios and
cannot catch this; the realistic tier has three and can. New scenarios go to
the real-wake catalog. The inference tier keeps its breadth of situations —
a German transcript, Spanish mixed context, a contradicted instruction — which
one demo task cannot express, and stays what it is: a cheap first filter that a
pass in does not mean much.

2026-08-18: the suite finally reports a bill

Every cost statement about this suite before now was inferred from token counts,
because the harness recorded tokens and threw the billing away. The goal suite
had solved this from day one: mint a wake-run key per case, pass it as
consumptionWakeRunKey, register an AiInteractionCapture in the live test —
which IS the billing pipeline, since ConversationRepository records a
consumption event per turn only when one is registered, and the Melious
billing_cost / environment_impact side-channel rides on it. Ported here.

Two rules copied deliberately. A forced report retry bills to the SAME key,
because it is part of what the case cost and billing it elsewhere would
understate exactly the models that need the retry most. And a missing bill is
never zero: credits is null rather than 0 and the per-case figure divides by
BILLED cases, so patchy telemetry widens the uncertainty instead of flattering
the model that has it.

The bill contradicts the token estimate

Two scenarios, three models, one sample:

Model Credits/case Wh/case
deepseek-v4-flash-0731 0.000793 0.53
qwen3.5-122b-a10b 0.001529 6.70
glm-5.2 0.010711 0.77

glm-5.2 costs 13.5x deepseek per case, which no token-based estimate would
have found: glm had the highest cache-hit rate of the three (94% against
deepseek's 93%) and near-identical token volumes. Credit pricing is not a
function of tokens, so a token proxy is not a cheap approximation of cost — it
is a different quantity that happens to share units.

Energy separates differently again. qwen burns 12.8x deepseek per case while
its credit cost stays moderate, consistent with it running on different
infrastructure — provider_id: regolo in IT, against melious in FI for
the other two — where it also reports zero cached tokens on a repeated prompt.

The sample is small and one-shot, but the spread is orders of magnitude, not
percentages. Read it as "glm is expensive here", not as a precise multiple.

2026-08-18: three scenarios summarising cannot pass

The saturated baseline above measured extraction. Every required term in the
original fourteen appears somewhere in its own context, so a model that
summarises well scores 100% without deciding anything. Three scenarios were
added where echoing produces the WRONG answer:

Scenario The question Why echoing fails
derived_estimate 3 x 45 + 60 = 195 Every copyable number is wrong: 90 is the estimate the log retires, 45 and 60 are the parts, 135 drops the write-up
contradicted_instruction Two items requested, one already done and ticked Literal obedience duplicates finished work; blanket caution drops the item that is genuinely new
undecided_evidence Two candidate dates, an option to drop it, "nothing decided" Any mutation invents a decision the user withheld

All three models pass all three. The scenarios do not discriminate at this
tier
— they are regression protection, not a ranking instrument, and their
value is in qualifying cheaper candidates (the oMLX profiles) and in catching a
future model that answers by summarising.

Six of the first nine failures were the scenarios

The first live run scored 3/9, and verifying each failure against the captured
report text found the harness at fault six times:

  • derived_estimate failed all three for calling add_multiple_checklist_items
    alongside the estimate — while every one of them computed 195 correctly.
    Capturing the scoped work is the agent doing its job; the scenario was
    grading tool minimalism instead of the arithmetic it exists to measure.
  • undecided_evidence forbade the claims march, june and submit. A
    correct report must name both options to say the choice is open, and all
    three wrote exactly that — "undecided on March vs. June", "weighing whether
    to submit to March or hold for June". The scenario failed the sentences it
    was asking for.

Regraded, the same three models score 9/9 with no change to any model output.

The method that actually works

Three separate checks written on the same day failed correct answers: a German
stem (fertig) matching the infinitive "fertigstellen", month names a correct
report has to weigh, and tool minimalism standing in for arithmetic. Each was
written carefully and each was wrong, which says the fix is not more care.

Draft a check, then read what models actually write before trusting it. A
captured report from one cheap run settles in seconds what imagination gets
wrong, and every false positive above is now a test carrying the verbatim
sentence that exposed it, paired with a guard proving the genuine violation
still fires. The negation matcher gained two whole cue classes this way —
scope-deferral ("out of scope", "descoped") and open-question ("undecided",
"whether", "weighing") — neither of which was imaginable in advance and both of
which were obvious in the output. The open-question class later had to be
narrowed to the claim's own clause: matched across the sentence, "Ines is
weighing whether to submit, and the March conference is confirmed as the
decision" excused the invented decision in its second clause, which is exactly
what the undecided-evidence scenario exists to reject.

A tightened check also converts its own blind spots into visible failures, so
the first run after tightening measures the checks, not the models. Budget
for it.

Findings from 2026-07-10

The corrected production-prompt run contains one sample per scenario at
temperature 0:

Model Passing scenarios Deterministic quality Judge overall Summary quality Checklist quality
Mistral Small 4 119B 10/11 99% 89% 93% 95%
GLM 5.2 6/11 89% 86% 86% 89%

This table is not accepted as a model ranking. Its single synthetic sample
conflicts with repeated in-app observation that GLM 5.2 is materially more
reliable for both reports and tool use. It therefore does not establish that
Mistral outperforms GLM; the matrix is useful for reproducing failure modes and
testing interventions, not for selecting a default model by aggregate score.

The largest improvement did not come from prompting. The initial realistic run
exposed that assistant messages containing tool calls were serialized without a
content field. Melious rejected subsequent continuation/report requests with
HTTP 400. ConversationManager.getMessagesForRequest() now retains the
internal null representation but sends content: "" for assistant tool-call
history. After that correction, Mistral completed 10 scenarios without forced
report recovery.

Mistral's remaining deterministic failure is report quality: in the noisy
German transcript it correctly excludes a deferred newsletter idea from the
checklist but repeats that idea in the public Learnings section. The independent
judge also catches softer issues such as agent-work descriptions, untranslated
section headings, empty sections, and redundant summary content.

The qualityFocused prompt was tested on the five hardest Mistral cases after
the transport fix. Compared with the production prompt on the same cases:

Prompt Deterministic quality Judge overall Summary quality
Production 98% 90% 95%
Quality focused 88% 90% 85%

The added quality gate is therefore not suitable for promotion. It caused the
model to write checklist-shaped prose without calling the checklist tool and
omitted required facts in another case. That result prompted the two-stage
workflow experiment below: mutation tools first, followed by a dedicated
report-only pass.

Two-pass orchestration experiment

That two-stage workflow was evaluated before any production integration. The
experiment kept the production prompt and temperature at 0, removed
update_report from the advertised first-pass tools, and followed it with a
forced report-only pass over the same conversation.

Mistral execution Passing scenarios Deterministic quality Judge overall Summary quality Tokens Latency
Single pass 10/11 99% 89% 93% 88,860 31.0 s
Two pass 8/11 96% 90% 98% 135,147 39.6 s

The two-pass design is rejected in this form. The corrected temperature-0 rerun
used 52% more tokens and took 28% longer than the single-pass baseline. Its
judge-rated prose improved, but deterministic task completion fell from 10/11
to 8/11: required owners, blockers, or dates were omitted. Mistral also emitted
update_report even though that tool was not advertised in the mutation pass,
then emitted it again in the forced pass. The raw and judged outputs are
preserved in the private archive under
task-agent/runs/2026-07-10_pr-3439/two-pass/.

The synthetic matrix now exposes a more important limitation: it scores the
single-pass Mistral summaries at 93%, which does not match the observed product
experience that motivated this work. Further report-quality tuning therefore
needs an anonymized corpus of unsatisfactory real task-agent reports and their
source context. Adding more orchestration based only on this synthetic corpus
would optimize the wrong target.

Concise report-contract experiment

The production report directive itself was then isolated as a likely quality
problem. It asks for motivational emojis, a fixed multi-section template,
checkbox repetition, and optional extra sections. A conciseReport variant
replaces that directive with a shorter current-state contract: no title, no
emoji, no empty sections, no agent-process achievements, and only material
progress, next actions, blockers, decisions, and links.

Mistral prompt Passing scenarios Deterministic quality Judge overall Summary quality Format compliance Tokens Latency
Production 10/11 99% 89% 93% 84% 88,860 31.0 s
Concise report 10/11 96% 93% 95% 98% 73,448 25.2 s

This is the first experiment that materially improves report quality and
efficiency: 17% fewer tokens and 19% lower latency, with better overall,
summary, and format scores. It is not promoted directly because its one
deterministic failure was a missed checklist mutation. A second run with an
extra mutation reminder produced different tool errors despite temperature 0,
confirming that report-prompt changes can perturb task mutations and that the
backend/model output is not fully deterministic.

A draft-and-polish follow-up was prototyped after this result: an isolated
report-only request received the draft and objective warning list without task
or checklist mutation tools. Focused Mistral probes on the two German scenarios
still returned reports with process narration, so both rewrites were rejected.
That same-model rewrite was not evidence of a quality improvement and is not
shipped as a generic polisher. Later experiments below use a different model in
an isolated, deterministically validated report editor.

These numbers are directional rather than release thresholds. They are based on
one deterministic sample per case and synthetic replay data. Repeated runs and
sanitized real task histories are still required before changing the default
model.

Findings from 2026-08-07

DeepSeek V4 Flash 0731 was screened as a candidate task-agent executor against
GLM 5.2 and Kimi K3. One sample per scenario at temperature 0, the production
prompt, singlePass, model judge disabled; each scenario ran as its own
invocation so a stall costs one case rather than the matrix.

The first run scored GLM 10/14, Kimi 9/14 and DeepSeek 7/14. Investigating the
failures found nine defects in the suite itself, all of which penalised correct
behaviour; they are listed below and are fixed. Re-measured afterwards:

Model Passing scenarios Before the suite fixes
GLM 5.2 14 / 14 10 / 14
Kimi K3 14 / 14 9 / 14
DeepSeek V4 Flash 0731 10 / 14 7 / 14

Two of the three candidates now pass every scenario. Treat the earlier column
as a measurement of the suite, not of the models.

Kimi K3's result here covers 14 scenarios. Over the whole catalog on
2026-09-17 it scored 454/480, the lowest of four models, for €25.16 — 7.7× the
glm-5.3 control and 24× glm-5.3-flash. It is not a candidate for any Lotti
route
; see LottiGym, four models.

Latency separates them further: on the clean matrix GLM completed the suite in
38 s with a 5.9 s worst case and Kimi in 159 s with an 18.9 s worst case, while
DeepSeek needed 760 s and stalled for 360 s on one scenario. Those stalls are
intermittent — the same scenario later finished in 7.5 s — so they are not a
stable model property and may be provider congestion.

DeepSeek V4 Flash 0731 is not viable for task-agent work, and its four
remaining failures survived every suite correction.

It invents tool names. On metadata_explicit it called set_task_estimate,
which does not exist, with {"estimate": "2.5"} where the real
update_task_estimate takes integer minutes — three times in five
observations. On progress_update it called update_task_status, where the
real name is set_task_status. It guesses the prefix in both directions,
which the registry invites by mixing set_task_title, set_task_language and
set_task_status with update_task_estimate, update_task_due_date and
update_task_priority. GLM and Kimi absorb that inconsistency; DeepSeek does
not.

Critically, it does not recover. Once the harness began returning the
dispatcher's real Unknown tool error, DeepSeek received it, did not retry
with the correct name, and published a report describing the task as
configured while the user's requested estimate was never set.

It also mutates what nobody asked for: update_task_priority twice on
progress_update, and on latest_deadline_wins only record_observations
and update_report, never setting the due date the scenario requires. Its
fourth failure, no_op_background_refresh, was an inferenceFailed after
195 s — infrastructure rather than judgement.

The suite's own defects

Seven checks were penalising correct behaviour. They are listed here because
each one silently lowered every model's score, and two of them contradicted
directives the same prompt gives the agent.

  1. Forbidden terms ignored negation. "The fix is not yet validated"
    scored identically to a claim that it was validated. All three models
    failed user_completed_item_resurfaced for this alone. Terms a correct
    report may name in order to rule out now live in forbiddenReportClaims,
    matched only in affirmative context, with a negation window on both sides —
    English negates before the claim, German after.
  2. spanish_mixed_context banned a correct status change, described
    below.
  3. metadata_explicit required the report to echo "P1" while the report
    directive forbids narrating metadata changes. The mutation is already
    asserted through expectedToolCalls.
  4. implicit_workflow_plan demanded the literal verb "implement", which
    passed only because an earlier fixture happened to contain
    "implementation"; "fix the seeding so empty profiles are no longer
    selectable" is the same step.
  5. deferred_scope_filter forbade "underway" on a task whose status is
    IN PROGRESS and whose log calls the certificate work active. The word was
    accurate.
  6. The harness confirmed fabricated tools. processToolCalls answered
    every call with "Eval harness accepted ", including names that do not
    exist, where TaskToolDispatcher returns an error the model can recover
    from. The harness now mirrors the dispatcher.
  7. HttpOverrides.global was never cleared, so the test binding failed
    every request with a synthetic HTTP 400 in under 100 ms and scored 0%. A
    run that trips the test timeout also discarded all artifacts; the timeout is
    now configurable and runs are executed per scenario.

spanish_mixed_context is a broken expectation, not a model failure. All three
models produced the identical sequence — add_multiple_checklist_items,
set_task_status, update_report — at 100% content quality, and all three
failed only because set_task_status is absent from allowedExtraToolNames.
The task's log says "Seguimos bloqueados porque el proveedor no ha enviado las
credenciales"
while its status still reads IN PROGRESS, so marking it
blocked with a grounded reason is correct behaviour. Correcting this scenario
raises every model by one: GLM 11, Kimi 10, DeepSeek 8.

user_completed_item_resurfaced failed for all three models, and
deferred_scope_filter for two of three, both on report content. The report
directive never states that an idea the user explicitly deferred must stay out
of the public report — deferred appears in seeded_directive_content.dart
only in reference to deferred tools and the deferred-proposal mechanism —
yet the suite asserts forbiddenReportTerms: ['newsletter'] against exactly
that unwritten rule. Kimi passes messy_german_transcript, so the rule is
inferable, but a rule only the strongest model infers belongs in the contract.

What the failures taught us about the suite

Five of the nine defects share one root cause: substring matching standing in
for semantic judgement.
It cannot see negation, cannot see paraphrase, and
fails precisely when a model expresses the right thing in unexpected words —
which capable models do more often, not less.

The other four have separate causes worth naming, because they will not be
caught by better matching. Two are scenario contracts that contradicted
directives the same system prompt issues, so a model was penalised for obeying
its instructions. One is harness fidelity: the runner accepted tools the
dispatcher rejects. Two are test infrastructure: leaked HttpOverrides and a
timeout that discarded results.

The practical rule for new scenarios: assert mutations through
expectedToolCalls, where the contract is exact, and keep report assertions
to facts that must appear rather than phrasings that must match. Use
forbiddenReportClaims for anything a correct report may legitimately mention
in order to rule out, and reserve forbiddenReportTerms for strings that must
never appear at all, such as internal identifiers.

  • Normalise the task-field tool names onto one prefix. This is now evidence-
    backed rather than speculative: DeepSeek fabricated names in both directions,
    and the registry's mixed set_*/update_* scheme is what invites it.
  • Leave the report directive alone. The deferred-scope rule looked like a
    prompt gap when three models failed those scenarios, but all three pass them
    once the checks stop matching negated mentions. There is no prompt change to
    make here.

Retaining GLM 5.2 as the high-end thinking model is supported by this run.
Nothing here re-opens the shipped Qwen/Mistral routing, which these scenarios
did not exercise.

Does the payload hold models back?

A 27B dense model ought to be able to help with a task, and on-device
assistants of that size are shipping. So the suite was used to ask whether the
request we send is what stops small models being useful.

The task agent receives about 21,000 characters of system prompt to act on
a task context of under 900 characters, and is offered 20 tools:

Component Chars Share
Tool Usage Guidelines 8,880 42%
Report scaffold 3,739 18%
Report directive 3,684 18%
Suggestion Hygiene 2,237 11%
Scaffold core 1,628 8%
General directive 1,508 7%
Soul and voice ~500 2%

LocalTaskAgentEvalPromptVariant.lean keeps every rule a correct wake depends
on — end with a report or nothing, stay grounded in the context, do not undo
the user's work, do not narrate your own process, write in the task's
language — and drops the tool-etiquette prose, most of which teaches the model
to avoid calls TaskToolDispatcher already rejects with an error. It also
advertises nine tools rather than twenty, chosen as what a wake generally
needs rather than what each scenario expects, so no scenario is handed its own
answer. The result is 1,216 characters and 9 tools.

Both variants, one sample per scenario at temperature 0:

Model Production payload Lean payload
Qwen3.6 27B (dense) 10 / 14 13 / 14
Qwen3.6 35B A3B (~3B active) 8 / 14 8 / 14

Two different bottlenecks. The dense model gains three scenarios from the
payload alone, reaching 13/14 — ahead of DeepSeek V4 Flash 0731 and one
scenario behind GLM 5.2. Capacity was not its limit; headroom was.

The mixture-of-experts model gains nothing, and four of its six failures are
argumentMismatch: it selects the right tool and fills the arguments wrong.
Shrinking the prompt cannot fix that, because argument precision is a capability
floor rather than an attention budget. If on-device ever becomes a target, that
is the wall, and it argues for narrower tools with simpler schemas rather than
shorter prose.

The lean variant changes prompt size, tool count and report contract together,
so it does not isolate which one carries the gain. Given the earlier
conciseReport result, both the tool-etiquette bulk and the report contract
plausibly contribute.

This measures scenario pass rates, not whether a model is pleasant to work with
over weeks. Maintainers report small models being poor in daily use while this
suite scores them near GLM, so the gap between the two remains the suite's main
blind spot.

Caveats

One sample per scenario on a backend that is not deterministic even at
temperature 0. Run-to-run variance is real and was observed repeatedly: a
fabricated tool call, a 305 s stall, and two of Kimi's failures all failed to
reproduce on a second sample. Treat single-scenario differences as noise and
only repeated, inspected failures as signal.

Findings from 2026-07-12

The production evidence-first contract was replicated with Qwen3.5 122B A10B
as the direct executor three times across the then-current 13-scenario suite:

Measure Result
Scenario runs 38 / 39
Deterministic checks 257 / 258
Required mutations 42 / 42
Unauthorized mutations 0
Input tokens 604,857
Output tokens 29,699
Average latency 5.792 s

The one failure omitted the deadline from a German report; the required task
mutations still succeeded. At that checkpoint, direct product, reliability, and
editorial review found the mutation behavior suitable for a default-off
experiment, while report prose remained more mechanical and occasionally less
conservative than the larger-model baseline. Qwen used its model or profile
reasoning default.

The final Mistral route kept Mistral as the only task-mutation executor and sent
new built-in reports to an isolated Qwen editor with compact, ID-free successful
mutation facts. The retained full run produced:

Measure Result
Scenarios 13 / 13
Deterministic checks 94 / 94
Report cases 11
No-op cases 2
Editor calls on no-op cases 0
Input tokens 168,653
Output tokens 10,341
Total latency 89.618 s

This establishes two explicit experimental selections rather than a silent
model substitution:

  • Qwen3.5 122B A10B directly executes task mutations and writes its report.
  • Mistral Small 4 119B executes task mutations; an isolated Qwen pass may
    replace its draft only after the known-regression checks accept it.

Both models are present in the curated Melious catalog and are selected through
the normal inference profile. The config flag supplies the evaluated prompt,
tool contract, and temperature-zero path. It preserves custom report directives
and does not claim parity on unsanitized real user histories. Full artifacts and
the GPT-5.6 Sol simulated expert review are kept
in the private evaluation archive under 2026-07-12_qwen35 and
2026-07-12_qwen-gated-editor-v31.

Release-candidate reproduction

The exact tree at commit 8413b6320 was rerun after Qwen became selectable in
the curated Melious catalog:

Route Scenarios Checks Input tokens Output tokens Latency
Qwen direct 10 / 13 90 / 94 164,822 11,862 86.714 s
Mistral executor + Qwen editor 13 / 13 94 / 94 172,443 12,923 96.801 s

Qwen still made every required mutation and no unauthorized mutation. Its three
failures were public-report grounding defects: a deferred newsletter remained
visible, an untouched certificate rotation was called underway, and a
resurfaced issue acquired unsupported deployment history. A focused prompt
addition passed 0/3 and was removed. Isolated Qwen and Mistral edits of Qwen's
drafts passed 1/3 and 2/3 respectively, so neither route was promoted.

The Mistral route again passed the full suite. Eleven scenarios produced
reports, two no-op scenarios made no editor call, and three reports required
one bounded repair. Direct GPT-5.6 Sol review through simulated product,
reliability, and editorial roles found the final reports concise, actionable,
and materially clearer than the Mistral drafts. The prose is intentionally
operational and still somewhat formulaic; the result establishes a viable
default-off release candidate, not parity with GLM 5.2 or proof on unsanitized
real task histories. Raw artifacts and the review are archived under
2026-07-12_release-candidate-8413b6320 in the private evaluation repository.

Evolved directives and implicit-plan reproduction

The directive-aware route was subsequently rerun on commit f9ee86f37 with
seven synthetic report contracts representative of evolution output. All seven
cases passed all 78 deterministic checks. The Mistral executor used 108,132
input and 9,038 output tokens; the isolated Qwen editor needed eight attempts
across seven reports. A same-commit regression of the original suite passed all
13 cases and all 94 checks with 175,229 input and 12,379 output tokens.

Live product testing then exposed a missing scenario: the user stated a
committed six-step workflow without saying "create a checklist". The original
agent required an explicit follow-up request. A focused held-out reproduction
now uses that natural wording and requires one batch containing implementation,
pull request, Gemini review, code review, merge, and multi-platform release.
The Mistral executor created all six actions on the first wake; Qwen replaced
its process-oriented draft with a grounded action report. The case passed all
15 checks using 16,044 input and 1,628 output tokens in 13.912 seconds. Its
artifact is archived locally under
2026-07-12_live-repro-implicit-workflow-r2 pending final release archival.

This focused result proves first-wake behavior for the reproduced wording. It
does not by itself establish convergence across arbitrary real histories. The
production workflow therefore also enforces report freshness after successful
mutations and persists the editor-route outcome in agent internals, while AI
consumption tests require distinct per-model events under the shared wake key.

Production-workflow reproduction

The inference-only fixture still did not cover production orchestration,
deferred checklist persistence, agent-internals routing, or AI Impact records.
The real TaskAgentWorkflow harness was therefore generalized for Melious and
changed to replay the screenshot-derived task text verbatim. It holds the
Riverpod inference repositories alive, captures persisted agent entities, and
records each AiConsumptionEvent generated at the conversation boundary.

Prompt-only Qwen iterations removed unsupported root-cause, reviewer-type, and
deployment claims but continued to emit process narration and absent-metadata
filler. Further prompt accretion was stopped. Direct Qwen reports now receive a
local known-regression preflight; clean drafts stay single-pass, while drafts
matching captured harmful patterns receive an isolated Qwen repair with exact
correction codes. This is not model self-rating, but it is also not general
semantic validation of arbitrary prose.

The final held-out app-path runs both created the six requested actions without
an explicit checklist request and passed content checks that reject checklist
or workflow narration, unsupported readiness, invented explanations, and empty
metadata commentary:

Route Result Calls Input Output Latency
Mistral executor + Qwen editor pass 2 Mistral + 2 Qwen 17,786 2,337 28.370 s
Qwen direct + conditional Qwen repair pass 3 Qwen 16,806 1,621 12.018 s

Every call has a distinct consumption UUID with its own provider model ID,
tokens, credits, and energy. The persisted route outcomes were
qwen_report_editor_accepted and
qwen_report_editor_direct_qwen_repaired. Final reports named the concrete
seeding fix, pull request, both review passes, merge, and all-platform release
without claiming that work had started. The retained artifacts are
2026-07-12_app-path-implicit-workflow-mistral-final3 and
2026-07-12_app-path-implicit-workflow-qwen-r4 in the private archive clone.

Final production-routing matrix

The exact production route at commit 8d34a3088 was rerun across the expanded
14-scenario suite for both selectable executors:

Route Scenarios Checks Total tokens Latency Editor attempts
Mistral executor + Qwen editor 14 / 14 112 / 112 232,322 145.458 s 16
Qwen direct + conditional repair 14 / 14 112 / 112 233,490 157.180 s 9

Five of twelve direct-Qwen report cases passed preflight without another model
call; seven triggered repair, and one used the full three-attempt bound. Direct
GPT-5.6 Sol review found Qwen's final reports richer and more natural, while the
Mistral route was more compact and conservative. The default Melious profile
therefore uses Qwen for thinking and retains Mistral as a selectable task-agent
executor and as the profile's multimodal vision model. Full generated outputs,
the manifest, and the direct review are archived privately under
2026-07-12_production-routing-8d34a3088-full-r4.

2026-08-08: the real-wake suite

Every result above was produced against a hand-written context. The harness
declared the task as a JSON blob — _taskDetailsJson carried an empty checklist
and a single log line restating the description — so the suite never measured
what the app actually asks a model to read.

penguin_wake_workflow_eval_live_test.dart runs the real TaskAgentWorkflow
over real in-memory databases and asserts on rows read back out: pending
proposals, the persisted report, the task itself. AiInputRepository assembles
the context exactly as the app does. The seeded wake carries fourteen checklist
items across three lists, six weeks of linked notes, logged time, a blocked
status, a due date and an estimate, and measures 9,004 characters against
the 921–2,207 the synthetic scenarios carried.

Scenario 1 — `requalification` (demo world, real prompt)

The wake is "Trace the humidity spike in Bay C", taken from
ManualDemoWorld.penguinLogistics — the fixture DemoSeeder writes on a user's
first run. Blocked, two labels, a four-item checklist with one already done.
The only authored addition is the closing note, which is how an instruction
actually reaches an agent. It reports the sensor swap and the seam walk done,
resolves the blocker, and leaves the write-up explicitly outstanding.

Everything the model reads is assembled by the app: seeded categories and
labels, EntitiesCacheService resolving them, AgentTemplateSeeding supplying
the directives, AgentTemplateService resolving the template through a real
templateAssignment link, and AiInputRepository building the context. 3,938
characters.

Three samples per model:

Model Passed Failure
Kimi K3 3 / 3 —
Qwen3.5 397B 3 / 3 —
Qwen3.6 27B 3 / 3 —
DeepSeek V4 Flash 0731 3 / 3 —
GLM 5.2 2 / 3 ran out of turns before proposing the status change

DeepSeek's first attempt at a third sample was lost to a five-minute provider
timeout; re-run, it passes, so it is 5/5 across completed runs.

GLM's one failure is a turn-budget problem rather than a reasoning one. Both its
runs call set_task_language twice — the task genuinely has no language, so the
first call is correct and the second is rejected by the single-use guard — and
both also call record_observations. In the passing run set_task_status still
fits; in the failing one it does not, and the report it publishes says so
outright: "the task is still marked blocked despite the log saying
'unblocked.'"
It saw the blocker resolve and ran out of turns before proposing
it. Its two checklist completions were the two supported ones in both runs.

Read it narrowly. One scenario, three samples, and four of five models are at or
near the ceiling — it separates broken from working, not good from better. The
earlier tables on this page were produced against an authored fixture with no
labels and, for a period, no general directive; this one was not.

Scenario 2 — `noOp`

Nothing materially changed. A correct wake proposes no data changes and does not
republish the report.

That rule is real and is what production sends. TaskAgentPromptBuilder
substitutes TaskAgentEvidenceSynthesis.reportDirective for every stock agent:

When no report exists yet or the report materially changed, call
update_report exactly once as the final action. Otherwise finish with a
brief plain-text note and do not republish unchanged content.

Model Passed
Qwen3.6 27B 3 / 3
GLM 5.2 1 / 3
Kimi K3 0 / 3
Qwen3.5 397B 0 / 3
DeepSeek V4 Flash 0731 0 / 3

No model proposed a data change, so the failure is narrow: four of five
republish an unchanged report. Their rewrites are paraphrases — all five
produced a one-liner saying "blocked on Ross Station customs".

Caveat on these numbers. The runs were made with the template's
generalDirective empty (1,509 characters absent). The report contract was
present — an empty directive still counts as built-in and is substituted — so
the rule under test reached the model. The result is very likely sound but one
variable differed from production, and it should be re-run with the full prompt
before being cited as final.

These results were once retracted in error. The retraction was based on
reading the seeded taskAgentReportDirective constant, which says the opposite
("You MUST call update_report … do not end your turn with a plain text
message") and is never sent to a stock agent — both an empty and a stock
directive are replaced by the evidence-synthesis version. A test now asserts the
built prompt, not the constant. Verify prompt rules against a built prompt.

Scenario 3 — `pendingProposal` (withdrawn, not a result)

This scenario was written to catch a model re-proposing a change already queued
and awaiting the user. It reported ten failures out of ten across five models.
That number was wrong and is retracted. It was measurement error twice over:

  1. The proposals were read from getPendingChangeSets after the wake, which
    still contains the change set the fixture seeded. Every run counted the
    fixture's own item as a model proposal. Filtering by the wake's run key
    removed that.
  2. The number did not move after the filter, because ChangeSetBuilder.build
    consolidates pre-wake pending sets into the set the wake creates and
    retires the originals. The seeded item is therefore carried into the wake's
    own change set legitimately, and an identical model proposal would have been
    dropped by deduplicateItems before it was ever persisted.

The second point is the substantive one: the app already prevents duplicate
proposals structurally
, through dedup against still-open items plus
consolidation. There was never a behaviour here for models to fail.

It also means the persisted change set cannot answer the question. Whether a
model called a redundant tool is only visible in its tool calls, not in what
survived the builder. The scenario now reads the action messages the wake
records — each carries metadata.toolName and metadata.runKey — which is the
model's actual behaviour rather than the builder's output.

On that instrument the scenario does discriminate:

Model Called set_task_status again
Kimi K3 no
Qwen3.6 27B yes
Qwen3.5 397B yes
DeepSeek V4 Flash 0731 yes
GLM 5.2 inconclusive (build race, see below)

Read it narrowly. Because dedup and consolidation already absorb the duplicate,
the user never sees it twice — so this measures wasted turns and payload, not a
user-visible defect. It is a reason to withhold the tool, not evidence of harm.

Runner note. Concurrent flutter test processes contend on
build/unit_test_assets, which surfaces as PathNotFoundException on
NativeAssetsManifest.json and is not a model failure.
scripts/penguin_wake_eval_matrix.sh warms the build once before fanning out
for this reason; ad-hoc parallel loops must do the same.

Narrowing the tool surface (results retracted)

narrowToolSurface was measured against noOp and reported as no better than
noise. That comparison is void because the staged exposure never ran: ConversationRepository passed
manager.turnCount to toolsForTurn, and that counts user messages with this
turn's already logged — so the first request arrived as index 1, not 0.
ConversationRepository passed manager.turnCount to toolsForTurn, and that
counts user messages with this turn's already logged — so the first request
arrived as index 1, not 0. TaskAgentStagedToolExposure treats only 0 as the
opening turn, so it restored the full list immediately. The flag-on runs
exercised the precondition gates alone.

Fixed and covered by a test that fails on the off-by-one. The flag stays off and
unmeasured.

The fixture was wrong first

The first noOp run failed on all five models, each proposing exactly
update_task_due_date: 2026-08-14. They were right. The variant had dropped the
note that supersedes the 07-24 extension request while leaving the due date
unmoved, so one genuine unfulfilled request remained in the context. The models
found it; the fixture was corrected to grant the extension in the prior wake.

Worth recording as method: a scenario every model fails deserves the same
suspicion as one every model passes. Read what they proposed before believing
the score.


2025 12 02 Sync Investigation (`docs/2025-12-02_sync_investigation.md`)

Sync Investigation - Root Cause Analysis

Date: 2025-12-02
Issue: Entries not syncing between devices after sync refactor (Sept-Oct 2025)

Executive Summary

The sync system underwent a major rewrite from September-October 2025. While the new architecture is more sophisticated (stream-first pipeline, typed metrics, retry with backoff), it introduced several reliability regressions that cause entries to be permanently skipped.

Key Findings

1. Retry Cap with Marker Advancement (`treatAsHandled`)

Location: lib/features/sync/matrix/pipeline/matrix_stream_consumer.dart:340-354

Problem: After _maxRetriesPerEvent (5 attempts), events are marked as treatAsHandled = true, which allows the read marker to advance past them - permanently skipping the event.

dart
if (nextAttempts >= _maxRetriesPerEvent && !isMissingAttachment) {
  treatAsHandled = true;  // THIS IS THE PROBLEM
  _retryTracker.clear(id);
  // ... event is now permanently skipped
}

Impact: Any event that fails 5 times (network issues, attachment not ready, processing errors) is lost forever.

2. Lazy Attachment Fetching Breaks Ordering

OLD CODE: saveAttachment() immediately downloaded and saved attachments when the attachment event arrived.

NEW CODE: AttachmentIngestor.process() only records the descriptor in an in-memory AttachmentIndex. Actual download happens later in SmartJournalEntityLoader._ensureMediaOnMissing().

Problem: If the sync payload event arrives before its attachment descriptor (due to Matrix event ordering), the entity processing fails because the attachment can't be found. After 5 retries, the entry is lost.

3. Fallback Tail Limit When Marker Not Found

Location: lib/features/sync/matrix/pipeline/matrix_stream_helpers.dart:134-152

OLD CODE: If marker not found, processed ALL events in timeline.
NEW CODE: If marker not found, falls back to only the last 30 events (tailLimit = 30).

dart
final slice = idx >= 0
    ? events.sublist(idx + 1)
    : events.sublist((events.length - tailLimit).clamp(0, events.length));

Impact: If device was offline for a while and the marker event is no longer in Matrix's local timeline, all events between the lost marker and the last 30 are skipped.

4. In-Memory State Loss

Problem: AttachmentIndex and RetryTracker are in-memory only. If the app crashes or restarts mid-sync:

  • Attachment descriptors that were indexed but not yet used are lost
  • Retry state is lost, but marker might have already advanced

5. Catch-up Pagination Limits

Location: lib/features/sync/matrix/pipeline/catch_up_strategy.dart

Problem: maxLookback = 4000 events. If more than 4000 events occurred since last sync, older events won't be caught up.

Comparison: Old vs New

Aspect Old Code New Code
Attachment handling Immediate download Lazy (index only)
Retry on failure No explicit retry cap 5 retries then skip
Marker not found fallback Process ALL events Process last 30 only
State persistence Minimal In-memory only
Failure recovery Retry on next sync cycle Permanent skip after cap

Fixes Applied (2025-12-02)

PR: https://github.com/matthiasn/lotti/pull/2485

Fix 1: Remove `treatAsHandled` Marker Advancement ✅ DONE

Changed matrix_stream_consumer.dart to keep retrying indefinitely instead of marking events as handled after retry cap. Failed events now block marker advancement forever until they succeed.

Fix 2: Increase Fallback Tail Limit ✅ DONE

Changed _liveScanTailLimit from 30 to 1000 in matrix_stream_consumer.dart:219.

Fix 3: Stop Dropping Failed Events in Filter ✅ DONE

Location: lib/features/sync/matrix/pipeline/matrix_stream_helpers.dart:162-194

Problem: filterSyncPayloadsByMonotonic() was dropping events that were "not newer" AND "had attempts". But having attempts > 0 doesn't mean the event was completed - it might have failed and needs retry!

Scenario:

  1. E1 (T=100) fails → attempts=1, marker stays before E1
  2. E2 (T=200) succeeds → attempts=0 (cleared), marker advances to E2
  3. Next scan: E1 is older than marker, has attempts → DROPPED forever!

Fix: Changed hasAttempts parameter to wasCompleted - now only drops events that were successfully completed, not events with pending retries.

dart
// OLD (buggy):
hasAttempts: (id) => _retryTracker.attempts(id) > 0,

// NEW (fixed):
wasCompleted: _wasCompletedSync,

Deferred Improvements

Priority 2: Restore Eager Attachment Download ✅ DONE (2025-12-02)

Modified AttachmentIngestor to eagerly download and save attachments when recording descriptors:

  • Added documentsDirectory parameter to AttachmentIngestor
  • Downloads attachment via event.downloadAndDecryptAttachment() when descriptor is recorded
  • Writes to disk using atomicWriteBytes() for safe file operations
  • Fast-path deduplication: skips download if file already exists and is non-empty
  • Graceful error handling: logs exceptions but doesn't throw (SmartJournalEntityLoader can retry later)
  • Path traversal protection: blocks attempts to write outside documents directory

Files modified:

  • lib/features/sync/matrix/pipeline/attachment_ingestor.dart - Added eager download logic
  • lib/features/sync/matrix/pipeline/matrix_stream_consumer.dart - Pass documentsDirectory to ingestor
  • lib/features/sync/matrix/matrix_service.dart - Pass getDocumentsDirectory() to consumer

Priority 2.5: Wake From Standby Detection ✅ DONE (2025-12-02)

Problem Identified: When a device wakes from standby after being asleep for >30 seconds, the live scan would immediately process recent events and advance the marker before a proper catch-up could process older events in the backlog. This caused events sent during standby to be permanently skipped.

Root Cause:

  1. Desktop wakes from standby after 15 minutes
  2. LiveScan runs immediately and processes only the tail of the timeline (30 events)
  3. Marker advances to the newest event
  4. CatchUp eventually runs but uses the NEW marker - missing older events

Fix Applied:

  • Added _wakeCatchUpPending flag and _standbyThreshold (30 seconds)
  • When a signal arrives after a gap > 30 seconds, detect "wake from standby"
  • Trigger an immediate catch-up and defer marker advancement until catch-up completes
  • Reset audit mode to scan larger tails on wake (3 scans with computed audit tail)

Files Modified:

  • lib/features/sync/matrix/pipeline/matrix_stream_consumer.dart
    • Added wake detection in _scheduleLiveScan()
    • Added marker deferral in _processOrdered() when _wakeCatchUpPending
    • New logging: wake.detected, wake.catchup.start/done, marker.deferred.wake

Priority 3: Persist Failed Event IDs (DEFERRED)

Store failed event IDs in the database (not just in-memory) so they can be retried after app restart:

dart
// Suggested: Add failed_sync_events table
class FailedSyncEvent {
  final String eventId;
  final DateTime firstFailure;
  final int attempts;
  final String? lastError;
}

Priority 4: Add "Missing Base" Detection (DEFERRED)

The code has JournalUpdateSkipReason.missingBase but it doesn't seem to block marker advancement properly for linked entries.

Files Modified

  1. lib/features/sync/matrix/pipeline/matrix_stream_consumer.dart

    • ✅ Removed treatAsHandled = true for retry cap (lines 342-355, 390-399)
    • ✅ Increased _liveScanTailLimit from 30 to 1000 (line 219)
    • ✅ Changed filter callback from hasAttempts to wasCompleted (line 915)
    • ✅ Added _wakeCatchUpPending flag and _standbyThreshold constant
    • ✅ Added wake detection in _scheduleLiveScan() with catch-up trigger
    • ✅ Added marker deferral in _processOrdered() when wake catch-up pending
  2. lib/features/sync/matrix/pipeline/matrix_stream_helpers.dart

    • ✅ Renamed hasAttempts → wasCompleted in filterSyncPayloadsByMonotonic
    • ✅ Updated filter logic to only drop completed events, not failed retries

Files to Modify (Deferred)

  1. lib/database/database.dart (or new file)

    • Add persistence for failed sync events
  2. lib/features/sync/matrix/smart_journal_entity_loader.dart

    • Improve handling when attachment not in index

Testing Recommendations

  1. Test offline scenario: Create entry on device A, wait for marker to advance, bring device B online after 50+ events - verify all entries sync
  2. Test attachment ordering: Send attachment descriptor after payload - verify entity is eventually synced
  3. Test app restart mid-sync: Kill app during sync, restart - verify no entries lost
  4. Test retry exhaustion: Simulate persistent failure - verify entry is NOT permanently skipped

Conclusion

The core issue is the introduction of treatAsHandled = true after retry exhaustion, combined with the lazy attachment fetching that creates ordering dependencies. The old code was simpler and more robust - it just processed everything it saw, downloading attachments eagerly, without complex marker-based skipping logic.


2026 08 10 Manual Accuracy Audit (`docs/2026-08-10_manual_accuracy_audit.md`)

Manual accuracy audit — English manual vs. source

Date: 2026-08-10
Scope: all 42 English pages under docs-site/docs/, verified against lib/
at commit 00b4ca3fe.
Method: every load-bearing claim (labels, counts, enumerations, thresholds,
security properties, navigation paths) was checked against the implementing
source file. Findings below carry the file and line that establishes them.

Translations were not audited. Every prose fix in section 1 must be applied
to the ten non-English trees under
docs-site/i18n/<locale>/docusaurus-plugin-content-docs/current/ as well —
make manual_check rejects a translated tree whose page set diverges from
English, but it cannot notice that a translated sentence still states the old
fact.


Summary

Section Count Nature
1. Factual errors 7 (§1.4 covers two) Wrong or incomplete statements that will mislead a reader
2. Verified correct 19 Claims checked and confirmed — recorded so the audit is falsifiable
3. Gaps and weak explanations 8 Accurate but unhelpful, or missing entirely
4. Notable strengths 2 Worth preserving as the house style

The error rate is concentrated in labels, lists and navigation paths, not in
mechanics. Where the manual explains how something works, it is reliably
right; where it names a thing or enumerates options, it has drifted.


1. Factual errors

1.1 The transcription language list is wrong

Page: docs-site/docs/plan-and-capture/recordings.mdx

"The language selector currently offers Auto, English, and Deutsch."

Reality: the dropdown renders auto plus every SupportedLanguage
value — 42 languages, Arabic through Yoruba.

  • lib/features/journal/ui/widgets/entry_details/speech_modal/language_dropdown.dart:43-54
    — DropdownButton items are the literal auto entry followed by
    ...SupportedLanguage.values.map(...).
  • lib/classes/supported_language.dart:5-46 — 42 enum values.

Impact: highest in the manual. A Portuguese, Japanese or Swedish speaker
reads this and concludes Lotti cannot transcribe their speech.

Fix: state that the selector offers automatic detection plus the full
supported-language list, and do not enumerate it in prose (it will drift again).


1.2 The Language setting is under-described and under-counted

Page: docs-site/docs/reference/advanced-settings.mdx, "Choose the Manual
language"

"Open Language to decide which published Manual the app opens. Follow
system
is the default and chooses the English, German, French, Italian,
Spanish, Czech, Romanian, or Portuguese Manual from your device language."

Two errors:

(a) It lists 8 languages; the app offers 11. Dutch, Danish and Swedish are
missing.

  • lib/providers/manual_language_controller.dart:20-32 — the
    ManualLanguage enum: english, german, french, italian, spanish, czech, dutch, romanian, portuguese, danish, swedish.
  • lib/features/settings/ui/pages/advanced/manual_language_settings_page.dart:43-125
    — the page renders "Follow system" plus all eleven.

(b) The setting changes Lotti's own UI language, not only the manual link.
The manual never says this.

  • lib/beamer/beamer_app.dart:1298, :1318, :1340 — the stored override is
    read and passed as locale: to the app's localized widget tree.
  • lib/providers/manual_language_controller.dart:10-14 — "The
    stored key intentionally retains its original name so existing user
    preferences keep working after the setting began controlling Lotti's UI."
  • lib/l10n/app_en.arb:5037 — the in-app subtitle already says it: "Use your
    device language in Lotti and the Manual when it is supported."

Impact: a user looking for "how do I change the app's language" will never
find this page, because the manual describes it as a documentation-link setting.

Fix: retitle the section (it is "Language", not "Manual language"), lead with
the app-language effect, and replace the enumeration with a pointer to the
in-app list.


1.3 Two pages contradict each other on theming

  • docs-site/docs/reference/settings.mdx — "Appearance for light, dark, and
    automatic display modes plus independent theme palettes."
  • docs-site/docs/reference/appearance.mdx — "Lotti ships a single carefully
    tuned theme with a light and a dark rendition, so the only choice to make is
    which of the two the app should use."

The code agrees with appearance.mdx:

  • lib/features/theming/README.md — "There is exactly one theme — the design
    system's — built for each brightness."

Fix: delete "plus independent theme palettes" from settings.mdx.


1.4 Settings paths that do not exist as written

Two distinct problems live here: pages that name the destination wrongly, and
pages that send the reader to a leaf that is switched off by default.

(a) Wrong or incomplete names. Categories, Labels, Habits, Dashboards and
Measurables all hang off Settings → Definitions rather than off the Settings
root — though only three of the five are always present, see (b):

  • lib/features/settings/domain/settings_tree_data.dart:206-242 — the
    definitions branch and its five declared leaves.
  • lib/features/settings/domain/settings_tree_index.dart:36-61 — leaf ids
    are namespaced definitions/… while their deep-link URLs stay flat.
Page Says Actual
organize-and-reflect/dashboards.mdx "Settings → Dashboard management" No such string exists. Leaf is "Dashboards" (app_en.arb:4889)
organize-and-reflect/habits-and-measurables.mdx "Settings → Measurable data types" Leaf is "Measurables" (app_en.arb:5097)
categories.mdx, labels.mdx, habits-and-measurables.mdx, daily-os.mdx "Settings → Categories / Labels / Habits" Correct destination, but omits the Definitions branch
models-and-profiles.mdx, surveys.mdx "Settings → Definitions → …" Correct — and inconsistent with the four pages above
sync.mdx, conflicts.mdx, maintenance.mdx "Settings → Sync" Section is "Sync Settings" (app_en.arb:5071); add-device.mdx gets this right
events.mdx "Settings → Advanced → Flags" "Advanced Settings → Config Flags" (app_en.arb:4742, :4895); advanced-settings.mdx gets this right

(b) Two of those leaves do not exist on a default install. The Habits and
Dashboards leaves are config-gated, and both flags ship off:

  • lib/features/settings/domain/settings_tree_data.dart:226, :232 —
    if (enableHabits) and if (enableDashboards) wrap the two leaves.
  • lib/features/settings/ui/settings_tree_builder.dart:22-25 — both are fed
    from configFlagProvider(enableHabitsPageFlag) /
    configFlagProvider(enableDashboardsPageFlag).
  • lib/database/journal_db/config_flags.dart:75-85 — both are seeded
    status: false.

Neither dashboards.mdx nor habits-and-measurables.mdx mentions the flag
anywhere. A reader on a fresh install follows the path and finds nothing —
which the naming sweep alone would not fix, since it would merely replace one
unreachable path with another.

events.mdx is the model to copy. It is listed above only for its path
wording; its handling of the precondition is exactly right:

"Events are currently an optional feature. Open Settings → Advanced →
Flags
and turn on Enable Events. The Events destination then
appears in the desktop sidebar and under More on mobile."

Impact: higher than the naming drift. A wrong label still lands the reader
in Settings; a path to a disabled leaf leaves them concluding the feature does
not exist.

Fix: two passes, not one.

  1. One naming sweep, using the exact parent path for each destination rather
    than a single form applied everywhere — the three branches differ:

    Parent path Pages to correct
    Settings → Definitions → <leaf> categories.mdx, labels.mdx, habits-and-measurables.mdx, daily-os.mdx, dashboards.mdx (5)
    Settings → Sync Settings → <leaf> sync.mdx, conflicts.mdx, maintenance.mdx (3)
    Settings → Advanced Settings → Config Flags events.mdx (1)

    sync.mdx needs care: it already uses the correct form twice (:27, :45)
    and the wrong one once (:15), so this is not a blind find-and-replace.

  2. Give dashboards.mdx and habits-and-measurables.mdx the events.mdx
    treatment — state the flag and how to turn it on before giving the path.
    This is content work, not a find-and-replace.


1.5 The manual says "Journal"; the app says "Logbook"

The whole of docs-site/docs/organize-and-reflect/journal.mdx — a page titled
"Keep a useful journal" — plus the index page and the keyboard-shortcuts table
call the destination the Journal. The app calls it the Logbook:

  • lib/l10n/app_en.arb:4142 — "navTabTitleJournal": "Logbook".
  • Used at lib/beamer/beamer_app.dart:1041 (sidebar destination),
    lib/features/journal/ui/pages/infinite_journal_page.dart:236 (page title),
    and lib/features/keyboard/domain/app_command_text.dart:33 (the ⌘6 command
    reads "Go to Logbook").
  • Renamed in commit aa71e3ec6 (2023-05-15, "Journal tab renamed to Logbook").
    The manual was authored in 2026 and never picked it up.

Related naming drift in the same family:

  • The Daily OS tab label is "DailyOS" (app_en.arb:4138); the manual writes
    "Daily OS" throughout.
  • keyboard-shortcuts.mdx says "Open Dashboards, Journal, Events, or
    Settings"; the destination is labelled Insights (app_en.arb:4141).
    dashboards.mdx gets this right ("Open Insights").

Fix — documentation side, no decision required. Wherever the manual names
the destination or the keyboard command, it must say Logbook, because
that is the shipped label: journal.mdx, index.mdx and the
keyboard-shortcuts.mdx ⌘6 row. Likewise Insights for ⌘5 and DailyOS
for the tab. Do this regardless of how the question below is settled.

The generic noun stays untouched: "journal entries", "your journal" and the
page title "Keep a useful journal" describe the data and the practice, not the
tab, and the app uses "journal" that way too — JournalEntity
(lib/classes/journal_entities.dart:115) and JournalDb
(lib/database/database.dart:109).

Open question — needs a product owner, not an audit. Whether the tab should
revert to "Journal" is a naming decision this document cannot make. Note that
the app is itself undecided: the ARB key is navTabTitleJournal while its
value is "Logbook" (app_en.arb:4142). Until someone rules, the manual follows
the shipped label per the paragraph above.


1.6 `sync.mdx` names a page that has been renamed

Page: docs-site/docs/sync-and-data/sync.mdx

"Sync node profile identifies the current device to the rest of the sync
group."

The page is titled "This device", subtitled "Device name and capabilities":

  • lib/l10n/app_en.arb:5150 — "settingsSyncNodeProfileTitle": "This device".
  • lib/l10n/app_en.arb:5149 — "settingsSyncNodeProfileSubtitle": "Device name and capabilities".

1.7 The agent auto-apply exception is wider in code than in the manual

Pages: docs-site/docs/index.mdx:101,
docs-site/docs/getting-started/mental-model.mdx:69

"The only narrow exceptions are an initial title or language for an
otherwise empty task."

Reality: the guard is per field, not per task. Nothing tests whether
the rest of the task is empty:

  • lib/features/agents/workflow/task_agent_change_handlers.dart:506-524 —
    _shouldAutoApplyInitialField(read) resolves a TaskMetadataSnapshot, then
    returns current == null || current.isEmpty for the single field read
    selects.
  • lib/features/agents/workflow/task_agent_strategy.dart:345-348 — the two
    call sites pass (s) => s.title and (s) => s.languageCode.
  • The implementation comment says so plainly: "when the task has no title
    yet", and "the very first set_task_language on a task with no language
    yet" (task_agent_strategy.dart:330-341).

So a task with a description, checklists and logged time — but no language set
— will have an agent's first set_task_language applied without
confirmation
. The same holds for a populated task whose title is blank.

Impact: this is the manual's central trust claim, and it is the one place
where being wrong costs the most. The promise as written is narrower than the
code, which is the dangerous direction: a reader who believes "otherwise empty
task" will not expect a silent change to a task they have been working on.

Fix: state the actual condition — the field being set is empty, and it is
the agent's first use of that tool on the task (canUseInitialAutoApply,
task_agent_strategy.dart:342). Do not describe it in terms of the task being
empty.

Note: this row was originally certified under §2 and was wrong; it was
moved here after review.


2. Verified correct

Recorded so this audit is falsifiable and so a future reader does not re-check
the same ground.

The list is not infallible: the agent auto-apply row was originally certified
here and turned out to be wrong under review. It now sits at §1.7. Treat a row
as a pointer to the evidence, not as a substitute for it.

Claim Page Evidence
⌘1–8 destinations, ⌘K palette, ⌘N text, ⌘T task, F1 / ⌘? help keyboard-shortcuts.mdx lib/features/keyboard/domain/app_command_catalog.dart:7-187
Four priorities P0–P3, unset behaves as P2 tasks.mdx lib/classes/task.dart (TaskPriority, fallback: TaskPriority.p2Medium)
Automatic updates bundle changes "for about two minutes" task-agents.mdx lib/features/agents/wake/wake_orchestrator.dart:323 — throttleWindow = Duration(seconds: 120)
Daily OS drag/resize snaps to 15 minutes daily-os.mdx lib/features/daily_os_next/ui/widgets/day_timeline_block.dart:60
Dashboard ranges 30 / 90 / 180 / 365 days dashboards.mdx lib/widgets/misc/timespan_segmented_control.dart:15
Habit outcomes Success / Missed / Skip habits-and-measurables.mdx lib/classes/entity_definitions.dart:46; labels at app_en.arb:1867-1869
Five aggregations incl. hourly sum habits-and-measurables.mdx lib/classes/entity_definitions.dart:44
PANAS: 20 affect words, five-point scale, separate positive/negative totals surveys.mdx lib/features/surveys/definitions/panas_survey.dart:8-95
Celebration styles Sparks/Fireworks/Confetti/Embers/Bubbles + Random + Combine two completion-celebrations.mdx celebration_variant.dart:11-29; celebration_selection.dart:36-41
Six health-import families, mobile only health-import.mdx lib/features/settings/ui/pages/health_import_page.dart:27-28, :348-385
Supertonic 3; ten voices F1–F5 / M1–M5; speed 0.5×–2× speech.mdx tts_model_option.dart:52-62; tts_voice.dart:41-56; tts_settings.dart:12-26
Onboarding providers: Melious / Mistral / Gemini / Qwen first, OpenAI + Ollama under More options onboarding.mdx lib/features/onboarding/ui/widgets/onboarding_connect_panel.dart:13-24
Pairing check code derives from account, room and homeserver only — not the password — and is a recognition aid, not a security control add-device.mdx lib/features/sync/models/pairing_check_code.dart:18-29
Closing the Add-device sheet does not revoke the code add-device.mdx provisioning_controller.dart:301-317 — regenerateHandover re-encodes the current password; no rotation
A fresh provisioning bundle rotates the account password; handover bundles do not first-device.mdx provisioning_controller.dart:134-142, :209-224
Time Analysis merges overlaps per (day, category), splits at local midnight, surfaces Uncategorized time-analysis.mdx lib/features/insights/logic/time_bucketing.dart:46-140
Period units Day/Week/Month/Quarter/Year time-analysis.mdx lib/features/insights/model/insights_models.dart:131
Knowledge graph is desktop-only tasks.mdx lib/features/tasks/ui/task_expandable_app_bar.dart:37-40
Theme mode syncs across devices appearance.mdx lib/features/theming/state/theming_controller.dart (enqueues SyncMessage.themingSelection); features/theming/README.md

3. Gaps and weak explanations

3.1 Demo mode is effectively undocumented

lib/features/demo/ is a substantial user-facing feature: a separate sandbox
world with its own databases, three entry points (onboarding welcome, tasks
empty state, Settings → Onboarding), a persistent banner, and an exit sheet that
copies demo-created tasks, entries and AI setup into the real journal. Reset
and Delete are separate settings actions.

  • lib/features/demo/README.md:1-33 documents all of the above.

The manual mentions it only inside a :::note aside about penguins on
index.mdx, plus one line in onboarding.mdx.

It is almost entirely absent from docs-site/metadata/surface-inventory.json,
whose stated scope is "every major workflow that creates or materially changes
user data or cross-cutting configuration."
Exactly one demo-adjacent row
exists — settings-sync-unavailable, "Sync unavailable (demo world)". The
entry points, banner, exit sheet and copy-over flow have no rows at all.

That single row is also the inventory's only unverified one. Of 103 surfaces,
102 are verified and it is documented, and
validate-manual.mjs:172-174 errors on any surface that is not verified
under --require-complete. So the gate does not currently pass:

console
$ npm --prefix docs-site run coverage:complete   # exit 1
Manual validation failed with 1 error(s):
- settings-sync-unavailable is documented; complete coverage requires verified.

The blind spot is therefore not that the gate is green while demo mode is
undocumented — it is that the gate can only ever fail on a row someone
remembered to add. The release gate measures the inventory, not the app, so
the entire demo feature stays outside the count no matter what the command
reports.

Recommendation: a page under "Start here" covering enter / explore / exit /
copy-over / reset / delete, plus inventory entries for the three entry points,
the demo banner, the exit sheet and the real-AI setup sheet.


3.2 `skills.mdx` is vague where it should be concrete

"tasks can offer text and task-context actions; audio entries can offer
transcription and audio-aware actions; …"

This tells a stuck user nothing. The live skill set is exactly five:

  • lib/features/ai/state/consts.dart:113-119 — enum SkillType { transcription, imageAnalysis, imageGeneration, promptGeneration, imagePromptGeneration }.
  • lib/features/ai/state/skill_trigger_providers.dart:60-64 — the five types
    the trigger provider offers.
  • taskSummary and checklistUpdates are legacy and hard-blocked from
    executing: consts.dart isLegacyType, enforced at
    lib/features/ai/repository/unified_ai_inference_repository.dart:111-118.

Naming the five would let a reader distinguish "my profile is misconfigured"
from "that action does not exist".


3.3 The human-approval promise needs one stated condition

onboarding.mdx:

"When structuring produces checklist suggestions, they arrive on the task as
proposals for you to confirm instead of changing the task silently."

True only when the chosen category has a default agent template.
_assignCategoryAgent returns early when category.defaultTemplateId == null,
and the structured checklist is then dropped — not applied, not proposed:

  • lib/features/onboarding/services/onboarding_capture_to_task_service.dart:283-284
    — final templateId = category?.defaultTemplateId; if (category == null || templateId == null) return;, guarding the call to _seedChecklistProposals.

The onboarding flow itself is not the way to reach this, contrary to an
earlier draft of this section. Every category onboarding touches gets Laura
bound as its default template whenever a profile was seeded, including
"Add your own" ones — _addOwn merely appends to _custom
(onboarding_welcome_modal.dart:541-547), which _options folds into the same
list (:511) that _continue processes through one code path:

  • onboarding_welcome_modal.dart:615 — new categories are created with
    defaultTemplateId: profileId != null ? lauraTemplateId : null.
  • :589-596 — reused categories get Laura too, when they have no template yet.

And when no profile was seeded, automaticInferenceEnabled is left null
(:624) so nothing structures in the first place — there is no suggestion to
drop.

The reachable case is a category created outside onboarding.
createCategory leaves defaultTemplateId null unless a caller sets it
(lib/features/categories/repository/categories_repository.dart:113-119), and
the Settings form does not require one. A task in such a category, structured
by an agent, drops its checklist silently — no proposal, no error.

So the condition is worth stating, but as "the task's category needs a default
agent template", not as an onboarding caveat.


3.4 `first-device.mdx` buries its prerequisite

The page opens with the matrix_provisioner CLI and --admin-user. The
sentence a normal reader needs — if you do not run a Matrix homeserver, this
path is not available to you
— arrives in paragraph three as "ask the person
who operates the server". State the prerequisite in the first paragraph.


3.5 The manual never says what actually syncs

sync.mdx says "supported data" and stops. Verifiable facts that belong in a
short table:

The synced set is the SyncMessage union in
lib/classes/sync/sync_message.dart. Enumerating it is the only way to
get this right, and it is considerably wider than "entries and definitions":

Syncs Stays on the device
Journal entries and tasks (journalEntity:73), entry links (entryLink:116), definitions — categories, labels, habits, dashboards, measurables (entityDefinition:111), AI configs and their deletions (aiConfig:131, aiConfigDelete:158), saved task filters and their deletions (savedTaskFilter:168, savedTaskFilterDelete:174), config flags (configFlag:178), theme mode (themingSelection:185), sync node profiles (syncNodeProfile:141), Daily OS user name (dailyOsUserName:199), notifications and their read state (notification:205, notificationStateUpdate:214), task agents and their links (agentEntity:352, agentLink:370), AI consumption events — tokens, cost, energy (consumptionEvent:389) TTS voice and speed, pane widths, AI concurrency, agent throttle deadlines, day-planning exclusions

Two caveats a writer needs. First, the remaining variants — backfillRequest,
mediaRequest, outboxBundle, the onboardingSnapshot* family — are
transport machinery, not user data, and should not appear in a user-facing
table. Second, not everything that syncs is journal data: syncNodeProfile and
dailyOsUserName are explicitly "device-preference value, not journal data"
and skip gap detection (:137-140, :195-198), and derived task counts are
never sent even though the filter that produces them is (:167).

  • Theme: lib/features/theming/state/theming_controller.dart (enqueues a sync
    message); features/theming/README.md — "Device-local preferences … do not
    sync; the theme does."
  • Throttle state: lib/features/agents/wake/wake_throttle_coordinator.dart:82
    — "throttle state is per-device and should NOT be synced to other devices."
  • TTS: lib/features/tts/model/tts_settings.dart (SettingsDb keys, no sync
    message) — speech.mdx already says the voice is device-local, which is
    correct.

This is likely the single most useful addition available to the sync section.


index.mdx sets the bar:

"choose a provider only after checking its retention, training, jurisdiction,
and account settings."

onboarding.mdx then names Melious.ai "the recommended EU-hosted default
with dynamic model routing" and supplies none of those four facts.

In code Melious is an ordinary third-party provider with its own base URL and
API key (lib/features/ai/repository/melious_inference_repository.dart); the
in-app tagline is "EU-hosted · dynamic catalog · eco routing"
(app_en.arb:1395). Nothing is wrong with the integration. The problem is
editorial: a page that sets a due-diligence bar and then clears it for nobody
reads as an endorsement without evidence.

Recommendation: one sentence on who operates Melious, its retention policy,
and Lotti's relationship to it — or drop the word "recommended".


3.7 The roadmap describes unshipped features in the present tense

roadmap.mdx:

"Relationship data gets the strictest treatment Lotti has: it is stored
locally on your devices, never on a Lotti server."

The page header disclaims the whole page, but a paragraph read in isolation —
or quoted — is a shipped privacy guarantee about a feature that does not exist.
Use future tense consistently ("will be stored").


3.8 `manual-maintenance.mdx` is contributor documentation in a user sidebar

make manual_check, R2 buckets, screenshot-cases.json, the release-gate
command. All accurate; wrong audience for the final entry under "Reference".
Consider moving it to docs-site/README.md or CONTRIBUTING.md and linking it
from the manual footer.


4. Notable strengths — preserve these as house style

sync-and-data/add-device.mdx is unusually good security writing. It
separates the check code (recognition) from emoji verification
(authentication), states plainly that the check code says nothing about who
is on the other end, and warns that closing the sheet hides but does not revoke
the code. All three match the source exactly
(pairing_check_code.dart:18-21, provisioning_controller.dart:301-317).

sync-and-data/health-import.mdx explains why a permission prompt cannot
be re-raised — Apple deliberately does not tell an app whether it may read a
type — instead of saying "check settings". That is the difference between
documentation and a FAQ.


Suggested fix order

  1. §1.7 first, then §1.1, §1.2 and §1.4(b). §1.7 is the human-approval
    promise and the only finding where the manual under-states what the app
    will do without asking; the other three mislead about what the product can
    do or where it can be reached.
  2. §1.3, §1.4(a), §1.5, §1.6 — one naming and navigation sweep across the
    English tree, then the ten translated trees.
  3. §3.1 — demo mode page plus surface-inventory entries. Note that this
    does not "make the gate pass": the gate already fails on
    settings-sync-unavailable, and adding demo rows adds work rather than
    removing it. The point is coverage, not a green command.
  4. §3.5, §3.2, §3.3 — content additions where the manual is accurate but
    unhelpful.
  5. §3.4, §3.6, §3.7, §3.8 — editorial.

Items 1 and 2 require the same edit in
docs-site/i18n/<locale>/docusaurus-plugin-content-docs/current/ for all ten
non-English locales. Run make manual_check afterward; note that it validates
page-path parity and rejects untranslated copies, but cannot detect a
translated sentence that still asserts the old fact.


ARCHITECTURE (`docs/ARCHITECTURE.md`)

Lotti Architecture

Table of Contents

Overview

Lotti is a privacy-first personal assistant built with Flutter, featuring local-first data storage, AI integration, and end-to-end encrypted synchronization. The architecture prioritizes data ownership, privacy, and extensibility while providing powerful AI capabilities.

Core Principles

  1. Local-First: All data is stored locally using SQLite, with no cloud dependency
  2. Privacy by Design: User content leaves a device only for AI inference you configured or user-enabled end-to-end encrypted Matrix sync, both of which can then run automatically. Sync homeservers receive, store and relay ciphertext plus the associated account and traffic metadata; see PRIVACY.md for the precise boundaries
  3. Modular Architecture: Features are organized as independent modules with clear boundaries
  4. Provider Agnostic: AI capabilities work with multiple providers (OpenAI, Anthropic, Gemini, Ollama)
  5. Cross-Platform: Single codebase for iOS, macOS, Android, Windows, and Linux

High-Level Architecture

text
┌─────────────────────────────────────────────────────────────┐
│                        UI Layer (Flutter)                    │
├─────────────────────────────────────────────────────────────┤
│                     Feature Modules                          │
│  ┌──────────┬────────────┬──────────┬──────────────────┐   │
│  │ Tasks    │ Agents     │ Journal  │ Habits & Health  │   │
│  ├──────────┼────────────┼──────────┼──────────────────┤   │
│  │ Audio    │ Categories │ Sync     │ Settings         │   │
│  └──────────┴────────────┴──────────┴──────────────────┘   │
├─────────────────────────────────────────────────────────────┤
│                     Core Services                            │
│  ┌──────────────┬───────────────┬──────────────────────┐   │
│  │ Database     │ AI Providers  │ Audio Processing     │   │
│  │ (SQLite)     │ Integration   │ (Whisper)           │   │
│  └──────────────┴───────────────┴──────────────────────┘   │
├─────────────────────────────────────────────────────────────┤
│                  Infrastructure Layer                        │
│  ┌──────────────┬───────────────┬──────────────────────┐   │
│  │ Persistence  │ Encryption    │ Background Tasks     │   │
│  │ & Migration  │ (Matrix Sync) │ & Notifications      │   │
│  └──────────────┴───────────────┴──────────────────────┘   │
└─────────────────────────────────────────────────────────────┘

Feature Modules

AI Integration

  • AI Module: Core AI provider abstraction and configuration
  • Agents: Scoped assistants, improvement flows, and shared text/voice conversation UI

Content Management

  • Tasks: Task lifecycle management with AI-enhanced summaries
  • Journal: Text and audio journal entries with transcription
  • Categories: Organize content with configurable AI providers per category

Audio & Speech

  • Speech: Audio recording and transcription using Whisper or cloud providers

Data & Visualization

  • Calendar: Time-based views of entries and activities
  • Dashboards: Analytics and insights from collected data
  • Habits: Habit tracking and completion monitoring
  • Surveys: Custom questionnaires and assessments

System Features

  • Settings: Configuration management and preferences
  • Sync: End-to-end encrypted synchronization via Matrix (requires Matrix account - self-hosted or public homeserver)
  • Tags: Flexible tagging system for organization
  • User Activity: Activity tracking and analytics

Data Flow

1. Local Data Storage

text
User Input → SQLite Database → UI Updates

All user data is stored in a local SQLite database with support for:

  • Full-text search
  • Efficient querying
  • Data export/import
  • Incremental backups

2. AI Processing Pipeline

text
User Request → Category Config → Provider Selection → API Call → Response Processing
  • Users can configure different AI providers per category
  • Requests are routed to the appropriate provider
  • Responses are processed and stored locally
  • No data retention on provider side (with appropriate plans)

3. Synchronization

text
Local Changes → Encryption → Matrix Protocol → Other Devices
  • Changes are encrypted locally
  • Transmitted via Matrix's decentralized network
  • Decrypted on receiving devices
  • Conflict resolution handled automatically

AI Provider Architecture

Provider Abstraction

The system supports multiple AI providers through a unified interface.

Note: The interface below is conceptual to illustrate the design. The production code uses configuration models such as AiConfigInferenceProvider and repositories (for example lib/features/ai/conversation/conversation_repository.dart) to orchestrate requests and streaming.

dart
abstract class AiProvider {
  Stream<String> sendMessage(String message, List<Message> context);
  Future<String> transcribe(AudioData audio);
  bool get supportsStreaming;
  bool get supportsAudio;
}

Error handling and retries

  • Provider‑specific error parsing (e.g., model not found, rate limits) with user‑friendly messages
  • Exponential backoff for transient errors; fail fast for configuration issues
  • Optional fallbacks between configured providers when applicable

Supported Providers

  1. OpenAI: GPT-4, GPT-3.5, Whisper
  2. Anthropic: Claude 3.5, Claude 3
  3. Google: Gemini Pro, Gemini Flash
  4. Ollama: Local models (Llama, Mistral, etc.)
  5. OpenAI-Compatible: Any provider with compatible API

Configuration Management

  • Per-category provider selection
  • API key management (stored securely)
  • Model selection within providers
  • Fallback strategies for failures

Security Architecture

Data Protection

  • At Rest (today): Local databases are stored as plain SQLite. We recommend enabling full‑disk/device encryption (e.g., FileVault on macOS, BitLocker on Windows, File‑based encryption on Android, LUKS on Linux)
  • In Transit: TLS for all network communication
  • Sync: End-to-end encryption via Matrix
  • AI Calls: HTTPS with API key authentication

Key Storage (API keys and secrets)

Lotti uses OS‑backed secure storage via flutter_secure_storage:

  • iOS: Keychain Services
  • macOS: Keychain Services
  • Android: Android Keystore (keys) with encrypted SharedPreferences
  • Windows: Credential Locker (DPAPI)
  • Linux: Secret Service (libsecret; via GNOME Keyring/KWallet depending on environment)

Secrets stored in secure storage include AI provider API keys, the GitHub token, and the sync login config (homeserver, user, password). The live Matrix session is not among them: the access token, refresh token and Olm identity sit in the Matrix SDK's unencrypted SQLite database (see security and privacy).

Data at Rest (Databases)

  • Current state: SQLite databases (Drift) are stored unencrypted
  • Recommended mitigation: rely on OS/device full‑disk encryption and user account protections
  • Roadmap: optional database‑level encryption for SQLite (SQLCipher)

Backups

  • Secret backup/restore is delegated to the OS keystore.
  • On iOS and macOS, Lotti stores secrets non‑synchronizable: SecureStorage (lib/services/secure_storage.dart) passes only accountName to IOSOptions/MacOsOptions, and flutter_secure_storage defaults synchronizable to false. API keys and Matrix credentials therefore stay on the device and are not copied to iCloud Keychain. Enabling iCloud sync for them would require setting synchronizable: true explicitly.
  • Consequence: reinstalling or moving to a new device does not carry secrets across — they are re-entered, or arrive through device pairing.

References (platform APIs/libraries)

  • Flutter secure storage: https://pub.dev/packages/flutter_secure_storage
  • Apple Keychain Services (iOS/macOS)
  • Android Keystore System + EncryptedSharedPreferences
  • Windows Data Protection API (Credential Locker)
  • Linux Secret Service (libsecret)

Privacy Controls

  • No telemetry or analytics
  • No vendor/cloud accounts required for core functionality (local-only use)
  • Multi-device sync requires a Matrix account (self-hosted or public homeserver) - no vendor lock-in as Matrix is decentralized
  • AI processing is opt-in per category; enabling it is the consent, after which agents and transcription can call the configured provider without a further prompt
  • Neither content nor secrets leave the device except to destinations the user configured — the sync homeserver and the AI providers they chose. Secrets are stored non‑synchronizable, so they are not carried out by OS keychain sync either (see Backups)

Testing Strategy

Unit Tests

  • Core business logic
  • Data models and serialization
  • Service layer functionality
  • See repository Codecov badge for current coverage

Integration Tests

  • Database operations
  • AI provider communication
  • Sync functionality
  • Platform-specific features

Widget Tests

  • UI component behavior
  • User interaction flows
  • State management
  • Accessibility compliance

Build & Deployment

Code Generation

bash
make build_runner  # Generate code for serialization, routing, etc.

Platform Builds

  • iOS/macOS: Xcode, TestFlight distribution
  • Android: Gradle, APK/AAB generation
  • Windows: MSIX packaging
  • Linux: Flatpak, AppImage, tar.gz

Continuous Integration

  • GitHub Actions for all platforms
  • Automated testing on PR
  • Release builds on tags
  • TestFlight deployment for Apple platforms

Performance Considerations

Optimization Strategies

  1. Lazy Loading: Load data on demand
  2. Pagination: Handle large datasets efficiently
  3. Caching: In-memory caches for frequently accessed data
  4. Background Processing: Heavy operations off main thread
  5. Streaming: Real-time AI responses without blocking

Resource Management

  • Efficient memory usage
  • Battery-conscious background tasks
  • Network request batching
  • Audio file compression

Future Architecture Plans

Planned Enhancements

  1. Plugin System: Extensible architecture for custom features
  2. Local AI Models: Expanded support for on-device inference
  3. Advanced Analytics: Local ML for pattern recognition
  4. Federation: Decentralized sharing with privacy
  5. Voice Interface: Hands-free interaction

Scalability Considerations

  • SQLite handles single-user data efficiently at any scale
  • Incremental sync optimization
  • Parallel AI processing
  • Multi-device coordination

Development Guidelines

Implementation Notes

  • State management and dependency injection use Riverpod
  • Persistence via Drift over SQLite; schemas live under lib/database and feature‑specific *.drift files
  • Localization with Flutter gen‑l10n; ARB files in lib/l10n/ and generation via make l10n
  • Code generation via build_runner; run make build_runner

Code Organization

text
lib/
├── features/       # Feature modules
├── services/       # Core services
├── models/         # Data models
├── widgets/        # Shared UI components
├── utils/          # Utility functions
└── main.dart       # Application entry

Best Practices

  1. Follow Flutter style guide
  2. Write tests for new features
  3. Document complex logic
  4. Use dependency injection
  5. Handle errors gracefully

Contributing

See CONTRIBUTING.md for guidelines on:

  • Code style and standards
  • Testing requirements
  • Pull request process
  • Community guidelines

For development environment setup, see DEVELOPMENT.md.


BACKGROUND (`docs/BACKGROUND.md`)

The Story Behind Lotti

A Moment with Grandma

The inspiration for Lotti began with a simple question and a powerful moment of human memory.

I was recording videos with my grandmother, going through her photo albums together. She was 92 at the time, and we came across a photograph of her standing in Iceland, clearly in front of a Geysir.

"Grandma, which year was that? Who were you with?" I asked.

She tried to remember. As her memory began to fail her, I could see the frustration building. But then something remarkable happened. She got up, walked to one of her drawers, and pulled out a folder. Inside were handwritten recordings of all her travels—she had traveled six times per year throughout her life.

She scanned the index, flipped through a few pages, and found what she was looking for. The entire lookup and reading took less than a minute. But what happened next was magical: life returned to her eyes. She was happy, smiling, and the memories came flooding back. She began reporting as if she was there again, describing the amazing trip from Hamburg via the Shetland Islands and Faroe Islands to Iceland with her friend Marlies.

The brief paragraph in her journal had unlocked far more information than what was written on the page. It was 1987 she was recalling—nearly 30 years later—with just a little help from her notes.

The Seed of an Idea

In that moment, I thought about my own life. I had been to over 40 countries by that point, but how much did I truly remember? How many details had faded? I wanted to remember my experiences the way my grandmother could—with that spark of life and vivid recall.

This inspired me to build what initially was conceived as a travel journal app with audio recording capabilities. The goal was simple: record experiences as they happen, then later—when AI technology matured—be able to summarize and search through these memories just as my grandmother had done with her handwritten notes, but digitally and more powerfully.

Evolution Through Necessity

As I developed the initial journal, I realized something important about feedback loops. It wasn't practical to record things now and wait decades to see if they were useful. I needed something with a much shorter feedback cycle.

That's when I recognized that memory augmentation and context recovery are valuable on much shorter timescales:

The Focus Problem

In everyday work, when someone asks, "Do you have a minute?" my gut reaction is always "Yes, sure." But it's never just a minute—it's also the 20 minutes needed to get back into the zone, to recover the mental context of what I was doing.

What if, when returning to a task, I could get a quick summary of where I was? Context for my brain, context for AI—these aren't very different concepts. With the right context, everything becomes easier.

From Journal to Task Intelligence

This realization led to implementing a comprehensive task management system with:

  • Different statuses (open, groomed, in progress, blocked, done, rejected)
  • Time recording
  • Audio notes and screenshots
  • Image attachments
  • Automatic summarization

Now, whenever I return to a task—whether after an interruption, or days or weeks later when something becomes unblocked—I can quickly get back into context. The AI summarizes my notes, my progress, my thinking at the time.

The Product Vision Crystallizes

As AI capabilities exploded starting in 2023, I began integrating these new powers into Lotti. Initially, this meant adding AI features to the task management system—summaries, transcriptions, checklists. For a moment, Lotti risked becoming just another AI-enhanced task list.

But that was never the destination—it was merely a stepping stone. The real vision became clear: Lotti should be a context manager for your entire life and work, a system that understands not just what you need to do, but what you've done, what you've learned, and how it all connects. A digital extension of memory that you fully own and control.

The core philosophy emerged:

  • Collect data about what you're doing (tasks, travels, thoughts, learnings)
  • Maintain full ownership of that data
  • Use AI to make that data useful and accessible
  • Never be locked into a single provider

Privacy by Design

The privacy aspect isn't an afterthought—it's fundamental. Most AI services want to collect your data, build profiles, and lock you into their ecosystem. If you stop paying, you lose not just the service but your entire history and context.

Lotti solves this by:

  • Storing everything locally on your devices
  • Letting you choose AI providers per category
  • Supporting local inference for complete privacy
  • Using your own API keys for cloud services
  • Never storing your data in the cloud

Looking Forward

Today, running large language models locally requires powerful hardware. For example, I now use a laptop with 128GB of RAM and 4TB of SSD. But this is temporary. Over the coming years, local AI inference will become feasible for everyone.

Lotti is built for that future: where AI augments our memory and productivity without compromising our privacy, where we can ask "What did I learn in the first half of 2024?" or "What were the key decisions in Project X?" and get intelligent answers from our own data.

From Grandmother's Journal to Digital Memory

My grandmother's handwritten travel journal unlocked decades-old memories with a simple paragraph. Lotti aims to do the same for the digital age—helping us capture, organize, and recall our experiences and work, whether we need that context in 20 minutes or 20 years.

The difference is that now we can search in any language, get intelligent summaries, and maintain perfect recall—all while keeping our memories and thoughts exactly where they belong: with us.


Building Lotti in public. Follow the journey on GitHub and Substack.


DEVELOPMENT (`docs/DEVELOPMENT.md`)

Development Setup

This document outlines the recommended development workflow for Lotti.

Tooling

  • Flutter via FVM (recommended). The repo includes .fvmrc to pin the version.
  • Makefile targets wrap common tasks.

One-Time Setup

text
make deps

Frequent Tasks

  • Analyze: make analyze
  • Format: dart format .
  • Tests: make test
  • Coverage report: make coverage
  • Code generation: make build_runner
  • Localization generation: make l10n

Coverage tools (lcov/genhtml)

To generate the HTML report with make coverage, install lcov (includes genhtml):

  • macOS: brew install lcov
  • Ubuntu/Debian: sudo apt-get update && sudo apt-get install -y lcov
  • Fedora: sudo dnf install lcov
  • Arch: sudo pacman -S lcov

After installation, run make coverage and open coverage/index.html.

Running the App

  • macOS: fvm flutter run -d macos
  • Other platforms: fvm flutter run -d <device>

Linux audio codecs

Linux development and unpackaged release builds use GStreamer to decode Lotti's
archived AAC/M4A recordings before temporary Voxtral MP3 encoding. Install the
libav plugin that provides the AAC decoder:

  • Ubuntu/Debian: sudo apt install gstreamer1.0-libav
  • Fedora: sudo dnf install gstreamer1-plugin-libav
  • Arch: sudo pacman -S gst-libav

The Flatpak 26.08 runtime already includes this decoder. A missing decoder does
not prevent compilation, but Voxtral transcription fails immediately with an
installation hint instead of waiting for the request timeout.

Linux emoji fonts

Emoji render as empty boxes without a color emoji font. Install one and run the
helper script, which registers it with fontconfig for the app:

  • Ubuntu/Debian: sudo apt install fonts-noto-color-emoji
  • Fedora: sudo dnf install google-noto-emoji-color-fonts
  • Arch: sudo pacman -S noto-fonts-emoji
bash
./linux/install_emoji_fonts.sh

Localization

  • ARB files live under lib/l10n/
  • Generate localizations: make l10n
  • Optional: sort ARB files: make sort_arb_files

Code Generation

  • Run once: make build_runner
  • Watch mode (optional): make watch

Analyzer Policy

  • Aim for zero warnings or infos before opening a PR. Address all analyzer messages; prefer fixes over ignores in production code.

Commit & PR Guidelines

  • Conventional Commits (e.g., feat:, fix:, docs:, chore:)
  • Keep subjects concise and imperative.
  • PRs should pass make analyze and make test and include a clear description (and screenshots/GIFs for UI changes where relevant).

HISTORY (`docs/HISTORY.md`)

Meins/Lotti

Edit 05/2023: meins now lives in its own repo

This repository used to contain two related projects, Meins and Lotti.

Meins
started out as a journaling application, with a focus on recording
arbitrary measurable data (such as exercise repetitions, intake of water,
alcohol, medications) in combination with mood and imported health data. The
desktop application is written in Clojure and ClojureScript using
Electron to target all the relevant desktop platforms Linux, Mac,
and Windows. There used to be a mobile companion app for importing
health data, photos, and audio recordings on the phone.
This was also written in ClojureScript, using React Native to target both iOS and Android.
This companion mobile app has been deprecated for a while in favor of a rewrite
in Flutter, since there were too many issues with the approach.

Lotti is
more or less an ongoing rewrite of the aforementioned
Clojure and ClojureScript project, using Flutter.
The main reason behind this migration, at least at the beginning, was Flutter's promise to allow building for all screens with a single codebase.
This project is however not a one-for-one migration, since the project aims
have evolved since. It is more and more becoming a toolkit for designing interventions, and thus proactively
creating a better life to look back on, as opposed to just recording what is.
Such interventions could for example be losing weight, improve blood pressure to
prevent cardiovascular disease, and anything else you would want to change, and
then monitor success.

Both applications share one important goal: keep private data private.
Therefore, sync between devices is encrypted and takes place entirely within
user-provided infrastructure in the form of an IMAP folder. Thus, it is not
required to share sensitive information (e.g. medical) with anyone.

Come back soon for links to blog posts detailing the reasoning behind the
ongoing migration, and about creating a better, healthier life for yourself by
creating and monitoring interventions.


PRIVACY (`docs/PRIVACY.md`)

Lotti Privacy Policy

Effective date: August 30, 2026

Overview

Lotti is a privacy-first personal productivity app developed by Matthias
Nehlsen and published by Nehlsen EDV Beratung GmbH. Neither Matthias Nehlsen
nor Nehlsen EDV Beratung GmbH collects, receives, stores, or has access to data
you enter or create in Lotti.

This policy reflects Lotti's App Store privacy declaration: the developer
does not collect data from the app
.

Data Storage

Your tasks, habits, tracked time, voice notes, journal entries, and other app
content are stored on your own devices. Lotti does not require a developer-run
account or upload this content to the developer. Nehlsen EDV Beratung GmbH
cannot view or retrieve it.

Synchronization

The developer, Matthias Nehlsen, plans to offer synchronization between your
own devices. When you use synchronization, all synced content is end-to-end
encrypted (E2EE) before it leaves your device. Only your devices hold the keys
needed to decrypt the content. The developer, server operators, and other
intermediaries cannot read the synced content.

Servers used to relay or store synchronized data may handle encrypted data,
but they receive no readable copy of your app content.

AI Inference

AI inference is optional. Lotti does not mandate or bundle a particular AI
inference provider; you choose and configure the provider, if any, that you
trust.

The only app content that leaves your devices in readable form is content you
explicitly send for AI inference, such as summarization. A local inference
provider can keep this processing on your own device. If you select a remote
provider, the content needed for the request is sent directly to that provider
and is governed by its privacy policy, security practices, and retention terms.
Selecting and using that provider is your choice and responsibility.

Nehlsen EDV Beratung GmbH does not receive or retain the content sent to your
chosen inference provider.

Data Collection by the Developer

Lotti contains no developer-operated service that collects your app content.
The developer does not collect data from Lotti for analytics, advertising,
profiling, or other purposes. Optional end-to-end encrypted synchronization
does not give the developer access to readable content, and optional AI
requests go only to the provider you choose.

Open Source Transparency

Lotti's source code is publicly available on
GitHub, allowing its data-handling
implementation to be independently inspected.

Changes to This Policy

This policy may be updated if Lotti's features or data-handling practices
change. The effective date above will be updated when changes are published.

Contact

For privacy questions, contact the publisher:

Nehlsen EDV Beratung GmbH

Email: [email protected]


App Store Listing (`docs/app-store-listing.md`)

App Store listing — first submission draft

Copy and answers for App Store Connect, written to pass review first and be
tuned later. Character limits are Apple's; every field below is within them.
The screenshots come from make store_screenshots_ios (see
knowledge/conventions/screenshots.md).

App information

Field Value
Name (30) Lotti
Subtitle (30) Private logbook, tasks & time
Primary category Productivity
Secondary category Lifestyle
Bundle ID com.matthiasn.lotti
Age rating 4+ — no objectionable content, no user-generated content shared with others, no gambling, no unrestricted web access
Privacy policy URL https://github.com/matthiasn/lotti/blob/main/PRIVACY.md
Support URL https://github.com/matthiasn/lotti/issues
Marketing URL https://github.com/matthiasn/lotti
Copyright © 2016–2026 Matthias Nehlsen
License note for the description GPL-3.0, source on GitHub

Promotional text (170 — 167 characters)

text
Tasks, habits, tracked time, voice notes and journal, kept on your own devices. No account, no Lotti server. AI and encrypted sync are optional and yours to configure.

Description (4000)

text
/* Detailed source-code truncated for AI context efficiency. */

Keywords (100, comma-separated, no spaces — 88 characters)

text
task,time tracking,habit,journal,logbook,privacy,offline,encrypted,notes,voice,checklist

"Productivity" is the primary category and is searched as such; it would only
have pushed the string past the limit.

What's New (first release)

text
First App Store release.

Screenshots

Upload the dark set first (it is the default theme), then the light set as
additional frames if wanted. Files come from build/store_screenshots/ios/:

Slot in App Store Connect Device folder Size
iPhone 6.9" Display iphone_17_pro_max/ 1320 × 2868
iPhone 6.5" Display (only if the record insists on it) iphone_14_plus/ 1284 × 2778
iPad 13" Display ipad_pro_13_inch_m5/ 2064 × 2752

App Store Connect keeps one tab per display size; a file dropped on the wrong
tab is rejected with that tab's sizes ("1242 × 2688 … 1284 × 2778" is the
6.5" tab). The very same message also means "this PNG has an alpha channel" —
the script flattens its captures, but a screenshot taken any other way must be
run through tool/store_screenshots/strip_alpha.py first. The 6.9" set is the one Apple scales down for every smaller
iPhone, so the 6.5" set is a fallback, captured with
LOTTI_IOS_DEVICES="iPhone 14 Plus" on a simulator created from that device
type (xcrun simctl create "iPhone 14 Plus" com.apple.CoreSimulator.SimDeviceType.iPhone-14-Plus <runtime>).

Order within a slot, as captured (store_en_dark_01_tasks.png …):

  1. Tasks — what you meant to do
  2. Task detail — checklist, cover art and logged time attached to the intent
  3. Habits — four imperfect weeks
  4. Time analysis — where the tracked hours went
  5. Journal — notes, photos and time records in one stream

App Preview

Optional in App Store Connect, and the first thing a visitor sees when there
is one: up to three videos per device size and language, 15–30 seconds each —
so the iPhone and iPad slots below are two separate sets, not one shared one.
make store_preview_ios records the storyboard on a simulator
— the task list, one task and a checklist item ticked, two habits completed,
the logbook they land in — narrates it in the voice of the manual's tutorial
videos, and writes
build/store_preview/ios/iphone_17_pro_max/store_preview_en_dark.mp4 in the
form the 6.9" slot takes (886 × 1920, H.264, 30 fps, stereo AAC); the recipe is
in knowledge/conventions/screenshots.md.
The lines are in
tools/tutorial_videos/config/scenarios/app_store_preview.yaml,
in English and German; narrating a listing in another language means adding
its lines there. Speaking them needs GEMINI_API_KEY in .env, as the
tutorial videos do; LOTTI_PREVIEW_NARRATION=off cuts a silent preview.

Slot in App Store Connect Size Status
iPhone 6.9" Display (scaled down for every smaller iPhone) 886 × 1920 simulator rehearsal from make store_preview_ios
iPad 13" Display 1200 × 1600 not recorded — the walk drives the phone layout

Before uploading one:

  • Apple describes a preview as "footage captured on device" and points at
    QuickTime Player for it; its pages never mention a simulator, and no
    command-line tool records a physical iPhone. The simulator cut is the
    rehearsal. For the upload, walk
    the same storyboard on a phone in demo mode ("Explore with sample data"),
    capture it with QuickTime Player over USB (File › New Movie Recording, the
    phone as camera), and run the file through
    tool/store_screenshots/app_preview.sh capture.mov preview.mp4 886x1920 <start> <length>.
    That cut is silent: the narration is laid by the timeline only a simulator
    walk can hand over, so a phone capture has no beat times to place it by.
  • A preview "must show only content within the app itself" — no people
    interacting with a device, no fingers tapping the screen — and its
    transitions must not imply functionality the app lacks. The walk is
    unedited footage of the app, so it has no transitions to get wrong.
  • It autoplays muted, so nothing in it may depend on sound: every
    narrated line restates what the footage already shows. A visitor with
    autoplay off sees a poster frame instead, and
    changing the poster frame of an approved preview means submitting the
    preview again — the cut opens on the task list so an early frame serves.
  • Not confirmed against an actual upload yet: whether App Store Connect accepts
    this file as is. Its published spec gives 10–12 Mbps as a target bit rate,
    and a screen recording of a mostly still UI encodes well below that.

App Privacy questionnaire

Two facts are not in question: the developer operates no server and ships no
analytics, advertising or crash-reporting SDK (pubspec.yaml has none; see
PRIVACY.md), and optional Matrix sync moves end-to-end encrypted data between
the user's own devices through a homeserver the user chooses — the developer
never receives it, and a homeserver holds only ciphertext.

The one judgement call is optional AI. When the user connects a provider
under their own key, journal content is sent to that provider in readable form,
and PRIVACY.md says plainly that a cloud provider may log or retain requests.
Apple counts data as collected when it leaves the device and is retained
beyond servicing the request, whoever does the retaining. Apple's optional
disclosure exemption for user-directed transfers requires, among other things,
that the user affirmatively chooses each transfer — true for a manual "Update
now", not for an agent's automatic wakes once the user has switched those on.

Recommended answer: declare the optional AI path rather than rely on the
exemption.
Under-declaring is what gets a listing pulled; over-declaring
costs nothing.

Question Answer
Do you or your third-party partners collect data from this app? Yes
Data types User Content → Other User Content (journal text, voice-note transcripts, task titles and checklists the user chooses to send to their AI provider)
Purposes App Functionality
Linked to the user's identity? Yes — the provider receives it under the user's own account and API key, which identifies them to that provider; the absence of a Lotti account does not make it unlinked
Used for tracking? No

Keep "Data Not Collected" only if the account holder decides the exemption
holds for every supported provider; that decision is theirs, not the code's.

Permissions the reviewer will see

Every permission the app actually uses maps to a visible feature:

Permission Where it is used
Microphone Voice notes (record button on a task or the journal)
Camera Scanning the QR code when pairing a second device for sync
Photo library (read / add) Attaching photos to entries; saving an image back to the library
Health (read / update) Settings → Health import: steps, sleep, workouts
Location (when in use) Optional location on journal entries
Contacts Picking people for the relationships feature; only the chosen contact is read

Calendars and Apple Music appear in the plist only because the permission
library requires the strings; they are marked as unused there.

Export compliance

ios/Runner/Info.plist declares ITSAppUsesNonExemptEncryption = false, so
App Store Connect will not ask the encryption questions on upload. The app does
use encryption beyond HTTPS — Matrix end-to-end encryption via vodozemac (Olm /
Megolm: Curve25519, AES-256, HMAC-SHA-256), all standard algorithms. That is the
"uses standard encryption, exempt from a CCATS" category, which is what the
declaration expresses, but it is a legal classification the account holder
should confirm once, not something the code decides.

Review notes (App Review Information)

text
No account or sign-in exists, and Lotti operates no server; optional AI and
Matrix sync talk only to services the user configures. To see the app populated,
choose "Explore with sample data" on the first-run welcome screen (or later via
Settings → Onboarding). That opens a sandboxed demo world with tasks, habits,
tracked time, notes and photos, clearly marked by a banner, and does not touch
real data.

AI features require the user to connect their own provider and key (Settings →
AI). Without one, everything else works fully offline. Health import reads
Apple Health only after the user grants access in Settings → Health.

Contact: the account holder's name, phone and email go in the review contact
fields; demo credentials are not needed.


Daily Os Ai Runtime Architecture (`docs/daily_os_ai_runtime_architecture.md`)

Daily OS AI Runtime — Architecture Vision

Status: Draft / design proposal · Date: 2026-05-30 · Scope: the AI/agent runtime behind Daily OS (cross-cuts features/agents, features/daily_os_next, features/sync, features/ai).

This is a vision-and-architecture document, not an implementation record. It proposes how Lotti's agent runtime evolves from independent per-entity agents into a coherent executive-assistant runtime that manages the user's attention over a long horizon. It is grounded in two things: (1) what the codebase actually is today, and (2) a verified literature review (see Research & Literature below). Where it proposes new structure, it names the real Lotti types it would extend.


1. The vision

An executive assistant, not a secretary. A secretary records and reminds. An assistant manages your attention: it prepares a max-impact schedule, says "no" on your behalf, holds standing agreements, and reflects reality back without flattering you — "you said you'd do X; here's what you actually did; what are we doing about it?"

Concretely, the target runtime should:

  • Let per-task and per-project agents negotiate with a central planner for the user's scarce time, rather than each acting in isolation.
  • Honor standing non-negotiables (e.g. "gym 3×/week", allowed to pre-empt other commitments) and day-to-day priorities, and ask the user only when it genuinely matters.
  • Let a project in a given phase request recurring attention on its own (e.g. a monitoring phase asking for "15 min once a week").
  • Grow a long horizon without babysitting: stateless agent wakes, each handed older → summary + recent → verbatim, writing onto an append-only log. "The agent is the log."
  • Track long-term outcomes (fitness, hours, money) and nudge against drift — proactively, but never naggingly.
  • Run on-device first, fall back to EU-hosted GDPR-compliant inference, and use proprietary models only if strictly required — behind a vendor-agnostic, native-Dart architecture.
  • Keep it simple. The infrastructure that makes this hard is largely already built; the work is mostly additive.

2. The thesis

Lotti is already the substrate that the agentic-systems literature is converging on — an event-sourced, vector-clocked, multi-device-synced, federated typed-edge graph. The structural anchor for this claim is Nakajima's The Log is the Agent (arXiv 2605.21997, May 2026): make the append-only event log the source of truth, treat the working graph as a deterministic projection of that log, and let behaviors react to typed-edge changes and emit new events. Lotti's AgentMessageEntity log + AgentLink/EntryLink typed edges + vector_clock.dart are the closest production-shaped instance of exactly that design.

The paper explicitly leaves two problems unresolved: multi-agent contention over the shared graph, and compaction/checkpointing of long logs. Those two gaps are precisely the work this document specifies — and Lotti already has dormant scaffolding for one of them and a mature human-gate for the other.

The architecture gap therefore reduces to two moves — one largely additive, one a genuine storage migration:

  1. Make agent-derived state a projection of the log, not a synced mutable row. Today some agent state (AgentStateEntity pointers, etc.) is stored and synced as authoritative last-write-wins rows. Treating it as a recomputed projection of the immutable log shrinks the multi-device conflict surface to conflict-free facts. Because agent entities are currently upserted in place (agent_repository.upsertEntity → insertOnConflictUpdate) and identities carry a mutable currentStateId, this is a migration of existing storage, not a purely additive change.
  2. Add negotiation / project-phase / outcome as new node+edge types plus a planner behavior — reusing the existing ChangeSet/ChangeDecision human gate and WakeOrchestrator. No new orchestration subsystem.

Everything below is an elaboration of those two moves.


3. What exists today (this is an evolution, not a greenfield)

The useful unit of work is the delta from what's already shipped. The following are real and load-bearing (see features/agents/README.md and features/daily_os_next/README.md):

Capability Where it lives today Status
Immutable, append-only agent message log AgentMessageEntity in agent.sqlite Built — log persists; the prevMessageId/messagePrev causal-chain fields are defined but not yet populated (see gaps)
Federated typed-edge graph EntryLink (3 journal variants) + AgentLink (13 agent variants incl. messagePrev, agentTask, agentProject, captureToPlan) crossing into journal entities by stable UUID Built
Multi-device sync AgentSyncService over Matrix (E2E-encrypted), vector-clock stamped, outbox-buffered Built
Causal ordering + conflict primitive vector_clock.dart — four-way VclockStatus (equal/concurrent/a_gt_b/b_gt_a), element-wise-max merge; LWW-by-updatedAt for presence-style state Built
Stable-prefix prompt assembly TaskAgentWorkflow orders wake prompts "stable-first … byte-identical across wakes" so a prompt-prefix cache can restore them Built
Human gate (propose → decide) ChangeSetEntity/ChangeDecisionEntity, proposal ledger, agent self-retraction, confirmation service Built
Wake orchestration WakeOrchestrator: dedup, single-flight per agent, 120 s throttle, vector-clock self-suppression, deferred + scheduled wakes Built
Day planning DayPlanEntity/DayPlanData/PlannedBlock, draft → agreed → committed/needsReview, capacity + energy bands, Capture/Reconcile/Draft/Refine (Shepherd day agent) Built
Provider abstraction ProfileResolver resolves an inference profile per wake; same template routes through different providers (ADR 0008) Built
Souls (personality) SoulDocumentEntity with structured voiceDirective, toneBounds, coachingStyle, antiSycophancyPolicy Built
Wearable / health ingestion HealthService + health_import → synced QuantitativeEntry/WorkoutEntry (Apple Health / Google Fit: steps, workouts, HR, BMI, BP) Built
Memory compaction AgentMessageKind.summary, summaryStart/EndMessageId, summaryDepth, recentHeadMessageId, latestSummaryMessageId Scaffolding only — not yet written by production (agents README: "prepared, not active")

Genuinely missing — the real work:

  1. Cross-agent negotiation / arbitration for attention. Agents read each other's distilled reports (a task agent can consume a sibling's tldr; a project agent reads task-agent TLDRs) but never bid for the user's time or resolve conflicts. (→ Thread A, G)
  2. Project-phase model + recurring time-requests. No phase concept; time budgeting is per-category/day, not "this project's monitoring phase wants 15 min weekly." (→ Thread A, F)
  3. The active compaction pipeline that turns the dormant summary scaffolding into a real stable prefix and long-horizon memory. (→ Thread B, C)
  4. Outcome tracking / actual-vs-intended loop. WakeRunLog and ratings exist, but nothing closes the "you said X, you did Y" loop. (→ Thread E, F)

Current-state gaps the design must close (not true today)

Some load-bearing claims below describe the target, not the runtime. The design must treat them as work, not givens:

  • Execution is in-process single-flight only. WakeRunner guards one wake per agent via an in-memory lock map (_activeLocks); there is no cross-device coordinator. Two offline devices can each believe they own execution.
  • Sync applies concurrent agent payloads by arrival order. sync_event_processor_agent_handlers skips an incoming entity/link only when the local vector clock dominates (a_gt_b/equal); concurrent and b_gt_a are applied as they arrive — no deterministic merge or single-writer guarantee for agent state yet.
  • Agent entities are upserted in place. agent_repository.upsertEntity uses insertOnConflictUpdate, and identities carry a mutable currentStateId — so "state as a projection of the log" (§4) is a migration, not current behavior.
  • The compaction scaffolding has fields but no schema. AgentMessageKind.summary and the head pointers exist, but there is no replay/digest schema and no production compaction path.
  • Message causal chaining is not wired. prevMessageId is declared on AgentMessageEntity and the messagePrev AgentLink variant exists, but no production code populates either — so "the log is a DAG" (§8) is a target built on existing fields, not current behavior.

These are the gaps §§4–8 must close; §10 sequences them so convergence lands before anything writes new synced derived state.


4. The substrate: log → projection → behavior

The runtime is one loop. The append-only event log (AgentMessageEntity + AgentLink, vector-clock stamped) is the source of truth. The working graph and all agent state are a deterministic projection of that log. Behaviors (the existing task/project/day workflows, plus a new planner) react to projected changes and emit new events. Side-effecting outputs pass through the existing ChangeSet gate before they re-enter the log as committed facts.

mermaid
flowchart LR
  subgraph Log["Append-only event log — agent.sqlite (immutable, vector-clocked)"]
    E["AgentMessageEntity + AgentLink"]
  end
  E -->|"deterministic fold (VC-ordered)"| Proj["Projection: working graph + agent state<br/>(derived, NOT authoritative)"]
  Proj --> Behaviors["Behaviors / workflows<br/>task · project · day(Shepherd) · planner · improver"]
  Behaviors -->|emit events| E
  Behaviors -->|side effects| Gate["ChangeSet / ChangeDecision<br/>human gate (VOI-triggered)"]
  Gate -->|confirmed decision| E

Move 1 — state as projection. Today AgentStateEntity is a synced mutable row; under concurrent multi-device edits it is a last-write-wins conflict surface. The target is that agent-derived state (head pointers, slots that summarize log position) is recomputed from the log rather than trusted as authoritative replicated state. Genuinely user-authored mutable documents (souls, templates) keep last-write-wins — and Lotti already has the right pattern for them: immutable Version/Head snapshots (SoulDocumentVersionEntity/SoulDocumentHeadEntity, AgentTemplateVersionEntity/Head). Generalize the snapshot pattern; don't invent it. This is corroborated by Anthropic's finding that long-running-agent cold-start state is best reconstructed from durable artifacts, not trusted to compacted in-context state (Effective harnesses for long-running agents).

Move 2 — negotiation/phase/outcome as types + a planner behavior. New AgentDomainEntity variants and AgentLink types carry attention-requests, bids, project phases, and outcomes; a single planner behavior consumes them and emits a ChangeSet. This is structurally Hayes-Roth's meta-level controller over a blackboard — see §5.


5. Attention negotiation (the contention layer the anchor leaves open)

Lotti is already a blackboard system in disguise: the append-only log is the event source, the projected typed-edge graph is the shared blackboard, and per-task/per-project/day agents are the knowledge sources writing to it. What's missing is Hayes-Roth's separate meta-level control mechanism that treats arbitration itself as a planning problem (A Blackboard Architecture for Control, Hayes-Roth 1985).

Design:

  • Bids are events, not RPCs. A task/project agent emits an attention_request event carrying impact, priority, deadline-slack, energy-fit, and (for recurring asks) a cadence. Modeled as new AgentDomainEntity + AgentLink variants on the existing synced graph. The message shape follows the Contract Net Protocol (call-for-proposals → bid → award → inform) (CNP).
  • No auction incentive-compatibility needed. Every bidder is a sub-agent of one principal (the user), so Vickrey-style truthful-bidding machinery collapses to a centralized utility ranking. But one principal does not make LLM agents calibrated — an agent can overstate impact or misjudge urgency — so bids carry evidence references (links to the task/project/day facts that justify them) and bounded fields, and the planner derives utility from those facts, not from agent-self-assigned scores. (Auction theory — Shoham & Leyton-Brown ch. 11 — also warns that expressive/combinatorial winner-determination is computationally hard, arguing for a bounded heuristic arbiter rather than optimal allocation.)
  • The planner is a behavior, and its output is a ChangeSet. It projects a candidate DayPlan (reusing capacity + energy bands), ranks requests by utility, and routes the result through the existing human gate. The Shepherd day agent's propose_plan_diff → ChangeSet → accept/revert path is the existing mechanism to reuse.
  • Non-negotiables are NOT enforced by prompting. Recent LLM-planning work shows hard constraints are "neither guaranteed nor enforced" by instruction alone and must be checked by a deterministic verifier (U-Define, arXiv:2605.02765). So standing non-negotiables (gym 3×/week, with pre-emption) become a declarative hard-constraint check run deterministically over the projected graph during the draft → agreed transition. Soft daily priorities stay heuristic/LLM-scored.
  • "Ask when in doubt" = value-of-information. Interrupt the user only when the expected value of their answer exceeds the cost of interrupting (Sarne & Grosz 2013). The DayPlan (capacity/energy bands) is the "scheduler module" the VOI computation queries; recent ChangeDecision accept/reject history is the receptivity/fatigue signal. Low-VOI conflicts auto-resolve and are merely logged — but only for reversible, low-stakes actions; committed schedule changes, block drops, and any external side effect stay gated regardless of VOI until the user has calibrated trust. High-VOI conflicts raise a ChangeSet.
mermaid
sequenceDiagram
  participant Agent as Task / Project agent
  participant Log as Event log
  participant Planner as Planner behavior
  participant Verify as Non-negotiable verifier
  participant User
  Agent->>Log: emit attention_request (impact, deadline-slack, energy-fit, cadence)
  Log-->>Planner: projection updates with open requests
  Planner->>Verify: candidate DayPlan vs hard constraints
  Verify-->>Planner: violations (if any)
  Planner->>Planner: rank by utility, compute VOI
  alt VOI > interruption cost
    Planner->>User: ChangeSet (proposed schedule / conflict)
    User-->>Log: ChangeDecision (accept / reject)
  else low VOI
    Planner->>Log: auto-resolve + logged rationale
  end
  Planner->>Log: award -> PlannedBlock(s) on the DayPlan

Project phases & recurring time-requests

A project gains a phase (e.g. active, monitoring, paused), modeled as project state in the graph. A phase can carry a standing recurring request ("monitoring → 15 min weekly"), emitted by the project agent as a recurring attention_request. The planner treats these like any other bid, but with a cadence the deterministic verifier can enforce as a soft floor. This is the literal mechanism for the user's "the project should ask for that itself."


6. Long-horizon memory: the compaction pipeline

The dormant scaffolding maps almost 1:1 onto the proven MemGPT/Letta mechanism (MemGPT, arXiv:2310.08560): AgentMessageKind.summary is the recursive-summary node; summaryStart/EndMessageId is provenance for the evicted range; recentHeadMessageId is the verbatim-tail boundary; latestSummaryMessageId lets a stateless wake reconstruct context as frozen-summary + recent-tail — the same cold-start shape Anthropic reaches via durable progress files.

The pipeline (a background behavior, not on the hot path):

  1. When the tail past the active checkpoint exceeds a model-specific budget, append a summary/checkpoint event naming the frontier it covers (and the prior checkpoint it folds in) — an append, not a pointer write.
  2. The projection selects the active checkpoint and head by reverse-indexing the log (ADR 0016); recentHeadMessageId/latestSummaryMessageId are a local cache, never authoritative, so compaction adds no mutable conflict surface. Preserve decisions, open commitments/negotiations, and non-negotiables; discard redundant tool chatter (per Anthropic context engineering: "overly aggressive compaction … loses subtle but critical context").
  3. Treat the summary as a derived projection, not a destructive overwrite — and don't expect a digest to make LLM outputs converge. Two independent summarizations will not be byte-identical (a digest names an output; it can't make two equal). Summaries are candidate checkpoints over causal frontiers (§8): a summary covers a frontier (an antichain). Frontiers join cleanly (a semilattice), but the join of two candidates may have no materialized text, so the active checkpoint is the maximal complete materialized checkpoint — among checkpoints ancestral to every head, the one covering the most history; context is that summary + the uncovered tail of original (non-summary) events (non-active summaries excluded, so no derived text or double-counting). Same-frontier candidates share a frontierDigest (coverage only), so they tie-break by a separate content key — lowest (contentDigest, id); incomparable maxima fall back to their meet (common base) + full verbatim uncovered region, which a merge-summary then collapses into one dominating checkpoint — fired eagerly if that verbatim region would exceed the on-device context budget (still append-only checkpoints over canonical frontiers — iteratively over bounded sub-frontiers if the region is already huge — original events retained; eager in timing, not a truncation), so the fallback never overflows (so a merge-summary always eventually becomes active). Never pick one candidate's text as the checkpoint when candidates are incomparable — that drops the other branch's history. frontierDigest (a hash of the antichain's canonical id-set) identifies coverage only; a separate contentDigest over a canonical form (sorted keys, RFC 3339 UTC timestamps, normalized numbers, UTF-8 canonical JSON/JCS, versioned tag sha256-v1) is the dedup/verification key, so the checkpoint's full key is (frontierDigest, contentDigest). The lease (§8) only avoids usually summarizing twice; it is not required for convergence.
mermaid
stateDiagram-v2
  [*] --> Idle
  Idle --> Assembling: wake fires
  Assembling --> Prefix: build stable header
  Prefix --> Tail: append recent tail past recentHeadMessageId
  Tail --> Running: inference with warm prefix cache
  Running --> Appending: emit events to log
  Appending --> CompactionCheck: tail beyond budget?
  CompactionCheck --> Compacting: yes
  CompactionCheck --> Idle: no
  Compacting --> Idle: append checkpoint event, projection selects active checkpoint

This compaction is also what makes the on-device prefix cache pay off (§7): the rolling summary is a long-lived stable prefix, the recent tail is the volatile suffix.


7. Inference tiers and the two caches

Tier ladder (vendor-agnostic, behind one adapter)

On-device first (Ollama / llama.cpp today), EU-hosted GDPR-aligned API second, proprietary only if required. The EU tier has standardized on an OpenAI-compatible surface across Mistral, OVHcloud, Scaleway, Nebius, and IONOS, so providers are swappable behind a thin adapter — which maps directly onto Lotti's existing ProfileResolver / inference-profile system (ADR 0008). The API surface is swappable; the compliance posture is not uniform — retention, residency, no-train defaults, and model-version pinning differ per provider and need per-provider handling and verification (see the Thread D caveat and §11), not a single generic assumption. Because open-weight families overlap between local and cloud, the same model family can spill from device to EU endpoint with comparable behavior.

mermaid
flowchart LR
  Req["Wake request (stable prefix + recent tail)"] --> Cache{"Response cache hit?<br/>hash(prompt + model + params + tools + soul)"}
  Cache -->|yes| Resp["Stored response — deterministic replay"]
  Cache -->|no| T1["On-device: Ollama / llama.cpp"]
  T1 -->|capacity / quality miss| T2["EU API: GDPR, no-train, pinned model id"]
  T2 -->|only if strictly required| T3["Proprietary (last resort)"]
  T1 --> Store["persist response (content-addressed)"]
  T2 --> Store
  T3 --> Store
  Store --> Log["agent.sqlite event log"]

The remote tier sits outside the Matrix sync trust boundary: only the durable, vector-clocked results of EU calls are written to agent.sqlite and replicated, so provider choice never weakens the multi-device encryption model. Every message that triggered a remote call must persist the exact provider + pinned model id + parameters — version-pinning is load-bearing for replay (§below).

The two caches must not be conflated

This is the distinction the user personally flagged (the "why isn't the KV cache keyed by message ID" question), and the architecture is fragile to getting it wrong:

The KV cache reuses computation within one forward pass and is prefix/position-bound and backend-internal; the response cache reuses whole outputs across runs and devices, is content-addressed, and is the layer Lotti implements for forkable, auditable, sync-replayable runs.

  • (a) Application-level response memoization — the layer Lotti owns. hash(rendered prompt + pinned model id + decoding params + resolved tool set + soul config) → stored response, persisted alongside the immutable log and looked up out of order by request hash. Provider-agnostic (identical whether Ollama or an EU endpoint), it is the determinism boundary for any non-local tier and the mechanism the anchor paper's deterministic replay and cheap forking depend on. This is the realizable version of "key = the request, value = the response." Two purposes, two keys. For deterministic replay/forking the key is the verbatim rendered prompt — volatile fields like currentLocalTime included, so a miss when the clock advances is expected and harmless. For active de-duplication of concurrent duplicate calls, hashing the volatile prompt would miss on every wake, so dedup instead uses the frontier-based behavior idempotency key (agentId + behaviorKind + frontierDigest + triggerId + toolName, §8), where triggerId is a stable, source-derived id (source event id / scheduled-wake entity id / shared trigger token, never a per-run local UUID) — so the key collapses the same wake run on two devices, not two distinct wakes (e.g. a later scheduled, time-sensitive wake) over an unchanged frontier. It drops the wall-clock value but stays scoped to the wake epoch. And as a prompt-construction rule, volatile fields (currentLocalTime) belong in the very last, volatile position of the prompt, never in the stable prefix, so the KV/prefix cache (b) stays warm regardless.
  • (b) Model-level KV/prefix cache — backend-internal, not Dart-controllable beyond prompt construction. It is prefix- and position-bound for a hard reason: a token's keys/values depend on all preceding tokens (vLLM keys blocks by hash(prefix + block tokens), vLLM APC), and RoPE bakes absolute position into each key, so the same text at a new position yields different KV unless re-encoded (Block-Attention, arXiv:2409.15355). On Lotti's actual stack (llama.cpp/Ollama), reuse is per-slot, matches the longest common prefix, and recomputes only the diverging suffix — never keyed by message ID (llama.cpp #13606). Position-independent reuse (Prompt Cache, CacheBlend, EPIC, Block-Attention, KVLink) requires schemas, RoPE re-encoding, trainable glue, or fine-tuning a stock-GGUF app cannot perform — out of scope for the model layer.

The architectural consequence: Lotti exploits the on-device KV cache only by keeping a byte-stable prefix (soul/anti-sycophancy prompt → tools → rolling summary → recent head) — which TaskAgentWorkflow already does, and which the compaction pipeline (§6) extends. The branching log (prevMessageId can fork) means only one linear path occupies the single KV slot per model, so planner and per-task agents compete for one warm prefix per device — a scheduling problem, not a correctness one. That competition is the same contention the anchor leaves open, resurfacing at the cache.


8. Multi-device convergence (the synchronizable graph)

Sync turns the anchor's "multi-agent contention" gap into a concrete distributed-systems problem — and the codebase already sits on the correct side of every line. The CRDT/local-first literature splits into two layers the anchor conflates: convergence of replicated state (CRDT theory) and ordering metadata (logical clocks).

Vector clock vs HLC is a false choice — keep the vector clock. A vector clock is the only common logical clock that can return CONCURRENT; a Hybrid Logical Clock is O(1) but total-ordering and provably cannot distinguish concurrent from causally-ordered events (logical clocks, crdt.tech). Being able to detect true concurrency is exactly what tells the human gate that a real conflict (not a causal update) needs deciding. vector_clock.dart already implements this.

"Vector clock + LWW" must mean: classify with the VC, LWW only on the concurrent branch. The convergent fold uses the vector clock to classify each pair — causal order (a_gt_b/b_gt_a) is honored by replay order — and consults the updatedAt LWW tiebreak only on the concurrent branch. Two conditions make the projection fully deterministic:

  1. Extend the partial order — the causal messagePrev DAG (the vector clock classifies concurrency but is not the ordering input) — to a single deterministic total order with a replica-independent tiebreak (a stable hostId + id key on otherwise-concurrent events) so every device linearizes concurrent events identically.
  2. Make the LWW comparator a true total order with a deterministic secondary key — break equal updatedAt by hostId (then id) so two replicas never disagree when timestamps are identical. These are two distinct problems, and the tiebreak only fixes the first: (a) equal-timestamp divergence — solved by the hostId/id tiebreak; (b) a skewed/fast physical clock winning a concurrent branch outright — not solved by the tiebreak, because the fast clock's updatedAt is strictly greater, so the equal-timestamp tiebreak never fires. Bounding (b) requires a monotonic clock — a hybrid logical clock (or bounded physical-clock drift) on the concurrent-branch comparator. That is the one place an HLC earns its keep; it still does not replace the vector clock used for causal classification.

Replicate facts; lease execution — but the lease is an optimization, not the correctness foundation. Pure log appends converge for free under CRDT semantics, and correctness comes from the convergent DAG projection (below), not from mutual exclusion. The lease only avoids usually doing duplicate expensive or user-visible work and guards irreversible side effects. So side-effecting actions take a leader lease keyed to the side-effect boundary — (agentId, behaviorKind) for per-agent execution/compaction, (userId, dayId, planner) for the shared day planner — with a monotonic fencing token the resource rejects when stale (Kleppmann). This is not new machinery: WakeOrchestrator already does vector-clock self-suppression, and the lease promotes that from intra-device to inter-device. When the lease fails (split-brain mobile+desktop) nothing is wrong — both devices act and the work converges; idempotency + fencing, not the lease, is the safety net.

Forks are legal — the log is a convergent DAG. Two devices waking the same runtime from a shared prefix both append, creating a fork: concurrent messagePrev children of a shared parent. This is normal, not corruption, and the repair is mostly free — the projection folds the whole event set in canonical order (a deterministic linear extension of the messagePrev DAG), so it is multi-head tolerant: any two devices with the same events compute identical state regardless of branching. prevMessageId is provenance, not a linearization lock; recentHeadMessageId/latestSummaryMessageId are derived by reverse-indexing messagePrev, not authoritative fields. What needs real work is bounded cost and meaning, not correctness:

  • Cost — heal the head lazily. Unbounded heads make context and the prefix grow, so a join-by-continuation node (linking to all current heads) caps the fork — emitted lazily (only when ≥2 heads survive past one wake cycle). Its id is content-addressed — hash("join-v1" + sorted parent-head ids), domain-separated from the summary coverage frontierDigest — so two devices emitting the join concurrently write the same log entry and set-union merges them into one node — concurrent joins can't themselves fork (no join storm). For that to hold, the join's payload is deterministic (sorted parent-head ids + a fixed kind, no clock/host in the content) and the projection reconciles per-device envelope metadata (hostId, VC, createdAt) canonically, so the shared id can't diverge under LWW. For prefix stability, not correctness.
  • Summaries are candidate checkpoints over causal frontiers (antichains); the active checkpoint is the maximal complete materialized checkpoint ancestral to all heads (common-base fallback for incomparable maxima), with the uncovered tail of original events read verbatim until a lazy merge-summary collapses it — so two hosts summarizing the same trunk converge without needing byte-identical text (§6).
  • Side effects carry an idempotency key agentId + behaviorKind + frontierDigest + triggerId + toolName — scoped to the wake epoch (triggerId), not just the frontier, so a later time-sensitive wake isn't wrongly suppressed; the projection dedups duplicates (ChangeSet dedup, ADR 0009). Irreversible external effects (a sent email) can't be undone, so those stay behind the lease + gate, kept minimal.
  • Meaning — reconcile visibly. Derived state converges silently by canonical pick; divergent user-facing commitments (one device marked a task done, another proposed dropping it) surface as a ChangeSet ("your devices disagreed — here's the reconcile"), never silently overwritten.
mermaid
flowchart TD
  subgraph A["Device A — holds executor lease + fencing token"]
    BA["Behaviors run here (planner, agents)"]
  end
  subgraph B["Device B — replica"]
    PB["Projection only"]
  end
  BA -->|append events| Sync["Matrix E2EE sync (vector-clock stamped)"]
  Sync -->|union merge| PB
  Sync -->|union merge| BA
  PB -->|"skips redundant execution while A holds the lease"| Suppressed["(connected-case optimization)"]

9. Accountability UX and outcome tracking

No-bullshit, without becoming a nag

The line between a respected partner and an ignored nag converges on: default to silence, intervene only when state warrants, reflect discrepancy with calibrated honesty, and actively counter-steer the model's sycophantic grain.

  • Anti-sycophancy is the load-bearing risk. RLHF rewards agreement over truth; production assistants "wrongly admit mistakes when questioned … and mimic errors made by the user" (Sharma et al., arXiv:2310.13548). Any default model acting as planner will validate a stated-vs-actual gap away and flip under pushback. The antiSycophancyPolicy soul field is the exact seam, and should encode retraining-free mitigations — dynamic truth-seeking prompts, a non-sycophantic critic pass, and (where the local stack exposes logits) contrastive decoding / activation steering (mitigations survey, arXiv:2411.15287). Caveat: small local models may need the EU fallback to clear the honesty bar.
  • Proactivity is state-gated (JITAI). Intervene only on vulnerability/opportunity/receptivity, with a mandatory "provide nothing" option; persistent non-response itself becomes a tailoring variable (Nahum-Shani et al. 2018). The ChangeSet gate is the JITAI intervention surface — a proposal is an intervention option, silence is a legitimate one.
  • Notifications buy attention, not retention. A notification raised next-hour app-open 3.5× but did not change time-to-disengagement (Bell et al., JMIR mHealth 2023) — reinforcing that the reflection's value, not its frequency, is what matters.

Outcomes the agent can nudge against

Model long-term outcomes on the 4DX lead/lag split (FranklinCovey): a lagging numeric target (weight, deep-work hours) plus its decomposed leading indicators, which are both predictive of the lag and directly influenceable — so the agent acts on leads, not lags. Monitoring works, but you must monitor the specific thing you want to move: across 138 studies, monitoring the behavior changed the behavior but not the outcome, and vice versa (Harkin et al. 2016).

Design: an outcome is a typed graph entity (lag target + leading indicators), linked via new AgentLink variants into journal entries and DayPlan tasks; non-negotiables are leading indicators with hard floors. Drift detection is an event-sourced behavior that fires when an actual-vs-intended delta on a leading indicator crosses a threshold (with a tolerant window/decay so one harmless lapse isn't a false alarm), reading actuals projected from the immutable log. Actuals are sensor-backed, not self-reported — Lotti already imports Apple Health / Google Fit into synced QuantitativeEntry/WorkoutEntry, so "gym 3×/week" is verified against real workout entries and steps/activity are genuine leading indicators. The nudge output is a ChangeSet.


10. Phased delivery (keeping it simple)

The moves are additive, so they ship incrementally — each is useful alone:

  1. Projection kernel + convergence tests first. Build the deterministic projection with canonical ordering (§8) and concurrent-agent sync conflict tests, before any new synced derived state is written. Everything else depends on this.
  2. Compaction as a local read-side cache (§6). Ship it unsynced first so summary pointers can't become a new conflict surface; promote to synced only once (1) lands and compaction is single-writer or deterministic-selection.
  3. State-as-projection migration (Move 1). Migrate the upsert-in-place entities (agent_repository.upsertEntity) to derived projections; generalize the Version/Head snapshot pattern for genuinely user-authored state.
  4. Planner MVP — proposal only. Event-sourced attention_request,
    durable standing agreements, indexed planner-window lookup, the
    deterministic hard-constraint verifier, and a ChangeSet proposal. No
    auto-mutations, and no auto-resolution of irreversible actions.
  5. Executor lease + fencing (§8) with a named backend and explicit offline behavior, before any cross-device auto-execution or single-writer compaction.
  6. Project phases + recurring requests; outcome tracking + drift nudges (§§5, 9).
  7. Provider compliance + model-pinning checks before relying on the EU fallback tier (§7, Thread D).

This sequences convergence and a proposal-only planner ahead of any autonomous mutation.

Realized as ADRs 0016 (agent state as a projection), 0017 (deterministic compaction), 0018 (convergent execution: lease, fencing, fork reconciliation), and 0019 (attention-negotiation protocol). These extend the existing ADR series (0002 wake scheduling, 0008 inference profiles, 0009 redundant-proposal suppression, 0010 scheduled wakes).


11. Open questions & contradictions

Carried forward from the verified research; these need product decisions or experimentation, not more literature:

  • Bid-for-attention vs blackboard-posting (A/G). Is the primary abstraction a per-task agent bidding (needs bid/award AgentLink types) or knowledge sources posting candidate DayPlan changes arbitrated purely at projection time? They compose; the choice determines whether new edge types are required.
  • VOI proxies (A/E/F). What concrete proxies stand in for "expected value of information" and "cost of interruption", and how are they weighted? JITAI receptivity leans on phone/wearable sensors — and Lotti already has them: the health pipeline (HealthService/health_import → synced QuantitativeEntry/WorkoutEntry) supplies real activity, workout, and step signals alongside day-plan utility delta, deadline slack, energy-band fit, and recent dismissal rate. The open part is signal selection and calibration, not whether the data exists.
  • Silence vs discrepancy reflection (E/F). The mandatory "provide nothing" default tensions with discrepancy-reflection, which requires surfacing gaps. No source fixes how often a respected partner should break silence before it's a nag — needs in-product experimentation. It is also unproven that agent-witnessed commitments retain the effect sizes measured for human-witnessed ones.
  • On-device thresholds (B/C). MemGPT's 70/100/50% thresholds are tuned for large cloud windows; the right equivalents for small, variable on-device contexts (and token- vs message-count triggers) are unknown.
  • Summary correctness under sync (B/G). Recursive summarization can amplify hallucination at depth; each summary stores provenance and a replay hash so a bad one is regenerable. Cross-device convergence is now handled (§6, §8): summaries are candidate checkpoints over causal frontiers, the active checkpoint is the maximal complete materialized checkpoint (common-base fallback for incomparable maxima) + a verbatim tail of original events, and a lazy merge-summary collapses divergence — so byte-identical LLM output is not required. The open part is tuning the merge-summary trigger and bounding verbatim-tail growth, not convergence itself.
  • Numeric increments under merge (F/G). A continuously-incrementing measurement (gym sessions this week) is unsafe under element-wise-max + updatedAt-LWW, which can silently drop a concurrent increment. Counter-style outcomes likely need a CRDT counter, not an LWW register — unresolved against the current sync model.
  • EU tier verification (D). Whether Zero-Data-Retention is contractual-by-default vs enterprise-only, whether model version tags are immutable or silently rotated (load-bearing for cache determinism), and whether JSON-schema/function-calling fidelity is consistent across the OpenAI-compatible facade — all need benchmarking. The most sovereign tiers (IONOS native, Aleph Alpha on-prem) may need provider-specific code paths that strain the single-adapter goal.
  • Leader line-drawing (A/G). Which actions are side-effecting (notifications, external calendar writes, paid LLM calls) vs purely log-appending determines how much lease+fencing machinery is actually needed; only the former requires single-writer execution.

Research & Literature

The following is a verified literature review produced by a multi-agent research run (7 thread analysts → adversarial fetch-and-check of load-bearing claims → synthesis). One claim was refuted during verification and removed (see Verification note). It is reproduced here as the doc's research grounding; the architecture sections above cite into it.

The architecture this section informs is an in-app, vendor-agnostic agent runtime for Lotti: per-task and per-project agents negotiate with a central planner for the user's scarce attention, on an append-only AgentMessageEntity log that already syncs E2E-encrypted over Matrix with a real vector clock plus last-write-wins-by-updatedAt tiebreak. The structural anchor is Nakajima's The Log is the Agent (arXiv 2605.21997), which makes the event log the source of truth and the working graph a deterministic projection, and which explicitly leaves two problems open: multi-agent contention over the shared graph, and compaction/checkpointing of long logs.

Thread A — Attention-negotiation & multi-agent allocation of a scarce shared resource

The canonical answer to "many agents, one scarce resource, one arbiter" is a 45-year-old still-live lineage: Contract-Net-style negotiation, auction/mechanism design that generalizes it, and the blackboard pattern in which many opportunistic knowledge sources write to one shared structure under a separate meta-level controller. Recent LLM-planning work adds a sharp warning that hard constraints cannot be enforced by prompting alone.

  • The Contract Net Protocol structures task allocation as a four-phase manager/contractor negotiation — call-for-proposals, bid/reject, award/accept, inform-on-completion — but offers no global-optimality guarantee and is subject to communication saturation and the decommitment problem (Contract Net Protocol — Wikipedia).
  • The blackboard architecture for control treats arbitration itself as a dynamic planning problem: a separate control mechanism runs control knowledge sources concurrently with domain knowledge sources to construct and execute an explicit control plan over the shared structure — i.e. a planner-as-arbiter (Hayes-Roth, Artificial Intelligence 1985).
  • For "ask the user when in doubt," the decision-theoretic rule is value-of-information: interrupt only when the expected value of the user's private information exceeds the interruption cost, computed by querying a separate scheduler module — and not knowing exactly what the user knows forces evaluation over multiple hypotheses, raising VOI complexity (Sarne & Grosz, JAAMAS 2013). For non-negotiables, U-Define shows prior soft-only prompting leaves hard constraints "neither guaranteed nor enforced," and compiles them to LTL for a formal model checker instead (Lee et al., arXiv:2605.02765).

Lotti mapping. Lotti is already a blackboard system in disguise: the append-only AgentMessageEntity log is the event source, the projected typed-edge graph (EntryLink + AgentLink) is the shared blackboard, and per-task/per-project agents are the knowledge sources. Introduce a single PLANNER behavior as Hayes-Roth's meta-level controller, with a Contract-Net-shaped exchange expressed as new AgentLink variants and message kinds. Because every bidder is a sub-agent of one principal, drop true auction incentive-compatibility and treat bids as honest preference reports feeding a centralized utility ranking. Standing non-negotiables must not be left to the on-device model to honor by instruction; encode them as a declarative hard-constraint check run deterministically over the projected graph during the draft → agreed transition. The "ask when in doubt" gate is Sarne-Grosz VOI: raise a ChangeSet/ChangeDecision only when expected value of the user's answer exceeds interruption cost, querying the DayPlan (capacity/energy bands) as the scheduler module; low-VOI conflicts auto-resolve and are merely logged.

Thread B — Long-horizon agent memory as append-only log + rolling/hierarchical summarization

The dominant design is a two-tier model: a small in-context working set plus an unbounded external store, with a deterministic policy that converts overflow into summaries while keeping a recent verbatim tail. Production practice increasingly moves memory work off the hot path and reconstructs state on cold start from durable external artifacts — almost exactly the "log is the agent" posture.

  • MemGPT partitions the context window into system instructions + working context + a FIFO message queue over external recall storage (full history) and archival storage, using explicit thresholds: at ~70% it injects a memory-pressure message, and at ~100% flush it evicts ~50% of messages and folds them, with the prior recursive summary, into a new recursive summary at the FIFO head (arXiv:2310.08560).
  • Anthropic defines compaction as summarizing a near-full window while preserving decisions/open bugs/implementation details and discarding redundant tool output, and warns that "overly aggressive compaction can result in the loss of subtle but critical context whose importance only becomes apparent later" (Effective context engineering for AI agents). Their long-running-agent harness finds compaction alone insufficient: each fresh agent reconstructs state by reading durable artifacts — a progress narrative, git logs, a typed feature list — on cold start (Effective harnesses for long-running agents).
  • Generative Agents establish the complementary append-only memory stream scored by recency + importance + relevance, with periodic reflection synthesizing higher-level memories written back into the same stream (arXiv:2304.03442). ESAA independently instantiates the event-sourced posture (structured-JSON intentions → append-only activity.jsonl → hash-verified projection → replay) but, like the anchor, leaves long-log compaction unaddressed (arXiv:2602.23193).

Lotti mapping. The dormant scaffolding maps almost 1:1 onto the proven MemGPT/Letta mechanism: AgentMessageKind.summary is the recursive-summary node; summaryStart/EndMessageId is provenance for the evicted range; recentHeadMessageId is the verbatim-tail boundary; latestSummaryMessageId lets a stateless wake reconstruct context as frozen-summary + recent-tail. Implement a deterministic in-app compaction policy: when the tail past recentHeadMessageId exceeds a model-specific budget, append a checkpoint event naming the covered frontier (the projection selects the active checkpoint; the persisted pointers are a local cache — §6), and preserve decisions, open commitments/negotiations, and non-negotiables while discarding redundant tool chatter. Treat summaries as candidate checkpoints whose cross-device reads converge by selecting the maximal complete materialized checkpoint (common-base fallback for incomparable maxima) plus a verbatim tail of original events, collapsed by a lazy merge-summary — not by content-addressing LLM text (§6, §8). Run summarization and the honest actual-vs-intended reflection as a separate background identity writing into the same log.

Thread C — On-device KV/prefix caching vs application-level response memoization

Two structurally different caches must be kept apart. The model-level KV/prefix cache reuses precomputed attention keys/values within a single forward pass and is prefix- and position-bound; the application-level response cache reuses a whole output across runs and is content-addressed and model-external.

  • The KV cache is prefix-bound because a token's keys/values depend on all previous tokens; vLLM keys each block by hash(prefix tokens + block tokens), not by content or message ID (Automatic Prefix Caching — vLLM). RoPE bakes absolute position into each key by rotation, so the same passage at a different position yields different KV; correct out-of-order reuse requires re-encoding position (Block-Attention, arXiv:2409.15355).
  • Escaping the prefix constraint always costs extra machinery: Prompt Cache needs an explicit schema with pre-assigned position ranges, reporting 8× (GPU) to 60× (CPU) TTFT speedups (arXiv:2311.04934); CacheBlend recomputes the top 10–20% high-deviation tokens per layer to restore quality (arXiv:2405.16444). On Lotti's stack, llama.cpp/llama-server reuse is strictly prefix-bound and per-slot — longest common prefix, recompute the diverging suffix, not keyed by message ID; Ollama inherits this (llama.cpp Discussion #13606). The most flexible production scheme (SGLang RadixAttention) is still prefix-structured (LMSYS).
  • The application-level layer is distinct: a deterministic hash of prompt + params + model keys the stored final response, returned on byte-identical requests, model-external and provider-agnostic.

Lotti mapping. (1) The KV/prefix cache lives inside the inference backend; Lotti gets on-device hits only by keeping a stable, byte-identical prefix (soul prompt → tools → rolling summary → recent head). The branching log means only one linear path occupies the KV slot, so planner and per-task agents compete for one prefix cache per device — a scheduling problem. Position-independent reuse is out of scope on stock GGUFs. (2) The application-level content-addressed response cache is what Lotti owns and what makes deterministic replay and cheap forking work: hash(rendered prompt + model id + decoding params + resolved tool set + soul config) → stored response, identical whether from Ollama or an EU API.

Thread D — GDPR-compliant EU-hosted LLM inference (the cloud fallback tier)

A mature "EU-hosted, GDPR-aligned, open-weights" tier exists and is converging on a common contract: an OpenAI-compatible HTTP API, EU data residency, zero/short retention, no training on prompts, and a catalog dominated by open-weight families (Llama, Mistral/Mixtral, Qwen, DeepSeek, gpt-oss).

  • Mistral La Plateforme hosts API data in the EU by default, retains inputs/outputs 30 rolling days for abuse monitoring then deletes, does not train on paid-API data by default, and offers Zero Data Retention on request plus a DPA (Anarlog). OVHcloud AI Endpoints is a sovereign, OpenAI-compatible API exposing 40+ open-weight models, keeping only billing data and never training on prompts (OVHcloud).
  • The tier has effectively standardized on an OpenAI-compatible surface across Mistral, OVHcloud, Scaleway, Nebius, and IONOS, making providers swappable behind a thin adapter (Scaleway Generative APIs).
  • Open-weight families overlap between local and cloud, so the same model run via Ollama can be served from an EU endpoint, enabling on-device-to-cloud escalation on the same family (Scaleway supported models).

Compliance caveat — verify against primary sources before relying. These provider claims are point-in-time and several lean on secondary write-ups (the Mistral retention summary above is a third-party article, not the primary DPA). Primary docs confirm the load-bearing shape: Mistral's 30-day abuse-monitoring retention and Zero Data Retention option; Scaleway's default ZDR and no-train; IONOS's German-only processing, no-train per DPA. But specific superlatives — Mistral "EU by default" and "no training on paid-API data by default", OVHcloud "only billing data" / "never trains on prompts", and any model-version immutability guarantee — are not explicitly confirmed by those primary pages and must be checked against each vendor's current DPA/terms (with an as-of date) before they inform a residency or cache-determinism decision. This restates §11's open question (D) at the point where the claims live.

Lotti mapping. Model "EU fallback" as a single capability behind a thin Dart adapter (one client; pluggable base-URL + auth + model-id + residency/retention policy), matching the vendor-agnostic, no-Python goal and the existing ProfileResolver. For determinism, every triggering message must persist the exact provider + pinned model id + parameters, and the content-addressed response cache becomes the determinism boundary for any non-local tier (version-pinning is load-bearing). Prefer contractual Zero Data Retention and no-train defaults; the maximally sovereign tiers (IONOS German-only; Aleph Alpha EU-only plus on-prem) are the option for users demanding a single jurisdiction. The remote tier sits outside the Matrix sync trust boundary: only the durable, vector-clocked results are replicated.

Thread E — No-bullshit accountability UX without becoming a nag

The line between a respected partner and an ignored nag converges on: intervene only when state warrants, default to silence, reflect discrepancy with calibrated honesty, and actively counter-steer the model's sycophantic grain.

  • RLHF preference data rewards agreement over truth: matching a user's views is among the most predictive features of human preference, and five production assistants "wrongly admit mistakes when questioned, give predictably biased feedback, and mimic errors made by the user" (Sharma et al., Anthropic, arXiv:2310.13548). This can be reduced at inference time without retraining via contrastive decoding against a leading prompt, activation steering, dynamic truth-seeking system prompts, and a non-sycophantic preference model for best-of-N (arXiv:2411.15287).
  • The JITAI framework formalizes proactivity as state-gated: intervene only on vulnerability/opportunity/receptivity, with a mandatory "provide nothing" option to avoid fatigue, and persistent non-response itself becoming a tailoring variable (Nahum-Shani et al. 2018).
  • Notifications buy a short-term lift but not retention: a notification raised next-hour app-open 3.5-fold, but time-to-disengagement was no different from the no-notification policy (Bell et al., JMIR mHealth 2023).

Lotti mapping. Anti-sycophancy is the load-bearing risk: any default LLM acting as planner will validate a stated-vs-actual gap away and flip under pushback. The antiSycophancyPolicy "Souls" field is the right seam and should encode the retraining-free mitigations, holding across the on-device → EU → proprietary ladder (small local models may need the EU fallback to clear the honesty bar). The planner's decide-when-to-interrupt logic should be a JITAI decision-rule engine with a first-class "provide nothing" option and missingness-as-signal — the formal antidote to nagging, aligned with the existing ChangeSet/ChangeDecision gate.

Thread F — Outcome tracking & goal systems an agent can nudge against

  • The lead/lag split is the central modeling primitive: lagging indicators (weight, revenue, hours-shipped) are read-only history, while leading indicators are both predictive of the lag and directly influenceable — so a nudging actor must act on leads, not lags (FranklinCovey 4DX).
  • Monitoring causes attainment: across 138 randomized studies (N=19,951), prompting people to monitor progress reliably promoted goal attainment (d+ = 0.40). Decisively, monitoring the behavior changed the behavior but not the outcome, while monitoring the outcome changed the outcome but not the behavior — you must monitor the specific thing you want to move (Harkin et al. 2016).
  • The JITAI four-component model (decision points, tailoring variables, intervention options including "do nothing," decision rules) is the transferable runtime blueprint (Nahum-Shani et al.).

Lotti mapping. A long-term outcome should be a typed graph entity modeling the 4DX split — a lagging numeric target plus decomposed leading indicators — linked via new AgentLink variants into journal entries and DayPlan tasks; non-negotiables are leading indicators with hard floors. Drift detection is an event-sourced behavior that fires when an actual-vs-intended delta on a leading indicator crosses a threshold (tolerant window/decay to avoid false alarms), reading actuals projected from the immutable log. Actuals are not self-reported: Lotti already imports Apple Health / Google Fit data (HealthService/health_import → synced QuantitativeEntry/WorkoutEntry), so "gym 3×/week" is verified against real workout entries and steps/activity become genuine, sensor-backed leading indicators. The nudge output is a ChangeSet — the existing human gate is the JITAI intervention surface. Continuously-incrementing numeric measurements need care under merge (see Thread G).

Thread G — Local-first / CRDT / convergent event-sourcing under multi-device sync

The state of the art splits into two layers the anchor conflates: convergence of replicated state (CRDT theory), and ordering metadata (logical clocks). The crucial synthesis is that a vector clock and a hybrid logical clock answer different questions and are not substitutes.

  • There are exactly two families of sufficient conditions for Strong Eventual Consistency: operation-based (concurrent operations commute, delivered in causal order, applied exactly once) and state-based (merge forms a join-semilattice — commutative, associative, idempotent), and the two are formally equivalent (Shapiro et al., SSS 2011).
  • A vector clock is the only common logical clock that can decide whether two events are concurrent (equal / A-dominates / B-dominates / CONCURRENT), at O(N) space; Lamport and Hybrid Logical Clocks are O(1) but impose only a total order and cannot tell concurrent from causally-ordered events apart (Normore). The correct convergent fold uses the vector clock to classify each pair — causal order is respected by replay order — and consults a timestamp LWW tiebreak only on the genuinely concurrent branch (crdt.tech).
  • A distributed lease alone cannot guarantee single-writer side effects (a process can pause past lease expiry and still issue a stale write); the standard fix is a monotonically increasing fencing token the resource side rejects if lower (Kleppmann). The candid open weakness of CRDT/local-first systems is precisely the anchor's second gap: retaining full history "creates performance problems" — compaction is the unsolved cost (Local-first software, Ink & Switch, Onward! 2019).

Lotti mapping. The codebase confirms Lotti sits on the correct side of every line. lib/classes/vector_clock.dart implements a real version vector: a four-way VclockStatus, compare returning concurrent exactly when neither clock dominates, and element-wise-max merge — so Lotti can detect concurrency, which a scalar HLC cannot. The right reading of "vector clock + LWW" is not LWW-everywhere: the vector clock classifies each pair, causal order is respected by merge/replay, and the updatedAt LWW tiebreak is consulted only on the concurrent branch. Two conditions must hold for a fully deterministic projection: (1) extend the partial order — the causal messagePrev DAG, with the vector clock classifying concurrency rather than ordering — to a single deterministic total order with a replica-independent tiebreak (a stable hostId+id key on otherwise-concurrent events); and (2) make the LWW comparator a genuine total order with a deterministic secondary tiebreak — without breaking updatedAt ties by hostId, two devices can diverge on equal timestamps. The anchor's two open problems map directly: compaction should be an append-only, content-addressed checkpoint event naming the exact prefix it summarizes (so replay-from-summary reproduces the same projected state, provenance, and verbatim uncovered tail as replay-from-genesis — not byte-identical summary text, which two independent LLM summarizations cannot guarantee; see §6); and side-effecting actions (notifications, paid inference, external calendar writes, and especially the PLANNER committing a schedule) must serialize behind a lease keyed to the side-effect boundary (§8) + fencing token rather than merge via LWW, while pure log appends converge for free.

Synthesis

The central thesis holds against the literature, and the codebase backs it. Lotti is already an event-sourced, vector-clocked, multi-device-synced, federated typed-edge graph, matching Akka/Pekko-style replicated event sourcing (op-based CRDT events + version vectors + commutative handlers). The Log is the Agent supplies the structural frame; Lotti's substrate is the closest production-shaped instance of it. The gap reduces to the two additive moves the thesis names — (1) make agent-derived state a projection of the log (corroborated by Anthropic's cold-start-from-artifacts finding and MemGPT's tiering that the dormant fields already mirror), and (2) add negotiation/phase/outcome as new node+edge types plus a planner behavior (exactly Hayes-Roth's meta-level controller over a blackboard, with Contract-Net message shapes, Sarne-Grosz VOI deciding when the gate fires, and a deterministic hard-constraint verifier protecting non-negotiables). The anchor explicitly leaves multi-agent contention and log compaction unresolved; Threads A/G and B are the two layers Lotti must add, and both reduce to event-sourcing the relevant decisions so they inherit replay and forking.

Three distinctions must be stated plainly because the architecture is fragile to conflating them: (a) application-level response memoization (content-addressed, the determinism boundary Lotti owns) vs (b) model-level KV/prefix caching (backend-internal, prefix/position-bound, exploited only via a byte-stable prefix); and (c) vector clock + LWW is sufficient for a convergent deterministic projection — with the two named conditions above — and HLC is not a substitute for the vector clock, only a possible hardening of the concurrent-branch tiebreak.

Verification note

The research run adversarially fetch-checked load-bearing claims (3 verifiers per claim; ≥2 refutes to drop). One claim was refuted and removed: an overstated version of Gollwitzer & Sheeran (2006) on implementation intentions. The accurate version: implementation intentions (if-then plans) produced a medium-to-large effect on goal attainment (d = .65) across 94 independent tests; effects are larger when (a) there is a genuine self-regulatory problem, (b) the underlying goal intention is strong/activated, and (c) the plan uses the contingent if-then format and is precise, viable, and instrumental. The claim that "effects are larger when the plan is rehearsed at least once" is not a finding of that meta-analysis and was struck.

Post-research codebase correction. The research run's open questions assumed Lotti has no passive-sensing pipeline (Threads E/F). A check of the codebase found this incorrect: Lotti already imports Apple Health / Google Fit data via HealthService/health_import into synced QuantitativeEntry/WorkoutEntry rows (steps, workouts, HR, BMI, BP). Receptivity and outcome actuals are therefore sensor-backed; §3, §9, §11 and ADR 0019 reflect the correction.

References

Sources cited above, grouped by thread. (arXiv IDs in the 2602/2605 range are 2026 preprints surfaced and source-checked during the research run.)


Grounding files referenced: lib/classes/vector_clock.dart, lib/classes/agents/agent_link.dart, lib/features/agents/README.md, lib/features/daily_os_next/README.md.


Flatpak Flathub Recovery (`docs/flatpak-flathub-recovery.md`)

Flatpak/Flathub Build Recovery – Progress Log

Summary

  • Goal: Restore a reproducible Flathub submission build for Lotti, generate a submission‑ready manifest (urls + sha256 only), and pass local validation without ad‑hoc network during build.
  • Status: Flatpak pipeline largely refactored. flatpak-flutter is now preferred and preserved; nested Flutter 3.35.7 is used; Rust toolchain resolves via SDK extension (with an offline rustup bootstrap for cargokit’s rustup calls); SQLite and mimalloc are provided via declared sources; cargokit patches are applied and ordered correctly. The build reaches the CMake/ninja stage and fails while building the flutter_vodozemac plugin (link/compile step).

Key Changes Implemented

  • Prefer flatpak-flutter outputs; fail fast on failure

    • Preserve pubspec-sources.json and flutter-sdk-*.json if flatpak-flutter succeeds; do not overwrite with fallback generators.
    • Abort the run if flatpak-flutter fails, unless ALLOW_FALLBACK=true is set for local debugging (strict, submission-friendly default).
    • Code: manifest_tool/prepare/orchestrator.py
  • Flutter 3.35.7 and nested SDK by default

    • Detect and use FVM tag 3.35.7 from repo (.fvmrc), generate flutter-sdk-3.35.7.json, and use nested SDK to avoid Dart SDK downloads during build.
    • Code: manifest_tool/cli.py, manifest_tool/prepare/orchestrator.py
  • Eliminate build-time network for plugin toolchains

    • SQLite and mimalloc are supplied as manifest sources and a SQLite CMake patch is applied to use URL_HASH instead of re-downloading.
    • cargokit patches (run_build_tool.sh.patch) are injected only for super_native_extensions and flutter_vodozemac, and moved after pubspec/cargo sources in the manifest.
    • Code: manifest_tool/flutter/plugins.py, manifest_tool/flutter/patches.py, manifest_tool/prepare/orchestrator.py
  • Rust toolchain and cargo config

    • Ensure /usr/lib/sdk/rust-stable/bin is on PATH; remove rustup install from build.
    • Stage cargo vendor config into CARGO_HOME; add helper commands for cargokit (mkdir .cargo, link vendor, copy config).
    • Code: manifest_tool/flutter/rust.py, manifest_tool/flutter/offline_fixes.py
  • Handle local path dependency (tool/lotti_custom_lint)

    • flatpak-flutter clones the repo then runs flutter pub get; if the commit lacks the tool path, pub get fails.
    • Pre-stage tool/lotti_custom_lint into the flatpak-flutter build tree before pub get and later strip any local dir sources from the final manifest.
    • Code: manifest_tool/prepare/orchestrator.py
  • Pub tool deps (pinned versions for cargokit tools)

    • Preserve flatpak-flutter’s pubspec-sources.json when available.
    • As a guarded fallback, inject specific pinned packages (e.g., yaml 3.1.2) into pubspec-sources.json as url+sha entries when missing.
    • Avoid path-based sources for submission; builder downloads from pub.dev using sha256.
    • Code: manifest_tool/prepare/orchestrator.py

Current Blocker

  • The build completes Flutter assemble and then ninja stops with a subcommand failure while building flutter_vodozemac (no .so produced yet). super_native_extensions builds successfully.
  • Failure details (captured from verbose build):
    • Target: plugins/flutter_vodozemac/libvodozemac_bindings_dart.so
    • Cargokit external command: rustup run stable cargo build … --target aarch64-unknown-linux-gnu
    • Cargo error: error: no matching package found searched package name: ctr location: registry crates-io, required by: vodozemac_bindings_dart v0.1.0
    • Interpretation: Cargo is configured to use vendored sources (crates-io replaced), but the vendored set is incomplete — crate ctr is missing.

Root cause analysis

  • Our cargo-sources.json was generated from an outdated Cargo.lock for dart‑vodozemac.
  • We downloaded flutter_vodozemac-Cargo.lock from commit a3446206…, but the build actually uses flutter_vodozemac-0.3.0 (tag commit 5319314e…).
  • The 0.3.0 lockfile includes ctr = 0.9.2; the older lockfile did not, so ctr never got vendored. Result: offline cargo cannot resolve ctr and fails.

Fix plan

  • Update the Cargo.lock source for dart‑vodozemac to match the plugin version used in the build (0.3.0):
    • Replace the lockfile URL for flutter_vodozemac with: https://raw.githubusercontent.com/famedly/dart-vodozemac/5319314eb397bc3c8de06baddbe64fa721596ce0/rust/Cargo.lock.
    • Regenerate cargo-sources.json so it includes ctr 0.9.2 (and any other newly required crates) and rebundle.
  • Keep cargokit’s run_build_tool.sh patch to force dart pub get --offline (already applied). Cargo offline is handled via CARGO_HOME/.cargo/config and vendored sources; no change is required there.
  • Ensure the offline rustup bootstrap module is included (we already include rustup-1.83.0.json) so rustup run stable cargo … works without network.

Quick verification steps

  • Recreate submission payload (strict mode): ./prepare_flathub_submission.sh
  • Validate: ./validate_flathub.sh
  • Inspect flathub-build/output/cargo-sources.json and confirm entries for ctr-0.9.2 are present (archive + .cargo-checksum.json inline).
  • Re-run the failing target inside the builder directory for quick feedback:
    • cd flathub-build/output/.flatpak-builder/build/lotti-1/build/linux/arm64/release
    • ninja -v install

How To Reproduce Locally

  1. Prepare Flathub submission artifacts (strict mode):
    • ./prepare_flathub_submission.sh (fails if flatpak-flutter fails)
  2. Validate with offline manifest:
    • ./validate_flathub.sh
  3. Debug the CMake/ninja failure (verbose):
    • cd flathub-build/output/.flatpak-builder/build/lotti-1/build/linux/arm64/release
    • ninja -v install (ensure ninja is installed on the host)

What The Submission Manifest Should Contain

  • Only url+sha256 entries for 3rd‑party sources (GitHub, pub.dev, sqlite.org, etc.).
  • Local assets (icons, screenshot, pubspec-sources.json, cargo-sources.json, flutter-sdk-*.json, small patches) remain type: file. The .desktop and AppStream (.metainfo.xml) files are now installed from the upstream lotti repository during the lotti module build.
  • No dir sources (we strip them in post-processing).
    • File: flathub-build/output/com.matthiasn.lotti.yml

Relevant Files (for quick navigation)

  • Generator/Orchestrator: manifest_tool/prepare/orchestrator.py
  • Flatpak-flutter wrapper/tools: flatpak-flutter/flatpak-flutter.py
  • Plugins and patches:
    • manifest_tool/flutter/plugins.py
    • manifest_tool/flutter/patches.py
    • manifest_tool/flutter/offline_fixes.py
    • manifest_tool/flutter/rust.py

Notes / Decisions

  • We now fail fast on flatpak-flutter failures by default to mirror Flathub behavior and keep reproducibility.
  • ALLOW_FALLBACK=true can be set to continue with local fallback generation during investigation, but outputs must remain submission‑safe.
  • We prefer flatpak-flutter outputs (pubspec-sources.json, flutter-sdk-*.json) to stay aligned with Flathub’s pipeline.

Addendum: Rust toolchain/rustup

  • Cargokit shells out to rustup run …. To avoid build-time network, we include an offline rustup bootstrap (rustup-1.83.0.json) that seeds RUSTUP_HOME=/var/lib/rustup with the toolchain from static.rust-lang.org artifacts bundled as files. PATH includes /usr/lib/sdk/rust-stable/bin so cargo/rustc are available; rustup run stable … resolves to the seeded toolchain without network.

Next Planned Steps

  • Regenerate cargo-sources.json using the 0.3.0 dart‑vodozemac lockfile and retry. If further crates are reported missing, iterate until ninja install succeeds for flutter_vodozemac.

Next Planned Steps

  • Capture verbose ninja output for flutter_vodozemac and patch the manifest/env as needed (e.g., pkg-config, linker flags, feature toggles).
  • If its cargokit rust build requires additional vendored crates/config, extend cargo vendor staging (already partly in place via cargo-sources.json).

Macos Release (`docs/macos-release.md`)

macOS Release

This document covers the GitHub Release distribution path for Lotti macOS — a Developer ID signed and notarized .dmg produced automatically by .github/workflows/flutter-macos-release.yml whenever a tag is pushed.

This is separate from the Mac App Store / TestFlight path, which is driven by macos/fastlane/Fastfile (do_build / do_upload) and uses an App Store distribution certificate via match. Do not mix the two — they use different certificates, different provisioning profiles, and different exportOptions.plist settings.

Path Cert type Profile type Driver
GitHub Release .dmg Developer ID Application Developer ID flutter-macos-release.yml
TestFlight / MAS Mac App Distribution Mac App Store fastlane do_upload

Prerequisites

  • Apple Developer Program membership for team 7DN35ABWYL.
  • Access to the developer portal at https://developer.apple.com/account.
  • A Mac with Xcode and Keychain Access for exporting credentials.

One-time setup

1. Developer ID Application certificate

If you don't already have a Developer ID Application certificate in the login keychain:

  1. In Keychain Access, choose Certificate Assistant → Request a Certificate from a Certificate Authority. Save the CSR to disk.
  2. In the developer portal, create a new certificate of type Developer ID Application. Upload the CSR. Download the resulting .cer and double-click to install.

Export as .p12:

  1. Open Keychain Access, search for Developer ID Application: Matthias Nehlsen (7DN35ABWYL).
  2. Expand the entry so the private key is visible.
  3. Select both the certificate and its private key (⌘-click).
  4. Right-click → Export 2 items… → save as lotti-developerid.p12.
  5. Set a strong password. This becomes MACOS_CERTIFICATE_PASSWORD.

2. Developer ID provisioning profile

In the developer portal:

  1. Navigate to Profiles → + → Developer ID (under Distribution, macOS).
  2. App ID: com.matthiasn.lotti.
  3. Include the application group SS586VG7L7.lottiobx (matches macos/Runner/Release.entitlements).
  4. Select the Developer ID Application certificate from step 1.
  5. Download as lotti_developerid.provisionprofile.

3. App-specific password for notarytool

  1. Open https://appleid.apple.com/account/manage.
  2. Under App-Specific Passwords, generate a new password labelled e.g. lotti-notary-ci.
  3. Copy the value. This becomes APPLE_APP_PASSWORD.

4. Base64 encode for GitHub Secrets

Encode each file as a single unwrapped line. macOS BSD base64 does not wrap by default; -b 0 makes that intent explicit (and is harmless on systems whose base64 does wrap):

bash
base64 -b 0 -i lotti-developerid.p12              -o lotti-developerid.p12.b64
base64 -b 0 -i lotti_developerid.provisionprofile -o lotti_developerid.provisionprofile.b64

To copy a value to the clipboard for pasting into the GitHub secret editor:

bash
pbcopy < lotti-developerid.p12.b64

5. GitHub Secrets

In the repository: Settings → Secrets and variables → Actions → New repository secret.

Secret name Value
MACOS_CERTIFICATE_BASE64 contents of lotti-developerid.p12.b64
MACOS_CERTIFICATE_PASSWORD password used when exporting the .p12
MACOS_PROVISIONING_PROFILE_BASE64 contents of lotti_developerid.provisionprofile.b64
MACOS_KEYCHAIN_PASSWORD any random string — only locks the temp keychain on the runner. Generate with openssl rand -hex 24
APPLE_ID Apple ID email used for notarization
APPLE_APP_PASSWORD app-specific password from step 3
APPLE_TEAM_ID 7DN35ABWYL

6. Local verification before pushing a tag

bash
# Confirm the exported cert really is Developer ID Application:
security find-certificate -c "Developer ID Application" -p login.keychain-db \
  | openssl x509 -noout -subject -issuer

# Inspect the provisioning profile:
security cms -D -i lotti_developerid.provisionprofile | plutil -p - | head -40

Both should reference team 7DN35ABWYL and bundle id com.matthiasn.lotti.

After verification, delete the unencoded .p12 and .provisionprofile files from disk — the encoded copies in GitHub Secrets are now the source of truth for CI.

Triggering a release

Push a tag (any tag matches the workflow trigger):

bash
git tag v0.X.Y
git push origin v0.X.Y

The workflow will:

  1. Import the certificate into a temp keychain on the runner.
  2. Drop the provisioning profile into ~/Library/MobileDevice/Provisioning Profiles/.
  3. Run flutter build macos --release --no-codesign, then xcodebuild archive, then xcodebuild -exportArchive with a generated developer-id exportOptions.plist.
  4. Notarize the .app with notarytool submit --wait and staple the ticket.
  5. Build Lotti.dmg via hdiutil.
  6. Notarize and staple the .dmg.
  7. Create a prerelease GitHub Release (gh release create -p) and upload the .dmg.
  8. Print the total build duration to logs and the job summary.

The release is created as a prerelease. After all platform workflows (Android, Linux, macOS, …) finish, manually mark it as latest in the GitHub UI.

Rotating credentials

  • Certificate expires (every ~5 years for Developer ID): redo step 1, re-encode, update MACOS_CERTIFICATE_BASE64 and MACOS_CERTIFICATE_PASSWORD.
  • Provisioning profile expires: redo step 2, re-encode, update MACOS_PROVISIONING_PROFILE_BASE64.
  • App-specific password lost or revoked: redo step 3, update APPLE_APP_PASSWORD.

Troubleshooting

  • errSecInternalComponent during xcodebuild archive — the imported key wasn't authorized for codesign. The workflow handles this via security set-key-partition-list; check that step's logs.
  • No matching profiles found — bundle id, team, or entitlements (notably application-groups) on the profile don't match macos/Runner/Release.entitlements. Recreate the profile.
  • Notarization status Invalid — fetch the log with xcrun notarytool log <submission-id> --apple-id … --team-id … --password …. Common causes: hardened runtime not enabled, unsigned helper binaries inside the app bundle, or use of disallowed entitlements for Developer ID.
  • Gatekeeper still warns after install — confirm the staple succeeded: xcrun stapler validate Lotti.dmg and spctl -a -vv -t install Lotti.dmg.

Docs Site Docs Roadmap (`docs-site/docs/roadmap.mdx`)


title: Roadmap sidebar_label: Roadmap

Roadmap

Everything on this page is design intent, not a shipped feature; scope and
details can change before release.

Check your understanding, not just your output

Learning quizzes turn your own tasks into quick comprehension checks. From
any task with quizzable content you will be able to tap Check my
understanding
and get a short quiz tailored to that task, mixing
multiple-choice questions with open questions you can answer by typing or
by voice; a quiz needs AI configured for the task's category, and one quiz
per task runs at a time. Grading is conversational: when an answer is
shallow or ambiguous, the AI asks a follow-up — at most two per question —
before judging, and you can end probing, skip a question, or reveal the
answer at any time; every miss is explained, grounded in the task content
the question came from. Each quiz ends with a score, a label,
and a gap list, and keeps its own timeline — questions, answers, follow-ups,
and grades — so you can reopen it from the task later. Grades are AI
feedback about one quiz, never a credential or a comparison with other
people, and quiz history stays private, syncable, and deletable like other
agent data.

The planned progression:

  1. Quiz any eligible task on demand, with a quick-check or deep-dive
    choice and fresh questions each time.
  2. More surfaces and gentle suggestions — projects, days, and agent
    reports, plus an optional "Quiz yourself on this?" card with strict caps
    and disable controls.
  3. Consented workspace evidence so engineering quizzes can draw on
    repository diffs and test summaries through a read-only integration.
  4. History insights that surface recurring gap themes over time.

Questions and grades come only from content Lotti actually captured — thin
content yields fewer questions rather than filler, suggestions never run AI
before you accept, and quizzes never block completing a task.

Stay close to the people who matter

Relationships become a first-class part of Lotti: one long-running entry
per person, with its own timeline, alongside your tasks and projects. After
you see someone, you will be able to log a check-in — met in person,
phone call, video, or message — capturing what you talked about, how the
interaction felt, and what to pay attention to or avoid next time.
Relationships link to tasks, so the call you need to prepare or the visit
you promised sits right on that person's timeline. You will also be able
to connect a relationship to a contact from your address book — person by
person, never as a bulk import — and call or message them straight from
the briefing; when you return to Lotti, it offers to log that interaction
as a check-in. Mark a relationship as
important and Lotti gently reminds you to check in when too much time
has passed — you choose the rhythm per person, and only relationships you
marked important ever produce reminders. Each relationship gets its own
dedicated agent — the same durable agents that look after tasks and
projects — which keeps the picture current and, before you next meet
someone, prepares an executive briefing: how things are going, the
topics from recent check-ins, how conversations have felt over time, and
what to bring up or steer around — like a thoughtful assistant preparing
you for the conversation.

The planned progression:

  1. Relationships with a timeline — a person-centered entry with linked
    notes, photos, and tasks.
  2. Check-ins — quick structured capture of each interaction: type,
    sentiment, topics, and next-time guidance.
  3. Reminders for important relationships — cadence-based nudges you
    control per person.
  4. Executive briefings — an AI-prepared summary before your next
    conversation, grounded only in your own check-ins.

Relationship data will get the strictest treatment Lotti has: it will be
stored locally on your devices, never on a Lotti server — there is none. If you
turn on sync, entries will travel end-to-end encrypted between your devices, so
the relay server would only ever handle ciphertext. Briefings run on local AI
models by default; if you explicitly pick a cloud provider, Lotti names it
before anything is sent — and with a GDPR-compliant provider offering zero
data retention, inference remains transient processing, with nothing
stored outside your devices. Handing relationship data to third
parties without your explicit choice would be irresponsible — so Lotti
simply doesn't.


Adr 0001 Agent Capabilities Runtime Model (`docs/adr/0001-agent-capabilities-runtime-model.md`)

ADR 0001: Agent Capabilities Runtime Model

  • Status: Accepted
  • Date: 2026-02-27

Context

Agent Capabilities now includes persistent task agents and template evolution
sessions. The system must stay robust under app restarts, cross-device sync,
and bursty task updates while remaining testable and easy to evolve.

Decision

  1. Keep two persistence domains:
    • Journal domain (db.sqlite) for task/checklist source-of-truth
    • Agent domain (agent.sqlite) for agent identity/state/messages/reports,
      template versions, and wake runs
  2. Execute task agents through a single orchestration path:
    • WakeOrchestrator manages subscription matching, suppression, throttling,
      and queue/drain execution
    • TaskAgentWorkflow owns context assembly, conversation execution, tool
      routing, and sync-aware persistence
  3. Build linked-task context from linked task-agent reports:
    • Use latestTaskAgentReport from linked task agents
    • Strip latestSummary from linked task payloads before prompt submission
  4. Keep state-layer wiring provider-first:
    • Riverpod providers assemble orchestrator/workflow/runtime dependencies
    • GetIt access is isolated behind dependency providers where needed

Architecture Snapshot

mermaid
flowchart LR
  UI["Task UI"] --> INIT["agentInitializationProvider"]
  INIT --> ORCH["WakeOrchestrator"]
  ORCH --> WF["TaskAgentWorkflow"]
  WF --> CONV["ConversationRepository"]
  CONV --> MODEL["Inference Provider"]
  WF --> EXEC["AgentToolExecutor"]
  EXEC --> JOURNAL["Journal Repository and DB"]
  WF --> SYNC["AgentSyncService"]
  SYNC --> AGENTDB["AgentRepository and agent.sqlite"]
  SYNC --> OUTBOX["Sync Outbox"]

Wake Call Tree

mermaid
flowchart TD
  A["UpdateNotifications.localUpdateStream"] --> B["WakeOrchestrator._onBatch"]
  B --> C["WakeOrchestrator.processNext"]
  C --> D["WakeOrchestrator._drain"]
  D --> E["WakeOrchestrator._executeJob"]
  E --> F["wakeExecutor callback"]
  F --> G["TaskAgentWorkflow.execute"]
  G --> H["ConversationRepository.sendMessage"]
  H --> I["TaskAgentStrategy.processToolCalls"]
  I --> J["AgentToolExecutor.execute"]
  J --> K["Task handlers"]
  G --> L["AgentSyncService.upsertEntity and upsertLink"]
  L --> M["AgentRepository writes"]

Wake Sequence

mermaid
sequenceDiagram
  participant T as "Task UI"
  participant N as "UpdateNotifications"
  participant O as "WakeOrchestrator"
  participant W as "TaskAgentWorkflow"
  participant C as "ConversationRepository"
  participant M as "Model Provider"
  participant J as "Journal Repository"
  participant A as "AgentRepository"

  T->>N: "Emit changed tokens"
  N->>O: "_onBatch(tokens)"
  O->>O: "match + suppress + throttle + enqueue"
  O->>O: "processNext and _executeJob"
  O->>W: "wakeExecutor(agentId, runKey, triggers, threadId)"
  W->>C: "sendMessage(system + context + tools)"
  C->>M: "LLM request"
  M-->>C: "tool calls and assistant text"
  C->>J: "tool side-effects via handlers"
  W->>A: "persist report/messages/state"
  W-->>O: "WakeResult"
  O->>A: "update wake_run status"

Consequences

  • Task-agent context reflects the latest durable agent output instead of summary
    snapshots that are being phased out.
  • Wake behavior is deterministic and easier to reason about because matching,
    suppression, throttle timing, and drain execution are centralized.
  • Cross-device behavior remains consistent because all agent writes flow through
    AgentSyncService.
  • Test harnesses can override runtime wiring at provider boundaries without
    rewiring global runtime setup.
  • lib/features/agents/README.md
  • PR #2710

Adr 0002 Wake Scheduling And Throttling Policy (`docs/adr/0002-wake-scheduling-and-throttling-policy.md`)

ADR 0002: Wake Scheduling and Throttling Policy

  • Status: Accepted
  • Date: 2026-02-27

Context

Task edits can arrive in bursts while a wake is already running. The runtime
needs deterministic behavior for queueing, throttling, and manual reanalysis
without double-running an agent.

Decision

  1. Use defer-first scheduling for subscription wakes:
    • First matching subscription signal enqueues a wake and starts a throttle
      window (120s) before drain.
  2. Coalesce incoming tokens per agent while queued/throttled:
    • Merge tokens into the first queued job for that agent instead of
      creating duplicate jobs.
  3. Manual wakes override queued subscription work:
    • Clear throttle for the agent.
    • Remove queued jobs for the same agent.
    • Enqueue one manual job immediately.
  4. Keep drain single-flight:
    • processNext() is guarded so only one drain loop runs at a time.
    • New drain requests set a flag and are handled by the active loop.
  5. Persist throttle state:
    • Persist nextWakeAt on set/clear so UI and restart behavior stay
      consistent.
  6. Keep a safety net:
    • Periodic timer (60s) triggers drain when queue has pending jobs and
      no drain is active.

Scheduling Flow

mermaid
flowchart TD
  N["Notification batch"] --> M{"Matches subscription?"}
  M -- "No" --> X["Drop"]
  M -- "Yes" --> S{"Suppressed?"}
  S -- "Yes" --> X
  S -- "No" --> T{"Agent throttled?"}
  T -- "Yes" --> C["Merge tokens or enqueue deferred job"]
  T -- "No" --> E["Enqueue subscription job"]
  E --> D["Set throttle deadline (nextWakeAt)"]
  D --> Q["Deferred drain timer"]
  C --> Q
  Q --> R["processNext / _drain"]
  R --> J["Execute wake job"]

Manual Wake Override

mermaid
sequenceDiagram
  participant UI as "Agent UI"
  participant O as "WakeOrchestrator"
  participant Q as "WakeQueue"

  UI->>O: "enqueueManualWake(agentId)"
  O->>O: "clearThrottle(agentId)"
  O->>Q: "removeByAgent(agentId)"
  O->>Q: "enqueue(manual job)"
  O->>O: "processNext()"

Consequences

  • Bursty edits collapse into one queued wake per agent with merged tokens.
  • Manual reanalysis runs immediately and supersedes stale queued subscription
    work.
  • Throttle behavior survives app restarts via persisted nextWakeAt.
  • Drain execution remains deterministic without overlapping loops.
  • ADR 0027: Wake Notification Propagation and Storm Prevention
    — the origin-routing model and cross-entity fan-out that decide which write
    reaches this throttle path, and on behalf of which agents.
  • lib/features/agents/wake/wake_orchestrator.dart
  • lib/features/agents/wake/wake_queue.dart
  • lib/features/agents/wake/run_key_factory.dart

Adr 0003 Task Agent Linked Task Context Contract (`docs/adr/0003-task-agent-linked-task-context-contract.md`)

ADR 0003: Task Agent Linked-Task Context Contract

  • Status: Accepted
  • Date: 2026-02-27

Context

Task-agent wake prompts need linked-task context, but linked task summaries are
being phased out. The wake path must consume linked task-agent reports instead
and remain resilient when linked context/report resolution fails.

Decision

  1. Build linked-task context on the task-agent wake path via
    TaskAgentWorkflow._buildLinkedTasksContextJson (forked shape from
    AiInputRepository.buildLinkedTasksJson).
  2. Source linked task lists from:
    • AiInputRepository.buildLinkedFromContext(taskId)
    • AiInputRepository.buildLinkedToContext(taskId)
  3. Remove latestSummary from all linked-task rows before prompt submission.
  4. Inject task-agent report fields when available:
    • taskAgentId
    • latestTaskAgentReportOneLiner
    • latestTaskAgentReportTldr
  5. In TaskAgentWorkflow._resolveLatestTaskAgentReport, resolve linked task
    agent by agent_task links sorted with:
    • primary: createdAt descending
    • secondary: deterministic tie-breaker on link.id
  6. Keep failures non-fatal:
    • If linked-task context building fails, return '{}'.
    • If report lookup for one linked task fails, skip injection for that task.

Context Build Sequence

mermaid
sequenceDiagram
  participant W as "TaskAgentWorkflow"
  participant AI as "AiInputRepository"
  participant AR as "AgentRepository"

  W->>AI: "buildLinkedFromContext(taskId)"
  W->>AI: "buildLinkedToContext(taskId)"
  W->>W: "remove latestSummary from all rows"
  loop "each linked task id"
    W->>AR: "getLinksTo(taskId, type: agent_task)"
    W->>AR: "getLatestReport(link.fromId, current)"
    AR-->>W: "report or null"
  end
  W->>W: "inject taskAgentId + compact report fields"
  W-->>W: "linked JSON for wake prompt"

Data Shape

mermaid
flowchart LR
  A["linked_from[] row"] --> C["remove latestSummary"]
  B["linked_to[] row"] --> C
  C --> D["add taskAgentId (if report found)"]
  D --> E["add latestTaskAgentReportOneLiner (if report found)"]
  E --> F["add latestTaskAgentReportTldr (if report found)"]

Consequences

  • Task-agent prompts no longer rely on task summaries.
  • Linked-task report rows omit per-report timestamps so dependent wakes keep a
    more stable prompt suffix and avoid spending local inference budget on
    low-value volatile fields.
  • Linked-task report selection is deterministic under equal link timestamps.
  • Linked-task context failures cannot abort wake setup.
  • ADR 0027: Wake Notification Propagation and Storm Prevention
    — linked-task report bodies are refreshed at the dependent agent's next wake
    (read-time), not pushed when a neighbor republishes; that wake is itself driven
    by the cross-entity fan-out described there.
  • lib/features/agents/workflow/task_agent_workflow.dart
  • lib/features/ai/repository/ai_input_repository.dart

Adr 0004 Task Agent Tool Execution Policy (`docs/adr/0004-task-agent-tool-execution-policy.md`)

ADR 0004: Task Agent Tool Execution Policy and Audit Trail

  • Status: Accepted
  • Date: 2026-02-27

Context

Tool calls are the mutation boundary between LLM output and journal data. The
runtime needs strong policy enforcement, durable audit messages, and explicit
self-notification suppression data.

Decision

  1. Enforce category scope fail-closed in AgentToolExecutor:
    • Resolve target entity category before mutation.
    • Deny when category is missing or not in agent allowlist.
  2. Persist action/result audit messages for each tool call:
    • Persist action message before execution.
    • Persist tool result message after execution.
    • Record policy denial metadata when denied.
  3. Use deterministic operation IDs:
    • Derive operationId from run key + tool/action stable inputs.
  4. Capture vector clocks after successful mutations:
    • Read vector clock of mutated entity.
    • Expose map of mutatedEntries for orchestrator suppression.
  5. Keep audit write failures non-fatal where possible:
    • Do not mask policy decisions or handler outcome when audit writes fail.

Tool Call Flow

mermaid
sequenceDiagram
  participant S as "TaskAgentStrategy"
  participant E as "AgentToolExecutor"
  participant H as "Task Tool Handler"
  participant J as "Journal DB"
  participant A as "AgentSyncService"

  S->>E: "execute(toolName, args, targetEntityId)"
  E->>E: "resolve category + enforce allowlist"
  alt "policy denied"
    E->>A: "persist action message (policyDenied=true)"
    E-->>S: "ToolExecutionResult(policyDenied)"
  else "policy allowed"
    E->>A: "persist action message"
    E->>H: "execute handler"
    H->>J: "mutate entity"
    H-->>E: "ToolExecutionResult"
    E->>J: "read vector clock"
    E->>A: "persist toolResult message"
    E-->>S: "ToolExecutionResult + mutatedEntries update"
  end

Consequences

  • Tool scope is enforced consistently before mutations.
  • Audit history is durable and tied to deterministic operation IDs.
  • Orchestrator suppression gets precise post-mutation vector clocks.

Addendum 2026-04-18: `retract_suggestions`

The task-agent tool surface gained retract_suggestions, an immediate
(non-deferred) tool that lets the agent withdraw its own previously
proposed change items without a user prompt. It fits the same execution
policy as the other immediate tools (update_report,
record_observations, get_related_task_details):

  • Routed through TaskAgentStrategy.processToolCalls and dispatched via
    SuggestionRetractionService.
  • Action + tool-result messages are persisted on the same audit path as
    any other tool call, so every retraction leaves an auditable trail.
  • The mutation target is agent-side state only (ChangeSetEntity +
    ChangeDecisionEntity in agent.sqlite). No journal entity is touched,
    so category-scope enforcement is inherited from the owning task but
    does not require resolving a separate target entity category.
  • Concurrency: SuggestionRetractionService writes the decision record
    first, then re-reads the parent change set before transitioning the
    item — same ordering as ChangeSetConfirmationService.confirmItem.
    Racing a user confirmation produces either outcome (confirmed or
    retracted) cleanly; both leave a matching decision record.
  • lib/features/agents/tools/agent_tool_executor.dart
  • lib/features/agents/workflow/task_agent_strategy.dart
  • lib/features/agents/service/suggestion_retraction_service.dart

Adr 0005 Template Model Resolution Policy (`docs/adr/0005-template-model-resolution-policy.md`)

ADR 0005: Template Model and Provider Resolution Policy

  • Status: Accepted
  • Date: 2026-02-27

Context

Task-agent and template-evolution workflows both rely on template-selected
model IDs. Runtime provider selection must stay deterministic and fail clearly
when configuration is incomplete.

Decision

  1. Model selection precedence for task-agent wake:
    • Use active template version model when present.
    • Fallback to template head model when version model is null.
  2. Resolve provider via configured model metadata:
    • Find AiConfigModel by providerModelId.
    • Resolve provider from the model's inferenceProviderId.
  3. Require valid provider config:
    • Provider must be an AiConfigInferenceProvider.
    • Provider must have non-empty API key.
  4. Abort workflow when provider cannot be resolved:
    • Task-agent wake returns failure (No Gemini provider configured).
    • Template evolution start/proposal operations stop early.

Resolution Flow

mermaid
flowchart TD
  T["Template + active version"] --> M["Select modelId (version first)"]
  M --> R["resolveInferenceProvider(modelId)"]
  R --> C["Find AiConfigModel by providerModelId"]
  C --> P["Load provider by inferenceProviderId"]
  P --> V{"Provider valid + apiKey present?"}
  V -- "Yes" --> OK["Proceed with conversation call"]
  V -- "No" --> FAIL["Abort workflow with provider error"]

Usage Sites

mermaid
flowchart LR
  A["TaskAgentWorkflow.execute"] --> R["resolveInferenceProvider"]
  B["TemplateEvolutionWorkflow.startSession"] --> R
  C["TemplateEvolutionWorkflow.proposeDirectives"] --> R

Consequences

  • Model/provider routing is deterministic across agent runtime paths.
  • Missing or invalid provider config fails early instead of failing during
    inference calls.
  • Task-agent and template-evolution workflows share one resolver contract.
  • lib/features/agents/workflow/task_agent_workflow.dart
  • lib/features/agents/workflow/template_evolution_workflow.dart
  • lib/features/ai/util/inference_provider_resolver.dart

Adr 0006 Change Set Deferred Tool Confirmation (`docs/adr/0006-change-set-deferred-tool-confirmation.md`)

ADR 0006: Change Set — Deferred Tool Confirmation Workflow

  • Status: Accepted
  • Date: 2026-02-27 (updated 2026-02-28)

Context

The task agent can autonomously mutate journal entities (titles, estimates, due
dates, priorities, statuses, checklist items, labels) via tool calls. Some of
these mutations are high-impact or subjective — e.g., changing a task's status to
BLOCKED or adding checklist items based on inferred requirements. Users need
visibility and control over what the agent proposes before mutations are applied.

Without a confirmation step, the only recourse is to undo changes after the fact,
which erodes trust and makes the agent feel unpredictable.

Decision

  1. Classify tools as deferred or immediate. A static set
    (AgentToolRegistry.deferredTools) lists tools whose mutations require user
    confirmation. Locally-handled tools (update_report, record_observations)
    and non-deferred tools (e.g., set_task_language) execute immediately.

  2. Accumulate proposals in a ChangeSetBuilder. When the strategy encounters
    a deferred tool and a ChangeSetBuilder is provided, the tool call is added
    to the builder instead of being executed. The LLM receives a
    "Proposal queued for user review." response and can continue its
    conversation normally.

  3. Explode batch tools into individual items. Batch tools (e.g.,
    add_multiple_checklist_items with 5 items) are split into individual
    ChangeItem entries so each element can be independently confirmed or
    rejected. The registry maps batch tool names to their array key
    (AgentToolRegistry.explodedBatchTools).

  4. Persist the change set as an AgentDomainEntity. At the end of the wake,
    the builder produces a ChangeSetEntity with status pending. Each item
    carries a toolName, args map, humanSummary, and per-item
    ChangeItemStatus.

  5. Record user decisions as ChangeDecisionEntity. Each confirm/reject
    action creates a decision entity with itemIndex, verdict, and optional
    rejectionReason, enabling the agent to learn from user preferences over
    time.

  6. Generate human-readable summaries. Each change item gets a tool-specific
    summary (e.g., Set title to "Fix login bug", Add: "Design mockup",
    Set estimate to 60 minutes) for display in the confirmation UI.

  7. Sync change sets across devices. All writes go through AgentSyncService,
    which means change sets, item status updates, and decision entities are
    automatically enqueued for cross-device sync. A proposal made on one device
    can be reviewed and confirmed on another.

Change Set Lifecycle

mermaid
stateDiagram-v2
  [*] --> pending: builder.build()
  pending --> partiallyResolved: some items decided
  pending --> resolved: all items decided
  partiallyResolved --> resolved: remaining items decided
  resolved --> [*]
  pending --> expired: TTL exceeded
  expired --> [*]

End-to-End Flow

text
/* Detailed source-code truncated for AI context efficiency. */

Tool Call Routing

mermaid
flowchart TD
  A["Tool call received"] --> B{"update_report or\nrecord_observations?"}
  B -->|Yes| C["Handle locally"]
  B -->|No| D{"changeSetBuilder\npresent?"}
  D -->|No| E["Execute via AgentToolExecutor"]
  D -->|Yes| F{"Tool in\ndeferredTools?"}
  F -->|No| E
  F -->|Yes| G{"Tool in\nexplodedBatchTools?"}
  G -->|Yes| H["Explode into individual items"]
  G -->|No| I["Add single item"]
  H --> J["Add to ChangeSetBuilder"]
  I --> J
  J --> K["Respond: 'Proposal queued'"]

Confirmation UI Architecture

mermaid
flowchart TD
  subgraph TaskForm
    A[TaskAgentReportSection] --> B[ChangeSetSummaryCard]
    B --> C[LinkedTasksWidget]
  end

  subgraph ChangeSetSummaryCard
    D[pendingChangeSetsProvider] --> E[_ChangeSetCard]
    E --> F["_ChangeItemTile × N"]
    F -->|"Swipe right / tap ✓"| G[confirmItem]
    F -->|"Swipe left / tap ✗"| H[rejectItem]
    E -->|Confirm All button| I[confirmAll]
  end

  subgraph ChangeSetConfirmationService
    G --> J[TaskToolDispatcher.dispatch]
    J --> K[persist ChangeDecisionEntity]
    K --> L[update ChangeSetEntity status]
    H --> M[persist ChangeDecisionEntity]
    M --> L
    I --> G
  end

  L --> N[updateNotifications.notify]
  N --> D

Confirmation Service Design

ChangeSetConfirmationService mediates between the UI and the tool dispatcher:

  • Re-reads before acting. Every confirmItem/rejectItem call re-reads the
    ChangeSetEntity from the repository to guard against stale snapshots from
    rapid taps or concurrent clients on other devices.
  • Atomic per-item. Each item is confirmed or rejected independently. A failed
    tool dispatch does not persist a decision — the item stays pending for retry.
  • confirmAll iterates sequentially. Re-reads the change set after each item
    to see committed state from the previous handler. This guarantees ordering
    (e.g., title change is visible to the next tool).

UI Safety

Async confirmation methods capture ref-dependent values (service, notifier)
before the await to prevent accessing ref after the widget is unmounted
during provider rebuilds.

Consequences

  • Users see proposed changes before they are applied, building trust.
  • Granular per-item confirmation allows partial acceptance of batch proposals.
  • Decision history enables agent learning from user preferences.
  • The ChangeSetBuilder is optional — callers without it get the previous
    immediate-execution behavior, maintaining backward compatibility.
  • Batch tool explosion means the singular tool handler (e.g.,
    add_checklist_item) must exist alongside the batch variant for re-execution
    of confirmed items.
  • Change sets sync across devices — proposals can be created on one device and
    confirmed on another.
  • Validation (type checks, rate limits) happens at confirmation time, not at
    proposal time. Invalid args are still deferred; errors surface when the user
    confirms.
  • Implementation plan: docs/implementation_plans/2026-02-27_change_set_confirmation_ui.md
  • lib/features/agents/tools/agent_tool_registry.dart — deferred/batch tool sets
  • lib/features/agents/workflow/change_set_builder.dart — builder implementation
  • lib/features/agents/workflow/task_agent_strategy.dart — routing logic
  • lib/features/agents/service/change_set_confirmation_service.dart — confirmation/rejection logic
  • lib/features/agents/ui/change_set_summary_card.dart — confirmation UI
  • lib/features/agents/state/change_set_providers.dart — Riverpod providers
  • lib/features/agents/workflow/task_tool_dispatcher.dart — tool dispatch at confirmation time
  • lib/classes/agents/change_set.dart — ChangeItem value type
  • lib/classes/agents/agent_domain_entity.dart — ChangeSetEntity, ChangeDecisionEntity
  • ADR 0004: Tool execution policy (immediate path)

Adr 0007 Token Usage Wake Run Log Storage (`docs/adr/0007-token-usage-wake-run-log-storage.md`)

ADR 0007: Token Usage as Synced Agent Entity

Status

Accepted

Context

Agents execute wake cycles that invoke LLM inference via ConversationRepository.sendMessage(), but token usage from these calls is currently discarded. We need to capture, persist, and display token usage data to enable cost visibility per agent template and per week — across all devices.

Three approaches were considered:

  1. Flat columns on wake_run_log — Add model_id, input_tokens, etc. columns directly to wake_run_log. Simple SQL aggregation, but wake_run_log is not synced via Matrix. Usage would be device-local only.

  2. New AgentDomainEntity variant — Create wakeTokenUsage as a freezed variant that flows through the existing entity sync pipeline via Matrix. Visible from any device.

  3. Separate sync mechanism — A new table with its own sync path. Maximum flexibility but significant infrastructure overhead.

Decision

Use a new AgentDomainEntity.wakeTokenUsage variant (option 2).

Rationale

  • Cross-device visibility is required: The user needs to see exactly what each template spent each week in the 1-on-1 evolution chat, regardless of which device ran the inference. This rules out device-local-only storage.
  • Existing sync infrastructure: AgentDomainEntity variants are automatically synced via Matrix through AgentSyncService. Adding a new variant requires minimal incremental work — one freezed variant, one case in AgentDbConversions, and it syncs for free.
  • Template-level aggregation: By storing templateId on the entity, we can aggregate costs per template across all agent instances and all devices.
  • Immutable audit trail: Each wake produces exactly one wakeTokenUsage entity. Like agentMessage, these are append-only — never updated after creation.

Sync Flow

mermaid
flowchart LR
    A[Device A: Wake cycle] --> B[WakeTokenUsageEntity]
    B --> C[agent_entities table]
    C --> D[Matrix Sync]
    D --> E[Device B: agent_entities]
    E --> F[UI: Token Usage Section]
    C --> F

Entity Design

dart
const factory AgentDomainEntity.wakeTokenUsage({
  required String id,
  required String agentId,      // the agent instance
  required String runKey,        // links back to wake_run_log
  required String threadId,      // conversation thread
  required String modelId,       // which model was used
  required DateTime createdAt,
  required VectorClock? vectorClock,
  String? templateId,
  String? templateVersionId,
  int? inputTokens,
  int? outputTokens,
  int? thoughtsTokens,
  int? cachedInputTokens,
  DateTime? deletedAt,
}) = WakeTokenUsageEntity;

Consequences

  • Token usage is synced across devices like all other agent entities.
  • Per-instance aggregation queries fetch entities by type and group in Dart (not raw SQL GROUP BY). At current volumes (tens of wakes per day) this is adequate.
  • Per-template aggregation uses a SQL JOIN through agent_links (template_assignment type) to collect token records across all instances in a single query (added in v0.9.882).
  • The wake_run_log table remains unchanged — no schema migration needed.
  • Future monetary cost calculation can be done by mapping modelId to a cost-per-token lookup.

Adr 0008 Inference Profiles Agent Provider Mapping (`docs/adr/0008-inference-profiles-agent-provider-mapping.md`)

ADR 0008: Inference Profiles — Agent-to-Provider Mapping via Profiles

  • Status: Proposed
  • Date: 2026-02-28
  • Supersedes: ADR 0005 (partially — extends the resolution chain)

Context

Agents currently reference a single providerModelId string on their template.
This works for the thinking slot but has several shortcomings:

  • No multi-capability support. An agent that needs thinking, vision,
    transcription, and image generation must use the same model for all, even when
    specialized models exist.
  • No privacy grouping. Users who want to keep data local (Ollama) or within
    the EU (Mistral) must manually pick the right model on every template. There
    is no way to express "use this set of models" as a reusable unit.
  • Provider switching is tedious. Changing from Gemini to OpenAI means
    editing every template individually.
  • Local providers rejected. resolveInferenceProvider() rejects providers
    with empty API keys, but Ollama/Voxtral/Whisper don't need keys.

Alternatives Considered

Alternative Why Rejected
A. Per-template multi-model fields — add imageRecognitionModelId, transcriptionModelId, imageGenerationModelId directly on the template. Duplicates model assignments across templates. No reusable grouping. Doesn't solve provider-switching friction.
B. Provider-level default models — each AiConfigInferenceProvider declares default models per capability. Ties capability routing to the provider entity, which is a configuration concern not a routing concern. Doesn't allow mixing providers (e.g. local transcription + cloud thinking).
C. Implicit privacy enum — add an InferenceProfilePrivacy enum (local, regional, cloud) and enforce routing constraints. The app cannot enforce data residency (a "local" model could proxy to cloud). False sense of security. Privacy intent is better encoded in the profile name, which the user controls.

Decision

Introduce Inference Profiles — named, user-manageable configurations that
bundle providerModelId strings for four capability slots:

text
Profile "Gemini Flash"
├── thinking:         models/gemini-3-flash-preview
├── imageRecognition: models/gemini-3-flash-preview
├── transcription:    models/gemini-3-flash-preview
└── imageGeneration:  models/gemini-3-pro-image-preview

1. Profile Data Model

Profiles are a new variant of the existing AiConfig sealed union, stored in
ai_config.sqlite alongside providers, models, and prompts. No schema migration
needed — the table uses a generic JSON column.

mermaid
erDiagram
    AiConfigInferenceProfile {
        string id PK
        string name "encodes privacy intent"
        string thinkingModelId "required providerModelId"
        string imageRecognitionModelId "nullable"
        string transcriptionModelId "nullable"
        string imageGenerationModelId "nullable"
        bool isDefault
        bool desktopOnly
    }

    AgentIdentityEntity {
        string agentId PK
        string configProfileId "agent-level override"
        string configModelId "legacy / backward compat"
    }

    AgentTemplateEntity {
        string id PK
        string modelId "legacy"
        string profileId "preferred"
    }

    AgentTemplateVersionEntity {
        string id PK
        string agentId
        string modelId "legacy snapshot"
        string profileId "snapshot"
    }

    AgentIdentityEntity }o--o| AiConfigInferenceProfile : "config.profileId"
    AgentTemplateEntity ||--o| AiConfigInferenceProfile : "profileId"
    AgentTemplateVersionEntity ||--o| AiConfigInferenceProfile : "profileId"

2. Resolution Chain

Profile assignment follows a precedence chain. The first non-null profileId
wins; if none is set, the legacy modelId path is used unchanged.

mermaid
flowchart TD
    A[Wake triggered] --> B{agent.config.profileId?}
    B -->|Set| C[Use agent profileId]
    B -->|Null| D{version.profileId?}
    D -->|Set| E[Use version profileId]
    D -->|Null| F{template.profileId?}
    F -->|Set| G[Use template profileId]
    F -->|Null| H[Legacy: use modelId]

    C --> I[Load profile]
    E --> I
    G --> I

    I --> I1{Profile found?}
    I1 -->|Yes| J[Extract slot modelId]
    I1 -->|No| H

    J --> K[resolveInferenceProvider]
    H --> K

    K --> K1{Model found?}
    K1 -->|Yes| K2{Provider found?}
    K1 -->|No| X[Abort wake]
    K2 -->|Yes| K3{API key?}
    K2 -->|No| X
    K3 -->|Valid or not required| L[Proceed]
    K3 -->|Empty and required| X

3. Per-Slot Capability Dispatch

Today only the thinking slot is used by TaskAgentWorkflow. The remaining
slots are plumbed through for future activation when vision, transcription, and
image generation tools are added.

mermaid
flowchart LR
    P[Profile] --> T[thinking → TaskAgentWorkflow]
    P --> V[imageRecognition → future vision tool]
    P --> A[transcription → future audio tool]
    P --> IG[imageGeneration → future image tool]

    T --> R1[resolveInferenceProvider]
    V -.-> R2[resolveInferenceProvider]
    A -.-> R3[resolveInferenceProvider]
    IG -.-> R4[resolveInferenceProvider]

4. API Key Handling for Local Providers

Patch resolveInferenceProvider() to check ProviderConfig.requiresApiKey()
before rejecting empty keys. This unblocks Ollama, Voxtral, and Whisper.

mermaid
flowchart TD
    A[resolveInferenceProvider] --> B[Find AiConfigModel]
    B --> C[Load provider]
    C --> D{apiKey empty?}
    D -->|No| E[Proceed]
    D -->|Yes| F{requiresApiKey?}
    F -->|Yes| G[Return null]
    F -->|No| E

5. Profile Lifecycle

mermaid
flowchart TD
    S[App startup] --> SEED[Seed default profiles]
    SEED --> LIST[Profile list in settings]

    LIST --> CREATE[Create custom profile]
    LIST --> EDIT[Edit profile]
    LIST --> DEL{Delete profile}

    DEL --> CHK{In use by agents<br/>or templates?}
    CHK -->|Yes| BLOCK[Block deletion]
    CHK -->|No| REMOVE[Delete]

    CREATE --> ASSIGN[Assign to template or agent]
    EDIT --> ASSIGN
    ASSIGN --> WAKE[Used at next wake]

6. Mandatory Selection at Agent Creation

Profile selection is required when creating an agent — createTaskAgent takes
a non-nullable profileId. The selected profile is stored on
AgentConfig.profileId and used for all subsequent wakes. Users can reassign
the profile later from the agent detail page.

7. Sync

Profiles sync between devices via the existing AI config outbox
(SyncMessage.aiConfig). The profileId on agent entities syncs via
AgentSyncService. If a template arrives before its referenced profile, the
legacy modelId fallback ensures the agent can still wake.

Consequences

  • Reusable model bundles. Users configure models once per profile and
    assign it to any number of agents/templates.
  • Privacy intent via naming. Profile names like "Local (Ollama)" or
    "Mistral EU" communicate data handling intent without false enforcement.
  • Backward compatible. Existing templates with modelId but no profileId
    continue to work unchanged. Migration is opt-in.
  • Multi-capability ready. Four slots are defined; only thinking is active
    today. Vision, transcription, and image generation activate as tools are added.
  • Local providers unblocked. The API key fix benefits all callers, not just
    profile-based resolution.
  • Slightly more complex resolution. The chain adds a profile lookup step
    before the existing model → provider resolution. Mitigated by clear
    precedence rules and fallback to legacy path.
  • Implementation plan
  • ADR 0005: Template Model Resolution Policy (predecessor)
  • lib/classes/ai/ai_config.dart — AiConfig sealed union
  • lib/features/ai/util/inference_provider_resolver.dart — existing resolver
  • lib/features/agents/workflow/task_agent_workflow.dart — wake cycle
  • lib/features/ai/constants/provider_config.dart — noApiKeyRequired

Adr 0009 Redundant Change Proposal Suppression (`docs/adr/0009-redundant-change-proposal-suppression.md`)

ADR 0009: Redundant Change Proposal Suppression

  • Status: Accepted
  • Date: 2026-03-01

Context

The task agent frequently proposes tool calls for changes that would be no-ops:
setting a priority to its current value, checking off an already-checked
checklist item, or setting an estimate to the value the user just set. These
redundant proposals pass through the deferred confirmation workflow (ADR 0006)
and appear as pending suggestions in the UI, making the assistant appear unaware
of the current state.

The LLM's system prompt already instructs it to check current values before
calling tools (the "no-op rule"), but models don't always follow this
instruction. A particular pain point: after a user updates an estimate, the
agent wakes and proposes reverting to the old estimate because its context still
contains the pre-update value.

Filtering at execution time (after user confirms) is insufficient — the user
shouldn't see proposals that are already satisfied.

Decision

Filter redundant proposals at proposal-building time (before they enter the
change set) and feed back "already in that state" to the LLM so it can correct
its context.

Two filtering layers

mermaid
flowchart TD
    LLM["LLM tool call"] --> IS_DEFERRED{Deferred tool?}
    IS_DEFERRED -- No --> EXECUTE["Execute immediately"]
    IS_DEFERRED -- Yes --> IS_BATCH{Batch tool?}

    IS_BATCH -- Yes --> EXPLODE["Explode into items"]
    EXPLODE --> CHECK_ITEM["Per-item redundancy check\n(ChangeSetBuilder)"]
    CHECK_ITEM --> REDUNDANT_ITEM{Redundant?}
    REDUNDANT_ITEM -- Yes --> SKIP_ITEM["Skip + record detail"]
    REDUNDANT_ITEM -- No --> ADD_ITEM["Add to change set"]

    IS_BATCH -- No --> CHECK_META["Metadata redundancy check\n(ChangeProposalFilter)"]
    CHECK_META --> REDUNDANT_META{Redundant?}
    REDUNDANT_META -- Yes --> SKIP_META["Return skip message\nto LLM"]
    REDUNDANT_META -- No --> ADD_SINGLE["Add to change set"]

    SKIP_ITEM --> FORMAT["Format batch response\nwith redundancy info"]
    ADD_ITEM --> FORMAT
    FORMAT --> FEEDBACK["Feed response to LLM"]
    SKIP_META --> FEEDBACK
    ADD_SINGLE --> FEEDBACK_OK["'Proposal queued'"]

Layer 1: Checklist item redundancy (batch tools)

Inside ChangeSetBuilder.addBatchItem(), for each update_checklist_item
element the builder resolves the item's current state via a
ChecklistItemStateResolver callback. If the proposed isChecked matches the
current value AND no title change is proposed, the item is suppressed.

The resolver returns a record ({String? title, bool? isChecked}) — richer
than the previous title-only resolver — so the builder can compare both fields
in a single lookup.

Layer 2: Task metadata redundancy (non-batch tools)

In TaskAgentStrategy._addToChangeSet(), before calling
csBuilder.addItem(), the strategy resolves the current task metadata via a
ResolveTaskMetadata callback. ChangeProposalFilter.checkTaskMetadataRedundancy()
compares the proposed value against the current value for:

Tool Compared field
update_task_estimate minutes
update_task_priority priority
update_task_due_date dueDate
set_task_status status
set_task_title title

LLM feedback loop

When proposals are suppressed, the response fed back to the LLM includes the
reason. This serves as a correction signal:

text
Proposal queued for user review (1 item(s) queued).
Skipped 2 redundant update(s): "Buy groceries" is already checked; "Walk dog" is already checked.

or for non-batch tools:

text
Skipped: estimate is already 120 minutes.

This feedback is critical: without it, the LLM would believe its tool call
succeeded and might build subsequent reasoning on that assumption.

Conservative fallback

If the resolver is unavailable, returns null (item not found), or throws an
exception, the proposal is kept (not suppressed). This ensures we never
silently drop a legitimate change due to a transient DB error.

mermaid
flowchart LR
    RESOLVE["Resolve state"] --> FOUND{Found?}
    FOUND -- Yes --> COMPARE["Compare values"]
    FOUND -- No --> KEEP["Keep proposal\n(conservative)"]
    COMPARE --> MATCH{Match?}
    MATCH -- Yes --> SUPPRESS["Suppress + feedback"]
    MATCH -- No --> KEEP

File changes

File Role
lib/.../change_proposal_filter.dart New. Static helpers for redundancy checks and response formatting.
lib/.../change_set_builder.dart ChecklistItemTitleResolver → ChecklistItemStateResolver. Per-item redundancy check in addBatchItem(). BatchAddResult gains redundant + redundantDetails.
lib/.../task_agent_strategy.dart ResolveTaskMetadata callback. Non-batch redundancy check in _addToChangeSet(). Delegates to ChangeProposalFilter.
lib/.../task_agent_workflow.dart Wires resolver callbacks using ChangeProposalFilter.resolveTaskMetadata().

Consequences

Positive

  • Users no longer see no-op proposals in the confirmation UI.
  • The LLM receives corrective feedback, reducing repeated redundant proposals.
  • The fix for the "reverted estimate" issue: the agent now sees "estimate is
    already X minutes" and doesn't propose a change.
  • All filtering logic is in a well-tested helper class (ChangeProposalFilter).

Negative

  • Each deferred tool call now requires an additional DB lookup (task metadata or
    checklist item state). This is acceptable given that agent wakes are
    already I/O-heavy (LLM calls, context assembly).
  • The resolver callbacks add coupling between the workflow and the DB layer.
    This is mitigated by the callback abstraction — tests inject simple lambdas.

Neutral

  • The LLM's "no-op rule" in the system prompt is still valuable as a
    first-pass filter. This ADR adds a safety net, not a replacement.

Adr 0010 Scheduled Wake Infrastructure (`docs/adr/0010-scheduled-wake-infrastructure.md`)

ADR 0010: Scheduled Wake Infrastructure

  • Status: Proposed
  • Date: 2026-03-01

Context

The current WakeOrchestrator only supports event-driven wakes: an entity change emits
tokens on UpdateNotifications.localUpdateStream, which are matched against agent
subscriptions. This model works well for task agents that react to user edits, but it
cannot support time-based rituals such as the weekly one-on-one template evolution
ceremony.

Improver agents need to wake on a schedule (e.g., every Sunday at 9 AM) regardless of
whether any entity changes occurred.

Important: The existing nextWakeAt field on AgentStateEntity is already in
active use
by the subscription throttle system. WakeOrchestrator._setThrottleDeadline
writes the throttle expiry into nextWakeAt, and TaskAgentService._hydrateThrottleDeadline
restores it on startup. The UI also reads nextWakeAt to display a countdown timer.
Reusing this field for scheduled wakes would create a semantic collision — a subscription
throttle deadline could be mistaken for a scheduled ritual, and vice versa.

Decision

  1. Add a new field scheduledWakeAt: DateTime? to AgentStateEntity for
    time-based scheduled wakes. This keeps it cleanly separated from the existing
    nextWakeAt which serves the subscription throttle system.
  2. Introduce a ScheduledWakeManager that runs a periodic check (default: every 1 hour)
    to detect agents whose scheduledWakeAt <= now AND lifecycle == active.
  3. When a due agent is found, enqueue a WakeJob into the existing WakeQueue with
    reason: WakeReason.scheduled.
  4. Scheduled wakes bypass the 120-second subscription throttle (ADR 0002) since they
    are already rate-limited by their own schedule.
  5. After ritual completion, the workflow computes
    scheduledWakeAt = lastOneOnOneAt + interval and persists it to AgentStateEntity.
  6. On app launch, ScheduledWakeManager immediately checks for any missed wakes
    (agent was due while app was closed) and fires them.
  7. On mobile platforms (iOS/Android), integrate with WorkManager / BGTaskScheduler
    for background execution. On desktop, Timer.periodic suffices.

Field semantics (clarification)

Field Owner Purpose
nextWakeAt WakeOrchestrator Subscription throttle deadline — "earliest this agent may wake from a subscription trigger." Cleared after the throttle expires.
scheduledWakeAt ScheduledWakeManager Ritual schedule — "when this agent's next scheduled ritual should fire." Updated after each ritual to lastOneOnOneAt + interval.

Both fields coexist on the same AgentStateEntity. Task agents (which have no scheduled
rituals) will have scheduledWakeAt = null. Improver agents will have both fields
populated independently.

Architecture

mermaid
flowchart TD
    subgraph "ScheduledWakeManager"
        TIMER["Timer.periodic\n(1 hour)"]
        CHECK["Query: agents where\nscheduledWakeAt <= now\nAND lifecycle = active"]
        ENQUEUE["Create WakeJob\nreason: scheduled"]
    end

    subgraph "Existing Wake Infrastructure"
        WQ["WakeQueue"]
        WO["WakeOrchestrator._drain()"]
        EXEC["_executeJob()"]
    end

    TIMER --> CHECK
    CHECK -->|"due agents found"| ENQUEUE
    ENQUEUE --> WQ
    WQ --> WO
    WO --> EXEC

    subgraph "Post-Ritual"
        UPDATE["Update AgentStateEntity\nscheduledWakeAt = lastOneOnOneAt + interval"]
    end

    EXEC --> UPDATE

Consequences

Positive

  • Reuses existing WakeQueue and WakeOrchestrator — no parallel execution path.
  • Clean separation: scheduledWakeAt for rituals, nextWakeAt for throttle. No
    semantic collision or risk of one system corrupting the other's state.
  • Missed wakes are automatically recovered on app launch.
  • Platform-specific background execution is isolated behind ScheduledWakeManager.

Negative

  • Hourly check granularity means scheduled wakes can be up to ~59 minutes late.
    This is acceptable for weekly rituals but may need refinement for higher-frequency
    schedules.
  • Mobile background execution has platform-specific constraints (iOS limits background
    tasks to ~30 seconds; Android WorkManager may defer execution).
  • Adding a new field to AgentStateEntity requires a freezed model regeneration and
    serialization migration. Since agent.sqlite stores entities as JSON in a
    serialized column, the new nullable field is backward-compatible (missing key
    defaults to null).

Neutral

  • WakeReason.scheduled is a new enum value requiring a minor schema migration
    (wake_run_log stores reason as text, so this is backward-compatible).

Adr 0011 Feedback Classification Strategy (`docs/adr/0011-feedback-classification-strategy.md`)

ADR 0011: Feedback Classification Strategy

  • Status: Proposed
  • Date: 2026-03-01

Context

The weekly one-on-one ritual requires the improver agent to understand what went well
and what didn't
across all task agent instances. Today, feedback exists in several
raw forms:

  1. Decision history (ChangeDecisionEntity): explicit user verdicts (confirmed,
    rejected, deferred) on agent proposals.
  2. Agent observations (AgentMessageEntity with kind: observation): free-text
    working notes written by task agents during wakes.
  3. Wake run metrics (wake_run_log): duration and user ratings. (Note: the
    status field only reflects whether the LLM conversation completed without
    errors — it is not a quality signal and should not be used for sentiment
    classification.)
  4. Agent reports (AgentReportEntity): agent's self-assessment with confidence score.

These raw signals must be classified by sentiment (positive/negative/neutral) and
categorized by aspect (accuracy, communication, prioritization, tooling, timeliness)
to produce actionable input for the evolution agent.

Decision

Use a hybrid classification strategy:

  1. Rule-based classification for structured data:

    • ChangeDecisionEntity with verdict: rejected → negative sentiment
    • ChangeDecisionEntity with verdict: confirmed → positive sentiment
    • ChangeDecisionEntity with verdict: deferred → neutral sentiment
    • Category inferred from toolName (e.g., set_task_estimate → accuracy,
      set_task_title → communication)
    • User ratings below threshold (< 0.3) → negative, above (> 0.7) → positive
  2. LLM-based classification for unstructured data:

    • Agent observation text → fast model (e.g., Gemini Flash) classifies sentiment
      and category
    • Prompt constrained to output structured JSON for parsing
    • No strict token budget — send full observation text when practical; the
      weekly ritual runs once, so cost is negligible
  3. Metric-based signals derived from aggregates:

    • Declining user rating trend → negative / general
    • High rejection rate for specific tool → negative / tooling
mermaid
flowchart LR
    subgraph "Structured Data"
        CD["ChangeDecisionEntity"]
        UR["wake_run_log\n(user_rating only)"]
    end

    subgraph "Unstructured Data"
        OBS["Observation text\n(free-form)"]
    end

    subgraph "Aggregated Data"
        PM["PerformanceMetrics\n(trends)"]
    end

    CD -->|"rule-based"| RULES["Rule Engine\n(deterministic)"]
    UR -->|"rule-based"| RULES

    OBS -->|"LLM call"| LLM["Fast Model\n(full text)"]

    PM -->|"threshold"| METRIC["Metric Analyzer\n(trend detection)"]

    RULES --> AGG["ClassifiedFeedback\n(merged output)"]
    LLM --> AGG
    METRIC --> AGG

Consequences

Positive

  • Deterministic classification for structured data — no LLM cost, no latency,
    no non-determinism for clear-cut signals.
  • LLM classification only where needed — handles nuance, sarcasm, implicit feedback
    in observation text.
  • Token cost is modest (weekly ritual, using a fast model) and not budget-constrained.
  • Metric-based signals catch systemic issues that individual items might miss.

Negative

  • Two classification code paths to maintain (rules + LLM prompt).
  • LLM classification quality depends on the fast model's capability — may need
    prompt iteration.
  • Rule-based category inference from toolName is heuristic and may misclassify
    edge cases.

Neutral

  • Classification results are ephemeral (computed during ritual, not persisted as
    separate entities). If persistence is needed later, the ClassifiedFeedback model
    can be serialized into an AgentMessagePayloadEntity.

Adr 0012 Recursive Self Improvement Depth Policy (`docs/adr/0012-recursive-self-improvement-depth-policy.md`)

ADR 0012: Recursive Self-Improvement Depth Policy

  • Status: Proposed
  • Date: 2026-03-01

Context

The self-learning cycle is inherently recursive: an improver agent evolves a task agent
template, but the improver itself is governed by a template that could also be improved.
This creates a chain:

  • Level 0: Task agents (governed by task template)
  • Level 1: Template improver (governs task template, governed by improver template)
  • Level 2: Meta-improver (governs improver template, governed by meta-improver template)
  • Level N: ...

Without a policy, this recursion is unbounded. An unbounded chain risks:

  1. Runaway self-modification: each level changes the level below, creating cascading
    rewrites that are difficult to audit or revert.
  2. Drift from human intent: after enough recursive improvements, the original
    human-authored intent may be diluted.
  3. Resource waste: each recursion level costs LLM tokens and compute.
  4. Debugging complexity: failures in deeply nested improvers are hard to diagnose.

Decision

  1. Fixed recursion depth cap of 2:

    • Level 0: Task agents — improved weekly by Level 1
    • Level 1: Template improver — improved monthly by Level 2
    • Level 2: Meta-improver — its own template is human-curated only (no Level 3 agent)
  2. Enforcement mechanism: each improver agent stores recursionDepth in its
    AgentSlots. The ImproverAgentService.create() method:

    • Reads the target template's current improver (if any) to determine depth
    • Rejects creation if the resulting depth would exceed 2
    • Stores the computed depth in the new agent's slots
  3. Frequency scaling by depth:

    • Level 1 (template improver): weekly ritual
    • Level 2 (meta-improver): monthly ritual
    • This natural scaling prevents high-frequency cascading changes
  4. Human override: the meta-improver's template (Level 2) can only be edited
    through the existing manual template editing UI. No agent can modify it.

mermaid
flowchart TD
    subgraph "Level 0: Task Execution"
        TA["Task Agent Instances"]
    end

    subgraph "Level 1: Weekly Improvement"
        L1["Template Improver\n(recursionDepth: 1)\nRitual: weekly"]
        L1 -->|"improves"| TT["Task Template"]
        TT -->|"governs"| TA
    end

    subgraph "Level 2: Monthly Meta-Improvement"
        L2["Meta-Improver\n(recursionDepth: 2)\nRitual: monthly"]
        L2 -->|"improves"| IT["Improver Template"]
        IT -->|"governs"| L1
    end

    subgraph "Level 3: Human Boundary"
        HUMAN["Human Curator\n(manual editing only)"]
        HUMAN -->|"curates"| MT["Meta-Improver Template"]
        MT -->|"governs"| L2
    end

    style HUMAN fill:#fcc,stroke:#c00,stroke-width:2px,color:#000
    style L1 fill:#bbf,stroke:#333,color:#000
    style L2 fill:#ff9,stroke:#333,color:#000

Consequences

Positive

  • Human oversight is preserved at the top of the chain — the system cannot fully
    self-modify without human involvement.
  • Two levels of automated improvement provide meaningful self-learning while remaining
    auditable.
  • Frequency scaling (weekly → monthly) naturally dampens cascading changes.
  • Simple enforcement via slot-stored depth — no complex graph traversal needed.

Negative

  • Fixed depth may be too restrictive for future use cases (e.g., domain-specific
    improvement chains). This can be revisited if evidence warrants it.
  • Monthly cadence for Level 2 means meta-improvements are slow to propagate.

Neutral

  • The depth cap is a policy decision, not a technical limitation. The infrastructure
    supports arbitrary depth — only the service layer enforces the cap.
  • Level 2 meta-improver is optional — the system works with only Level 1 improvers.
    Meta-improvement is an enhancement, not a requirement.

Adr 0013 Outbox Priority Queue (`docs/adr/0013-outbox-priority-queue.md`)

ADR 0013: Outbox Priority Queue & Sync Observability

Status

Accepted

Date

2026-03-03

Context

Two related problems surfaced during sustained multi-device usage:

  1. Priority inversion in the outbox FIFO queue. When a user triggers a
    manual resync (or backfill generates a large batch), 10k+ low-urgency
    entries flood the outbox. Because the queue is strict FIFO, any new
    journal entry the user creates gets stuck behind the bulk backlog. The
    user perceives edits as "not syncing" even though the system is busy.

  2. Silent sync convergence failures. Sync appeared healthy (green
    status) while 14–16k documents were missing on one device. The existing
    LoggingService.captureEvent() calls are scattered, inconsistently
    formatted, and lack domain-specific file sinks, making post-hoc
    diagnosis nearly impossible without manual DB queries.

These are addressed together because the priority change modifies the
outbox write-path where observability also needs improvement, and both
changes share the same migration version bump.

Decision

Priority queue

Add a priority integer column to the Outbox table with three levels:

Priority Index Examples
high 0 SyncJournalEntity, SyncEntryLink (user edits)
normal 1 SyncAgentEntity, SyncAgentLink, SyncBackfillRequest/Response, SyncThemingSelection
low 2 SyncEntityDefinition, SyncTagEntity, SyncAiConfig, SyncAiConfigDelete

Queries that determine processing order (oldestOutboxItems,
claimNextOutboxItem) sort by priority ASC, createdAt ASC, so
high-priority items always drain before lower tiers. The UI watch query
sorts by priority ASC, createdAt DESC to show high-priority items at the
top, newest first within each tier.

Priority queue flow

mermaid
flowchart TD
    UE[User creates/edits entry] -->|priority=0| OB[(Outbox table)]
    AG[Agent action / backfill] -->|priority=1| OB
    RS[Bulk resync / tags / AI config] -->|priority=2| OB
    OB -->|"ORDER BY priority ASC, createdAt ASC"| OP[OutboxProcessor]
    OP -->|send via Matrix| MX[Matrix room]

Message type to priority mapping

mermaid
graph LR
    subgraph "HIGH (0)"
        JE[SyncJournalEntity]
        EL[SyncEntryLink]
    end
    subgraph "NORMAL (1)"
        AE[SyncAgentEntity]
        AL[SyncAgentLink]
        BR[SyncBackfillRequest]
        BResp[SyncBackfillResponse]
        TS[SyncThemingSelection]
    end
    subgraph "LOW (2)"
        ED[SyncEntityDefinition]
        TE[SyncTagEntity]
        AC[SyncAiConfig]
        ACD[SyncAiConfigDelete]
    end

Sync health reporting cycle

mermaid
sequenceDiagram
    participant T as Timer (5 min)
    participant HR as SyncHealthReporter
    participant DB as SyncDatabase
    participant DL as DomainLogger

    T->>HR: _reportHealth()
    HR->>DB: getPendingOutboxCount()
    HR->>DB: getMissingSequenceCount()
    HR->>DB: getRequestedSequenceCount()
    HR->>DB: getSentCountSince(5min ago)
    HR->>DL: log(sync, "health: ...", subDomain: "health")
    DL->>DL: append to sync-YYYY-MM-DD.log

Sync observability

Inject DomainLogger (already used by the agent runtime) into the key
sync components and instrument five sub-domains:

  • outbox.enqueue / outbox.send / outbox.retry
  • ingest.receive / ingest.apply / ingest.skip / ingest.drop
  • backfill.detect / backfill.request / backfill.response
  • health — periodic 5-minute summary

A new SyncHealthReporter emits a compact health line every 5 minutes
when sync domain logging is enabled:

text
health: outbox.pending=42 outbox.sentRecent=128 seq.missing=3 seq.requested=7

All logging gates on LogDomains.sync which is already wired to the
logSyncFlag config flag. No extra flags needed.

Schema migration

  • schemaVersion bumps from 5 to 6.
  • Migration adds the priority column with DEFAULT 2 (low). Existing
    rows automatically receive the low priority, which is correct—they
    represent historical items that should not leapfrog any new work.
  • SQLite ALTER TABLE ADD COLUMN ... DEFAULT is non-locking.

Consequences

Positive:

  • User-created journal entries sync within seconds even during a 10k+
    resync.
  • Structured, domain-filtered log files make convergence failures
    diagnosable without manual DB queries.
  • Health summary provides a quick "pulse check" for sync status.

Negative / trade-offs:

  • Low-priority items (entity definitions, tags) take longer to sync when
    the queue is loaded. This is acceptable because they are rarely
    time-sensitive.
  • Additional DomainLogger parameter on ~7 constructors increases
    constructor arity. Mitigated by making it optional with null-safe
    fallback.
  • Outbox deduplication (merge logic): already in outbox_service.dart
  • Backfill request/response flow: backfill_request_service.dart,
    backfill_response_handler.dart
  • Domain logging infrastructure: domain_logging.dart, ADR pending

Adr 0014 Cross Wake Critical Observation Injection (`docs/adr/0014-cross-wake-critical-observation-injection.md`)

ADR 0014: Cross-Wake Critical Observation Injection

  • Status: Proposed
  • Date: 2026-03-03

Context

Agent observations are immutable log entries (AgentMessageKind.observation) that persist
across wakes. Today they serve as general-purpose memory — the agent can review its own past
observations when building context for a new wake. However, all observations are treated
equally: a routine operational note ("checked 3 linked tasks, no changes") has the same
visibility as a user grievance ("I asked you to change the priority and you ignored me").

A concrete incident exposed this gap: a user orally requested a priority change from P1 to
P0, the task agent failed to act, and the resulting grievance was recorded as a standard
observation. In the next wake, nothing distinguished it from dozens of routine notes. The
grievance was effectively invisible.

The existing feedback classification pipeline (ADR 0011) classifies observations
retroactively for the weekly one-on-one ritual, but that classification happens at
extraction time and only benefits the improver agent. The task agent itself — the one that
caused the grievance — has no mechanism to recognize and act on its own past failures with
appropriate urgency.

Decision

1. Structured observation priority and category at write time

Observations gain two optional fields in their payload content:

  • priority: routine | notable | critical
  • category: grievance | excellence | template_improvement | operational

These are stored in the AgentMessagePayloadEntity.content map (not on the entity itself),
keeping the generic AgentMessageEntity schema clean. The record_observations tool schema
is updated to accept structured items alongside the legacy bare-string format.

2. Task agents inject their own critical observations into wake context

When building the wake context for a task agent, the workflow queries the agent's own
observations from the current feedback window and filters for priority: critical (or
notable). These are injected as a dedicated section in the user message:

text
## Prior Critical Observations (Self-Review)
The following critical observations were recorded in your previous wakes.
Review them and adjust your behavior accordingly:

### Grievances
- [2026-03-02] Full grievance text with context...

### Excellence (keep doing this)
- [2026-03-01] Full excellence text with context...

This section appears before the task data, ensuring the agent addresses it first.

3. Improver agents receive critical observations with elevated visibility

The ritual context builder injects a HIGH-PRIORITY FEEDBACK section before the general
classified feedback summary. Critical observations are shown at full length (no truncation)
and the improver's system prompt instructs it to address grievances before general analysis.

4. No resolution tracking — observations age out

A directive change made in response to a grievance is a hypothesis, not a confirmed fix.
Only subsequent agent behavior proves whether the grievance was truly addressed. Critical
observations naturally drop out of the feedback window (typically 7 days for task agents,
configurable for improvers). No explicit "resolved" status is tracked.

5. No retroactive classification

Old observations written before this change retain their bare-string format and continue
using the keyword-based heuristic classifier. Only new observations benefit from structured
priority and category. The LLM classification pass (ADR 0011 Phase 4) remains a separate
future initiative.

6. No immediate notifications

Critical observations do not trigger push notifications or early ritual scheduling. They
accumulate within the standard weekly cadence, preserving the structured ceremony.

7. No token budget cap on critical section

The high-priority feedback section has no token limit. Critical observations are rare and
important enough to always show in full. The weekly cadence naturally limits volume.

mermaid
flowchart TD
    subgraph "Write Time (Task Agent Wake)"
        W1["Agent detects grievance/excellence signal"]
        W1 --> W2["record_observations\npriority: critical\ncategory: grievance|excellence"]
        W2 --> W3["AgentMessagePayloadEntity\n{text, priority, category}"]
    end

    subgraph "Read Time — Task Agent (next wake)"
        R1["TaskAgentWorkflow builds wake context"]
        R1 --> R2["Query own observations\nfilter: priority = critical|notable"]
        R2 --> R3["Inject 'Prior Critical Observations'\nsection in user message"]
        R3 --> R4["Task agent self-corrects"]
    end

    subgraph "Read Time — Improver Agent (weekly ritual)"
        I1["FeedbackExtractionService.extract()"]
        I1 --> I2["Classify with priority awareness\ncritical → confidence: 1.0"]
        I2 --> I3["RitualContextBuilder injects\nHIGH-PRIORITY FEEDBACK section"]
        I3 --> I4["Improver addresses grievances first\nproposes directive changes"]
    end

    W3 --> R1
    W3 --> I1

Consequences

Positive

  • Immediate self-correction: Task agents see their own grievances in the very next wake
    and can adjust behavior without waiting for a directive change. This closes the feedback
    loop from weeks to hours.
  • Structured write-time encoding: Priority and category are captured at the moment the
    agent detects the signal, preserving the full context rather than relying on post-hoc
    text classification.
  • Dual feedback path: The same observation reaches both the task agent (for immediate
    behavior adjustment) and the improver agent (for systemic directive improvement). These
    are complementary — one is a quick fix, the other is a lasting fix.
  • Backwards compatible: Legacy bare-string observations continue to work. The structured
    format is additive.

Negative

  • Relies on agent compliance: The task agent must correctly identify grievance signals
    and assign priority: critical. If the agent fails to recognize the grievance in the
    first place, no priority field will save it. System prompt engineering mitigates but
    does not eliminate this.
  • No guaranteed resolution: Self-correction is best-effort. The agent sees its past
    grievance but may still fail to act on it if the underlying behavioral issue is in the
    directive itself (which only the improver can fix).
  • Payload schema is convention-based: Priority and category live in a freeform
    Map<String, Object?> rather than typed entity fields. Drift queries on JSON content are
    possible but less robust than typed columns.

Neutral

  • The feedback window controls how long observations remain visible. This is configurable
    per agent and does not require a new mechanism.
  • The pattern is generalizable: any agent kind that supports observations can adopt
    cross-wake critical injection by querying its own high-priority observations during
    context building.

Adr 0015 Outbox Message Bundling (`docs/adr/0015-outbox-message-bundling.md`)

ADR 0015 — Outbox message bundling

Status: Accepted
Date: 2026-04-30
Related: ADR 0013 (outbox priority queue); PR #3009 (agent wake sync
bundling); closed PR #2957 (media-attachment bundling, retired).

Context

Bursty workloads — agent suggestion fan-out, checklist-item creation, sync
backfill replay — push tens to hundreds of small text-only sync messages
through the outbox in a short window. Pre-bundling, every row produced one
Matrix event, so the wire-event count tracked the row count linearly. Each
event paid the same per-message overhead (Matrix encryption, transmit, ack,
receiver inbox scan), which dominated end-to-end latency on slow networks.

PR #3009 introduced wake-cycle bundling for agent writes (SyncAgentBundle),
reducing one specific source. We extend the same pattern to the outbox as a
whole so any bursty source benefits.

Decision

Bundle on the dequeue side of the outbox.

OutboxProcessor.processQueue() reads a cached bundle-size cap each pass.
When the cap is 1 (legacy default) the legacy single-row claim path runs
unchanged. When the cap is > 1, OutboxRepository.claimNextBatch(maxSize)
returns either:

  • a single-element list [head] when the head row carries a media attachment
    (filePath != null), so attachments still travel alone, or
  • the maximal prefix of consecutive text-only rows in
    (priority, createdAt) order, capped at maxSize, stopping before the
    next attachment.

The processor wraps a multi-row batch in SyncMessage.outboxBundle(children)
and calls markSentBatch / markRetryBatch (single-transaction batch
updates) after the send. Single-row batches keep the legacy
markSent / markRetry path.

MatrixMessageSender always delivers SyncOutboxBundle as file-backed:
the children are serialized to /outbox_bundles/.json, uploaded, and
the inline children list is stripped from the text event in favour of a
jsonPath reference. Receivers download the sidecar via the existing
AttachmentIngestor.

On the receiver, OutboxBundleUnpacker.prepare recursively prepares each
child through the existing per-type pipeline (_prepareForMessage), and
OutboxBundleUnpacker.apply dispatches each prepared child through the
existing per-type apply path. The sequence log records each child's
vector clock individually — there is no bundle-level VC.

Gated by a per-user feature flag, useOutboxBundlingFlag, defaulting to
off.

Why dequeue-side and not enqueue-side

Enqueue paths already do per-type merge/dedup/sequence-log work. Touching
them risks vector-clock and ordering bugs. Dequeue-side bundling

  • mirrors the proven shape of PR #3009 (buffer → emit one envelope →
    child-iterate on receiver), and
  • naturally batches a backfill flood without needing to teach every
    enqueue site about bundling.

Why a 50-row cap (constant `SyncTuning.outboxBundleMaxSize`)

A 50-message envelope keeps the sidecar JSON well below realistic Matrix
event-size limits even with chatty children, and 50 is comfortably above
the typical agent-suggestion burst (≈10–20). The cap lives in
SyncTuning so it can be tuned (validated up to 100 in tests) without a
code change to consumers.

Why media attachments stay individual

The downstream AttachmentIngestor machinery is built around per-event
re-download semantics with VC-dominance gating. Bundling attachments
would require redesigning that flow (see closed PR #2957). Out of scope
here. "Attachment" in this ADR means media attachment; the JSON
sidecar that carries bundle children is technically also a Matrix
attachment, but it is bundle-internal infrastructure, not a user file.

Why a flag, default off

A receiver running an older build that does not understand
SyncOutboxBundle will log-and-skip the unknown variant — fail-soft, but
the user-visible result is silent data loss for the bundled children
until the receiver upgrades. Default-off lets us ship the receiver
unpacker first in one release, leave it baking, and flip the default
later. An emergency kill-switch is preserved either way.

Backfilling `originatingHostId` on bundle children

Children inside a SyncOutboxBundle skip the top-level
MatrixMessageSender._ensureOriginatingHostId call. We backfill each
child individually before the file is written, so a bundle-delivered
journal entity or entry link carries the same metadata as the same
message delivered standalone — receiver-side sequence tracking does not
regress.

Path-traversal hardening

SyncOutboxBundle.jsonPath arriving from outside this process (e.g. an
echoed Matrix message during a retry, or a tampered payload) is gated:
only paths that start with /outbox_bundles/ and contain no . or ..
segments are honoured for the disk write. Any other value falls back to
a freshly minted UUID-based path and the rejection is logged.

Per-child fault isolation on the receiver

OutboxBundleUnpacker rethrows any IOException
(FileSystemException, SocketException, HttpException,
TlsException, WebSocketException) from a child's prepare call so the
parent pipeline can retry the whole bundle later — partial application
would leave gaps in the sequence log. All other exceptions on a single
child are logged and skipped; the remaining children still apply.

Consequences

  • One Matrix event per up-to-50 small text-only outbox rows, with a
    single sidecar attachment carrying the children. Wire volume drops
    ~10× on bursty workloads.
  • Bundling never crosses the boundary defined by a media-attachment
    row, so attachment delivery is byte-for-byte unchanged.
  • Receiver running with bundling enabled by the sender must include
    OutboxBundleUnpacker (Step 6 of the implementation plan) — guaranteed
    by the rollout sequencing above.
  • Sequence-log semantics are unchanged: each child gets its own VC entry,
    so backfill, gap detection, and retire flows continue to operate at
    child granularity.

Alternatives considered

  • Enqueue-side bundling — rejected for risk, see "Why dequeue-side"
    above.
  • Inline-only delivery for small bundles — rejected for uniformity;
    receivers would need two delivery shapes. Followup if profiling shows
    the sidecar round-trip dominates for tiny bundles.
  • Bundle-level vector clock — rejected: backfill, retire, gap
    detection, and the existing supersession check all operate on child
    payload identity. A bundle-level VC would need a parallel set of
    resolution paths.

Adr 0016 Agent State As Log Projection (`docs/adr/0016-agent-state-as-log-projection.md`)

ADR 0016: Agent-Derived State as a Projection of the Append-Only Log

  • Status: Accepted
  • Date: 2026-05-30

Context

The agents feature already treats the append-only AgentMessageEntity log (plus
AgentLink edges) as durable, immutable, vector-clocked history. But some
agent-derived state — AgentStateEntity slots and pointers, and other mutable
rows — is persisted and synced as authoritative last-write-wins state. Concretely,
agent_repository.upsertEntity writes entities in place
(insertOnConflictUpdate), identities carry a mutable currentStateId, and
agent creation writes mutable state snapshots — so this move is a storage
migration, not a purely additive change
.

Under concurrent multi-device edits, every authoritative mutable row is a
conflict surface: LWW can silently drop a branch, and there is no single
deterministic way to reconstruct state. The event-sourcing literature (anchor:
The Log is the Agent, arXiv 2605.21997) and production long-running-agent
practice (Anthropic harnesses; MemGPT tiering) converge on the same posture:
derive state from the durable log instead of trusting mutable replicated state.

Decision

  1. The append-only log (AgentMessageEntity + AgentLink, vector-clock stamped)
    is the sole source of truth for agent-derived state.
  2. Agent-derived state — head pointers (recentHeadMessageId,
    latestSummaryMessageId), slots that summarize log position, the projected
    report/graph view — is a deterministic projection recomputed from the log,
    not an authoritative replicated row. Persisted projections are a regenerable
    cache, not ground truth.
  3. Genuinely user-authored mutable documents (souls, templates) remain
    last-write-wins, but via the existing immutable Version/Head snapshot
    pattern (SoulDocumentVersionEntity/Head, AgentTemplateVersionEntity/
    Head). Generalize that pattern; do not add new in-place mutable synced rows
    for derived state.
  4. The log is a causal DAG — causality is the AgentLink.messagePrev edge
    set, and the scalar prevMessageId is a denormalized primary-parent
    convenience, never authoritative. "Current head" and the summary pointers are
    derived by reverse-indexing messagePrev, not stored as fields. The
    projection fold is a deterministic linear extension of that DAG (ordering
    rule in ADR 0018), order-stable across devices and tolerant of multiple
    heads
    — concurrent branches are legal, not corruption.

Projection Loop

mermaid
flowchart LR
  Log["Append-only log: immutable, vector-clocked"] -->|deterministic fold| Proj["Projected state (regenerable cache)"]
  Proj --> Beh["Behaviors / workflows"]
  Beh -->|append events| Log

Consequences

  • The multi-device conflict surface shrinks to conflict-free facts (immutable
    appends); derived state can no longer diverge under LWW.
  • Deterministic replay and cheap forking (the anchor's guarantees) become
    available because state is a pure function of the log.
  • Cost: a projection layer must be built, and existing authoritative mutable
    agent state migrated to either a derived projection or a Version/Head
    snapshot.
  • Cold-start/replay cost grows with log length; mitigated by compaction
    checkpoints (ADR 0017).

Implementation Notes

  • Implemented: the deterministic projection kernel, storage adapter,
    messagePrev DAG append path, shadow comparison, and wake-start
    reconciledAgentState read path.
  • Still planned: Foundation B leader leasing/fencing and the attention planner
    that will rely on this convergent substrate.
  • docs/daily_os_ai_runtime_architecture.md (§4, Move 1)
  • lib/features/agents/README.md (Memory Model)
  • lib/classes/vector_clock.dart
  • ADR 0001, ADR 0017, ADR 0018

Adr 0017 Deterministic Log Compaction (`docs/adr/0017-deterministic-log-compaction.md`)

ADR 0017: Deterministic, Content-Addressed Log Compaction

  • Status: Accepted
  • Date: 2026-05-30

Context

The model originally carried dormant compaction scaffolding —
AgentMessageKind.summary, summaryStartMessageId, summaryEndMessageId,
summaryDepth, AgentStateEntity.recentHeadMessageId, and
latestSummaryMessageId. Foundation A now uses that substrate for
content-addressed input capture and append-only summary checkpoints.

Logs grow unbounded; long-lived agents need distilled history, and on-device
inference needs a stable summary "prefix" to keep the KV/prefix cache warm. The
anchor paper and ESAA (arXiv 2602.23193) both leave long-log compaction
explicitly open. Under multi-device sync a summary is derived state, so two
devices summarizing overlapping ranges could race under LWW and pick an
arbitrary winner.

Decision

  1. A background compaction behavior: when the verbatim tail past the active
    checkpoint exceeds a model-specific budget, append a summary/checkpoint
    event
    naming the frontier it covers (and the prior checkpoint it folds
    in). It is an append, not a pointer write — the projection selects the
    active checkpoint/head (ADR 0016), and the persisted
    recentHeadMessageId/latestSummaryMessageId are a local cache only, so
    compaction adds no mutable conflict surface.
  2. Summaries are derived projections, not destructive overwrites: the
    immutable log remains ground truth; summarized messages are retained.
  3. A content digest does not make two LLM summaries converge (different
    content yields a different digest). Convergence comes from treating summaries
    as candidate checkpoints over causal frontiers, not from the lease. A
    summary covers a frontier — an antichain {e : prior < e ≤ frontier}.
    Frontiers form a join-semilattice, but with a critical caveat: the join of
    two candidate frontiers may have no materialized summary text
    (no one
    summarized that exact cut). So the active checkpoint is the maximal complete
    materialized checkpoint
    : among materialized checkpoints whose frontier is
    ancestral to (⊆) every current head, the one covering the most history
    (largest frontier). Context = that checkpoint's summary + the uncovered
    tail
    , defined as the original, non-summary log events not covered by it —
    non-active summary/checkpoint events are excluded, so the tail carries no
    derived text and nothing is double-counted. If several candidates cover the
    same maximal frontier (concurrent summaries of the identical region), they
    share a frontierDigest — it identifies coverage, not text — so pick the
    active one by a separate content-level total order: lowest
    (contentDigest, checkpointMessageId) (a stable (hostId, id) also works). If there are multiple incomparable maxima
    (different frontiers, neither dominates), fall back to their meet (common
    base)
    and read the whole uncovered region verbatim; a lazy merge-summary
    then materializes one checkpoint over the joined frontier, which becomes the
    new unique maximum — so a merge-summary always eventually becomes active. When that verbatim fallback region would exceed
    the model's context budget (deeply diverged, multiply-compacted branches), the
    merge-summary fires eagerly rather than lazily. Any such emergency summary
    is still a normal compaction — an append-only checkpoint event over a
    canonical frontier/span, selected by the same maximal-complete rule, with the
    original events retained (never replaced or omitted); it is eager only in
    timing
    , not a truncation. When the uncovered region is already too large
    (e.g. on reconnect), it summarizes bounded canonical sub-frontiers
    iteratively
    — each an append-only checkpoint over a canonical span, by the
    same rules — until the uncovered tail fits the budget. So the fallback stays
    inside both the on-device window and the convergence rules, without ever
    truncating. (A
    "meet of all checkpoints" rule would starve the merge-summary forever, since
    the collapsed branches stay incomparable ancestors.) frontierDigest = hash of the
    antichain's canonical id-set — it identifies coverage only. The summary
    artifact is identified, deduped, and replay-verified by a separate
    contentDigest over a canonical serialization of the summary text +
    folded prior checkpoint + summarizer config (sorted keys, RFC 3339 UTC
    timestamps, normalized numbers, UTF-8 canonical JSON / JCS) with a versioned
    tag
    (e.g. sha256-v1, base64url); the checkpoint's full key is
    (frontierDigest, contentDigest), so distinct texts over the same frontier are
    never collapsed. The lease (ADR 0018) only avoids usually summarizing twice; it
    is not required for convergence.
  4. Compaction preserves decisions, open commitments/negotiations, and
    non-negotiables; it discards redundant tool chatter.
  5. Compaction runs as a distinct background identity writing into the same log.
    Because summaries are derived and regenerable, they are auto-applied (not
    user-gated).
  6. The stable prefix order for wake prompts is fixed: soul/anti-sycophancy →
    tools → rolling summary → recent tail, extending the existing stable-first
    ordering in TaskAgentWorkflow.

Compaction Lifecycle

mermaid
stateDiagram-v2
  [*] --> Idle
  Idle --> Assembling: wake fires
  Assembling --> Running: stable prefix + recent tail
  Running --> Appending: emit events to log
  Appending --> CompactionCheck: tail beyond budget?
  CompactionCheck --> Compacting: yes
  CompactionCheck --> Idle: no
  Compacting --> Idle: append checkpoint event, projection selects active checkpoint

Consequences

  • Long-horizon memory for persistent agents; the dormant summary fields finally
    earn their keep.
  • A long-lived, byte-stable on-device prefix yields real KV/prefix-cache reuse
    across wakes.
  • Summaries converge across devices by selecting the maximal complete
    materialized checkpoint
    (common-base fallback for incomparable maxima) plus a
    verbatim tail of original events, collapsed later by a lazy merge-summary —
    not by content-addressing LLM outputs (which differ run-to-run), and not by
    selecting a single "joined" frontier whose text may be unmaterialized.
  • Risks: recursive summarization can amplify hallucination at depth — mitigated
    by stored provenance + replay hash + regeneration; on-device window thresholds
    (MemGPT's 70/100/50% are cloud-tuned) need tuning for small contexts.

Implementation Notes

  • Implemented: ContentDigest.of, input capture/frontier projection,
    compaction planning, summary selection, and the task/project/day wake memory
    path that captures inputs and assembles summary + tail context.
  • Implemented (recall escape hatch): AgentLogCompactor.searchLog /
    resolveByIds — the search_memory tool, an on-demand reader that scans the
    full immutable log (folded events plus the verbatim tail), so a wake can
    recall detail that compaction folded out of the active summary. This is what
    makes summary lossiness acceptable. Append-only [[relation:id]] memory links
    (features/agents/memory/memory_links.dart) ride inside log-entry text;
    supersedes drives recency-wins recall, validated and forward-followed by the
    recall reader.
  • Still planned: merge-summary tuning for deeply diverged branches and any
    later planner-specific memory policies.
  • docs/daily_os_ai_runtime_architecture.md (§6, Threads B/C)
  • lib/features/agents/README.md (Memory compaction & input capture)
  • ADR 0016, ADR 0018

Adr 0018 Convergent Multi Device Execution (`docs/adr/0018-convergent-multi-device-execution.md`)

ADR 0018: Convergent Multi-Device Execution — Lease, Fencing, and Fork Reconciliation

  • Status: Accepted
  • Date: 2026-05-30

Context

Lotti syncs agent data across devices (Matrix E2EE, vector-clock stamped), so
multiple devices are concurrent writers. Pure log appends converge for free
under CRDT semantics. But behavior execution — LLM calls, notifications,
schedule commits, external writes — must not be replicated naively: if two
devices observe the same trigger and both run a behavior, side effects duplicate
and state diverges. The anchor paper leaves multi-agent contention over the
shared graph unresolved.

Today there is no cross-device coordinator: WakeRunner enforces
single-flight only in-process (an in-memory lock map), and
sync_event_processor_agent_handlers applies a deterministic concurrent-branch
tiebreak for agent rows. Matrix provides causal/eventual delivery, not a
linearizable primitive, so a hard lease cannot be assumed for free.

The lease is secondary to convergence. Correctness comes from the convergent
DAG projection (rules 4 and 7–10 below; ADR 0016) — branches are legal and must converge whether or not
the lease held. The lease only reduces duplicate expensive/user-visible work and
guards irreversible external effects; it is never the thing preventing
corruption.

"Vector clock + last-write-wins" must also be applied correctly. A vector clock
can detect true concurrency (which a scalar/hybrid logical clock cannot), so LWW
should apply only on the concurrent branch — and only that branch needs a
tiebreak.

Decision

  1. Two merge laws, by entity class. Append-only event classes
    (AgentMessageEntity, AgentLink, reports, observations, change decisions,
    summaries/checkpoints) converge by set-union + a deterministic DAG fold in a
    canonical linear extension of the causal order
    (a topological sort of the
    messagePrev parent DAG — the canonical causal graph — with ties broken by
    hostId then id; the vector clock is the consistency/conflict signal,
    validated against the edges and used to classify concurrency, not a
    second ordering input) — no LWW. Mutable registers (the few genuinely in-place rows — user-authored
    document heads via Version/Head, journal-side in-place edits) converge by
    LWW snapshot (rule 4). Separately, execution (running behaviors + side
    effects) is gated by the lease. Most agent state is the first class; the LWW
    path is the minority.
  2. Side-effecting actions serialize behind a leader lease keyed to the
    side-effect boundary
    — (agentId, behaviorKind) for per-agent
    execution/compaction, (userId, dayId, planner) for the shared day planner;
    not per-user (too coarse) nor bare per-agent (wrong boundary). The lease
    carries a monotonically increasing fencing token; the resource side
    rejects any write carrying a lower token. A bare lease is insufficient — a
    paused holder can issue a stale write past expiry.
  3. Exactly one device executes at a time while connected to the lease
    coordinator
    ; others project the resulting events. This is not a free
    extension of the in-process WakeRunner lock — it requires a real lease
    backend (a designated-primary election with the fencing token persisted in
    synced state, or an external coordinator). Offline the hard guarantee
    degrades:
    a partitioned device cannot know it still holds the lease, so
    during a partition side effects must be idempotent and reconciled on
    reconnect
    (dedupe via content-address; reject stale fencing tokens), not
    assumed-unique. "Exactly one executes" is therefore a connected-case guarantee
    plus an offline reconciliation contract — with both represented in the backend design.
  4. For mutable-register entities only — convergent projection rule: classify
    each pair with the vector clock (a_gt_b/b_gt_a honored by replay order;
    concurrent falls to a tiebreak); apply updatedAt LWW only on the
    concurrent branch
    . (Append-only event classes skip this entirely — they
    union and fold by canonical order, rule 1.) Extend the partial order to a
    single deterministic total order with a replica-independent tiebreak:
    dominance, then a stable hostId + id key.
  5. Make the LWW comparator a genuine total order: break equal updatedAt by
    a replica-independent secondary key
    so identical timestamps cannot diverge
    across replicas. Implementation note: for the mutable-register concurrent
    branch the two versions share the same id, so id cannot discriminate;
    agent_concurrent_resolver.dart instead breaks equal updatedAt by a
    canonical vector-clock comparison (sorted (hostId, counter) entries) —
    both replicas hold both clocks, so this is stable and needs no per-entity
    authoring hostId column. This realizes the rule's intent (a deterministic,
    replica-independent tiebreak); a literal hostId-then-id key would require
    first persisting an authoring host on every agent row.
    This is distinct from clock skew: a fast/skewed physical clock wins a
    concurrent branch because its updatedAt is strictly greater (the
    equal-timestamp tiebreak never fires), so bounding that needs a monotonic
    hybrid logical clock (or bounded drift) on the comparator — not the tiebreak.
  6. Keep the vector clock — it detects concurrency, which the human gate needs in
    order to know a real conflict exists. A hybrid logical clock may optionally
    harden the concurrent-branch tiebreak but does not replace the vector clock.
  7. The projection is multi-head tolerant; forks are legal. Two devices waking
    the same runtime from a shared prefix create a DAG fork (concurrent
    messagePrev children of a shared parent — ADR 0016). This is normal, not
    corruption: context assembly reads across all current heads in the canonical
    linear extension (rule 1), so every device converges without a join.
  8. Forks heal by lazy, capped join-by-continuation — a continuation node
    linking (messagePrev) to all current heads, emitted only when ≥2 heads
    survive past one wake cycle
    . Its id is content-addressed —
    hash("join-v1" + sorted parent-head ids), a domain-tagged digest kept
    distinct from the summary coverage frontierDigest so the two uses can't be
    confused or collide — so two devices emitting the join concurrently write the
    same log entry, which set-union merges into one
    node; concurrent joins therefore can't form a new fork (no join storm). For that
    shared id to truly merge, the join's structural payload must be fully
    deterministic
    — the sorted set of parent-head ids, fixed system kind,
    threadId == joinId, empty metadata, and no wall-clock, hostId, or vector
    clock in the content-addressed identity. The current implementation still
    carries per-device sync envelope fields (createdAt, vector clock) because
    the existing sync sequence/backfill path relies on them; projection ignores
    those fields (hostIdOf is not populated), so they do not affect ordering,
    head detection, or convergence. A replica-independent envelope canonicalizer
    remains planned for the same change that starts projecting persisted
    authoring host ids.
  9. Side effects carry an idempotency key agentId + behaviorKind + frontierDigest + triggerId + toolName, where triggerId is a stable,
    source-derived
    identity — the source event id, the scheduled-wake entity
    id, or the shared (sync-replicated) trigger token — never a per-run local
    UUID
    (two devices minting local tokens for the same wake wouldn't dedup), and
    not scheduledFor alone (two distinct causes can collide at the same instant). The key is scoped to the wake epoch, not
    just the frontier — otherwise a later time-sensitive wake (a scheduled re-plan
    or reminder) over an unchanged frontier would be wrongly suppressed. It
    collapses the same wake executed on two devices; the later projection
    dedups/suppresses those duplicates
    (reuse ChangeSet dedup, ADR 0009). Truly irreversible external effects (a sent
    email, a created calendar event) cannot be undone — they stay behind the lease
    • the human gate (ADR 0019), and that set is kept minimal; where no external
      key can be stored, log both and reconcile visibly.
  10. Silent vs visible reconciliation. Derived/internal divergence converges
    silently by canonical pick; divergent user-facing commitments surface as a
    ChangeSet ("your devices disagreed — here's the reconcile"), never silently
    overwritten.

Execution Topology

mermaid
flowchart TD
  Lease["Lease (side-effect boundary) + fencing"] --> A["Device A: runs behaviors + side effects"]
  A -->|append events| Sync["Sync: Matrix E2EE, vector-clocked"]
  Sync -->|union merge| B["Device B: replica (connected case)"]
  B -->|skips redundant execution while A holds lease| Stop["connected-case optimization; both act + converge under partition"]

Consequences

  • No duplicated side effects across devices while connected to the
    coordinator
    ; under partition, uniqueness degrades to
    idempotent-and-reconciled (stale fencing tokens rejected on reconnect). The
    planner commits a schedule in one place in the connected case.
  • Convergent, deterministic projection on every device. Forks are legal and
    converge with no coordination; lazy capped joins keep context and the on-device
    prefix bounded.
  • Cost: lease + fencing infrastructure and lease handoff; the secondary hostId
    tiebreak must be added before convergence can be claimed.
  • Pure log appends remain lock-free.
  • docs/daily_os_ai_runtime_architecture.md (§8, Thread G)
  • lib/classes/vector_clock.dart
  • lib/features/agents/README.md (Wake Orchestration: vector-clock self-suppression)
  • Kleppmann, "How to do distributed locking"
  • ADR 0001, ADR 0016, ADR 0017, ADR 0019

Adr 0019 Attention Negotiation Protocol (`docs/adr/0019-attention-negotiation-protocol.md`)

ADR 0019: Attention-Negotiation Protocol and Bid Schema

  • Status: Accepted
  • Date: 2026-05-30
  • Amended by: ADR 0021, which reclassifies attention requests as
    LLM-authored claims and the deterministic arbiter as a helper rather than the
    canonical planner decision-maker.

Context

Per-task, per-project, and day (Shepherd) agents run independently. They read
each other's distilled reports but never negotiate for the user's scarce
attention or resolve scheduling conflicts. The anchor paper leaves multi-agent
contention over the shared graph unresolved.

Lotti is already a blackboard system (append-only log = event source, projected
typed-edge graph = shared blackboard, agents = knowledge sources); what is
missing is a meta-level controller. Hard constraints cannot be enforced by
prompting an LLM (U-Define, arXiv 2605.02765), and "ask when in doubt" has a
decision-theoretic basis in value-of-information (Sarne & Grosz 2013).

Lotti already ingests wearable/health data (lib/services/health_service.dart +
lib/logic/health_import.dart → synced QuantitativeEntry/WorkoutEntry), so
receptivity and outcome signals are real and already in the graph, not
hypothetical.

Decision

  1. Introduce a single planner behavior as a Hayes-Roth meta-level controller
    over the shared graph.
  2. Bids are events, not RPCs. Task/project agents emit attention_request
    events carrying impact, priority, deadline-slack, energy-fit, and (for
    recurring asks) a cadence — modeled as new AgentDomainEntity variants and
    AgentLink types on the existing synced graph. The exchange is
    Contract-Net-shaped (call-for-proposals → bid → award → inform).
  3. No auction incentive-compatibility — but not blind trust. All bidders are
    sub-agents of one principal, so there are no Vickrey-style payments. But one
    principal does not make LLM agents calibrated: they can overstate impact or
    misjudge urgency. So bids carry evidence references (links to the
    task/project/day facts that justify them) and bounded fields. As amended
    by ADR 0021, the planner LLM weighs those claims from an evidence brief;
    deterministic code validates hard constraints and persistence, not the final
    allocation judgment.
  4. Non-negotiables are enforced by a deterministic verifier over the
    projected graph during the draft → agreed transition — not by instructing
    the LLM. The minimal constraint language is recurrence + preemption priority
    (e.g. "gym 3×/week may pre-empt"). Compliance is checked against real actuals,
    including WorkoutEntry/QuantitativeEntry from health import. Because sensor
    actuals can lag or miss (sync delay, dead battery, untracked activity), the
    verifier supports manual override / self-report / bypass: a sensor gap
    surfaces as a confirmable prompt, never a hard block on draft → agreed, so it
    cannot wrongly block or nag.
  5. "Ask when in doubt" = value-of-information. Raise a ChangeSet/
    ChangeDecision only when the expected value of the user's answer exceeds the
    interruption cost; low-VOI conflicts auto-resolve and are logged only for
    reversible, low-stakes actions
    — committed schedule changes, block drops,
    and external side effects stay gated regardless of VOI until the user has
    calibrated trust. VOI proxies:
    day-plan utility delta, deadline slack, energy-band fit, recent
    ChangeDecision dismissal rate, and device/health receptivity signals
    (recent activity, workout completion, steps) from the existing health
    pipeline.
  6. The planner's output is a ChangeSet routed through the existing human gate
    (ADR 0006); awards become PlannedBlocks on the DayPlan. A project phase
    can emit standing recurring attention_requests (e.g. "monitoring → 15 min
    weekly").
  7. Negotiation converges like any other agent state (ADR 0018): bids and
    awards are events folded in canonical order, so concurrent arbiter runs on two
    devices cannot drop a bid branch — convergence handles that, not the lease.
    The lease on (userId, dayId, planner) only reduces duplicate planner work and
    gates the irreversible schedule commit.

Negotiation Flow

mermaid
sequenceDiagram
  participant Agent as Task / Project agent
  participant Planner
  participant Verify as Non-negotiable verifier
  participant User
  Agent->>Planner: attention_request (impact, deadline-slack, energy-fit)
  Planner->>Verify: candidate DayPlan vs hard constraints
  Verify-->>Planner: violations
  Planner->>Planner: rank by utility, compute VOI
  alt VOI > interruption cost
    Planner->>User: ChangeSet
    User-->>Planner: ChangeDecision
  else low VOI
    Planner->>Planner: auto-resolve and log
  end
  Planner->>Agent: award becomes PlannedBlock

Consequences

  • Cross-agent attention arbitration with one accountable planner; reuses the
    ChangeSet gate, the DayPlan (capacity/energy bands), and WakeOrchestrator.
  • Non-negotiables are guaranteed by code, not hoped-for via a prompt.
  • Interruptions are governed by VOI with real receptivity signals — the formal
    antidote to nagging.
  • Updated by ADR 0021: the primary abstraction is a structured claim on the
    blackboard. Bid/award storage remains useful for provenance, but the day
    planner LLM weighs claims. Deterministic code validates hard constraints and
    persists decisions; deterministic ranking should only be added where a
    concrete planner path needs it. Concrete VOI weighting and calibration of the
    receptivity model remain open.

Implementation Notes

  • Implemented substrate: attention request/award/disposition records, durable
    standing agreement records, and indexed local projections for planner-window
    lookup without scanning the large agent_entities source table. Planned:
    planner brief construction, LLM-mediated proposal generation, hard-constraint
    verification, outcome tracking, and planner auto-commit.
  • docs/daily_os_ai_runtime_architecture.md (§5, §9, Thread A)
  • ADR 0021 (LLM-mediated attention claim weighing)
  • Hayes-Roth, "A Blackboard Architecture for Control" (1985); Contract Net
    Protocol; Sarne & Grosz (2013); U-Define (arXiv 2605.02765)
  • lib/services/health_service.dart, lib/logic/health_import.dart
  • ADR 0002 (wake), ADR 0006 (ChangeSet), ADR 0018 (lease)

Adr 0020 Agent Input Capture (`docs/adr/0020-agent-input-capture.md`)

ADR 0020: Agent Input Capture — Per-Source Content-Addressed Snapshots

  • Status: Accepted
  • Date: 2026-05-30

Context

The agent is a log, and its derived state is a projection of that log (ADR
0016). For the projection to be a pure function of the log — and therefore for
deterministic replay, replay-from-summary equivalence (ADR 0017), and
cross-device convergence (ADR 0018) to hold — the inputs the agent reasoned over
must live in the log, not be re-read from mutable external state at fold
time.

User-generated content the agent needs to know about — task titles,
descriptions, checklist items, comments, audio transcripts, image-analysis
results — lives in the journal domain, which has its own convergence model
and a user-facing Conflict-row resolution path (losing user-authored content
silently is unacceptable). The agent references that content; it does not
own it.

If an agent's log event only references a journal entity (by id), replay
re-reads whatever that entity says now — which may have been edited or deleted
since the wake. The fold then depends on mutable external state and stops being
pure: replay can diverge from history, provenance is lost ("what text actually
produced this proposal?"), the on-device prompt-prefix cache is busted by every
cosmetic edit, and the agent's input becomes coupled to the journal domain's
conflict resolution.

The codebase already snapshots in one place — the Daily OS capture flow stores
the transcript in a CaptureEntity — and the schema already has the right
primitive: AgentMessagePayloadEntity (a normalized large-content payload),
referenced via the messagePayload link, with contentEntryId pointing back at
the originating journal entity. The open decision is whether to generalize
snapshotting to all agent inputs (notably task and project agents reading
task content), and at what granularity: reference-only vs. a whole-rendered
context blob vs. per-source payloads.

Decision

  1. Capture inputs into the log; never reason from a live reference at replay.
    When an agent consumes user content during a wake, the exact text it fed the
    model is recorded as append-only payloads in the agent log. The projection
    folds the log alone; it never re-reads the journal domain to reconstruct what
    an agent saw.

  2. Per-source, content-addressed payloads — provenance on the reference, not
    the payload.
    Each distinct source — a task description, each comment, each
    transcript, each image-analysis result — is stored once as an
    AgentMessagePayloadEntity keyed purely by its contentDigest (the
    canonical-form content hash defined in ADR 0017 / §6: sorted keys, RFC 3339
    UTC, normalized numbers, canonical JSON, versioned tag). The payload holds
    content only — no originating-entity identity — so identical content
    dedupes to a single row across wakes and across agents. Provenance lives
    on the reference
    : the consuming message (and its messagePayload link)
    carries contentEntryId → the originating journal entity. The same shared
    payload is therefore pointed at by many links, each with its own provenance,
    so multi-entity provenance is preserved — a single contentEntryId field on
    the shared payload could not, and is deliberately not where it lives.
    Storage grows with the number of distinct content versions observed, not
    with wakes or agents.

  3. Per-wake input frontier. Each wake records the ordered set of source
    payload hashes it consumed (the messagePayload references on that wake's
    message). This frontier is what makes the model context reconstructible
    byte-for-byte for both replay and the prefix cache.

  4. Canonical assembly order — from in-log metadata. The rendered prompt
    context is assembled from the frontier in a fixed, replica-independent order —
    never insertion or arrival order — so two devices and a replay produce
    byte-identical prompts and the stable prefix keeps cache-hitting. The sort key
    is the source's createdAt then id captured into the log at capture
    time
    (snapshotted onto the messagePayload link / message), not a live
    read of the journal entity — which could be edited or deleted. Like the
    content itself, the ordering is thus a pure function of the log (Decision 1).

  5. Capture the rendered context, not unbounded raw history. The agent
    captures the derived text it actually fed the model (a transcript, an
    analysis result, the task's rendered section). Heavy raw artifacts (long
    audio, large images) stay referenced + hashed in the journal domain; only
    their derived text enters the agent log. This bounds capture by the prompt
    budget and records the true provenance (what produced the output).

  6. Retention and coverage are shared with compaction. A per-source payload
    is retained while any non-compacted event references it; a summary records
    the source payloads it covers as part of its frontier coverage. This reuses
    ADR 0017's frontier/coverage machinery rather than introducing a new one.

Consequences

  • Deterministic replay & provenance. The fold is a pure function of the log;
    "why did the agent propose X" is answerable from the exact captured text, and
    the sources/versions behind a decision are explicit and diffable between
    wakes.
  • Convergence with no LWW on inputs. Captured payloads are append-only,
    content-addressed events → they converge via the projection kernel (ADR 0018
    rule 1). The agent never last-writer-wins user content; the journal domain
    keeps its own convergence and Conflict UI, and the agent only references +
    snapshots it.
  • Storage is bounded by distinct-versions × edits (not wakes), with
    compaction folding old payloads away — which is what makes "full capture"
    affordable. Per-source dedup is strictly better here than a per-wake blob,
    which would re-store the entire context on any single-byte edit.
  • Stable prompt prefix for KV-cache reuse follows from canonical assembly
    order (rule 4), independent of storage granularity.
  • Cost: per-wake input-frontier bookkeeping, canonical-assembly discipline,
    and retention coupling with compaction — all built on the existing
    payload/link + frontier primitives, so no new mechanism.

Implementation Notes

  • Implemented: content-addressed per-source payloads, capture references,
    input frontier projection, retraction handling, and task/project/day wake
    memory assembly through AgentWakeMemory.
  • Still planned: planner-specific response caching and later retention tuning
    beyond the current compaction coverage model.

Rejected alternatives

  • Reference-only. Breaks replay purity, loses point-in-time provenance,
    couples agent inputs to journal-domain conflict resolution, and busts the
    prefix cache on every edit.
  • Whole rendered-context blob per wake. Any single-byte change to any source
    yields a new blob hash → re-stores the entire context, defeating dedup at the
    granularity edits actually occur, and collapses per-source provenance into an
    opaque lump. The per-wake input frontier (rule 3) already gives deterministic
    reassembly, so the blob has no remaining advantage.
  • ADR 0016 (agent state as log projection) — this extends the projection thesis
    from derived state to the agent's inputs.
  • ADR 0017 (deterministic log compaction) — shares the contentDigest /
    frontier / coverage machinery.
  • ADR 0018 (convergent multi-device execution) — captured inputs are append-only
    and converge via the kernel; user content itself stays on the Conflict path.
  • Roadmap: PR 5 (content-addressed input capture + compaction) implemented this
    input-side companion to state-as-projection and generalized the existing Daily
    OS CaptureEntity.transcript snapshot to task/project/day agent memory.

Adr 0021 Llm Mediated Attention Claim Weighing (`docs/adr/0021-llm-mediated-attention-claim-weighing.md`)

ADR 0021: LLM-Mediated Attention Claim Weighing

  • Status: Accepted
  • Date: 2026-06-05

Context

ADR 0019 introduced attention negotiation as a Contract-Net-shaped protocol:
agents emit attention requests, a planner behavior arbitrates them, and accepted
awards become day-plan changes through the existing ChangeSet gate.

The first implementation created useful primitives:

  • AttentionRequestEntity and AttentionAwardEntity as persisted log records.
  • Attention evidence, award/request, and award/plan links.

However, the product intent is not to let a fixed deterministic scoring formula
decide the user's day. Specialist agents are LLM-backed knowledge sources. They
should make high-quality, evidence-backed claims for attention. A day-planning
LLM should then weigh those claims against each other, the current plan, standing
agreements, recent outcomes, and the user's preferences.

The deterministic parts remain necessary, but they are the substrate and safety
rails: log projection, provenance, idempotency, validation, convergence, and
ChangeSet application. They are not the source of planning judgment.

Decision

  1. Attention requests are claims, not final bids. An
    AttentionRequestEntity is a specialist agent's structured claim that some
    user attention should be allocated. Fields such as impact, urgency,
    energyFit, windows, deadlines, and rationale are agent-stated assertions
    that the planner may accept, discount, combine, defer, or reject after reading
    the evidence.

  2. Specialist LLM agents author the claims. Task, project, fitness, sleep,
    finance, maintenance, and other agents may emit attention requests when their
    domain model indicates that calendar time, a check-in, or a protected habit
    block matters. Claims must cite evidence references and explain why the
    request matters now.

  3. The day-planner LLM weighs claims. The primary planning behavior consumes
    an attention brief, not just numeric scores. The brief contains the current
    day plan, pending claims, evidence summaries/snapshots, hard constraints,
    standing agreements, recent user decisions, and outcome signals. The planner
    LLM decides which claims should become proposed blocks, which claims are
    satisfied by the same block, and which claims should be declined or deferred.

  4. Deterministic code validates, records, and applies decisions. Code still
    owns hard checks: overlapping blocks, capacity, invalid windows, missing
    evidence, stale baselines, idempotent IDs, soft deletion, ChangeSet
    application, and projection convergence. The planner LLM may propose; it does
    not directly mutate the calendar.

  5. No speculative deterministic fallback. A deterministic utility ranker is
    not the canonical decision-maker, and it should not live in production as a
    fallback without a runtime caller. Add deterministic helper code only when a
    concrete planner path needs slot validation, candidate generation, or
    regression fixtures.

  6. Planner output must preserve claim provenance. A planner proposal records
    which request ids it satisfies, which request ids it declines or defers, and
    a rationale for each material decision. One proposed block may satisfy
    multiple claims, for example a workout block satisfying both a strength goal
    claim and a daily-steps claim.

  7. Awards are planner proposals, not objective winners. An
    AttentionAwardEntity represents the planner's proposed allocation of
    attention for one or more claims. It is evidence-linked and auditable, but it
    does not imply that a deterministic auction found an optimal winner.

  8. Standing agreements decide whether proposals need the user. A standing
    agreement may auto-accept low-risk proposals, require explicit user approval,
    or reject proposals that violate trust boundaries. The accepted calendar
    mutation still flows through ADR 0006's ChangeSet/ChangeDecision path.

  9. Planner claim discovery must use an indexed timeframe projection, never a
    table scan or day-plan key.
    agent.sqlite can be large, and
    agent_entities.serialized is a JSON payload. The planner must not discover
    claims by scanning agent_entities or filtering deserialized JSON in Dart.
    Claims are discovered by arbitrary planning windows such as
    [tomorrow 00:00, next midnight) or [now, next Sunday 17:00), not by
    requiring a dayplan-* key to exist first. The source of truth remains the
    synced AgentDomainEntity log, but claim lookup uses a small derived index
    table maintained inside agent.sqlite, for example:

    text
    attention_claim_index
      request_id        TEXT PRIMARY KEY
      agent_id          TEXT NOT NULL
      status            TEXT NOT NULL
      scope_kind        TEXT NOT NULL
      visibility_start   DATETIME NOT NULL
      visibility_end     DATETIME NOT NULL
      deadline          DATETIME
      next_review_at    DATETIME
      target_id         TEXT
      target_kind       TEXT
      updated_at        DATETIME NOT NULL
      deleted_at        DATETIME

    This table is a local projection/cache, not an independently synced source of
    truth. It can be rebuilt from agent_entities, but normal writes update it
    transactionally with attention request/disposition writes. Querying for
    tomorrow means an overlap query against visibility_start/visibility_end,
    not a lookup by day-plan id.

  10. Claim status is a projected lifecycle, not only a field on the original
    request.
    The original claim should stay auditable. Planner/user/system
    outcomes should be represented by disposition events or an equivalent
    projection so a claim can be open, proposed, satisfied, partially satisfied,
    declined, deferred, superseded, expired, or withdrawn without mutating away
    its original rationale/evidence.

Target Flow

mermaid
sequenceDiagram
  participant Specialist as Specialist LLM agents
  participant Brief as AttentionBriefBuilder
  participant Planner as Day-planner LLM
  participant Validate as Deterministic validator
  participant Gate as ChangeSet / standing agreement
  participant Plan as DayPlan projection

  Specialist->>Specialist: inspect domain evidence
  Specialist->>Brief: AttentionRequestEntity claims
  Brief->>Planner: current plan + claims + evidence + agreements
  Planner->>Validate: proposed blocks, satisfied claims, declined claims
  Validate-->>Planner: hard validation result
  Planner->>Gate: ChangeSet proposal with rationale
  Gate-->>Plan: accepted changes only

Implementation Plan

  1. Flexible claim scope. Attention requests carry arbitrary visibility
    windows, deadlines, and cadence hints so agents can express horizon claims
    such as "90 minutes before Sunday" or "3 workout sessions this week" without
    requiring a pre-existing DayPlanEntity or dayplan-* key.

  2. Indexed claim projection. Add attention_claim_index (or an equivalent
    indexed projection) with indexes for active timeframe lookup, for example:

    sql
    CREATE INDEX idx_attention_claims_active_window
      ON attention_claim_index(status, visibility_start, visibility_end,
        next_review_at, deadline, request_id)
      WHERE deleted_at IS NULL;
    
    CREATE INDEX idx_attention_claims_active_deadline
      ON attention_claim_index(status, deadline, request_id)
      WHERE deleted_at IS NULL AND deadline IS NOT NULL;

    Planner reads first query this projection for request ids using interval
    overlap (visibility_start < windowEnd AND visibility_end > windowStart),
    then hydrate only the matching agent_entities rows by primary key. Query
    plans should prefer narrow indexed reads or UNION ALL over broad OR
    predicates so SQLite does not fall back to a scan.

  3. Claim disposition model. Add disposition events/projection for proposed,
    satisfied, partially satisfied, declined, deferred, superseded, expired, and
    withdrawn states. Do not rely only on mutating
    AttentionRequestEntity.status.

  4. Attention brief builder. Add a service that reads the indexed claim
    projection for an arbitrary planning window, hydrates matching AttentionRequestEntity
    records, resolves evidence summaries from captured agent inputs, includes the
    current DayPlanEntity records that already exist or lightweight draft plans
    that the planner is allowed to modify, and produces a compact planner
    context.

  5. Planner output contract. Define the day-planner LLM response shape:
    proposed blocks, satisfiesRequestIds, declined/deferred requests, per-block
    rationale, baseline plan id, and explicit hard-constraint assumptions.

  6. Mechanical validator. Validate the proposed diff before persistence:
    no overlaps, valid windows, valid evidence ids, valid request ids, sane
    durations, no stale baseline, no direct mutation outside allowed ChangeSet
    actions.

  7. Persistence bridge. Persist planner proposals as AttentionAwardEntity
    records plus links to requests/evidence and concrete day plans when a block
    is proposed, then emit ChangeSet-compatible
    add_block/move_block/drop_block items.

  8. Standing agreements. Implemented foundation:
    StandingAgreementEntity records durable user policies/goals such as
    recurring workouts, sleep wind-down blocks, task focus time, paperwork
    limits, and low-risk check-ins. standing_agreement_index is a local
    projection for status/scope/window lookup so planner reads do not scan
    agent_entities. Remaining work: consume these agreements in the planner
    brief, evaluate proposal classes against their approvalMode and
    enforcement, and route matching proposals through auto-accept/ask/reject
    policy.

  9. Decision and outcome tracking. Record why claims were accepted, declined,
    deferred, or superseded, and feed user decisions and actual completions back
    into future agent claims.

  10. UI projection. Build the "No Bullshit" view as a projection of the log:
    what each agent claimed, what evidence it cited, what the planner proposed,
    what was accepted/rejected, and what actually happened.

Consequences

  • The system uses LLM judgment where judgment matters: balancing health, sleep,
    work, deadlines, energy, and user preference.
  • Numeric fields remain useful as claim metadata, but the planner must not treat
    them as trusted objective truth.
  • Testing shifts from "score decides winner" to "brief construction, output
    validation, persistence, and ChangeSet application are correct."
  • Do not keep deterministic arbitration code as speculative fallback. If a
    concrete planner service needs helper logic later, add it at that boundary
    with direct tests for that caller.
  • Planner claim retrieval needs dedicated indexing. Generic
    agent_entities(type, created_at) or agent_entities(agent_id, type, subtype)
    indexes are not enough for cross-agent horizon queries over a large
    agent.sqlite database.
  • More provenance is required: accepted blocks should explain which claims they
    satisfied, and declined claims should have a logged reason.
  • The planner can express substitutions and bundles, such as one workout block
    satisfying both strength-training and daily-step claims.
  • ADR 0019: Attention-Negotiation Protocol and Bid Schema — amended by this ADR.
  • ADR 0006: Change-Set Deferred Tool Confirmation.
  • ADR 0016: Agent State as Log Projection.
  • ADR 0018: Convergent Multi-Device Execution.
  • ADR 0020: Agent Input Capture.
  • lib/classes/agents/attention_negotiation.dart
  • lib/classes/agents/agent_domain_entity.dart

Adr 0022 Long Lived Daily Os Planner (`docs/adr/0022-long-lived-daily-os-planner.md`)

ADR 0022: Long-Lived Daily OS Planner

  • Status: Accepted
  • Date: 2026-06-07

Context

Daily OS Next currently models the planning agent as one active
AgentIdentityEntity per local calendar day. DayAgentService.createDayAgent
derives the agent identity from the day-plan id, stores that id in
AgentSlots.activeDayId, and routes capture, draft, refine, commit, memory, and
observations through that per-day agentId.

That shape is useful for task agents because each task should have a bounded
private context. It is the wrong boundary for day planning. The planner is meant
to learn across days and categories: what capacity the user actually commits
to, what gets carried over, when capture text refers to existing work, which
categories are usually under-estimated, and which interventions the user
accepts or rejects.

The current code makes those learning paths structurally weak:

  • DayAgentService.createDayAgent permits one day-agent identity per local day.
  • DayAgentPlanService.summarizeRecentPatterns reads recent plans by
    agentId, so a new day cannot see yesterday's plans under the current model.
  • DayAgentWorkflow loads observations, captures, and compaction memory by
    agentId, so the memory substrate is reset at each day boundary.
  • DayAgentWorkflow.execute derives the target day from
    state.slots.activeDayId, which is safe only while one agent owns one day.

At the same time, the day-plan storage model already has the right day boundary:
DayPlanEntity has a deterministic day-plan id, dayId, and planDate. The
day does not need to be represented as an agent identity.

Daily OS Next is still early enough that migration compatibility is not the
primary constraint. We should fix the model directly before the per-day identity
assumption becomes more expensive.

Decision

  1. Daily OS uses one long-lived planner/shepherd identity. There is one
    active planner AgentIdentityEntity for the Daily OS planning behavior. The
    persisted kind may remain day_agent until a broader naming cleanup is
    worth doing, but service and workflow semantics are planner-shaped, not
    date-agent-shaped.

  2. A day is an explicit workspace, not an agent identity. The day workspace
    key remains:

    text
    dayId = dayPlanId(localDay(date)) // dayplan-YYYY-MM-DD

    Day-scoped records must carry or derive this workspace explicitly. The
    planner may own many day workspaces.

  3. The planner workflow MUST NOT read AgentSlots.activeDayId, and must stop
    deriving it.
    A long-lived planner cannot read its target day from mutable
    agent state. This is stronger than "not authoritative": today activeDayId
    is derived from the per-day AgentDayLink by the state projection
    (derived_agent_state.dart) and written back by reconcileAgentState on
    every wake, so under one planner with many day links it would reconcile to a
    single most-recent day and persist it, corrupting the slot and emitting a
    permanent activeDayId derived-field mismatch. The refactor must therefore
    stop creating one AgentDayLink per day for the planner (or exclude
    activeDayId from derivation, reconcile write-back, and diagnostics), not
    merely stop reading the slot at execution time. Day-scoped wakes carry a
    target dayId through wake context and trigger tokens; the workflow fails
    fast when a day-scoped wake cannot resolve a day.

  4. Planner wakes are workspace-scoped. Every day-scoped wake carries an
    explicit token such as:

    text
    planning_day:<dayId>
    drafting:<dayId>
    refine:<dayId>
    capture_submitted:<captureId>
    decided_task:<taskId>
    decided_capture_item:<parsedItemId>

    Tool calls that include dayId must be rejected if the requested day does
    not match the wake workspace.

  5. Captures need explicit day scope. Captured time and planning target are
    not the same concept. CaptureEntity must carry the planning dayId
    directly or through an equivalent deterministic link. Parsed items can
    continue to derive day scope through their capture.

  6. Memory separates global planner knowledge from day workspace context.
    The planner's long-running memory is intentional and cross-day. Raw
    day-scoped inputs, such as capture transcripts, parsed items, draft blocks,
    and refine transcripts, must be filtered to the active workspace unless they
    are deliberately summarized into global learning.

  7. Per-day threads/runs remain useful, but not as identities. A day wake may
    run in a day-scoped thread/run for bounded prompt context, inspectability,
    retries, and debugging. Durable memory and learning belong to the
    long-lived planner identity.

  8. Provider-specific inference remains behind provider-neutral contracts.
    Forced tool-choice behavior is required for reliable day planning, but the
    workflow contract must stay generic across Gemini, Mistral, OpenAI-compatible
    providers, and future providers.

  9. Planner learning has two loops. The fast loop is daily and unsupervised:
    raw day-scoped inputs and planner observations accrue on the long-lived
    identity's log as episodic memory, compacted per ADR 0017. The slow loop is
    the weekly one-on-one ritual (TemplateEvolutionWorkflow), now bound to the
    single planner identity, which consolidates recurring daily observations into
    durable, user-approved knowledge. Nothing becomes a durable preference except
    through the weekly gate or an explicit user confirmation. Daily episodic
    memory may be aged aggressively precisely because anything worth keeping is
    promoted through the slow loop. This is the architectural answer to "learn
    day to day" while keeping "the weekly one-on-one".

  10. User-stated knowledge is durable and compaction-exempt. "Memorize what I
    tell you" requires a store that LLM log compaction cannot dissolve. Routing
    user instructions through agent-inferred record_observations into the
    shared compaction fold (ADR 0017) silently degrades them over a long-lived
    planner's life — relocating amnesia rather than curing it. Confirmed user
    knowledge (e.g. "never schedule deep work before 10:00") is therefore a
    keyed, supersedable, user-confirmable record, excluded from the compaction
    fold. To keep durable memory from growing the prompt without bound as the
    planner ages, it is surfaced two-tier, borrowing Claude Code's
    memory-index pattern: a compact index of one-line hooks is always
    present, and the full statement of an item is pulled in on demand, scoped
    to the active workspace (global always; category: / project: when the
    wake touches that scope), reusing the same scoped-retrieval machinery as
    attention claims. Always-on critical items may still be injected verbatim
    (cf. ADR 0014 critical-observation injection). Agent-inferred observations
    stay in the compactable episodic stream until the slow loop or an explicit
    user confirmation promotes them. The store is specified in the implementation
    plan's "Durable Planner Knowledge" section. Each record also carries optional
    author-time tags (immutable, set once at origin, surfaced as chips in the
    "What I've learned" panel). The episodic log behind this two-tier memory is
    reachable on demand via the search_memory recall tool (ADR 0017), whose
    hits resolve author-time [[relation:id]] links against both the episodic
    log and durable-knowledge keys (a moc-<topic> knowledge entry can thus act
    as a curated map into related memory).

  11. Domain agents are peers, not part of the planner. Specialist agents
    (e.g. fitness, sleep) are separate durable identities. They negotiate for
    calendar time through the existing attention-claim and standing-agreement
    protocol (ADR 0019, ADR 0021); the long-lived planner is the stable
    counterparty and sole arbitrator they negotiate with. The planner weighs
    their claims and proposes plan changes through the ChangeSet gate (ADR
    0006), but does not absorb domain reasoning. This is the inverse of a
    planner-spawned analyst run (planner-owns-throwaway-investigator vs.
    durable-peer-petitions-planner) and is specified separately in ADR 0023.

  12. Day-scoped scheduling needs explicit workspace context, not a single
    timestamp.
    A single AgentState.scheduledWakeAt cannot represent several
    outstanding day-scoped wakes under one planner; a second day's
    set_next_wake clobbers the first. Scheduled day wakes must be either
    global-only planner wakes or persisted scheduled-wake records carrying a
    workspace key and trigger tokens (ADR 0010). The self-scheduled morning
    pre-warm is day-scoped and therefore requires the latter; it must not be
    restored as a context-less wake, and "global-only scheduled wakes" must not
    silently remove it.

  13. Deep disposable analysis is deferred. One-off, planner-spawned
    investigation runs that write a compact artifact and close are deliberately
    out of scope here. Deferring them avoids pre-committing analysis ownership
    before the domain-agent boundary (ADR 0023) is settled — several of the
    motivating questions ("why does this project keep displacing workouts?") are
    exactly what a durable domain agent exists to answer. They may be
    reintroduced in a later ADR, reusing the existing AgentReportEntity scope
    (which already carries scope, confidence, and provenance) rather than a
    new artifact entity.

Target Runtime Shape

mermaid
flowchart TD
  Planner["Long-lived Daily OS planner<br/>AgentIdentityEntity"]
  Episodic["Episodic day memory<br/>observations + compacted log (fast loop)"]
  Weekly["Weekly one-on-one ritual<br/>TemplateEvolutionWorkflow (slow loop)"]
  Knowledge["Durable planner knowledge<br/>user-confirmed, compaction-exempt"]
  DayWorkspace["Day workspace<br/>dayId = dayplan-YYYY-MM-DD"]
  Capture["CaptureEntity<br/>agentId + dayId"]
  Plan["DayPlanEntity<br/>agentId + dayId + planDate"]
  Wake["Wake context<br/>plannerAgentId + dayId + trigger tokens"]
  Thread["Day-scoped thread/run<br/>bounded prompt and wake log"]
  Domain["Domain agents: fitness, sleep<br/>separate durable identities (ADR 0023)"]
  Claim["AttentionRequest claims<br/>requestedMinutes + window + cadence"]

  Planner --> Episodic
  Episodic --> Weekly
  Weekly --> Knowledge
  Knowledge --> Planner
  Planner --> Wake
  Wake --> DayWorkspace
  Wake --> Thread
  Domain --> Claim
  Claim --> Planner
  DayWorkspace --> Capture
  DayWorkspace --> Plan
  Capture --> Plan

Consequences

  • Cross-day learning becomes structurally possible because plans,
    observations, memory compaction, reports, and token usage belong to one
    durable planner identity.
  • Day isolation moves into explicit workspace context, validation, and filtered
    queries. This is safer than implicit isolation through agent identity because
    the boundary is visible in every wake and tool call.
  • getDayAgentForDate cannot simply return the same agent for every date. That
    naive change would leak captures and context across days. The service API
    must be reshaped around getOrCreatePlannerAgent and day workspace helpers.
  • Wake queue and scheduled wake semantics must become workspace-aware — across
    superseding, dedupe, and token merge/extraction. Current agent-wide
    removeByAgent superseding and mergeTokens merging (both keyed only by
    agentId), plus "first matching token wins" extraction helpers, would let one
    day's manual wake drop or contaminate another day's queued work once all days
    share one planner. This must land with or before the identity collapse,
    not in a later PR, or there is a live cross-day wake-cancellation and
    wrong-day-drafting window.
  • All planner wakes across all days now share one execution lease and one
    state chain
    (ADR 0018). Single-flight by agentId therefore becomes a
    global planner serialization point, not the per-day sharding the old model
    accidentally provided; a slow draft for one day blocks unrelated days. This is
    acceptable for planner judgment initially, but is a property of this decision
    and should be revisited only with evidence.
  • Scheduled wakes need either global-only semantics or persisted trigger tokens
    / workspace context. A single AgentState.scheduledWakeAt is not enough for
    multiple day-scoped planner wakes, and a context-less scheduled wake cannot
    drive the day-scoped morning pre-warm.
  • Durable cross-day memory needs a contradiction/decay policy. Confirmed
    knowledge is revisable (recency-wins supersession) at the weekly gate or by
    explicit user retraction; daily episodic memory is recency-weighted. Without
    this, durable memory becomes stale truth — the same risk previously flagged
    only for analysis artifacts now applies to the planner's own long-lived memory.
  • State reconstruction cost grows with the planner's lifetime. The projection
    loads and folds the agent's full observation/message set per wake (ADR 0016);
    collapsing N tiny per-day logs into one long-lived log removes the bound the
    old model accidentally had. Compaction (ADR 0017) bounds the rendered tail but
    not the query/fold input, so a multi-year planner needs a projection snapshot
    or incremental fold story.
  • Some existing docs and tests that describe "one day-agent per calendar date"
    are superseded by this decision and must be updated during implementation.

Adr 0023 Durable Domain Agents And Time Negotiation (`docs/adr/0023-durable-domain-agents-and-time-negotiation.md`)

ADR 0023: Durable Domain Agents and Time Negotiation

  • Status: Proposed
  • Date: 2026-06-07

Context

The long-lived Daily OS planner (ADR 0022) is the durable identity that owns the
day plan and arbitrates what gets scheduled. But the planner is not the only mind
the product wants. The goal is a small set of durable, domain-specific agents
— a fitness agent, a sleep coach, later nutrition, finances, maintenance — each
with its own memory, its own goals, and its own view of how the user is doing in
that domain. These agents should negotiate with the planner for calendar time:
a fitness agent should be able to ask for three workout blocks this week; a sleep
coach should be able to protect a wind-down window.

This is the inverse of the "disposable analyst run" idea that ADR 0022
deliberately deferred (Decision 13). An analyst run is ephemeral, planner-spawned,
read-only, and informational. A domain agent is durable, self-owned,
self-scheduled, and allocative — its output is a claim on scarce time, not a
report.

Most of the negotiation substrate already exists in lib/features/agents/, built
by ADR 0019 (attention negotiation protocol) and ADR 0021 (LLM-mediated claim
weighing). What is missing is the producer side: there is no durable domain
agent that can author claims for a non-task domain.

What already exists (verified in code)

  • AttentionRequestEntity (agent_domain_entity.dart) — an event-sourced,
    immutable, evidence-backed claim that already carries requestedMinutes,
    scopeKind (day | dateRange | deadline | recurrence), earliestStart
    / latestEnd / deadline, energyFit, impact, urgency, cadence,
    targetId / targetKind, rationale, and evidenceRefs. It already models
    "claim 45 minutes Tuesday evening", not merely "interrupt the user".
  • AttentionClaimDispositionEntity — projects claim lifecycle
    (open → proposed → satisfied / declined / deferred / superseded
    / expired / withdrawn) without mutating the original claim.
  • AttentionAwardEntity — a planner proposal for a concrete plan block
    (dayId, planId, blockId, startTime, endTime, rank, utilityScore).
    It is a proposal: schedule mutation still flows through the ChangeSet gate
    (ADR 0006).
  • StandingAgreementEntity with StandingAgreementScope already enumerating
    fitness and sleep, plus cadence, enforcement
    (preference | target | nonNegotiable), approvalMode
    (autoAccept | ask | reject), canPreempt, and quota fields
    (minCount / maxCount / minMinutes / preferredSessionMinutes).
  • AttentionEvidenceRef with AttentionEvidenceKind already including .health
    and .outcome.
  • The day planner already reads claims and standing agreements for the
    planning window: day_agent_context_builder.dart calls
    getAttentionPlanningInputsForWindow(start, end) and renders both into the
    planner prompt.

What is missing (the gap)

  • AgentKinds has only task_agent, project_agent, day_agent,
    template_improver — no domain agent kind.
  • request_attention is wired only to task agents: AttentionRequestHandler
    hardcodes _taskTargetKind = 'task' and reads task.categoryId, so a claim
    cannot be authored for a non-task domain.
  • There is no self-scheduled producer wake for a domain agent (e.g. a nightly
    "did the user hit 2 of 3 workouts?" check that emits or refreshes claims).
  • The planner's arbitration path — weigh claims → emit AttentionAwardEntity
    → propose an add_block ChangeSet — is designed in ADR 0021 but not yet wired
    for the day planner.
  • Claims are inherently horizon-scoped ("3 workouts this week"), but the
    planner's wake contract (ADR 0022) is rigidly planning_day:<dayId>.

Decision

  1. Domain agents are durable, first-class identities. Introduce a
    domain_agent AgentKind, one durable identity per life domain (initially
    fitness and sleep, mapped to StandingAgreementScope). They have their
    own memory substrate and learning loops, mirroring the planner's two-loop
    model (ADR 0022 Decisions 9–10), not a per-day or per-task identity. Memory
    coherence, not claim volume, sets the granularity: one durable agent per
    scope, not one per workout.

  2. Domain agents produce claims; they never write the calendar. A domain
    agent's only path to time is to author an AttentionRequestEntity (and,
    for recurring commitments, a StandingAgreementEntity). It does not add,
    move, or drop PlannedBlocks, and it does not call the planner synchronously.
    Claims are events on the synced log, discovered by the planner through the
    existing window-overlap projection — convergence-safe across devices
    (ADR 0018), exactly as ADR 0019 Decision 2 ("bids are events, not RPCs").

  3. request_attention is generalized off the task-only path. The handler
    must accept a category/target-agnostic claim so a fitness claim is not forced
    through a Task. targetKind becomes domain-shaped (e.g. fitness,
    sleep), categoryId is supplied by the domain agent's configuration rather
    than read from a task, and the task path becomes one caller among several.

  4. The planner is the sole arbitrator. The planner — and only the planner —
    weighs competing claims against the current plan, standing agreements, recent
    outcomes, and durable knowledge (ADR 0021 Decision 3), then emits an
    AttentionAwardEntity and a corresponding add_block ChangeSet. The award
    records provenance (which requestId it satisfies; one block may satisfy
    several claims). This claim → weigh → award → ChangeSet path is the core new
    build of this ADR. Domain agents are producers; the planner is the single
    consumer/arbitrator. This asymmetry is intentional: multi-agent contention
    needs one accountable arbitrator, not N peers writing shared plan state.

  5. The user stays in control through standing agreements. Whether an award
    is applied silently or shown for approval is governed by the matching
    StandingAgreementApprovalMode: autoAccept for low-risk recurring habit
    blocks, ask (default) routes through the ChangeSet / ChangeDecision gate
    (ADR 0006), reject blocks. enforcement = nonNegotiable