# Technical Documentation: matthiasn/lotti

> ℹ️ **Provenance:** Multi-Tier Ingestion · [CodeWiki Reference](https://codewiki.google/github.com/matthiasn/lotti)

### Overview (README.md)

# Lotti

[](https://flathub.org/en/apps/com.matthiasn.lotti) [](https://github.com/matthiasn/lotti/releases) [](https://codecov.io/gh/matthiasn/lotti) [](LICENSE)

**Tasks, time, journal and the people in your life — kept on your own devices,
synced end-to-end encrypted, with AI agents that propose while you decide.**

Lotti is a personal task manager, time tracker and journal. Speak a rambling
voice note and it comes back as a task with a checklist; an agent keeps a
living summary of every task and suggests the next change for you to confirm.
There is no Lotti cloud and no Lotti account: your record lives in a local
database on each of your devices, and the AI runs on a provider you pick — or
on none at all.

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


<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/tasks/workspace/desktop-dark.webp">
  <img alt="The task workspace on desktop: tasks grouped by due date, each with cover art, priority and status, beside an open task with its status, priority, due date, time spent and labels" src="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/tasks/workspace/desktop-light.webp">
</picture>

**[Install](#install)** · [Manual](https://matthiasn.github.io/lotti/manual/development/) ·
[Discord](https://discord.gg/uuSaa8NpY) · [Blog series](https://matthiasnehlsen.substack.com/p/meet-lotti)

On the [App Store](https://apps.apple.com/app/lotti-app/id6752654664) (iPhone,
iPad, Mac), [Google Play](https://play.google.com/store/apps/details?id=com.matthiasn.lotti)
and [Flathub](https://flathub.org/en/apps/com.matthiasn.lotti) · Windows from
source — Flutter, GPL-3.0.

## Why Lotti is different

- **Local-first.** Each device holds the whole record in local SQLite, with
  audio and images beside it on disk. No telemetry, no analytics, no account,
  no server that stores a readable copy of your data.
- **End-to-end encrypted sync through a relay you don't have to trust.**
  Devices sync over a [Matrix](https://matrix.org) homeserver that only ever
  sees ciphertext. Keys go only to devices you verified yourself by comparing
  emoji, and anything else is dropped.
- **Agents propose; you decide.** Task, project, goal, event and relationship
  agents read what you recorded and suggest changes. Each suggestion waits for
  you to confirm or dismiss it, apart from a small, named set of pre-approved
  writes such as transcribing a recording
  ([ADR 0102](docs/adr/0102-pre-approved-agent-changes.md)). Agent working
  memory lives in a separate database from your record.
- **Your AI, your choice — or none.** Lotti has no inference backend. You bring
  your own key for Mistral, OpenAI, Anthropic, Gemini and others, or run
  models locally, and route each category of your life to a different
  provider. Lotti is a complete task manager, time tracker and journal with AI
  switched off.

## What it looks like

<p align="center">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/tasks/agent-suggestions/mobile-dark.webp">
    <img width="260" alt="A task agent's summary with two proposed changes, a new checklist item and an estimate, each with dismiss and confirm controls, and Confirm all" src="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/tasks/agent-suggestions/mobile-light.webp">
  </picture>
  &nbsp;
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/onboarding/providers/mobile-dark.webp">
    <img width="260" alt="Onboarding: Lotti, drawn as a grandmother, recommends one provider key, with Mistral preselected and other providers behind a disclosure" src="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/onboarding/providers/mobile-light.webp">
  </picture>
  &nbsp;
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/sync/verification/mobile-dark.webp">
    <img width="260" alt="Confirming a new device: both screens show the same seven emoji, with They match and They differ buttons" src="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/sync/verification/mobile-light.webp">
  </picture>
</p>

<p align="center"><sub>A task agent's proposed changes · choosing an AI provider in onboarding · verifying a new device by emoji</sub></p>

## What you can do with it

- **Tasks** with checklists, estimates, priorities, due dates, labels, cover
  art and linked GitHub pull requests. A **task agent** keeps a living summary
  and proposes titles, estimates, checklist items, status changes, follow-up
  tasks and links — each one waiting for you.
- **Voice capture everywhere.** Record anywhere in the app and have it
  transcribed, on your device or by the provider you configured.
- **Time tracking** against the plan, with focus ratings and a time analysis
  by category.
- **A journal** of notes, photos, recordings, measurements and surveys, linked
  to the task, person, event or day they belong to.
- **Sections you switch on** under Settings → Sections: Projects, Goals,
  Habits, Dashboards, People and Events, each with its own agent where it
  makes sense — a project agent that reports health and next steps, a goal
  agent that tells you when a goal slips, an event agent that writes a recap,
  and a relationship agent that briefs you before you meet someone. Turning a
  section off only hides it; nothing is deleted.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/events/detail/desktop-dark.webp">
  <img alt="An event page: cover photo, rating, an AI recap of the evening, and the event agent proposing to add a person who was there and a note of what happened" src="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/events/detail/desktop-light.webp">
</picture>

The [manual](https://matthiasn.github.io/lotti/manual/development/) walks
through all of it, starting from
[the mental model](https://matthiasn.github.io/lotti/manual/development/getting-started/mental-model)
and [your first task](https://matthiasn.github.io/lotti/manual/development/getting-started/first-task/).

## Install

| Platform    | Where to get it                                                                                                                                                            |
|-------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **iOS / iPadOS** | [App Store](https://apps.apple.com/app/lotti-app/id6752654664)                                                                                                     |
| **macOS**   | [Mac App Store](https://apps.apple.com/app/lotti-app/id6752654664), or the signed and notarized DMG on [Releases](https://github.com/matthiasn/lotti/releases)             |
| **Android** | [Google Play](https://play.google.com/store/apps/details?id=com.matthiasn.lotti), or the APK on [Releases](https://github.com/matthiasn/lotti/releases)                    |
| **Linux**   | [Flathub](https://flathub.org/en/apps/com.matthiasn.lotti) (recommended, updates itself), or the AppImage or `tar.gz` on [Releases](https://github.com/matthiasn/lotti/releases) |
| **Windows** | [Build from source](docs/DEVELOPMENT.md) for now                                                                                                                             |


<p>
  <a href="https://apps.apple.com/app/lotti-app/id6752654664"><img height="48" alt="Download on the App Store" src="https://toolbox.marketingtools.apple.com/api/v2/badges/download-on-the-app-store/black/en-us"></a>
  <a href="https://apps.apple.com/app/lotti-app/id6752654664"><img height="48" alt="Download on the Mac App Store" src="https://toolbox.marketingtools.apple.com/api/v2/badges/download-on-the-mac-app-store/black/en-us"></a>
  <a href="https://play.google.com/store/apps/details?id=com.matthiasn.lotti"><img height="70" alt="Get it on Google Play" src="https://play.google.com/intl/en_us/badges/static/images/badges/en_badge_web_generic.png"></a>
  <a href="https://flathub.org/en/apps/com.matthiasn.lotti"><img height="48" alt="Get it on Flathub" src="https://flathub.org/api/badge?locale=en"></a>
</p>

The **AppImage** needs no installation: mark it executable (`chmod +x`) and
run it. It works on distributions with glibc 2.35 or newer (Ubuntu 22.04,
Debian 12, Fedora 36 and later); where FUSE is missing, start it with
`--appimage-extract-and-run`. Unlike the Flathub build it does not update
itself.

On first launch, a short onboarding asks for one API key — Mistral is
preselected, others are one tap away — and records your first task. You can
close it and use Lotti without AI.

## Privacy and sync, in brief

**What leaves your device:** ciphertext to the sync homeserver you chose, which
stores and relays it without ever being able to read it; requests to the AI
provider you configured for a category; and calls to `api.github.com`, only if
you link pull requests to tasks. None of your record goes to Lotti.

**How sync works:** each change is an event in a private, non-federated,
Megolm-encrypted Matrix room ([Vodozemac](https://github.com/matrix-org/vodozemac)
for Olm/Megolm); attachments are encrypted per file. Keys are shared only with
devices you verified by emoji, and events from anything else — or sent in
plaintext — are dropped. Every entry carries a vector clock, so a device that
was offline for a week rejoins without losing writes. Genuinely concurrent
edits to an entry show up as conflicts for you to resolve; for definitions such
as categories and labels, the later edit wins. You set up the first device
against a homeserver with the included
[`tools/matrix_provisioner`](tools/matrix_provisioner); every further device
pairs from one you already use by QR code and emoji check.

**What it does not protect against — read this before you trust it with
anything sensitive:**

- **Metadata.** The homeserver operator cannot read or alter your record, but
  can see the account, which device synced when, from which IP, and how much.
- **A compromised device.** The local databases are not encrypted by Lotti
  today; rely on your operating system's full-disk encryption. Passwords, API
  keys and the GitHub token are kept in the OS keystore; an AI provider key or
  GitHub token syncing to your other devices is also written to the local
  sync outbox, where it stays for about a week after it is sent.
- **Losing every device.** There is no server-side backup and no account
  recovery. A second paired device is your replica — after you send it your
  history from the first — and an ordinary backup of the database plus the
  attachments folder is still worth keeping.
- **Your AI provider.** Whatever you route to a provider is subject to its
  terms. Prefer one with zero data retention; Lotti cannot verify anyone's
  retention claims.

The full threat model is in
[security and privacy](knowledge/architecture/security-and-privacy.md), the
sync runtime in [the sync concept](knowledge/features/sync/overview.md), and
the policies in [PRIVACY.md](PRIVACY.md) and [SECURITY.md](SECURITY.md).

## AI, on your terms

- **Providers:** Mistral (recommended in onboarding: one key covers thinking,
  transcription and the read-aloud voice), Melious, OpenAI, Anthropic, Google
  Gemini, Alibaba, Nebius, OpenRouter, ElevenLabs for voices, and any
  OpenAI-compatible endpoint, including your own gateway.
- **Local:** speech recognition runs inside the app on every platform with
  sherpa-onnx (Whisper and other model families), and on desktop also through
  local Whisper or Voxtral servers. Ollama and oMLX have their own provider
  types; vLLM, llama.cpp's `llama-server`, LM Studio and similar servers
  connect as OpenAI-compatible endpoints.
- **Routing per category:** work can go to one provider, your journal to
  another, or to none. The provider page shows the actual base URL behind a
  friendly name, and every profile that depends on it.
- **Usage & Impact** shows tokens and requests for every cloud call, and cost,
  energy and CO₂e where the provider reports them (today: Melious). Nothing is
  estimated.
- **Which models are good enough** for the agents is measured, not guessed:
  [LottiGym](knowledge/features/ai/model-evaluation.md) runs candidates
  through the real agent harnesses ([results](docs/evaluations/)). Today the
  agents need a cloud-class model; local models are not yet fast enough for
  daily agent use.

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/ai/usage/desktop-dark.webp">
  <img alt="Usage &amp; Impact: cost, energy, CO2e, tokens and requests for the month, with cost per day broken down by category" src="https://pub-3df7bcf4b8ca493fa6acea182d69d9c7.r2.dev/manual/screenshots/development/ai/usage/desktop-light.webp">
</picture>

Setup is in the manual:
[connect an AI provider](https://matthiasn.github.io/lotti/manual/development/ai-and-automation/provider-setup/).

## In development

Built, documented, and changing quickly. Each is off by default.

- **Daily OS** — turns a spoken or typed check-in into a plan for the day,
  every proposed change shown with its reason, nothing committed until you
  confirm. Switch it on under Settings → Sections.
  [Manual](https://matthiasn.github.io/lotti/manual/development/plan-and-capture/daily-os)
- **The companion** — Lotti as a character you talk to: ask about your tasks,
  time and journal by voice or text, and hear the answer read aloud. Behind a
  flag in Settings → Advanced Settings → Config Flags.
- **Record provenance** — every entry signed by its author, so the record can
  prove who wrote what. The building blocks are in the codebase; entries are
  not signed yet.

See the [roadmap](https://matthiasn.github.io/lotti/manual/development/roadmap).

## Build from source

Install Flutter through [FVM](https://fvm.app/) (the repository pins the
version in `.fvmrc`), then:

```sh
fvm flutter pub get
fvm flutter run -d macos   # or linux, windows, or a connected device
```

Platform prerequisites (including Linux audio-codec and emoji-font packages)
are in [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md).

## Under the hood

Flutter and Dart on five platforms; local SQLite via Drift; Matrix with
Vodozemac for sync. The sync protocol and the agent runtime are specified as
[TLA+ models](specs/tla/README.md) and model-checked nightly under crashes,
injected failures and reordered messages — statements about the design, with
the specs saying exactly what is and isn't covered.

- [Knowledge bundle](knowledge/index.md) — how the app works at runtime,
  subsystem by subsystem, for contributors and coding agents alike
- [Security and privacy](knowledge/architecture/security-and-privacy.md) ·
  [Background](docs/BACKGROUND.md) — the threat model, and why Lotti exists
- [Changelog](CHANGELOG.md)

## Pricing

Linux is free, with full functionality, and will stay that way. On other
platforms the basics — task and journal capture, the task agent, voice
transcription — stay free too; some advanced agent features may eventually
become in-app purchases where that is the norm. Hosted sync is a real running
cost: self-host a Matrix homeserver, or bring one you already have.

## Contributing

Say hi on [Discord](https://discord.gg/uuSaa8NpY). **Bug reports** in
[GitHub Issues](https://github.com/matthiasn/lotti/issues) and
**translations** are very welcome. **Code pull requests are not accepted** —
review capacity is the limit, and Lotti holds people's personal data — so
please open an issue instead. [CONTRIBUTING.md](CONTRIBUTING.md) has the
details.

## License

GPL-3.0. See [LICENSE](LICENSE).

## Acknowledgments

Thanks to the [Flutter](https://flutter.dev) team, the
[Qwen](https://github.com/QwenLM) and [Mistral](https://mistral.ai) teams for
their open-weights models, [OpenAI](https://openai.com) for the
[Whisper](https://github.com/openai/whisper) weights, the
[Ollama](https://ollama.com) project, the [Matrix.org](https://matrix.org)
community, the [Vodozemac](https://github.com/matrix-org/vodozemac) authors, and
everyone contributing translations, issues, and ideas.

---

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

---
id: index
title: Lotti Manual
slug: /
sidebar_label: Welcome
description: Learn how to plan, capture, organize, and reflect with Lotti.
---

<div className="manual-hero manual-hero--welcome">
  <div className="manual-eyebrow">A private logbook, not a productivity panopticon</div>
  <h1>Keep the facts. Make the day yours.</h1>
  <div className="manual-hero-copy">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.</div>
  <div className="manual-hero-principles">
    <div><strong>Your history stays yours.</strong><span>It lives in your local logbook, not in a Lotti cloud account.</span></div>
    <div><strong>AI asks; you decide.</strong><span>Agents can notice, think, and propose. They do not get the keys to your life.</span></div>
    <div><strong>Make it memorable.</strong><span>Useful, serious, delightfully weird: the workspace gets to sound like you.</span></div>
  </div>
</div>

<ManualScreenshot
  caseId="tasks/detail"
  alt="Lotti task page for inspecting the orbital penguin habitat, with its category, status, priority, due date, logged time, labels, and AI summary"
  caption="A task is a living record: the outcome, its context, its next moves, and the evidence of the work all travel together."
/>

## 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

<div className="manual-cards">
  <a className="manual-card" href="getting-started/companion/">
    <strong>Just ask</strong>
    Ask the companion what is due or where your time went, or tell her what happened. She files it only when you tap.
  </a>
  <a className="manual-card" href="getting-started/mental-model/">
    <strong>Your life is not a backlog</strong>
    See how intent, plans, actual time, evidence, and reflection stay distinct—and useful.
  </a>
  <a className="manual-card" href="plan-and-capture/daily-os/">
    <strong>Build a day that can breathe</strong>
    Turn a spoken or typed check-in into an editable, reality-aware day plan.
  </a>
  <a className="manual-card" href="organize-and-reflect/tasks/">
    <strong>Give work a home</strong>
    Create tasks, attach context, set priorities, and turn ambiguity into next moves.
  </a>
  <a className="manual-card" href="ai-and-automation/provider-setup/">
    <strong>Choose a brain responsibly</strong>
    Pick local or cloud inference deliberately—privacy, retention, region, and energy are all part of the choice.
  </a>
</div>

## 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.

<div className="manual-responsibility-grid">
  <div className="manual-responsibility-card">
    <strong>Privacy is a routing decision.</strong>
    <p>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.”</p>
  </div>
  <div className="manual-responsibility-card">
    <strong>Energy is a routing decision too.</strong>
    <p>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.</p>
  </div>
  <div className="manual-responsibility-card">
    <strong>Human approval is a product rule.</strong>
    <p>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.”</p>
  </div>
</div>

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](./0042-typed-task-relationship-links.md) | 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](./0043-dependency-aware-planning.md) | 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](./0106-the-task-link-graph-across-devices.md) | 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](./0037-relationship-on-device-storage-and-privacy.md) | Accepted | Local-only storage, opt-in E2E sync, zero external retention, explicit cloud-AI consent, deletion cascade, GDPR framing. |
| [0038: Relationship Domain Model](./0038-relationship-domain-model.md) | Accepted | `relationship`/`checkIn` journal subtypes, embedded person identity, status union, `RelationshipLink` task/timeline linking, no schema change. |
| [0039: Relationship Check-In Reminders](./0039-relationship-check-in-reminders.md) | 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](./0040-relationship-executive-briefing.md) | 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](./0041-relationship-contact-linking.md) | 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](./0059-relationship-agent-runtime-and-nudge-generalization.md) | 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](./0033-learning-verification-checkpoint-policy.md) | 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](./0034-hybrid-understanding-evaluation.md) | Proposed | Frozen evidence snapshots, tailored quiz generation, deterministic validation, conversational LLM grading with bounded probes, injection resistance. |
| [0035: Learning Verification Session Persistence](./0035-learning-verification-session-persistence.md) | 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](./0036-learning-understanding-rating.md) | 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](./0053-goal-driven-agents-per-goal-producers.md) | 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](./0054-deterministic-first-two-tier-wakes.md) | 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](./0055-banner-nudge-attention-channel.md) | 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](./0056-need-to-know-visual-brief-boundary.md) | 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](./0057-decade-scale-agent-memory.md) | 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](./0058-procedural-text-banners-no-generative-imagery.md) | 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](../lotti-gym-2026-09-16.md).
**Four models and what a run costs, 2026-09-17:** [LottiGym, four models](../lotti-gym-2026-09-17.md).
**Qwen 3.8 27B rejected, 2026-09-21:** [LottiGym, Qwen 3.8 27B and two harness regressions](../lotti-gym-2026-09-21.md).

> **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](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 | 34, P1–P22 | 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 so is one about the agent's own notes from a month whose digest the
   wake has no room for (`journal_recall_older_notes`, P21, ADR 0169);
   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–P22) 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 — `<tool_call>update_goal_report
<arg_key>…` — 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.

## Recall by period, and of the agent's own month digests — 2026-11-29

Three changes to what a recall can reach, checked on `glm-5.3`, tier 1,
temperature 0:

- `search_goal_memory` takes a `from` / `to` period (#5185).
- It reads the stored month digests of the agent's own observations
  (ADR 0169, #5188).
- FACTS names the digest months the wake has no room for,
  `observationDigestsNotShown`, and how far back the check-ins go,
  `userVoice.history` (#5189, #5185). `buildJournalFacts` now passes the
  history line as the workflow does, counting the older entries a scenario's
  recall holds (`earlierCheckIns`) as production counts every live check-in.

| Scenario | Samples | Passed | What the model did |
| --- | ---: | ---: | --- |
| `journal_recall_older_entry` | 3 + 3 | 6 | one search each, `from 2026-03-01 to 2026-03-31` — three samples before the history line, three with it spanning the March entry |
| `journal_recall_older_notes` (new) | 3 | 3 | searched `2025-12-01`–`2026-02-28` and answered from the February digest; one sample tried the keyword `evening` first |
| The other six journal scenarios, history line in FACTS | 1 each | 6 | — |

The March scenario is the one the 2026-10-30 run showed searching `March ice
shelf`, missing, and retrying without the month: with a period to put the
date in, it no longer writes the month into the keywords.

`journal_recall_older_notes` asks what the agent itself "noticed last
winter" without naming a month or the answer. The wake shows two month
digests and lists six months as not shown, December 2025 to May 2026; all
three samples searched the winter months of that span. That is the
behaviour the index line exists for, at n = 3 on one model.

Not measured: other models, and a goal old enough that the months not shown
span more than one recall's budget.

## The month digest checked against the person's words — 2026-11-29

ADR 0170, as ADR 0171 amended it after this run: the digest of a month of
the agent's notes is written against that month's check-ins. Five cases through the production
`ObservationDigestService` (then `GoalObservationDigestService`), substance weight, three samples each, on
`glm-5.3` and `deepseek-v4.1-flash-1017` (Melious) and `mistral-large-4-0`
(Mistral):

```sh
GOAL_DIGEST_EVAL_API_KEY=... scripts/goal_digest_eval.sh glm-5.3
GOAL_DIGEST_EVAL_API_KEY=... scripts/goal_digest_eval.sh mistral-large-4-0 mistral
```

The harness is
`test/features/agents/memory/observation_digest_eval_live_test.dart`.
It gives each digest three wakes, as production would, counts the calls that
returned nothing, and scores keyword checks; the digests are in the JSON it
writes and were read for every figure below.

| Case | What it asks | glm-5.3 | DeepSeek Flash v4.1 | Mistral Large 4 |
| --- | --- | ---: | ---: | ---: |
| `clean_month`, notes alone | two wrong claims corrected | 0 of 6 | 0 of 6 | 0 of 6 |
| `clean_month`, checked | two wrong claims corrected; two sound notes kept; nothing added | 3 of 3 | 3 of 3 | 3 of 3 |
| `pruned_rewrite` | an old digest whose notes are pruned: one sentence corrected, five kept, nothing added | 3 of 3 | 3 of 3 | 3 of 3 |
| `repeated_rewrites` | four early facts survive ten rewrites of the running month | 3 of 3 | 3 of 3 | 3 of 3 |
| `no_false_correction` | a habit that changed stays a change; an opinion they quoted and rejected stays not theirs | 3 of 3 | 3 of 3 | 3 of 3 |
| `talkative_month` | a contradiction in the last of thirty long check-ins is caught | 3 of 3 | 3 of 3 | 3 of 3 |
| `talkative_month` | …and stated as the plain fact | 0 of 3 | 3 of 3 | 3 of 3 |
| Calls that returned nothing | | 0 of 48 | 0 of 48 | 0 of 48 |

Written from the notes alone, every model repeated both wrong claims in every
sample. Written against the month's words, every model corrected both.

What the run changed before it passed:

- **The completion cap.** At the 400 tokens the digest calls shared, Mistral
  Large 4 returned no text — it reasons before it answers, and the reasoning
  is counted against the cap (a direct probe: 650 to 1,400 reasoning tokens
  for this prompt, about 200 for a two-sentence summary). It still returned
  nothing at 1,200. DeepSeek failed now and then at 400. The cap is 4,000;
  the stored text has its own bound of 400 tokens. A failed call shows as the
  "not yet digested" placeholder, so on Large 4 nothing would have been
  digested.
- **An old digest picked up a stray remark.** Rewritten from its own text and
  the month's words with no notes left, `glm-5.3` and DeepSeek both appended
  "nothing new, just tired" in three of three. That case now says to write
  the earlier digest again, changing only what the words contradict: three of
  three on every model, the other five sentences word for word.
- **A running month's digest grew.** Folding the earlier text into every
  rewrite, `glm-5.3` reached 178 words against a limit of 120 after ten
  rewrites, a line per note. The earlier text is now folded in only for notes
  that are gone; with every note listed the digest is written from the
  notes. Ten rewrites and one fresh write are then the same call: 97 to 119
  words across the three models.
- **Evidence was read oldest first.** In a talkative month the newest
  check-ins were the ones left out. The budget is shared evenly now, which
  is what `talkative_month` holds.

Known and left: on `talkative_month`, `glm-5.3` gets the correction right but
writes it as "I noted they write most easily in the mornings, but on 07-30
they said mornings never work" in three of three, where the prompt asks for
the plain fact. The other two models state it plainly.

Seen and not explained: on an earlier prompt, Mistral Large 4 returned no
text once each at caps of 4,000 and 8,000 through the app, while the same
kind of prompt sent to its API directly answered six of six at 4,000. It did
not recur in the 48 calls of the final run.

Not measured: more than three samples, a month whose notes outnumber the
word limit, and the same completion cap on the check-in summary (500) and
check-in digest (400) calls, which reason less but share the pattern.

## 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.

## Related

- 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](../lotti-gym-2026-09-16.md).
**Four models and what a run costs, 2026-09-17:** [LottiGym, four models](../lotti-gym-2026-09-17.md).
**Qwen 3.8 27B rejected, 2026-09-21:** [LottiGym, Qwen 3.8 27B and two harness regressions](../lotti-gym-2026-09-21.md).

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

Eight 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.

8. **Recall** (`rc_*`) — FACTS list ten check-ins and count the older ones;
   a question only an unlisted check-in answers is answered after
   `search_relationship_memory`, and the old promise it finds becomes a task
   proposal sourced from the recalled check-in (ADR 0175). The harness
   answers the search from the scenario's own older entries, matched and
   rendered by production's code, and gives the one continuation turn
   production gives.

Every expectation derives from the policy matrix
`relationshipAgentPolicyMatrix` (R1–R22) 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.

## Recall and the changed prompt — 2026-11-29

ADR 0175 added `search_relationship_memory`, one clause to the system prompt
and the R22 scenario. Run through the live test directly (not the ledgered
LottiGym runner, so no run ids or prices), on the unsuffixed model ids:

| Model | `rc_recall_older_checkin`, three samples | All 29 scenarios, one sample |
| --- | ---: | ---: |
| `glm-5.3-flash` | 3 of 3 | 29 of 29 |
| `deepseek-v4.1-flash-1017` | 3 of 3 | 29 of 29 |
| `mistral-large-4-0` (Mistral's own API) | 3 of 3 | 29 of 29 |

Every recall sample searched the winter by period — Mistral also by the
word "promise", using two or all three of its searches — answered with the
promise, and proposed the task with the recalled check-in as its source.
One sample per scenario cannot show a rare regression; it shows the prompt
change did not break a rule outright.

## The month digest of the agent's notes — 2026-11-30

The relationship agent's notes are digested by month through the shared
service, under their own prompt. Its live case, `relationship_month`, runs in
the digest harness (`scripts/goal_digest_eval.sh <model>` with
`GOAL_DIGEST_EVAL_CASES=relationship_month`); the case and its results on
three models are in
[ADR 0176](../../adr/0176-relationship-agents-digest-their-notes-before-they-are-pruned.md).

## 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](../lotti-gym-2026-09-16.md).
**Four models and what a run costs, 2026-09-17:** [LottiGym, four models](../lotti-gym-2026-09-17.md).
**Qwen 3.8 27B rejected, 2026-09-21:** [LottiGym, Qwen 3.8 27B and two harness regressions](../lotti-gym-2026-09-21.md).

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`](https://github.com/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/<UTC timestamp>_<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](../lotti-gym-2026-09-17.md).

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 <name>", 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.

### Recommended changes

- 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.

---

### 3.6 Melious.ai is recommended without the disclosure the manual itself demands

`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](#overview)
- [Core Principles](#core-principles)
- [High-Level Architecture](#high-level-architecture)
- [Feature Modules](#feature-modules)
- [Data Flow](#data-flow)
- [AI Provider Architecture](#ai-provider-architecture)
- [Security Architecture](#security-architecture)
- [Testing Strategy](#testing-strategy)
- [Build & Deployment](#build--deployment)
- [Performance Considerations](#performance-considerations)
- [Future Architecture Plans](#future-architecture-plans)
- [Development Guidelines](#development-guidelines)
- [Related Documentation](#related-documentation)

## 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](../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

```
┌─────────────────────────────────────────────────────────────┐
│                        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](../lib/features/ai/README.md)**: Core AI provider abstraction and configuration
- **[Agents](../lib/features/agents/README.md)**: Scoped assistants, improvement flows, and shared text/voice conversation UI

### Content Management
- **[Tasks](../lib/features/tasks/README.md)**: Task lifecycle management with AI-enhanced summaries
- **[Journal](../lib/features/journal/README.md)**: Text and audio journal entries with transcription
- **[Categories](../lib/features/categories/README.md)**: Organize content with configurable AI providers per category

### Audio & Speech
- **[Speech](../lib/features/speech/README.md)**: 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
```
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
```
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
```
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](../knowledge/architecture/security-and-privacy.md#secrets)).

### 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
```
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](../CONTRIBUTING.md) for guidelines on:
- Code style and standards
- Testing requirements
- Pull request process
- Community guidelines

For development environment setup, see [DEVELOPMENT.md](DEVELOPMENT.md).

## Related Documentation

- [Development Setup](DEVELOPMENT.md)
- [Contributing](../CONTRIBUTING.md)
- [Privacy Policy](../PRIVACY.md)
- [User Manual](MANUAL.md)
- [Background & History](BACKGROUND.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](https://github.com/matthiasn/lotti) and [Substack](https://matthiasnehlsen.substack.com).*

---

### 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
```
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](https://github.com/matthiasn/meins)**

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

**[Meins](https://github.com/matthiasn/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](https://github.com/matthiasn/lotti/tree/main/lotti/README.md)** 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](https://github.com/matthiasn/lotti), 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: [lotti@matthiasn.com](mailto:lotti@matthiasn.com)

---

### 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](../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)

```
/* 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](../knowledge/conventions/screenshots.md#the-app-preview-is-the-same-world-walked-by-touch).
The lines are in
[`tools/tutorial_videos/config/scenarios/app_store_preview.yaml`](../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](#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](https://arxiv.org/abs/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`](../lib/features/agents/README.md) and [`features/daily_os_next/README.md`](../lib/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](https://www.anthropic.com/engineering/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](https://www.semanticscholar.org/paper/A-Blackboard-Architecture-for-Control-Hayes-Roth/c79a41dc13c796c26388f8cbf599c67126374e39)).

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](https://en.wikipedia.org/wiki/Contract_Net_Protocol)).
- **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](https://www.cambridge.org/core/services/aop-cambridge-core/content/view/1AFB25EC9CC4799BC455409B2EB37C43/9780511811654c11_p315-366_CBO.pdf/protocols-for-multiagent-resource-allocation-auctions.pdf) — 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](https://arxiv.org/html/2605.02765v1)). 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](https://link.springer.com/article/10.1007/s10458-012-9206-9)). 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](https://ar5iv.labs.arxiv.org/html/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](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents): "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](https://docs.vllm.ai/en/v0.7.3/design/automatic_prefix_caching.html)), 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](https://arxiv.org/html/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](https://github.com/ggml-org/llama.cpp/discussions/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](https://snormore.dev/blog/logical-clocks-in-distributed-systems/), [crdt.tech](https://crdt.tech/glossary)). 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](https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html)). 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](https://arxiv.org/abs/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](https://arxiv.org/html/2411.15287v1)). 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](https://pmc.ncbi.nlm.nih.gov/articles/PMC5364076/)). 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](https://mhealth.jmir.org/2023/1/e38342)) — 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](https://www.franklincovey.com/courses/the-4-disciplines/discipline-2-act/)): 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](https://eprints.whiterose.ac.uk/id/eprint/91437/)).

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](#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](https://en.wikipedia.org/wiki/Contract_Net_Protocol)).
- 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](https://www.semanticscholar.org/paper/A-Blackboard-Architecture-for-Control-Hayes-Roth/c79a41dc13c796c26388f8cbf599c67126374e39)).
- 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](https://link.springer.com/article/10.1007/s10458-012-9206-9)). 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](https://arxiv.org/html/2605.02765v1)).

**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](https://ar5iv.labs.arxiv.org/html/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](https://www.anthropic.com/engineering/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](https://www.anthropic.com/engineering/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](https://ar5iv.labs.arxiv.org/html/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](https://arxiv.org/abs/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](https://docs.vllm.ai/en/v0.7.3/design/automatic_prefix_caching.html)). 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](https://arxiv.org/html/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](https://arxiv.org/abs/2311.04934)); **CacheBlend** recomputes the top 10–20% high-deviation tokens per layer to restore quality ([arXiv:2405.16444](https://arxiv.org/html/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](https://github.com/ggml-org/llama.cpp/discussions/13606)). The most flexible production scheme (SGLang RadixAttention) is still prefix-structured ([LMSYS](https://lmsys.org/blog/2024-01-17-sglang/)).
- 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](https://anarlog.so/blog/mistral-data-retention-policy/)). **OVHcloud AI Endpoints** is a sovereign, OpenAI-compatible API exposing 40+ open-weight models, keeping only billing data and never training on prompts ([OVHcloud](https://www.ovhcloud.com/en/public-cloud/ai-endpoints/)).
- 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](https://www.scaleway.com/en/news/scaleway-launches-generative-apis-a-drop-in-alternative-to-openai-apis-100percent-made-in-europe/)).
- 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](https://www.scaleway.com/en/docs/generative-apis/reference-content/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](https://help.mistral.ai/en/articles/347628-how-long-do-you-store-my-data) and [Zero Data Retention option](https://help.mistral.ai/en/articles/347612-can-i-activate-zero-data-retention-zdr); Scaleway's [default ZDR and no-train](https://www.scaleway.com/en/docs/generative-apis/reference-content/data-privacy/); IONOS's [German-only processing, no-train per DPA](https://docs.ionos.com/cloud/ai/ai-model-hub/governance-and-compliance/eu-ai-act). 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](https://arxiv.org/abs/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](https://arxiv.org/html/2411.15287v1)).
- 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](https://pmc.ncbi.nlm.nih.gov/articles/PMC5364076/)).
- 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](https://mhealth.jmir.org/2023/1/e38342)).

**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](https://www.franklincovey.com/courses/the-4-disciplines/discipline-2-act/)).
- 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](https://eprints.whiterose.ac.uk/id/eprint/91437/)).
- 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.](https://pmc.ncbi.nlm.nih.gov/articles/PMC5364076/)).

**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](https://www.lip6.fr/Marc.Shapiro/papers/2011/CRDTs_SSS-2011.pdf)).
- 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](https://snormore.dev/blog/logical-clocks-in-distributed-systems/)). 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](https://crdt.tech/glossary)).
- 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](https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html)). 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](https://www.inkandswitch.com/essay/local-first/)).

**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.)

- **A:** [Contract Net Protocol](https://en.wikipedia.org/wiki/Contract_Net_Protocol) · [Hayes-Roth 1985, A Blackboard Architecture for Control](https://www.semanticscholar.org/paper/A-Blackboard-Architecture-for-Control-Hayes-Roth/c79a41dc13c796c26388f8cbf599c67126374e39) · [Sarne & Grosz 2013, JAAMAS](https://link.springer.com/article/10.1007/s10458-012-9206-9) · [Shoham & Leyton-Brown, MAS ch. 11](https://www.cambridge.org/core/services/aop-cambridge-core/content/view/1AFB25EC9CC4799BC455409B2EB37C43/9780511811654c11_p315-366_CBO.pdf/protocols-for-multiagent-resource-allocation-auctions.pdf) · [U-Define, arXiv:2605.02765](https://arxiv.org/html/2605.02765v1)
- **B:** [MemGPT, arXiv:2310.08560](https://ar5iv.labs.arxiv.org/html/2310.08560) · [Generative Agents, arXiv:2304.03442](https://ar5iv.labs.arxiv.org/html/2304.03442) · [Anthropic — Effective context engineering](https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents) · [Anthropic — Effective harnesses for long-running agents](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents) · [ESAA, arXiv:2602.23193](https://arxiv.org/abs/2602.23193)
- **C:** [vLLM Automatic Prefix Caching](https://docs.vllm.ai/en/v0.7.3/design/automatic_prefix_caching.html) · [Prompt Cache, arXiv:2311.04934](https://arxiv.org/abs/2311.04934) · [CacheBlend, arXiv:2405.16444](https://arxiv.org/html/2405.16444) · [Block-Attention, arXiv:2409.15355](https://arxiv.org/html/2409.15355) · [llama.cpp KV reuse #13606](https://github.com/ggml-org/llama.cpp/discussions/13606) · [SGLang / RadixAttention](https://lmsys.org/blog/2024-01-17-sglang/)
- **D:** [Mistral retention](https://anarlog.so/blog/mistral-data-retention-policy/) · [OVHcloud AI Endpoints](https://www.ovhcloud.com/en/public-cloud/ai-endpoints/) · [Scaleway Generative APIs](https://www.scaleway.com/en/news/scaleway-launches-generative-apis-a-drop-in-alternative-to-openai-apis-100percent-made-in-europe/) · [Scaleway supported models](https://www.scaleway.com/en/docs/generative-apis/reference-content/supported-models/)
- **E:** [Sharma et al., Sycophancy, arXiv:2310.13548](https://arxiv.org/abs/2310.13548) · [Sycophancy causes & mitigations, arXiv:2411.15287](https://arxiv.org/html/2411.15287v1) · [Nahum-Shani et al., JITAI 2018](https://pmc.ncbi.nlm.nih.gov/articles/PMC5364076/) · [Bell et al., JMIR mHealth 2023](https://mhealth.jmir.org/2023/1/e38342)
- **F:** [FranklinCovey 4DX — Lead Measures](https://www.franklincovey.com/courses/the-4-disciplines/discipline-2-act/) · [Harkin et al. 2016, monitoring meta-analysis](https://eprints.whiterose.ac.uk/id/eprint/91437/)
- **G:** [Shapiro et al., CRDTs, SSS 2011](https://www.lip6.fr/Marc.Shapiro/papers/2011/CRDTs_SSS-2011.pdf) · [Logical clocks](https://snormore.dev/blog/logical-clocks-in-distributed-systems/) · [crdt.tech glossary](https://crdt.tech/glossary) · [Kleppmann — distributed locking](https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html) · [Local-first software](https://www.inkandswitch.com/essay/local-first/) · [Hybrid Logical Clocks](https://jaredforsyth.com/posts/hybrid-logical-clocks/)
- **Anchor:** Nakajima, *The Log is the Agent*, [arXiv:2605.21997](https://arxiv.org/abs/2605.21997)

---

*Grounding files referenced: [`lib/classes/vector_clock.dart`](../lib/classes/vector_clock.dart), [`lib/classes/agents/agent_link.dart`](../lib/classes/agents/agent_link.dart), [`lib/features/agents/README.md`](../lib/features/agents/README.md), [`lib/features/daily_os_next/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
description: Planned Lotti capabilities that are designed but not yet available in the app.
---

# 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.

## Related

- `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.

## Related

- [ADR 0027: Wake Notification Propagation and Storm Prevention](./0027-wake-notification-propagation-and-storm-prevention.md)
  — 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.

## Related

- [ADR 0027: Wake Notification Propagation and Storm Prevention](./0027-wake-notification-propagation-and-storm-prevention.md)
  — 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.

## Related

- `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.

## Related

- `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

```
/* 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.

## Related

- 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](./0005-template-model-resolution-policy.md) (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:

```
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.

## Related

- [Implementation plan](../implementation_plans/2026-02-28_agent_privacy_profiles.md)
- [ADR 0005: Template Model Resolution Policy](./0005-template-model-resolution-policy.md) (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.

## Related

- 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:

```
## 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/<uuid>.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.

## Related

- `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.

## Related

- `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.

## Related

- `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 `PlannedBlock`s on the `DayPlan`. A project phase
   can emit standing recurring `attention_request`s (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.

## Related

- `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.

## Related

- 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.

## Related

- 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.

## Related

- [ADR 0006: Change Set — Deferred Tool Confirmation Workflow](./0006-change-set-deferred-tool-confirmation.md)
- [ADR 0010: Scheduled Wake Infrastructure](./0010-scheduled-wake-infrastructure.md)
- [ADR 0014: Cross-Wake Critical Observation Injection](./0014-cross-wake-critical-observation-injection.md)
- [ADR 0016: Agent State as Log Projection](./0016-agent-state-as-log-projection.md)
- [ADR 0017: Deterministic Log Compaction](./0017-deterministic-log-compaction.md)
- [ADR 0018: Convergent Multi-Device Execution](./0018-convergent-multi-device-execution.md)
- [ADR 0019: Attention Negotiation Protocol](./0019-attention-negotiation-protocol.md)
- [ADR 0020: Agent Input Capture](./0020-agent-input-capture.md)
- [ADR 0021: LLM-Mediated Attention Claim Weighing](./0021-llm-mediated-attention-claim-weighing.md)
- [ADR 0023: Durable Domain Agents and Time Negotiation](./0023-durable-domain-agents-and-time-negotiation.md)
  — the peer fitness/sleep agents that negotiate with this planner for time.
- [Long-Lived Daily OS Planner implementation plan](../implementation_plans/2026-06-07_long_lived_daily_os_planner.md)
- Supersedes the identity-granularity decision in
  [Day Agent Layer - Implementation Plan](../implementation_plans/2026-05-25_day_agent_layer.md)

---

### 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 `PlannedBlock`s, 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` + `canPreempt`
   let a durable commitment ("gym 3×/week") outrank a soft work block. A domain
   agent cannot silently colonize the user's evenings: every block it wins is
   either user-approved or governed by an agreement the user previously set.

6. **Domain agents are self-scheduled producers.** A domain agent wakes on its
   own cadence (e.g. nightly) to evaluate its domain model against actuals and
   emit, refresh, or withdraw claims. This is what makes it a coach with goals
   rather than a passive helper. It reuses the existing scheduled-wake
   infrastructure (ADR 0010); the new work is wiring a non-task, non-day producer
   into it.

7. **Negotiation is horizon-scoped, not day-scoped.** Because cadence claims span
   ranges ("3 workouts this week", "90 minutes before Sunday"), the planner
   gains a `planning_window:<range>` wake alongside ADR 0022's
   `planning_day:<dayId>`, so a weekly-cadence claim is weighable while drafting
   a single day. This is additive to ADR 0022's wake contract, not a
   contradiction of it.

8. **Claims carry inspectable justification.** A domain agent cites
   `evidenceRefs` of kind `health` / `outcome` (e.g. workout actuals, sleep
   actuals) plus a `rationale`. The planner reads evidence summaries in its
   brief and weighs them; it does not import the domain agent's raw memory.

## Target Runtime Shape

```mermaid
flowchart TD
  Fitness["Fitness agent<br/>kind=domain_agent scope=fitness<br/>durable identity + memory"]
  Sleep["Sleep agent<br/>kind=domain_agent scope=sleep"]
  Task["Task agents (existing)"]

  Agreement["StandingAgreementEntity<br/>fitness 3x/week, sleep wind-down"]
  Claim["AttentionRequestEntity<br/>requestedMinutes, window, cadence, evidence"]
  Index["Attention planning inputs<br/>window-overlap projection"]

  Planner["Long-lived Daily OS planner (ADR 0022)<br/>sole arbitrator"]
  Award["AttentionAwardEntity<br/>concrete block + provenance"]
  CS["ChangeSet add_block"]
  Gate["StandingAgreementApprovalMode<br/>autoAccept / ask / reject -> user gate (ADR 0006)"]
  Plan["DayPlanEntity.plannedBlocks"]

  Fitness --> Agreement
  Fitness --> Claim
  Sleep --> Claim
  Task --> Claim
  Agreement --> Index
  Claim --> Index
  Index --> Planner
  Planner --> Award
  Award --> CS --> Gate --> Plan
  Award -. provenance .-> Claim
```

## Consequences

- The product gains genuine specialist coaches that compete for time on the
  user's behalf, with the planner as a single, learning, accountable arbitrator.
- No new negotiation protocol is invented: the existing attention-claim /
  standing-agreement model is reused, and "attention" is understood as
  scheduled calendar time, not push-notification interruption.
- The decoupling discipline holds: domain agents depend only on the claim /
  agreement log and never on planner internals, and the planner reads
  materialized claim projections rather than fanning out to wake producers
  synchronously during drafting.
- ADR 0022 does **not** need reopening. Domain agents live in a separate feature
  and negotiate through an already-decoupled projection read; the durable planner
  ADR 0022 creates is in fact a *prerequisite* for good arbitration (weighing
  fitness vs. work needs cross-day memory of "this project keeps displacing
  workouts").
- A cadence/recurrence verifier (ADR 0019 Decision 4's "gym 3×/week may pre-empt"
  enforcement against health actuals) is still required to turn a one-off claim
  into a durable habit guarantee; it remains the largest unbuilt enforcement
  piece.

## Non-Goals

- Letting domain agents mutate the calendar directly. They claim; the planner
  arbitrates; the ChangeSet gate applies.
- Making the planner just one peer among equals. The planner is a *privileged*
  peer — the sole arbitrator of shared day-plan state.
- Shipping every domain at once. Fitness and sleep first; nutrition, finances,
  and maintenance reuse the same machinery via `StandingAgreementScope`.
- Reintroducing disposable analyst runs (ADR 0022 Decision 13). A domain agent
  is the durable answer to most questions an analyst run would have investigated.

## Open Questions

1. Identity granularity: one durable `domain_agent` per `StandingAgreementScope`,
   or per scope + category (e.g. running vs. strength vs. recovery)?
2. How autonomous should the planner be allowed to be? The mechanism exists
   (`StandingAgreementApprovalMode`); the *policy defaults* per scope are a
   product decision (silent recurring sleep block vs. always-ask).
3. Should the cadence verifier live with the domain agent (produces/withdraws
   claims based on actuals) or the planner (refuses to retire a claim until the
   quota is met)?
4. Does `planning_window:<range>` need first-class scheduled-wake support, or can
   the planner derive the relevant horizon from the active claims it reads?
5. Do domain agents reuse the planner's durable-knowledge store (ADR 0022
   Decision 10) for their own "what the user told me" facts, or hold a per-agent
   variant?

## Related

- [ADR 0006: Change Set — Deferred Tool Confirmation Workflow](./0006-change-set-deferred-tool-confirmation.md)
- [ADR 0010: Scheduled Wake Infrastructure](./0010-scheduled-wake-infrastructure.md)
- [ADR 0018: Convergent Multi-Device Execution](./0018-convergent-multi-device-execution.md)
- [ADR 0019: Attention Negotiation Protocol](./0019-attention-negotiation-protocol.md)
- [ADR 0021: LLM-Mediated Attention Claim Weighing](./0021-llm-mediated-attention-claim-weighing.md)
- [ADR 0022: Long-Lived Daily OS Planner](./0022-long-lived-daily-os-planner.md)
  — the planner these domain agents negotiate with.

---

### Adr 0024 Correction Lexicon And Transcript Correction (`docs/adr/0024-correction-lexicon-and-transcript-correction.md`)

# ADR 0024: Correction Lexicon and Deterministic Transcript Correction

- Status: Proposed
- Date: 2026-06-07

## Context

Speech-to-text and LLM generation consistently mis-spell a small set of terms
that matter to the user: the app's own name (`Lotti`, which cloud models tend to
write as the more common `Lottie`), personal place names (a town STT reliably
mis-hears), and domain jargon. These are not soft preferences — they are
"never again" corrections the user wants to be applied everywhere,
deterministically.

Lotti already has the seed of a fix, but only partially:

- `CategoryDefinition.speechDictionary` (a `List<String>`) is a per-category
  vocabulary list, addable from the editor context menu
  (`speech_dictionary_service.dart`). It is consumed during transcription two
  ways: as a biasing block written into the transcription prompt
  (`prompt_builder_helper.dart` → `skill_prompt_builder.dart`), and as
  vocabulary hints to local STT (`mlx_audio_channel.dart` `dictionaryTerms`).
- `CategoryDefinition.correctionExamples` is a sibling mechanism for checklist
  correction.

Four gaps make this insufficient for the "never again" cases:

1. **Category-scoped only — no global terms.** The app name and personal place
   names apply everywhere; today they would have to be added to every category.
2. **Biasing only, and biasing is engine-dependent.** Vocabulary/dictionary
   hints work only on engines that accept them. Local Whisper does not take a
   usable vocabulary, and prompt-style biasing there is unreliable — so there is
   no guarantee exactly where it is most needed.
3. **Transcription only.** Nothing corrects general LLM *generation* output, so a
   model writing `Lottie` in a summary or plan is unaffected.
4. **Unergonomic.** Maintaining lists in category settings is clunky, and adding
   a bare *correct* term never captures the *wrong → right* mapping that a
   deterministic correction needs.

This relates to the durable-memory work in ADR 0022: a correction term is durable
user knowledge. But it is a *different class* from planner preferences — it is
app-owned, always-on, and applied deterministically, not planner-scoped, lazily
recalled, and LLM-weighed.

## Decision

1. **A correction lexicon is durable, user-confirmed memory — app-owned, not
   planner-owned.** Model correction terms on the durable `Version` / `Head`,
   propose → user-confirm pattern (as in ADR 0022 Decision 10), but as an
   app-level store that the planner, every other agent, the transcription
   pipeline, and the editor all *read*. It extends, rather than replaces, the
   existing `category.speechDictionary`.

2. **Two scopes.** Keep per-category, and add **global** (always-on, applies
   everywhere regardless of category). The app name and personal place names are
   global.

3. **Two modes per term.**
   - `bias` — the existing behavior: term added to engine vocabulary / prompt
     hint. Opportunistic; "prefer this spelling."
   - `hardReplace` — a deterministic `knownWrong[] → canonical` map. Opt-in
     per term, word-boundary aware. "This must never survive."

4. **Deterministic post-STT correction is the guarantee, and it is
   engine-independent.** A correction pass runs over the transcript *text* in the
   pipeline, after whichever engine produced it — so it works identically for
   local Whisper, voxtral, mlx, and cloud engines. Engine biasing is an
   opportunistic first layer; the post-pass is what makes "never again" actually
   hold. This pass lives at the pipeline level (`skill_transcription_runner` /
   `unified_ai_inference_repository`), not inside per-engine adapters.

5. **Apply to generation, not just transcription.** Inject the global lexicon as
   a compact glossary into user-facing LLM generation prompts, and run
   `hardReplace` on generated output — so `Lotti` is enforced when a model
   *writes*, not only when it *transcribes*.

6. **Optional local-LLM cleanup layer for fuzzy errors.** For garbled phrases the
   deterministic map cannot catch, a small **local** model may clean up
   transcript segments, given the lexicon as context. It must be conservative
   (correct transcription errors only, never paraphrase or drop content), keep
   the **raw transcript as source of truth**, and store the corrected text as a
   derived artifact with provenance. It triggers on utterance/segment boundaries
   (correcting committed segments once), **finalize-time first** — not live
   "every other sentence", which would make the on-screen transcript flicker and
   is O(n²) on context. It is **degradable**: if no local model is available, the
   deterministic pass alone still works; capture never depends on it.

7. **Learned in-place.** Correcting a term where you see it (select the wrong
   word in a transcript, type the canonical form) stores a **global**
   `wrong → canonical` pair. This becomes the primary path, replacing the
   unergonomic category-settings flow, and captures the mapping the post-pass
   needs.

8. **Always-on, not lazily recalled.** The lexicon is the explicit exception to
   the planner's two-tier lazy recall (ADR 0022 Decision 10): the terms are
   small, high-value, and unpredictable in where they apply, so they are always
   present in the relevant prompt — and applied at the first capture of a day
   with no dependency on planner context or a wake.

9. **Raw is source of truth; corrected is derived.** Keep the raw transcript;
   store corrections as a derived artifact with provenance (which terms / model /
   lexicon version applied), inspectable and reversible, so corrections do not
   become unattributable mutations across synced devices.

## Layering

```mermaid
flowchart TD
  Audio["Audio capture (incl. day-planning stream)"]
  STT["STT engine (local Whisper / voxtral / mlx / cloud)"]
  Bias["Layer 1 — bias (opportunistic)<br/>vocab hints where engine supports it"]
  LLM["Layer 2a — optional local-LLM cleanup<br/>conservative, lexicon as context, segment-boundary"]
  Replace["Layer 2b — deterministic hardReplace (the guarantee)<br/>knownWrong -> canonical, engine-independent"]
  Lexicon["Correction lexicon (durable, user-confirmed)<br/>global + category, bias + hardReplace"]
  Out["Corrected transcript (derived) + raw transcript (source of truth)"]
  Gen["Any user-facing LLM generation<br/>(planner, summaries, ...)"]

  Audio --> STT
  Lexicon -. terms .-> Bias
  Bias --> STT
  STT --> LLM --> Replace --> Out
  Lexicon -. wrong->canonical .-> Replace
  Lexicon -. glossary + hardReplace .-> Gen
  Out -. correct-in-place teaches .-> Lexicon
```

## Consequences

- The "never again" guarantee no longer depends on the STT engine cooperating;
  it is enforced deterministically on output text, including for local Whisper.
- Global terms (app name, personal place names) are maintained once and applied
  everywhere — transcription and generation — rather than per category.
- The lexicon is a second, distinct durable-knowledge class alongside planner
  preferences (ADR 0022). Keeping them separate avoids leaking app-wide spelling
  rules into the planner's scoped, weighed memory.
- Corrections are auditable and reversible because the raw transcript is retained
  and the correction provenance is recorded.
- The optional local-LLM layer adds a quality bump for fuzzy errors without
  becoming a hard dependency or a privacy/network concern.

## Non-Goals

- Live "every other sentence" streaming correction in the first version. Start
  finalize-time, per committed segment; add live incremental only if long
  dictations need it.
- Aggressive LLM rewriting/paraphrasing of captures. The local-LLM layer fixes
  transcription errors only; planning captures must not have their meaning
  silently changed.
- Replacing `category.speechDictionary`. This extends it (adds global scope and
  the `hardReplace` mode) and keeps category-scoped jargon working.
- Putting correction terms in the planner's knowledge store. They are app-owned
  and always-on, not planner-scoped.

## Open Questions

1. Storage shape: a dedicated app-level `CorrectionLexiconEntity` (durable
   Version/Head), or a global counterpart to `category.speechDictionary` on a
   settings/profile entity?
2. False-positive containment for `hardReplace`: word-boundary + case rules are
   the baseline — is per-term case sensitivity worth exposing?
3. Should the optional fuzzy/phonetic match against canonical terms (to catch
   *new* garbled variants) be suggest-only, or auto-apply above a confidence
   threshold?
4. Which local model backs the cleanup layer, and is it shared with existing
   local inference (ollama / mlx) or a dedicated small model?

## Related

- [ADR 0020: Agent Input Capture](./0020-agent-input-capture.md)
- [ADR 0022: Long-Lived Daily OS Planner](./0022-long-lived-daily-os-planner.md)
  — the durable-knowledge / two-tier recall model; this lexicon is its
  always-on exception.
- `lib/features/speech/` and `lib/features/ai/` — the existing
  `category.speechDictionary` mechanism this decision extends.

---

### Adr 0025 Insights Time Analysis Data Layer (`docs/adr/0025-insights-time-analysis-data-layer.md`)

# ADR 0025: Insights Time-Analysis Data Layer

## Status

Accepted (2026-06-07)

## Context

The Daily OS tab gains a desktop-only Time Analysis dashboard
(`lib/features/insights/`, route `/calendar/time`) that must aggregate
10k+ time entries per category per day and switch between date ranges
(1d/7d/30d/MTD/YTD/last month/custom) in under 200ms. The codebase already
contains three divergent "time spent" computations (calendar query,
Daily OS time history, task progress union-merge), several latent traps
(`julianday()` on integer-epoch columns, `linked_entries` join fan-out),
and a hard product rule that background refreshes must never flash
established UI.

An adversarial design review of the initial plan surfaced two
would-be-shipping bugs — a `julianday()` duration filter that returns zero
rows against Drift's integer-seconds DateTime storage, and a LEFT JOIN on
`linked_entries` that double-counts any entry with multiple incoming
links — plus an inverted category-precedence rule and naive summing that
double-counts overlapping entries. This ADR records the corrected,
adopted design.

## Decision

1. **Slim SQL projection, aggregation in Dart.** One query
   (`JournalDb.insightsTimeRows`, mixin `_JournalDbInsightsQueries`)
   returns only `(date_from, date_to, resolved category)` for non-deleted
   `JournalEntry` rows overlapping the window — never the `serialized`
   JSON blob. Deserializing 10k `JournalEntity` payloads is what would
   blow the latency budget, not SQLite. All bucketing/aggregation lives in
   pure Dart (`logic/time_bucketing.dart`) where it is Glados
   property-tested.
2. **Integer-seconds arithmetic only.** `date_from`/`date_to` are Unix
   seconds (Drift default); `julianday()` on them returns NULL. Duration
   guards use plain column comparison (`date_to > date_from`).
3. **Fan-out-free category resolution, task-first precedence.** A
   correlated subquery picks at most one linked task per entry
   (`ORDER BY t.date_from DESC, t.id LIMIT 1`); the task's category wins
   over the entry's own, matching `actualTimeBlocksForEntries` and the
   unified Daily OS aggregation.
4. **What counts as time:** `JournalEntry` only; `JournalAudio` is
   excluded (recordings during a running timer double-count — the shipped
   Daily OS time-history rule). No 15-second floor: that legacy floor is a
   noise heuristic in `workEntriesInDateRange`, not a totals semantic.
5. **Union-merge per (day, category) cell** after DST-safe midnight
   splitting (calendar-constructor arithmetic, epoch-day int keys via UTC
   anchor). Property tests assert duration conservation and merge
   idempotence.
6. **Year-keyed window cache.** Buckets are served by a
   `StreamProvider.family` keyed on a `({startDay, endYear})` record —
   January 1st of the range-start year through the range-end year (the
   fetch end is capped at January 1st after `endYear`, so past-year
   custom ranges never load every year through today). Every preset
   within a year shares one in-memory cache, so range switching is a
   pure memory slice (measured:
   all six presets ~5ms on a 10k-entry year; cold fetch+bucketize ~35ms).
   A different year is a different provider instance — no mutable shared
   window, no stale-write races. Refetches ride
   `notificationDrivenItemStream` (serialized, coalesced) on the
   `TEXT_ENTRY`/`TASK`/`LINK_CHANGED`/`PRIVATE_FLAG_TOGGLED` tokens, with
   `cacheFor` keeping recent windows alive across tab switches.
7. **Deep value equality as the no-flash mechanism.** Models are
   hand-rolled immutables with deep equality (no codegen); an unchanged
   refetch produces an equal `InsightsDayBuckets`, Riverpod never
   re-notifies, the UI never rebuilds.
8. **URL as the single selection writer, full-screen surface.** The
   dashboard lives at `/calendar/time` under the Daily OS tab, pushed as
   a full-screen page by `CalendarLocation` (the set-time-blocks
   pattern) — deliberately not a split pane. `CalendarLocation` is the
   sole writer of `desktopShowTimeAnalysis`; the sidebar sub-entry
   beneath the Daily OS month calendar only reads it. (Originally
   embedded in the Insights/dashboards detail pane; moved per product
   feedback — the analytics surface gets the entire content area.)
9. **Visualization contract** (Stephen Few): stacked bars / pre-stacked
   cumulative area via fl_chart; hourly buckets for 1-day ranges, weekly
   above 120 days; max 6 series + slate "Other (+N)" distinct from the
   neutral-gray Uncategorized; chart fills are muted derivations of
   user-picked category colors (saturated originals only in swatches);
   no pies or donuts.

10. **Private visibility.** The query gates both the entry and the
    linked-task subquery on the global `private` config flag using the
    `COALESCE(private, FALSE) IN (FALSE, (SELECT status FROM config_flags
    WHERE name = 'private'))` idiom from `workEntriesInDateRange`; the
    buckets provider additionally subscribes to
    `privateToggleNotification`. (Found by post-release adversarial
    review: the first cut leaked private durations.)
11. **v43 category backfill.** The v21 migration added the denormalized
    `journal.category` column without backfilling, so pre-2024-07 rows
    could carry `''` while their JSON `meta.categoryId` held the real id —
    silently bucketed as "Uncategorized" by column readers. v43 backfills
    the column once from `json_extract(serialized, '$.meta.categoryId')`,
    which also corrects the Daily OS time-history header.
12. **Refetch throttling.** Notification-driven window refetches are
    throttled (5s trailing edge via `notificationDrivenItemStream`'s
    `refetchThrottle`, mirroring the time-history throttle): typing fires
    a batch every ~100ms, and each refetch costs a full window query
    (~35-130ms measured at 10k-50k entries).
13. **Link mutations notify.** Standalone link create/update/remove (and
    the sync apply path) now emit `linkNotification` alongside the
    affected ids; the buckets provider subscribes, so linking a time
    entry to a task refreshes attribution immediately. Previously only
    UUID tokens fired and the dashboard stayed stale until the next
    entity edit.
14. **Covering index.** `idx_journal_insights_time` (partial, on
    `type = 'JournalEntry' AND deleted = FALSE`, covering `date_from,
    date_to, category, private, id`) turns the inherently residual
    overlap scan into an index-only scan, keeping cold-fetch cost flat as
    lifetime history grows.

## Measured performance (50k entries / 36 months / 40 categories)

YTD cold fetch 56ms + bucketize 37ms; full 36-month custom range 131ms +
111ms (the only path over the 200ms budget, one-time per window); preset
switches ~10ms; page-build derivations 2.7ms (shared
`dailyTotals`/`rankedCategoryTotals` pass); deep equality ~16ms per
refetch emission (cheaper than the rebuild it prevents); retained window
≈6-10MB. Scaling note: only `date_from < end` can be index-bounded —
`date_to > start` is a residual filter, so the scan length grows with
lifetime entry count (~110ms extrapolated at 100k before the covering
index; decision 14 removes the per-row table fetches from that walk).

## Consequences

- The dashboard's totals can differ slightly from the Daily OS time
  history header, which attributes a midnight-crossing entry wholly to its
  start day and does not union-merge; this feature splits and merges. The
  divergence is deliberate and documented in the feature README.
- Focus-category preferences live in SettingsDb as JSON and are
  **local-only** (SettingsDb keys do not sync unless explicitly coded);
  syncing them would require a new `SyncMessage` variant.
- The eager year-wide fetch trades a single ~35ms query for zero-DB preset
  switching; custom ranges in earlier years cost one additional fetch and
  are cached for five minutes.
- `workEntriesInDateRange`'s broken `julianday()` filter is a separate
  pre-existing bug, deliberately not fixed here (different call sites,
  different semantics) — tracked for its own change.

---

### Adr 0026 Author Time Memory Links (`docs/adr/0026-author-time-memory-links.md`)

# ADR 0026: Author-Time Memory Links (Convergence-Safe A-MEM)

## Status

Accepted (2026-06-09)

## Context

The agent memory substrate is an **append-only**, content-addressed event log
that compacts deterministically (ADR 0016/0017) and converges across devices by
LWW + vector clocks (ADR 0018). A-MEM (Xu et al. 2025, arXiv:2502.12110)
proposes giving a self-learning agent an interconnected memory network — note
construction (attributes), dynamic linking, and memory *evolution* (rewriting
old notes). A-MEM realizes all three in a **mutable store**, which is exactly
what our invariants forbid: in-place rewrites break append-only set-union,
make the compaction fold non-reproducible, and invalidate the prompt
prefix-cache on every edit.

The critique behind A-MEM — "a rigid append-log is poorly suited to a
self-learning agent" — is about the *store*. The escape hatch is that the
**content** of each immutable note is free text we already author and sync, so
we can move the plasticity A-MEM gets from a mutable graph into note content
without touching structure. We want associative linking and "new versions of
memories" with zero violation of append-only / convergence / cache stability,
and with no hard dependency on local embeddings (Ollama).

## Decision

1. **Links live in note content, not in a schema or a mutable graph.** A note
   (an observation, or a durable-knowledge statement) may cite a related entry
   inline as `[[relation:id]]`. The vocabulary is **closed** —
   `refines` / `supersedes` / `contradicts` / `relates` — so handling is
   deterministic and specific relations can map onto existing mechanisms. The
   token is plain content of an append-only entry: it never mutates history,
   never enters the cached prompt prefix, and is convergent because the cited
   `id` is the synced entity id the agent saw in the log.

2. **Two flavors of linking, kept separate.**
   - *Frozen author-time links* (text in the note) — deliberate, durable
     relationship assertions the agent makes with intent.
   - *Live read-time association* — recomputed against the current query at
     read time via the `search_memory` recall tool, never stored. This is
     strictly fresher than a baked graph and costs zero storage / convergence.

3. **Resolution is a pure projection** (`lib/features/agents/memory/memory_links.dart`):
   `parseMemoryLinks` (tolerant, closed-vocab, de-duplicating) +
   `resolveMemoryLinks`, which validates a target's *existence* against the
   known log ids (plus caller-supplied `extraKnownIds` — e.g. durable-knowledge
   keys, so a cross-tier link resolves) and forward-follows a supersession
   chain (cycle-guarded) to the live version. A `supersedes` link is **never**
   forward-followed — its whole purpose is to name the *old* entry.

4. **Recall is the traversal primitive.** `search_memory`
   (`AgentLogCompactor.searchLog` / `resolveByIds`, wired in
   `DayAgentWorkflow._searchMemory`) takes a `query` (keyword) or `ids` (follow
   a link). It scans the **full** immutable log newest-first, lazily and
   bounded, attaching each hit's validated outgoing links and a
   `supersededByEntryId` flag. The system prompt instructs the agent to author
   links and to actually follow them.

5. **Maps of Content.** A `propose_knowledge` entry keyed `moc-<topic>` whose
   statement curates `[[relates:id]]` links is a durable, navigable hub
   (Zettelkasten) — zero new mechanism, just a key convention over the grammar.

## Consequences

- **Convergent.** Author-time tokens are content of append-only events
  (set-union). A cited id is a synced entity id, so links converge; a
  not-yet-synced target renders as a dead link and self-heals on sync; a
  hallucinated id resolves to "not found" and is **never** followed or
  fabricated.
- **Cache-safe.** Tokens add a few bytes to content the prompt already
  includes (append-only additive). Validation/expansion happens only in
  `search_memory` tool turns (after the cached prefix) or the volatile
  retrieval slot — never in the `dayLog` prefix.
- **Best-effort forward-follow.** A non-`supersedes` link to a superseded
  target only jumps to the live version when that superseder was within the
  recall scan window; otherwise it renders at its original (still-valid) id.
  This is presentation-only (transient tool output, never persisted), so the
  bound is acceptable.
- We get A-MEM's *expressiveness* (rich notes + links) without its *mutable
  store*. The cost: no single globally-canonical evolving graph — we use
  append-only per-origin links plus recomputed read-time association. Weaker
  than A-MEM's one network, but safe.

## Non-goals

- In-place rewriting/evolution of any episodic capture/observation or
  knowledge note (breaks convergence + caching). "Evolution" is realized only
  as append-only supersession.
- A single canonical, mutable link graph.
- A stored `knowledge_link` `AgentLink` edge set — deferred as a last resort,
  only if the text convention proves insufficient.
- Any hard dependency on Ollama; the substring recall + text links work on
  every platform. Semantic recall (embeddings) is a later, optional upgrade
  behind the same tool.

## Related

- ADR 0016 / 0017 (append-only input-event log + deterministic compaction —
  the recall reader is documented there), ADR 0018 (convergent multi-device
  execution), ADR 0022 (long-lived Daily OS planner durable knowledge).
- Plans: `docs/implementation_plans/2026-06-08_convergence_safe_a_mem.md`
  (Phases 0/1/1.5 implemented; 2/3/4 proposed),
  `2026-06-08_planner_log_search.md`, `2026-06-08_planner_embeddings.md`.
- Code: `lib/features/agents/memory/memory_links.dart`,
  `lib/features/agents/sync/agent_log_compactor.dart`,
  `lib/features/daily_os_next/agents/workflow/day_agent_workflow.dart`.

---

### Adr 0027 Wake Notification Propagation And Storm Prevention (`docs/adr/0027-wake-notification-propagation-and-storm-prevention.md`)

# ADR 0027: Wake Notification Propagation and Storm Prevention

- Status: Accepted
- Date: 2026-06-09

## Context

Background agents wake from database changes. That single fact creates three
failure modes that a naive "any write notifies every subscriber" design walks
straight into:

1. **Self-trigger loops** — an agent writes to the same entities it watches, so
   its own wake produces a notification that wakes it again.
2. **Cross-entity wake storms** — task B links task A; editing A should make B's
   agent reconsider, but if A's *agent* edits A and that wakes B's agent, whose
   write wakes A's agent, the system oscillates (the historically-observed
   A→B→A storm).
3. **Redundant re-execution on replicated changes** — a change that arrives via
   Matrix sync was already processed by the device that authored it; re-running
   the agent on every device would multiply work and risk divergence
   (ADR 0018).

The runtime solves all three with a **notification origin-routing model** plus a
**cross-entity fan-out graph**, composed with the throttle/queue policy of
ADR 0002 and the vector-clock self-suppression of ADR 0004. The mechanism was
built incrementally and, until now, lived only in code comments
(`lib/services/db_notification.dart`, `lib/logic/persistence_logic.dart`) and
scattered `lib/features/agents/README.md` prose. It is load-bearing for
correctness and cost, so it is captured here as a decision in its own right.
ADR 0002 governs *when* a matched wake drains (throttle/queue/single-flight);
this ADR governs *which write reaches the orchestrator at all, and on behalf of
which agents*.

## Decision

1. **Three notification streams, partitioned by origin**
   (`UpdateNotifications`, `lib/services/db_notification.dart:3-101`):
   - `updateStream` — **all** notifications (local, sync, UI-only). For UI
     widgets that must react to every change.
   - `localUpdateStream` — **locally-originated, non-agent** writes only. This
     is the **only** stream that drives agent wakes.
   - `syncUpdateStream` — **sync-originated** writes only (consumed by the
     synced-audio auto-trigger, never by the wake orchestrator).

2. **Writes are routed to streams by origin, at the write site**
   (`persistence_logic.dart:583-587`):
   - A **local user** write (`isAgentExecution == false`) calls `notify(ids)` →
     emitted on `updateStream` **and** `localUpdateStream`.
   - An **agent** write, i.e. code running inside the agent-execution zone
     (`agentExecutionZoneKey`, `db_notification.dart:134-144`; set by
     `wake_drain_engine` around executor work), calls `notifyUiOnly(ids)` →
     emitted on `updateStream` **only**. This is the primary loop-breaker: an
     agent's own journal writes are structurally invisible to the orchestrator.
   - A **sync-ingested** write calls `notify(ids, fromSync: true)` → emitted on
     `updateStream` **and** `syncUpdateStream` (never `localUpdateStream`), so a
     replicated change does not re-run the agent on the receiving device
     (ADR 0018).

3. **The wake orchestrator subscribes to `localUpdateStream` only**
   (`agent_providers.dart:386` → `WakeOrchestrator.start`). Consequence: **only
   local, user-originated, non-agent writes can wake an agent.** Layers (1)–(2)
   make "self-trigger loops" and "redundant sync re-execution" structurally
   impossible rather than throttled-after-the-fact.

4. **Cross-entity fan-out defines the wake graph.** Every journal write
   includes, in its notification id set, the entity's own affected ids **plus
   its linkers** — `parentLinkedEntityIds(id)` =
   `SELECT from_id FROM linked_entries WHERE to_id = :id`
   (`database.drift:1168-1169`), the entries that link **to** the edited entity.
   Links store `from_id` = linker, `to_id` = target
   (`persistence_logic.dart:210-241`). Because a task→task link is stored
   `from_id = B (linker), to_id = A (target)`, **editing task A surfaces B as a
   linker and notifies B's subscription** — this is the entire cross-task update
   graph. Each linker id is emitted **twice**: raw, and wrapped by
   `propagatedNotification(id)` = `PROPAGATED::<id>`
   (`db_notification.dart:164-170`, `persistence_logic.dart:576-582`).

5. **Direct vs propagated matches drive the deferral policy**
   (`wake_batch_router.dart:14-70`). A match is **direct** when the agent's own
   `matchEntityId` is present as a raw token (its own entity was edited) and
   **propagated** when only the `PROPAGATED::` form is present (a linked/child
   entity was edited). `AgentSubscription.deferPropagatedMatches` selects the
   policy:
   - **Project agents** set `true` → propagated-only matches defer to the
     scheduled daily digest, so linked-task churn under a project does not burn
     tokens on every child edit.
   - **Task agents** set `false` → propagated matches fast-drain on the normal
     120-second coalescing window, so a linked task's user-edits refresh the
     dependent task agent promptly.
   - A direct match arriving during a propagated deferral **escalates** the
     deadline to the fast throttle (`wake_batch_router.dart:117-146`).

6. **Storm prevention is the composition of five layers**, not any single guard:
   1. **Origin routing** — agent writes via `notifyUiOnly` stay off
      `localUpdateStream` (Decision 2); breaks A→B→A and self-loops at the source.
   2. **Propagated deferral** — `PROPAGATED::` + `deferPropagatedMatches`
      (Decision 5); bounds project-agent fan-in.
   3. **Throttle/coalesce** — 120-second window per agent, defer-first queueing
      (ADR 0002, `WakeThrottleCoordinator`).
   4. **Self-mutation suppression** — the orchestrator records the vector clocks
      of entities the agent mutated (`recordMutatedEntities`,
      `_preRegisterSuppression`, `WakeSuppressionTracker`,
      `wake_orchestrator.dart:321-345`; ADR 0004) and drops matching
      notifications within a TTL, closing the race between the DB write and the
      stream emission. The pre-registration uses the trigger tokens *before*
      execution, then is replaced by the actual mutated set after.
   5. **Single-flight + dedup** — one drain and one running wake per agent;
      jobs deduped by run key, tokens merged per `(agentId, workspaceKey)`
      (ADR 0002, ADR 0022).

7. **What is intentionally *not* propagated.** Agent-authored **report prose**
   is written to `agent.sqlite` (`task_agent_workflow.dart` report-head upsert),
   which emits **no** journal notification at all; and an agent's own journal
   writes use `notifyUiOnly`. Therefore **agent-origin** changes never wake
   another agent — there is deliberately no agent→agent push. A dependent task
   agent re-reads a linked task's current report at its *next* wake (driven by a
   user edit of either task), not on the linked agent's republish. This is a
   design choice in service of Decision 6, not a gap; adding agent→agent
   report-head propagation would reintroduce the storms layers (1)–(5) exist to
   prevent.

## Notification routing

```mermaid
flowchart TD
  W["Journal write (persistence_logic.updateDbEntity)"] --> O{"Origin?"}
  O -- "local user edit" --> N["notify(ids)"]
  O -- "agent wake zone\n(isAgentExecution)" --> U["notifyUiOnly(ids)"]
  O -- "Matrix sync ingest" --> F["notify(ids, fromSync: true)"]

  N --> US["updateStream"]
  N --> LS["localUpdateStream"]
  U --> US
  F --> US
  F --> SS["syncUpdateStream"]

  LS --> ORCH["WakeOrchestrator (only consumer of localUpdateStream)"]
  US --> UI["UI providers"]
  SS --> AUD["Synced-audio auto-trigger"]

  ORCH --> M{"Match AgentSubscription?\n(direct vs PROPAGATED::)"}
  M -- "suppressed by VC tracker" --> X["Drop"]
  M -- "match" --> THR["Throttle / defer / coalesce (ADR 0002)"]
  THR --> EXEC["Wake"]
```

## Cross-entity wake graph (why editing A wakes B)

```mermaid
flowchart LR
  subgraph links["linked_entries"]
    L["from_id = B (linker)\nto_id = A (target)"]
  end
  EA["User edits task A"] --> FAN["ids += parentLinkedEntityIds(A)\n= from_id WHERE to_id = A = {B}"]
  FAN --> TOK["emit B (raw) + PROPAGATED::B"]
  TOK --> SUBB["Task B subscription {B}\ndeferPropagatedMatches = false"]
  SUBB --> WB["B's agent fast-drains (120s) and wakes"]
```

## Consequences

- Self-trigger loops and redundant sync re-execution are eliminated
  **structurally** (origin routing), not merely throttled — the orchestrator
  never receives those notifications.
- Cross-task coordination is **real and event-driven** for the common case
  (a user editing a linked task), with the project/task deferral split tuning
  fan-in cost.
- The deliberate absence of agent→agent push means a dependent agent can hold a
  *stale* compact summary of a linked task until its next user-driven wake. This
  is accepted; the on-demand drill-down tool (ADR 0003) is the intended way to
  fetch fresher linked detail when a wake needs it.
- The five layers are interdependent: removing origin routing would make the
  throttle and VC suppression carry loops they were not sized for; removing
  propagated deferral would expose project agents to child-edit fan-in. Changes
  to any one layer must be evaluated against the whole.
- The model depends on the agent-execution zone being entered around **all**
  agent-side journal writes. A write that escapes the zone would route through
  `notify` and could wake peers — the zone boundary in `wake_drain_engine` is a
  correctness-critical invariant.

## Related

- [ADR 0002: Wake Scheduling and Throttling Policy](./0002-wake-scheduling-and-throttling-policy.md)
  — the throttle/queue/single-flight policy this ADR composes with.
- [ADR 0004: Task Agent Tool Execution Policy](./0004-task-agent-tool-execution-policy.md)
  — the post-mutation vector clocks used for self-mutation suppression.
- [ADR 0010: Scheduled Wake Infrastructure](./0010-scheduled-wake-infrastructure.md)
  — scheduled/manual wakes bypass subscription matching and this throttle path.
- [ADR 0018: Convergent Multi-Device Execution](./0018-convergent-multi-device-execution.md)
  — why sync-origin writes must not re-run agents on the receiving device.
- [ADR 0022: Long-Lived Daily OS Planner](./0022-long-lived-daily-os-planner.md)
  — `(agentId, workspaceKey)` partitioning of merge/supersede/cancel.
- Code: `lib/services/db_notification.dart`,
  `lib/logic/persistence_logic.dart:569-587`,
  `lib/database/database.drift:1168-1169` (`parentLinkedEntityIds`),
  `lib/features/agents/wake/{wake_orchestrator,wake_batch_router,wake_throttle_coordinator,wake_suppression_tracker}.dart`,
  `lib/features/agents/state/agent_providers.dart:386`.
- `lib/features/agents/README.md` (Wake Orchestration; "Why the wake design is
  this defensive").

---

### Adr 0028 Tagged Plaintext Payload And Day Summaries (`docs/adr/0028-tagged-plaintext-payload-and-day-summaries.md`)

# ADR 0028: Tagged Plaintext Planner Payload and Contemporaneous Day Summaries

## Status

Accepted (2026-06-10)

## Context

The long-lived Daily OS planner (ADR 0022) drafts one day at a time and was
blind to the surrounding days: it could not see that the user burned the
midnight oil all weekend (and should get a gentle Monday), that a planned gym
session was missed, or that a deadline lands in three days. The primary goal is
**sustainability, not throughput**; a hard secondary requirement is that
**weak local models must read the context well**.

Two structural problems stood in the way:

1. **The wake payload was one `jsonEncode`d document.** Every prose value —
   the compacted day log, knowledge statements — had its newlines escaped into
   run-on strings, the worst shape for weak local models.
2. **Compaction destroys the "why".** The deterministic facts of a day
   (planned vs recorded minutes) are derivable forever, but the agent's
   contemporaneous understanding of *why* a day went the way it did dissolves
   once the log folds (ADR 0017).

## Decision

1. **The payload converts from one JSON document to tagged plaintext
   sections** (`day_agent_prompt_sections.dart`). `<snake_case_tag>` sections
   keep what JSON provided — named sections, boundary integrity — while giving
   prose real newlines. Data-shaped, tool-facing content (attention claims
   with ids, capture corpus, drafting/refine baseline, observations, trigger
   tokens) stays JSON *inside* its tags so models copy ids verbatim into tool
   calls. Section order remains stable→volatile for prefix-cache reuse; the
   week-context sections sit after `knowledge_statements` and before the mode
   sections because the today-so-far line churns with tracked time.
   A single shared sanitizer neutralizes the full open/close tag vocabulary in
   every interpolation — including the JSON-kept sections, since `jsonEncode`
   does not escape `<`/`>` — and single-line interpolations collapse whitespace
   runs so multi-line values cannot fabricate structure.

2. **ADR 0020 v2 prompt records gain a `day-log-section` wrap kind.** The
   persisted wake record splices around the whole `<day_log>…</day_log>`
   section (head/tail split on section boundaries — the log is multi-line, so
   a single-line anchor no longer works). The legacy `json-day-log-line` wrap
   stays decodable so records persisted before the conversion still
   reconstruct for the history UI.

3. **`<recent_days>`: one paragraph per day over a rolling last-7-days
   lookback (plus the plan date), facts first, agent testimony second.**
   Facts are deterministic template rendering (`week_context.dart`, the single
   owner of all wording): per-category recorded-vs-planned minutes
   (integer-tenths arithmetic, never doubles), named block-level misses, plan
   status, capped lists with deterministic overflow markers. The testimony is
   the agent's **contemporaneous day summary**, rendered adjacent to the facts
   (self-auditing); facts never come from it, and on contradiction the facts
   line wins. **Day classification is anchored to the wall clock, not the
   wake's workspace day**: past days say "Missed:", today renders
   "(today so far)" / "Still planned:", and days after today render
   "(upcoming)" — never "Missed:" and never fake rest-day lines.
   `<week_ahead>` carries future days with plans plus claim deadlines within
   `[today, today+5)`.

4. **Day summaries are a keyed mutable register with first-write-wins
   concurrency — a deliberate amendment to ADR 0016 D3 / ADR 0018 D1.**
   `AgentDomainEntity.daySummary` (`day_agent_summary:<dayId>`) is agent
   testimony written at/near day close in the agent's own words for its own
   consumption. Within-window self-rewrites upsert the register in place
   (preserving `createdAt`); on **concurrent** versions the EARLIEST
   `createdAt` wins (`resolveConcurrentAgentEntityOverride`) — the most
   contemporaneous testimony is canonical, so a later stale-device write
   cannot silently replace it. A `createdAt` tie defers to the generic LWW +
   canonical-clock path.

5. **The `write_day_summary` window amends ADR 0022 D4.** The workspace-day
   tool guard rejects any tool call whose `dayId` differs from the wake's
   workspace. `write_day_summary` is the sole, ADR-governed exception: its
   window is anchored to the **wall clock, independent of the plan date** —
   `dayId ∈ {today, yesterday}`. Future days are rejected (a drafting-tomorrow
   wake must not write testimony for unhappened days); anything older than
   yesterday is rejected (stale-device wakes must not overwrite genuine
   testimony). If no wake lands inside a day's window, that day keeps a
   permanent hole — accepted; the seeded directive mitigates by instructing
   the agent to write a missing summary on any wake while writable.

6. **Day summaries are a new episodic tier — an amendment to ADR 0022 D9.**
   They are day-scoped agent testimony, compaction-exempt for now, and NOT
   preference memory: preferences still flow through the durable-knowledge
   gate. Compaction integration is deliberately deferred until a few weeks of
   real summaries exist (retention is unbounded meanwhile; the prompt renders
   only the lookback window). This explicitly acknowledges ADR 0022's "durable
   memory needs a contradiction/decay policy" consequence and defers it to the
   compaction-integration follow-up.

7. **Strict memory-channel partition** (seeded directive):
   `write_day_summary` is the SOLE channel for day retrospectives;
   `record_observations` is for forward-looking learnings/patterns ONLY,
   never day recaps — preventing the same content from being double-fed
   through both the day log and the recent-days section.

8. **Cost gating.** Week context builds only on wakes whose workspace came
   from day-carrying tokens (planning-day / drafting / refine / scheduled);
   capture-submitted wakes — the highest-frequency kind — skip the 8-day
   journal + links + claims load entirely. Recorded time resolves through the
   shared `recorded_time.dart` core (the same pairs the Actual timeline lane
   projects), and the per-day plan/summary lookups go through ONE chunked
   `getEntitiesByIds` call.

## Consequences

- Weak local models read prose with real newlines; ids stay copyable.
- The planner sees a week of planned-vs-actual and its own day notes, enabling
  sustainable planning; the "why" survives compaction.
- The facts-vs-testimony split is self-auditing and the facts line is
  authoritative on contradiction.

Accepted limitations (documented, not fixed):

- **Cold-start omission:** both sections are omitted independently when
  information-free — `recent_days` only when every lookback day has no plan,
  no summary, and zero recorded spans (a fresh install renders nothing
  instead of eight "Nothing recorded." lines), `week_ahead` when there are no
  future plans and no deadlines in the window.
- The `recent_days` today-so-far line churns with tracked time, costing prompt
  prefix cache on same-day re-wakes (user-accepted for wake cadence).
- A transient week-context load failure and genuine no-data are
  indistinguishable in the prompt (the failure is logged).
- Deadline coverage is gated by claim *visibility*
  (`getAttentionClaimsForWindow`): a claim whose `latestEnd` elapsed but whose
  deadline is ahead may be invisible, and at >200 claims the index ordering
  can truncate deadline-bearing claims.
- The facts line reflects *current* entity state: retroactive uncommit/edit
  changes a past day's line. Summaries are testimony, not caches — they are
  never regenerated on retroactive data changes.
- The summary id carries no agentId — the same latent identity-recreation
  hazard as `day_agent_plan:<dayId>`, precedented and accepted.
- A currently *running* timer is excluded from recorded time (its growing
  `dateTo` exists only in memory until stopped).
- Recorded spans bucket whole-duration by start day, diverging from the
  per-day timeline lane's containment window for midnight-spanning entries.

## Related

- ADR 0016 (state as log projection) — D3 amended by Decision 4.
- ADR 0017 (deterministic compaction) — summaries are compaction-exempt.
- ADR 0018 (convergent execution) — D1 amended by Decision 4.
- ADR 0020 (input capture / v2 prompt records) — wrap kind added.
- ADR 0022 (long-lived planner) — D4 and D9 amended.
- ADR 0023 (domain agents) — per-agreement quota fulfillment deliberately
  excluded here and deferred there.

---

### Adr 0029 Knowledge Graph Explorer (`docs/adr/0029-knowledge-graph-explorer.md`)

# ADR 0029: Knowledge-Graph Explorer

## Status

Proposed (2026-06-18)

## Context

Lotti accumulates a rich, heterogeneous knowledge graph — ~16 journal-entry types
and several definition/AI-config node types, joined by directional typed edges in
`linked_entries` (`EntryLink`: `BasicLink`, `ProjectLink`, `RatingLink`) plus
embedded/denormalized relationships (Checklist↔Item, Category ref, Label M:N,
HabitCompletion→HabitDefinition, AiResponse→source, DayPlan→Task/Category, and the
AI-config sub-graph Profile→Model/Skill→Provider). Every node and edge is
timestamped; Categories supply a natural color/grouping dimension; the graph is
sparse (1–10 links per typical node) with Project and Category nodes as hubs; a
heavy user reaches thousands of nodes. None of this link structure is currently
visible or explorable — there is no graph/network view (charting uses `fl_chart`,
`graphic`, `pie_chart`).

The goal is a visually compelling explorer that **aids reflection and recall** —
sitting between a "gamey, walk-the-world" feel and serious information
visualization — not a decorative toy. A four-discipline panel (information
visualization, ontology/graph-DB, open-world game design, Flutter rendering) was
convened; full findings and citations are in
[`docs/research/2026-06-18_knowledge_graph_visualization_panel.md`](../research/2026-06-18_knowledge_graph_visualization_panel.md).

All four disciplines converged independently on one load-bearing constraint:
**never render the whole graph.** The full force-directed "constellation of
everything" collapses into an unreadable hairball past a few hundred nodes (the
Obsidian graph view is the cautionary example), which is orders of magnitude below
a heavy user's node count. The field's answer — a DOI ego-network (InfoViz), a
schema-driven perspective (graph-DB), the "Local Sky" local-graph (game design) —
is the same idea: stand on one node, expand on demand, always seeded by a question.

## Decision

This ADR records the **shape** of the feature and its constraints. Nothing is built
yet; the phased plan (Decision 9) gates construction on a de-risking spike.

1. **Ego-centric, seed-and-expand — never the full graph.** Entry is always a seed
   (the open entry, a search hit, or "today"). Render only a bounded
   degree-of-interest neighborhood (graph distance + a-priori hub interest + recency,
   with `hidden`/soft-deleted edges scored ~0); double-tap expands a node's neighbors
   into the frontier. A hard visible-node cap is part of the contract, not a tuning
   afterthought (see Decision 6 budget).

2. **Schema-derived perspectives, not one canvas.** Ship a small set of saved,
   scoped lenses (visible node/edge types + per-type styling + seed query): (1)
   Project containment tree, (2) Provenance — what the AI touched, (3) Rating
   landscape, (4) Day-plan ↔ task flow, (5) Habit/measurement instance-of fan, (6)
   Category facet map. **The AI-config sub-graph is a separate, settings-only
   perspective** and is never mixed into journal views — it is plumbing, not lived
   experience.

3. **Layout follows the semantic relation class of the edges in view.** Layered
   (Sugiyama) for directed-acyclic relations — containment (`ProjectLink`,
   Checklist↔Item), provenance (`AiResponse`→source), AI-config, day-plan flow;
   organic/force for associative exploration; radial for instance-of fans
   (`HabitDefinition`→completions); adjacency matrix for dense many-to-many
   (Label↔entry, dense Rating); node-link whenever the user traces a path. Only the
   *visible* subgraph is ever laid out, keeping every layout job small.

4. **Visual encoding.** Category → color (the strongest pre-attentive grouping, and
   it already exists); node type → glyph using shape *families* plus the existing
   per-type icons (not 16 distinct shapes); hub degree → size; recency → luminance.
   User-authored links render solid; system-inferred/derived edges render faint and
   dashed so inference never masquerades as an asserted link.

5. **Time is a first-class axis.** Recency-as-luminance is the resting encoding (new
   bright/saturated, old dimmed). A scrubbable "graph diary" animates nodes/edges in
   as their timestamp crosses a window, and an opt-in "On This Day" flies to a
   genuine past cluster. **Layout stability is mandatory:** existing node positions
   are pinned and only new arrivals animate in — global re-layout never runs on a
   scrub tick or an incremental change (it destroys the mental map). Discovery is
   framed as honest *rediscovery* of the user's own forgotten connections, never
   fog-of-war over data they authored.

6. **Rendering stack: custom 2D `CustomPainter` + `Matrix4` viewport.** Nodes via
   `canvas.drawRawAtlas` against a pre-baked sprite atlas; edges via `drawVertices`/
   `drawRawPoints` (arrowheads only at high zoom). Force layout (Fruchterman-Reingold
   / ForceAtlas2 with a **Barnes-Hut** quadtree, O(N log N)) runs in a **long-lived
   isolate** that streams packed `Float32List` positions and **settles-then-freezes**
   (stops ticking at low kinetic energy; re-heats locally on mutation). Interaction is
   a custom `GestureDetector` (scale + pan + double-tap + fling), **not**
   `InteractiveViewer`; tap maps to a node by inverting the view matrix and querying a
   quadtree (the same spatial structure). **Committed node budget:** ≤300 visible live
   at 60fps; 300–800 with viewport culling + level-of-detail + atlas batching;
   800–2000 with cluster rasterization; beyond that, aggregate distant regions.
   **Rejected:** `graphview` (one widget per node — small graphs only; reference
   only); 3D via `flutter_scene`/`flutter_gpu` (preview, master-channel only —
   disqualified on a five-platform stable app); `flame` (production-grade but overkill
   for a pannable graph — reserved as a future escape hatch only if a true particle-
   rich "world" is later wanted). Reuse the existing `.frag` shader pipeline
   (`lib/features/ai/ui/animation/`) for optional glow.

7. **Data prerequisite — give `BasicLink` semantics, with no migration.**
   `BasicLink` is currently untyped; its meaning is reconstructed by UI context, so
   it cannot drive styling, filtering, or layout. Add one **nullable** `semantic`
   string property and **backfill by inference** from the rules already applied in the
   UI (`AiResponse`→source ⇒ `derivedFrom`; `DayPlan`→`Task` ⇒ `plans`; same-day
   entries ⇒ `relatedTo`; …), constrained to a small closed vocabulary aligned to
   PROV-O/SKOS/schema.org names. Old rows stay valid (null = unspecified association).
   This is independently useful and is the cheapest high-leverage groundwork.

8. **Calm game-feel; no gamification.** Permitted: inertial pan/zoom, a "walk the
   link" eased camera dolly along edges (~400–600ms, never linear, never a cut),
   semantic zoom, an arrival "settle", animated constellation-line draw, restrained
   default-off sound. **Forbidden:** streaks, XP/levels, badges, leaderboards,
   completionist "fill the sky" pressure, unlock-gating the user's own data — for
   private, single-player journal data these corrode the intrinsic motivation the
   feature depends on. Feedback may acknowledge an action; it may never congratulate
   the user for using their journal.

9. **Phased delivery, spike-gated.**
   - **Phase 0 — POC spike (throwaway).** Real ~300-node category subgraph from
     `linked_entries`; Barnes-Hut layout in an isolate; `CustomPainter` +
     `drawRawAtlas` + viewport culling; custom pan/zoom; tap-to-select; on-screen
     frame-ms / visible-node overlay. **Pass criteria:** sustained 60fps panning at
     300 nodes on a mid-range phone, smooth settle without UI-thread jank, correct
     hit-testing at 0.25×–4× zoom. Push test data to 800/2000 to find the cluster-
     rasterization threshold.
   - **Phase 1 — "Local Sky" panel.** An embedded per-entry local-graph view (ego,
     1–2 hops, expand-on-demand) shipped *alongside* existing list/database views.
     Proves the one thing that can kill the vision — does walking a link feel good and
     useful? — and structurally dodges the hairball.
   - **Phase 2 — "Stargazer" world.** A first-class spatial explorer (night-sky
     metaphor, perspectives, graph diary, "On This Day"), grown out of Phase 1 only
     once traversal is proven to feel good.

## Consequences

- The explorer answers a concrete personal question and ends in an action ("open
  this task", "link this orphan", "revisit this dormant cluster") rather than
  rendering a pretty constellation — the failure mode every PKM graph view hits.
- Time becomes legible (accumulation, dormancy, "On This Day") — the dimension
  mainstream PKM graph views ignore and Lotti's strongest differentiator, enabled by
  the existing per-node/per-edge timestamps.
- The `BasicLink.semantic` backfill (Decision 7) improves the data model regardless
  of whether the visualization ships, and unlocks per-type styling/filtering/layout.
- The rendering choice reuses existing competencies (`CustomPainter`, `.frag`
  shaders, off-thread isolates) and adds no heavyweight rendering dependency.

Accepted limitations and deferred questions (not yet resolved):

- The visible-node cap means the explorer is deliberately a *local* tool; there is no
  global overview, by design. Hub fan-out (a Category's hundreds of children) is
  collapsed-by-default with a count badge, expand-on-demand.
- Force-layout *quality* (gravity/repulsion/edge-length tuning, type-aware seeding) is
  the expected time sink; Phase 0 must surface it before Phase 1 commits.
- Isolate↔UI cadence (tick rate during settling, freeze on idle) and Drift fan-out
  must reuse the batched `database_links_ratings.dart` path and the
  `idx_linked_entries_from_id_hidden_to_id` index; a naive per-node query would
  regress DB performance (see ADR 0025's fan-out lessons).
- Impeller is opt-in on desktop, so desktop runs on Skia — the atlas/shader paths must
  be validated on both.
- The `semantic` vocabulary, whether inferred edges are persisted vs derived at read
  time, and the perspective save/share model are open and deferred to Phase 1 design.
- Whether Phase 2 ("Stargazer") is built at all is contingent on Phase 1 proving the
  traversal feel; this ADR does not commit to it.

## Related

- Research: [`docs/research/2026-06-18_knowledge_graph_visualization_panel.md`](../research/2026-06-18_knowledge_graph_visualization_panel.md)
- ADR 0025 (insights time-analysis data layer) — `linked_entries` fan-out / batched
  query lessons apply to building the visible subgraph.
- ADR 0026 (author-time memory links) — related edge-creation semantics.
- Data model: `lib/classes/entry_link.dart`, `lib/database/database_links_ratings.dart`
  (index `idx_linked_entries_from_id_hidden_to_id`).
- Rendering precedents: `lib/features/ai/ui/animation/` (shaders),
  `lib/widgetbook/zoom_pan_wrapper.dart`, `third_party/flutter_onnxruntime` (isolate).

---

### Adr 0030 Desktop Keyboard Command System (`docs/adr/0030-desktop-keyboard-command-system.md`)

# ADR 0030: Desktop Keyboard Command System

## Status

Accepted (2026-07-15)

## Context

Lotti's desktop keyboard behavior grew through several unrelated mechanisms:
macOS `PlatformMenuBar` items, widget-local Flutter `Shortcuts`, raw key-event
handlers, and lifecycle-sensitive `hotkey_manager` registrations in controllers
and dialogs. Bindings, labels, availability, and help text therefore have no
shared source of truth. A shortcut can outlive the surface that registered it,
macOS receives a richer command set than Windows and Linux, punctuation
shortcuts assume a US keyboard layout, and keyboard-only activity is invisible
to the sync idle gate.

The desktop application needs one architecture that supports global commands,
focused-surface commands, control-local interactions, native menu adapters, a
command palette, and fully localized help without broadcasting every key event
to unrelated features.

## Decision

1. **Commands, not raw keyboard events, are the application boundary.** Lotti
   uses Flutter `Shortcuts`, `Actions`, `Intent`, and `ContextAction` for
   in-application commands. It does not introduce a broadcast keyboard event
   bus or OS-global shortcuts.
2. **One typed catalog is authoritative.** Stable `AppCommandId` values map to
   immutable definitions containing category/context metadata, default
   platform bindings, palette/help visibility, repeat policy, and destructive
   status. Execution, macOS menus, the command palette, and shortcut help all
   consume this catalog. Localized text is resolved outside the pure catalog.
3. **Handlers follow focus and widget lifetime.** `AppCommandScope` contributes
   handlers for the focused page, editor, list, or modal. Resolution starts at
   the focused scope, falls through parent scopes, and ends at the app-global
   scope. Scope disposal removes its handlers; no controller registers process-
   global hotkeys. The last active scope is retained for native-menu invocation
   while focus temporarily leaves Flutter.
4. **Bindings respect keyboard layouts.** Generated characters such as `?`,
   `+`, and `-` use `CharacterActivator`; letters, digits, function keys,
   arrows, and other special keys use `SingleActivator`. Command on macOS and
   Control on Windows/Linux are represented as one product-level "Primary"
   modifier. Help labels are formatted for the active platform and locale.
5. **Bindings are fixed in v1.** Stable command IDs and a replaceable catalog
   boundary leave room for future remapping, but v1 adds no persistence,
   conflict editor, or unused override API.
6. **The palette preserves its invocation context.** Opening the palette
   captures the active scope before the search field takes focus. Executing a
   result closes the palette, restores focus, and invokes the captured handler
   only while its scope remains mounted and enabled. Unavailable commands are
   omitted; destructive commands retain their normal confirmation flow.
7. **Focus regions are first-class desktop navigation.** The sidebar and each
   visible list/detail pane register as `KeyboardFocusRegion`s. F6 and Shift+F6
   cycle regions and restore the last focused descendant. Inactive
   `IndexedStack` destinations are excluded from focus and command resolution.
8. **Command execution is guarded.** Creation, save, and other one-shot
   commands ignore key repeats and concurrent re-entry. Continuous commands
   such as zoom, pan, and resize may opt into repeats. Failures are logged at
   the dispatcher boundary; feature handlers remain responsible for user-
   facing validation and feedback.
9. **Keyboard input counts as user activity.** Key-down and key-repeat events
   update `UserActivityService` without consuming the event, so keyboard-only
   editing cannot be mistaken for idle time by sync gating.
10. **Native menus are adapters.** macOS File, View, Go, and Help menus use the
    same definitions and dispatcher as in-app shortcuts. Windows and Linux use
    the in-app bindings, palette, and help surfaces. Once the existing
    registrations are migrated, `hotkey_manager` is removed.

The fixed navigation map is semantic rather than dependent on feature flags:
Primary+1 through Primary+8 always mean Tasks, Daily OS, Projects, Habits,
Dashboards, Journal, Events, and Settings. Disabled destinations leave gaps.

## Consequences

- Behavior, native-menu accelerators, palette results, and localized help
  cannot drift independently.
- Contextual commands become ordinary widget lifecycle state instead of
  controller or plugin state.
- Feature surfaces must expose handlers and meaningful focus structure; adding
  a catalog entry alone never makes a pointer-only workflow keyboard usable.
- The migration crosses the app shell, design-system primitives, and every
  major desktop destination. Each slice must ship with focused tests so an
  incomplete registration cannot silently shadow another scope.
- Mobile keeps its existing interaction model. Shared widgets must not regress,
  but mobile hardware-keyboard navigation is not part of this decision.

## Related

- Implementation plan:
  [`2026-07-15_desktop_keyboard_command_system.md`](../implementation_plans/2026-07-15_desktop_keyboard_command_system.md)
- Flutter focus and shortcut primitives are pinned by the repository's FVM
  Flutter SDK.
- Existing native menu adapter: `lib/beamer/desktop_menu.dart`.
- Existing activity gate: `lib/features/user_activity/state/`.

---

### Adr 0031 Batch First Day Audio Capture (`docs/adr/0031-batch-first-day-audio-capture.md`)

# ADR 0031: Batch-First Day Audio Capture and Durable Processing

## Status

Accepted

## Date

2026-07-21

## Context

A Daily OS recording made on a degraded network could be lost entirely: the
capture controller finalized the audio file, ran transcription, and only
created the `JournalAudio` after transcription succeeded. A provider or
network failure left a stopped file with no journal row, no retry path, and
no way for a later planner invocation to rediscover what the user said.
Network-dependent inference sat on the source-data critical path.

Two mechanisms were evaluated and rejected on the way here:

- **Streaming/realtime transcription** (Mistral WebSocket, MLX realtime
  sessions) constrained provider choice to streaming ASR endpoints, accepted
  no dictionary/glossary context, produced reliably worse text for exactly
  the words that matter (proper nouns, domain terms), and its live
  transcript added distraction without value. Its deltas were also
  unreproducible: no stored input meant no re-transcription. Removed
  app-wide.
- **A crash-durable PCM spool with WAV finalization** (built in the closed,
  unmerged PR #3525). Its remaining justification after realtime removal was
  mid-recording crash durability, which is explicitly a non-goal: the
  observed failure mode is network failure after stop, not process death.
  AAC (`.m4a`) is the primary audio format — WAV is ~4x heavier for storage
  and Matrix attachment sync. The spool, PCM chunking, WAV pipeline, and
  spool-recovery surfaces were not ported.

## Decision

### 1. Local-first commit order defines a successful stop

The platform recorder writes a plain `.m4a`. Stop then, in order:

1. persists the `JournalAudio` with a `DayAudioContext` provenance payload;
2. enqueues and claims a durable transcription job in the device-local
   processing outbox; and
3. runs foreground batch transcription through that job's state machine.

A transcription, network, or provider failure after step 1 never loses the
recording: the journal entry stays, the job stays, and the background
runtime owns retries. The UI reports "saved, transcription pending" — never
a successful empty capture. Failure of step 1 itself surfaces as
`audioPersistFailed` and leaves the finished file on disk untouched.

The guarantee is **no recording lost after stop** — not "no audio lost
ever". Mid-recording process death is out of scope by design.

### 2. Session context is fixed before the microphone opens

Each voice session pre-computes: a recording-session id, a deterministic
UUIDv5 `activityEntryId` derived from it, the selected planning day's
`dayId`/`planDate` (the selected workspace, never the wall clock at stop),
the intent (`dayPlan` | `dayRefine`), and the origin host id. This
`DayAudioContext` is stamped onto the `JournalAudio` and denormalized into
indexed journal columns (`day_id`, unique `recording_session_id`), giving
Activity, outbox repair, and agent context bounded indexed lookups.

### 3. Pending transcription lives in a device-local outbox

A checksummed, file-backed job store (deterministic job id per recording
session) with lease/claim semantics, exponential jittered backoff, hard
`retryNotBefore` boundaries, and failure classification
(network/timeout/setup-required/deterministic/…). The runtime drains on
startup, on connectivity restoration, on every repository mutation, and via
periodic probes. Startup repair rebuilds lost jobs from persisted
`dayContext` provenance (skipping other hosts' recordings). Provider output
is persisted before the journal write-back so a local commit failure retries
without repeating inference. User-reviewed text fences the job to succeeded
so pending work never overwrites a human decision.

### 4. Day Activity is a local-first projection

The Day header exposes agenda | schedule | activity. Activity joins day
audio, outbox jobs, check-ins, the drafted plan, and day summaries on
activity ids; cards expose playback, retry, manual reviewed text, AI setup,
and use-to-plan/refine. A no-plan day with entries opens Activity so pending
recordings are the recovery path.

### 5. Recordings are agent-visible without user submission

`DayAudioEntryContextService` reads persisted transcript receipts straight
from journal provenance — deliberately independent of `CaptureEntity` — and
feeds the planner's `day_entries` prompt section, so a later wake discovers
completed offline check-ins immediately.

### 6. Batch transcription is the glossary integration point

`AudioTranscriptionService.transcribe` accepts speech-dictionary terms.
Correction-lexicon/glossary context (ADR 0024) attaches here; retained audio
plus replayable jobs make future re-transcription with a grown glossary
possible. (Follow-up work; not part of this change.)

## Consequences

### Positive

- Recordings survive offline/failed inference end-to-end; retries are
  durable and background.
- One transcription path; any batch-capable provider works; dictionary
  context applies uniformly.
- Deterministic ids make recovery idempotent joins, not heuristics.
- ~5k lines of streaming/spool machinery never enter the codebase.

### Negative and trade-offs

- No live transcript while speaking (measured as low-value; misspelled live
  text was worse than a few seconds' wait).
- A force-quit mid-recording loses that in-flight recording (accepted
  non-goal).
- An `.m4a` whose journal insert failed is on disk but invisible until the
  user re-records; there is no orphan-scan surface (accepted for now).

## Rejected alternatives

- **PCM spool + WAV finalization + crash recovery** — see Context; closed
  PR #3525 remains the reference implementation in git history.
- **Keeping realtime alongside batch** — double transcription stack for a
  preview feature; see Context.
- **Matrix sync outbox as the job queue** — the sync outbox transports
  already-durable entities; it does not represent pending inference.
- **In-memory wake/processing intent** — an app exit must not lose the
  user's request to have a recording transcribed.

## Related

- ADR 0024 (correction lexicon — the glossary integration point)
- ADR 0032 (hierarchical day agents — consumes this substrate; its phase 1
  extends the outbox to plan/parse jobs)
- Closed PR #3525 (spool-based predecessor, unmerged reference)

---

### Adr 0032 Hierarchical Day Agent Coordination (`docs/adr/0032-hierarchical-day-agent-coordination.md`)

# ADR 0032: Hierarchical Day-Agent Coordination

## Status

Accepted (phases 1–5 implemented; phase 6 partially implemented — see the
phase-6 amendment for the split). See Amendments below for where the
implementation diverged from this ADR's original text.

## Date

2026-07-20

## Context

### The problems, grounded in the current implementation

The Daily OS planner is a single durable agent identity,
`daily_os_planner` (`day_agent_service.dart`), that owns every day
workspace under one `AgentIdentityEntity`, one state chain, one execution
lease, and one memory/compaction substrate. ADR 0022 created this shape
deliberately: the earlier one-agent-per-day model reset all learning at
midnight because observations, captures, and compaction memory were keyed by
`agentId`. The collapse fixed learning but reintroduced four structural
problems:

1. **Unbounded context and serialized execution.** State reconstruction folds
   the planner's full observation set on every wake (ADR 0016), and the log
   grows for the lifetime of the identity — ADR 0022's own Consequences
   section flags that collapsing N per-day logs removed the bound the old
   model accidentally had. Worse, all days share one execution lease: a slow
   draft for Tuesday blocks the drain of Wednesday's queued wake.
2. **No per-day visibility.** The full visibility stack exists — durable
   `wake_run_log` rows, synced `WakeTokenUsageEntity` per wake, the
   append-only dialogue log, and the five-tab `AgentInternalsBody` UI
   (Stats / Reports / Conversations / Observations / Activity). But it is all
   keyed by `agentId`, so the planner's per-day work is indistinguishable
   inside one aggregate. There is no per-day wake history, token cost, or
   dialogue view, and no "inspect this day's agent" affordance on the Day
   page.
3. **Volatile processing intent.** `WakeQueue` is in-memory only. A queued
   draft/refine/parse wake dies with the process. ADR 0031's device-local
   processing outbox currently carries only the `transcribeAudio` job kind;
   `parseCapture`, `draftPlan`, and `refinePlan` need the same durability.
4. **Polling UX.** Draft/refine callers poll for a result with a timeout
   (`real_day_agent.dart`); a dropped queue or slow wake surfaces only as a
   timeout error. There is no async "your plan is ready" path, although a
   `dayPlanNotification` notification id already exists.

Additionally, ADR 0022 D12 documents that a single
`AgentState.scheduledWakeAt` cannot hold multiple outstanding day-scoped
wakes — a second day's `set_next_wake` clobbers the first. Per-day identities
dissolve this restriction.

### What the performance data actually says

With hosted models, input token throughput is not the bottleneck: a measured
wake processed ~41K input tokens and generated ~3.2K output tokens in ~16 s.
Shrinking input alone does not make a 16-second call feel snappy. The
levers that matter, in order:

1. **Perceived latency**: async completion with notification instead of a
   blocking wait (problem 4), plus pre-warmed per-day wakes.
2. **Output budget**: focused agents with narrow briefs produce shorter,
   more decisive output; output tokens dominate wall clock.
3. **Cache stability**: byte-stable prompt prefixes per agent. A per-day
   agent's prefix is stable within its day; the monolith's prefix churns as
   other days' state moves.
4. **Parallelism**: per-day leases let two days' wakes run concurrently
   under the existing bounded drain engine (device concurrency 1–8).
5. **Fold cost**: bounded per-day logs keep the ADR 0016 projection fold and
   compaction cheap forever, instead of degrading with planner age.

### What already exists that the hierarchy can reuse

- **Agent kind**: `AgentKinds.day_agent` exists; the wake executor routes by
  kind (`agent_workflow_providers.dart`).
- **Per-day partitioning**: `WakeJob.workspaceKey` = `day:<dayId>` already
  partitions queueing, coalescing, and cancellation per day — half of the
  sharding exists inside the monolith.
- **Day identity**: `dayPlanId(date)` = `dayplan-YYYY-MM-DD`
  (`lib/classes/day_plan.dart`) is a deterministic, date-keyed identity.
- **Scoped compaction**: planner memory already splits into
  `globalObservations | dayCaptures(dayId)` checkpoint scopes, and capture
  events are filtered to the wake's day. The `dayCaptures(dayId)` scope is
  exactly a per-day agent's native log content.
- **Report consumption**: ADR 0003's linked-context contract (distilled
  `agentReportHead` reports, pull-based at the consumer's next wake) is a
  working upward-communication protocol between agents.
- **Commitment substrate**: ADR 0019/0021 attention negotiation
  (`AttentionRequestEntity`, `AttentionAwardEntity`,
  `StandingAgreementEntity`, indexed window projections) is a working
  commitments ledger.
- **User approval gate**: ADR 0006 ChangeSets already make the user the
  final validator of plan mutations.
- **Durable knowledge**: the two-tier, compaction-exempt planner knowledge
  (ADR 0022 D10) and the weekly template-evolution loop are the cross-day
  learning assets that must not be lost.
- **Resilient capture**: ADR 0031's batch-first commit ordering and
  processing outbox guarantee recordings survive offline and are
  rediscoverable by day (`day_entries` section,
  `DayAudioEntryContextService` keyed by `dayId`).

### Constraint from concurrent direction decisions

Two product-direction decisions shape this ADR: realtime transcription has
been removed in favor of batch transcription with glossary/lexicon context
(ADR 0031/0024), and the day is moving toward being a first-class entity
with its own timeline, task-like. This ADR assumes both: per-day agents
consume batch transcripts from the durable outbox, and a day's context is
assembled from day-scoped entries, mirroring the task-agent linked-entry
pattern.

## Decision

### 1. Two roles: a coordinator and per-day agents

The single planner splits into:

- **Coordinator** — the existing `daily_os_planner` identity, retained and
  re-scoped. It keeps cross-day learning (two-tier durable knowledge, weekly
  one-on-one evolution loop), owns the commitments/capacity ledger, issues
  day directives, and consumes per-day reports. It stops executing per-day
  drafting/refining/capture wakes and stops accumulating capture events on
  its log.
- **Per-day agents** — one `AgentKinds.day_agent` instance per day, with the
  deterministic agent id `day_agent:<dayId>` (derived from
  `dayPlanId(date)`), created lazily on first day activity (first check-in,
  first plan request, or coordinator pre-warm). A per-day agent executes
  capture parsing, plan drafting, refinement, and day-status reporting for
  exactly one day. It is a full log-projected agent (ADR 0016): it gets
  wake runs, token usage, dialogue, and the internals UI for free under its
  own id.

Per-day agents are *bounded*, not ephemeral: they are durable identities
whose useful lifetime is naturally capped by the day. After day close and
summary, the agent goes `dormant`. Its distilled value survives it: the
`DaySummaryEntity`, its final report, and observations promoted into
coordinator knowledge. Dormant day agents are retained for
inspection/audit; they are never woken by subscriptions again.

This amends ADR 0022: Decisions 1 and 3 (single identity executes all day
workspaces) are superseded; Decisions 6, 9, 10, 12 (cross-day learning
loops, durable knowledge) carry over to the coordinator unchanged. The
midnight-reset failure that motivated ADR 0022 does not return, because
learning never lived in the per-day agents in this model.

### 2. Communication protocol: events on the synced log, pull-based

No RPC between agents. All coordination flows through durable, synced agent
entities, consistent with ADR 0016/0018/0019.

**Downward — `DayDirectiveEntity`** (new `AgentDomainEntity` variant), keyed
`day_directive:<dayId>`, revisioned (`directiveRevisionId`), written only by
the coordinator:

```text
DayDirectiveEntity {
  dayId / planDate / directiveRevisionId / issuedAt
  commitments: [ { id, source (attentionAward | standingAgreement |
                   userCommitment | carryOver), title, window?,
                   minutes?, evidenceRefs } ]
  capacityBudget: { availableMinutes, energyBands, alreadyScheduledMinutes }
  carryOver: [ { taskId | itemId, reason } ]
  constraints: [ freeform bounded directives, e.g. protected windows ]
  attentionNotes: [ distilled cross-day context relevant to this day ]
}
```

The directive is assembled by the coordinator from the attention-claim
index, standing agreements, committed plan blocks of surrounding days, and
its durable knowledge. It contains **no capture transcripts and no other
day's log content** — only distilled, bounded facts. A per-day agent reads
the newest directive revision at wake start via an indexed projection
(same pattern as `getAttentionClaimsForTarget`).

**Directive bindingness.** Directives are binding constraints, not hints:
the per-day agent's prompt contract requires each commitment in the
directive to be either (a) represented in the plan, (b) explicitly traded
away in a proposed ChangeSet the user must approve, or (c) escalated. It
may not silently drop a commitment. The user remains the final validator of
whether work actually happened — agents validate plans, humans validate
reality.

**Upward — three channels, all existing patterns:**

1. **Distilled report** via the existing `agentReportHead` mechanism
   (ADR 0003): one-liner + tldr, consumed by the coordinator pull-based at
   its next wake (ADR 0027 propagation).
2. **`DayStatusEvent`** appended to the per-day agent's log with a
   coordinator-indexed projection: `onTrack | attentionNeeded(reasons) |
   dayClosed`. `attentionNeeded` carries typed reasons
   (overCommitted, directiveUnsatisfiable, userDivergence,
   processingBlocked).
3. **Promotable observations**: the per-day agent tags observations
   `promotionCandidate`; the coordinator's daily digest wake reviews the
   day's candidates and folds accepted ones into its own observation log
   (feeding the existing weekly knowledge-promotion loop). Promotion is a
   coordinator decision, not an automatic copy — this is the throttle that
   keeps the coordinator log bounded.

### 3. Pushback is a capacity reconciliation, not a personality trait

Pushback ("you already committed to X; adding Y is not realistic") becomes a
deterministic input plus a judgment call, in that order:

- The directive gives the per-day agent the commitments ledger and capacity
  budget as structured data.
- On any request that adds work (new capture item, refine instruction), the
  agent's contract requires reconciling requested minutes against
  `capacityBudget` minus committed minutes before drafting. The arithmetic
  is in context; the model does not need to remember cross-day history —
  the coordinator already distilled it.
- If the request does not fit, the agent must respond with the conflict made
  explicit (which commitments collide, what trade would make it fit) and
  propose the trade as a ChangeSet rather than silently overpacking the
  plan.
- Cross-day pushback ("that's Thursday's third big commitment this week")
  is the coordinator's job, expressed in `attentionNotes` of the directive
  ahead of time, or raised at digest time as a next-day directive change.

The coordinator maintains the ledger from: attention awards and standing
agreements (ADR 0019/0021), committed `PlannedBlockState.committed` blocks
across the week's `DayPlanEntity` heads, and explicit user commitments it
observed in reports. No new bookkeeping agent state is invented; the ledger
is a projection over existing entities plus directive persistence.

### 4. Context budgets and caching

**Per-day agent prompt** (target ≤ ~12K input tokens, byte-stable prefix
first):

1. System prompt (soul + operational directives) — stable
2. `day_id` / `plan_date` — stable
3. `knowledge_index` (coordinator-published Tier-1 hook index) — stable
4. `day_directive` (newest revision, bounded) — stable within revision
5. `day_log` — this day's captures + own observations only (the
   `dayCaptures(dayId)` scope becomes the agent's native log; no scope
   machinery needed for foreign days because foreign days are other agents)
6. `day_entries` — ADR 0031 §15 provenance/status index (32 items / 4 KiB)
7. Mode block (`capture` | `drafting` | `refine`) — per-wake
8. Trigger tokens, current local time — volatile tail

Compaction hysteresis budgets shrink accordingly (a day's log rarely needs
50K/20K; concrete values fixed in the implementation plan). Tier-2
`knowledge_statements` are included scope-filtered exactly as today.

**Coordinator prompt**: knowledge index and statements, compacted
global-observations log, the report index of recent per-day agents
(one-liner/tldr, not dialogues), `week_ahead`, the commitments ledger, and
day-status events since its last wake. Never a capture transcript. The
coordinator's log growth rate drops to distilled-events-only, which is the
structural fix for its unbounded fold cost.

**Pre-warming**: the coordinator's morning routine (or a fixed schedule)
issues the day's directive and a scheduled pre-warm wake for that day's
agent before the user's typical check-in time, using per-agent
`ScheduledWakeEntity` records. Because each day agent has its own
`scheduledWakeAt`, the ADR 0022 D12 clobbering constraint disappears.

### 5. Durable processing intent and async UX

- `parseCapture`, `draftPlan`, and `refinePlan` become durable jobs in the
  device-local processing outbox (with AgentDb-side effect claims for
  agent-owned outputs), extending ADR 0031's transcription-only job model.
  The in-memory `WakeQueue` remains what it is: an execution scheduler, not
  an intent store. A process kill loses no requested plan work.
- Draft/refine polling in `real_day_agent.dart` is replaced by an
  event-driven completion path: wake completion milestone → provider
  invalidation → Activity timeline card state change → local notification
  (`dayPlanNotification`) when the app is backgrounded. The Day Activity
  timeline (ADR 0031 §14) is the progress surface: "drafting your plan"
  cards with durable status, never a modal spinner with a timeout.
- Batch transcription (with correction-lexicon/glossary context per
  ADR 0024) feeds the same pipeline: transcript receipt → per-day agent
  wake. Recordings remain discoverable by day through ADR 0031's provenance
  columns regardless of any downstream failure.

### 6. Visibility

Per-day agents inherit the complete existing stack keyed by their own id:
`wake_run_log`, `WakeTokenUsageEntity`, dialogue log, `AgentInternalsBody`,
pending-wakes UI. Additions are thin:

- An "Inspect day agent" affordance on the Day page routing to
  `AgentDetailPage(day_agent:<dayId>)`.
- Day-page badge summarizing the day agent's last wake status and per-day
  token spend (query by agent id — no new storage).
- The coordinator remains inspectable as today under `daily_os_planner`;
  its Conversations tab becomes readable again because per-day noise no
  longer lands there.

### 7. Persona mapping

The coordinator carries the persistent persona — the stable face, soul, and
voice the user builds a relationship with. Per-day agents run under the same
soul/template (the same character doing focused work on a specific day), so
the product surface presents one assistant delegating, not a cast of
strangers. Character animation states map to observable runtime facts:
idle (no pending wakes), working (running wake for the visible day),
attention (newest `DayStatusEvent` is `attentionNeeded`), celebrating
(day closed on-track). Distinct visual personas per day agent are
explicitly out of scope until the two-role model has proven itself.

### 8. Migration

Proof-based, following ADR 0031 §15/§17 discipline:

- Existing `dayCaptures(dayId)` checkpoints and day-scoped capture events
  seed the corresponding new per-day agent's log for recent/open days;
  older days get agents only on demand (user opens the day) — never a bulk
  backfill of years of days.
- `globalObservations` checkpoints, durable knowledge, and the evolution
  loop stay with the coordinator untouched.
- Legacy mixed/unscoped checkpoints remain excluded from new day wakes.
- `DayPlanEntity`/`DaySummaryEntity` ids are already day-keyed and remain
  valid; the writing agent changes, the entities do not.
- Existing wake-run history under `daily_os_planner` stays where it is;
  history is not rewritten.

## Consequences

### Positive

- Per-day context is bounded forever; the coordinator's log grows at
  distilled-event rate instead of transcript rate. Projection folds and
  compaction stay cheap regardless of app age.
- Per-day execution leases unlock concurrent wakes across days and remove
  cross-day head-of-line blocking.
- Per-day visibility (wakes, tokens, dialogue) falls out of the identity
  model with near-zero new infrastructure.
- Plan-processing intent becomes durable; the recording-loss class of bugs
  stays closed end-to-end (capture already durable via ADR 0031).
- Pushback becomes grounded in a structured ledger rather than the model's
  recollection, making it consistent and auditable.
- The pre-warm/scheduling model is simpler and per-day (D12 constraint
  gone).

### Negative and trade-offs

- **Distillation risk**: the per-day agent knows only what the directive
  and its own day contain. A weak coordinator digest produces weak
  directives and the day agent cannot compensate. Directive quality becomes
  a first-class testable artifact.
- **Coordination lag**: the coordinator learns of a day's outcome at its
  next wake, not instantly. Same-day cross-day reactions (e.g. "move
  tomorrow's commitment because today collapsed") arrive on the digest
  cadence unless a `DayStatusEvent(attentionNeeded)` triggers a coordinator
  subscription wake.
- **More identities**: agent-instance proliferation (365/year). Mitigated
  by lazy creation, dormancy, and on-demand instantiation for old days —
  but instance listing UIs need day-agent grouping/filtering.
- **Potentially more total token spend**: two-role coordination adds
  coordinator digest wakes. Expected to be offset by smaller per-wake
  contexts and rarer monolith mega-wakes; must be measured via the existing
  per-template token stats.
- **Two-hop information flow** adds protocol surface (directive +
  status/report) that must be versioned and tested like any API.

## Rejected alternatives

### Keep the monolith, compact harder

Scoped compaction (ADR 0031 §15) already exists and the fold/lease/
visibility problems persist structurally. Compaction cannot shard an
execution lease or un-mix a token-usage aggregate.

### Stateless per-wake day workers (no identity)

Cheapest contexts, but no durable log means no wake history, no dialogue
visibility, no per-day token attribution, and no place for the day's own
observations — it re-creates the debugging blindness this ADR exists to
fix.

### Direct agent-to-agent messaging (RPC)

Contradicts the log-projection architecture (ADR 0016/0018): un-synced,
un-replayable, race-prone. Bids/reports as durable events already proved
out in ADR 0019/0021.

### Per-day agents with their own learning (the pre-ADR-0022 model)

Already failed: learning keyed to a day-scoped identity resets daily. The
coordinator exists precisely to give learning a durable home.

### Matrix sync outbox as the job queue

Already rejected in ADR 0031: the sync outbox transports durable entities;
it does not represent pending inference.

## Open questions

1. **Coordinator wake cadence** — pure digest (morning directive + evening
   review) vs. also subscribing to `DayStatusEvent(attentionNeeded)` for
   same-day reaction. Proposed: digest + attention-subscription, throttled.
2. **Multi-day queries** ("how was my week?") — coordinator answers from
   reports/summaries, or a transient fan-out reader. Proposed: coordinator
   answers; it owns cross-day state.
3. **Journal `DayPlanEntry` vs agent `DayPlanEntity`** — both exist in the
   codebase; the exact runtime split (which surfaces read which) needs a
   focused exploration before the implementation plan fixes the write path.
4. **Day-as-entity convergence** — if the day becomes a first-class
   task-like entity with a linked-entry timeline, the per-day agent should
   consume the generic linked-entry context contract (ADR 0003) instead of
   Daily-OS-specific projections. Sequencing between that migration and
   this ADR must be decided in the implementation plan.
5. **Retention/pruning** of dormant day agents' full dialogue logs (keep
   forever vs. compact-to-summary after N days). Token-usage rows are small
   and synced; dialogues are the bulk.
6. **Directive authorship boundaries** — whether the user can edit a
   directive directly (making it a shared contract document) or only
   influence it through commitments/agreements.

## Implementation roadmap (high level)

Phased so every phase ships value alone; new code takes no dependency on
code it is scheduled to replace.

1. **Durable agent jobs** — implement `parseCapture` / `draftPlan` /
   `refinePlan` outbox job kinds with AgentDb-side effect claims; replace
   draft/refine polling with completion events + `dayPlanNotification`.
   Pure resilience/UX win, independent of the agent split.
2. **Per-day agent kind** — `day_agent:<dayId>` identity creation, workflow
   executing capture/draft/refine against the day-scoped log; seed from
   `dayCaptures(dayId)` scopes; wire wake routing by kind. Coordinator
   untouched; the monolith stops receiving new per-day wakes day-forward.
3. **Directive + status protocol** — `DayDirectiveEntity`,
   `DayStatusEvent`, report consumption in the coordinator digest wake;
   pushback contract in the per-day prompt; coordinator stops assembling
   per-day mode blocks entirely.
4. **Visibility surface** — Day page "Inspect day agent" + status badge;
   instance grouping in Settings > Agents.
5. **Pre-warm + persona** — morning directive/pre-warm schedule per day
   agent; map character states to wake/status facts.
6. **Coordinator slimming + migration cleanup** — remove per-day sections
   from the coordinator prompt, verify its log growth is distilled-only,
   and measure token spend before/after via template token stats.

## Amendments (phases 1–2 implementation)

Recorded where the shipped implementation diverged from this ADR's original
text, discovered while implementing rather than corrected by rewriting the
Decision section in place.

- **No `globalObservations` / `dayCaptures(dayId)` checkpoint scopes exist.**
  §"What already exists" claimed scoped compaction checkpoints as reusable
  substrate; the codebase only ever had one checkpoint chain per `agentId`
  plus a runtime day-filter over `CaptureEntity` rows. There was nothing to
  seed a new per-day agent's log *from* — see the next point.
- **Migration is day-forward cutover, not seeding.** §8 proposed seeding a
  new per-day agent's log from existing checkpoints/capture events for
  recent/open days. Since no such checkpoints exist, and re-parenting
  captures/observations onto a new identity is itself risky, the shipped
  rule is simpler: `DayAgentService.getOrCreateDayAgentForDate` creates a
  fresh `day_agent:<dayId>` identity only for days the coordinator does not
  already own (no existing plan or capture under the coordinator for that
  day). Every day the coordinator already touched — all history up to the
  cutover — stays under the coordinator's identity permanently. No data
  migrates.
- **`day_agent` kind is shared, not new.** §"What already exists" undersold
  this: `AgentKinds.dayAgent` was already the *only* kind the monolithic
  planner ran under. Per-day agents reuse the identical kind and workflow
  (`DayAgentWorkflow`); the coordinator and per-day agents are distinguished
  by id shape (`daily_os_planner` vs. `day_agent:<dayId>`, see
  `day_agent_identity.dart`), not by kind.
- **Knowledge stays coordinator-keyed, always.** §4 said the per-day prompt's
  knowledge index is "coordinator-published"; implemented literally: durable
  knowledge is read under `dailyOsPlannerAgentId` on every wake (coordinator
  or per-day), and a per-day agent's `propose_knowledge` tool calls persist
  under the coordinator's id too — there is no per-day knowledge store.
- **Directive/status protocol (phase 3) shipped with four deviations from
  this ADR's text.** (1) Upward channel 1 is day summaries, not
  `agentReportHead`: day agents never wrote `AgentReportEntity`, and the
  coordinator's `<recent_days>` week context already consumes
  `DaySummaryEntity` per day — a parallel report chain would duplicate that
  artifact. (2) Upward channel 3 (`promotionCandidate` observations) was
  unnecessary: `propose_knowledge` is coordinator-keyed even on per-day
  wakes, so promotion-with-user-throttle already exists. (3)
  `DayDirectiveEntity` needs no indexed projection — `day_directive:<dayId>`
  is a deterministic PK read like `DayPlanEntity`; only `DayStatusEventEntity`
  gets a query (`getDayStatusEventsSince`, served by an existing index).
  (4) The digest cadence is re-armed deterministically by code (completion
  re-arm + startup bootstrap), not by the model's `set_next_wake` — a digest
  that forgets to self-schedule cannot break the cadence. The
  `attentionNeeded` same-day subscription (open question 1) is deferred:
  phase 3 ships digest-cadence consumption only.
- **Phase 4 shipped thinner than proposed.** The Day page's "Inspect agent"
  menu entry and Settings > Agents Type-based instance filtering/grouping
  already existed before this phase. Net-new: the day-header status chip
  (`DayAgentStatusChip`) surfacing the persona state with the per-day token
  spend in its tooltip (per-day identities only — a coordinator-owned day
  shows no spend, since the coordinator's lifetime aggregate would
  misattribute other days), tappable straight into the agent internals.
- **Phase 6 splits three ways.** (a) *Distilled-only log growth* is
  implemented and verified: digest wakes assemble the digest block instead
  of per-day mode blocks, and a regression test pins that a digest persists
  only distilled entities (dialogue messages/payloads, state, the
  next-digest record) — never captures, plan mutations, or change sets
  under the coordinator's id. (b) *Token measurement* needs no new tooling:
  `WakeTokenUsageEntity` rows are agent-keyed, and the template detail
  page's per-instance token breakdown already separates the coordinator
  from every `day_agent:<dayId>` instance, so the before/after comparison
  reads directly from that surface as post-split usage accrues. (c)
  *Removing per-day prompt sections from the coordinator* is the one part
  deliberately deferred: pre-cutover days the coordinator owns still need
  capture/draft/refine blocks for retroactive work, so the sections stay
  until those days recede — or until a decision to force-complete the
  cutover (drop the `_plannerOwnsDay` fallback; reads already span owners
  via `isDailyOsDayOwner`), which would reverse this ADR's day-forward
  migration choice and needs its own sync-convergence review.
- **Weekly rollups added beyond the ADR text (digest pooling).** The digest's
  aggregation was extended past what this ADR specified: each digest wake
  maintains `WeekRollupEntity` registers (`week_rollup:<Monday>`,
  coordinator-owned) for the last 4 complete weeks — planned/recorded
  minutes per category plus days-with-plans, recomputed deterministically
  from day plans and recorded time (`ensureWeekRollups`: EVERY week
  recomputed from source on every digest — that is what makes plain LWW
  converge, since late-synced data and cross-device LWW races self-heal at
  the next digest; two spanning batch reads bound the cost, unchanged
  aggregates skip the write, tombstones never resurrected). Rendered as
  `<recent_weeks>` on digest wakes only, giving the coordinator month-scale
  pacing signal without re-reading a month of raw entities — the pooled
  counterpart to the severity-ranked status-event selection above.
- **Phase 5 is a mapping, not a scheduler or renderer.** Pre-warm is the
  deterministic digest re-arm plus the per-day agent's self-scheduled
  `set_next_wake` (both existed after phase 3); no separate pre-warm
  scheduler was added. Persona is `dayAgentPersonaStateProvider`, deriving
  §7's states (idle | working | attention | celebrating) from runtime facts
  (running wake, newest `DayStatusEventEntity`); the `character` feature has
  no Daily OS consumer yet, so the provider is the contract the animation
  binds to when it lands. Distinct visual personas stay out of scope.
- **No dormancy automation.** §1 described bounded-not-ephemeral per-day
  agents going `dormant` after day close. No day-close lifecycle exists yet
  (shutdown/reflection tools are still mocked in `RealDayAgent`), so per-day
  agents simply stay `active` indefinitely once created — an accepted
  follow-up, not a regression, since nothing today would trigger dormancy
  correctly.
- **Phase 1 durable jobs initially covered `draftPlan`/`refinePlan`, not
  `parseCapture`.** The `DayProcessingJobKind.parseCapture` job kind,
  `DayProcessingOutboxRepository.enqueueParseCapture`, and the executor's
  dispatch for it shipped implemented and tested in the first slice, but
  `DayAgentCaptureService`'s capture-submit path still enqueued a volatile
  wake directly via `WakeOrchestrator.enqueueManualWake`. This was closed in
  the follow-up slice: `submitCapture` and `retryCapture` now enqueue the
  durable `parseCapture` job (plus a deferred runtime nudge), and
  `enqueueParseCapture` re-arms a stuck or terminal job with fresh attempts
  while attaching to a queued/running one — which is what makes
  `retryCapture` restart-safe without a separate retry API.

## Related

- ADR 0048 (one device runs the coordinator digest — decides which device
  performs the digest this ADR schedules)
- ADR 0022 (long-lived planner — amended by this ADR)
- ADR 0023 (durable domain agents — coordinator remains the negotiation
  counterparty)
- ADR 0031 (batch-first capture/processing — extended, not changed)
- ADR 0003 (linked-context/report contract), ADR 0006 (ChangeSet gate),
  ADR 0016/0017/0018 (log projection, compaction, convergence),
  ADR 0019/0021 (attention negotiation), ADR 0024 (correction lexicon),
  ADR 0027 (wake propagation), ADR 0028 (day summaries)
- Closed PR #3525 (spool-based predecessor, unmerged reference)

---

### Adr 0033 Learning Verification Checkpoint Policy (`docs/adr/0033-learning-verification-checkpoint-policy.md`)

# ADR 0033: Learning Verification Checkpoint Policy

- Status: Proposed
- Date: 2026-07-21

## Context

Learning quizzes are learner-initiated: the user starts one from a task, the
questions are tailored to that task's content, and questions are not usually
repeated on a schedule. Automatic delivery is at most a later convenience.
The triggering policy therefore has to be small, deterministic, and
respectful of the user's attention — not a cross-device scheduling system.

## Decision

1. **Manual first, on every task.** "Check my understanding" is available on
   any task, whether or not an agent worked on it. Preconditions: the task
   has quizzable content, inference is configured for its category, and no
   other quiz for the task is awaiting answers. The UI mints a
   `quizRequestId` once per action and reuses it through retries.
2. **Depth is a user choice.** Quick check (~3 questions) or deep dive
   (~6–8); thin content yields fewer questions, never filler.
3. **No eligibility machinery for manual quizzes.** No cooldowns, priority
   scores, or spacing checks.
4. **Automatic suggestions are a later, feature-flagged phase.**
   Deterministic triggers only (a task with substantial content is completed,
   or a change set resolves), simple local guards (foreground, not recording,
   no open quiz), at most two suggestions per rolling week, and
   snooze/dismiss/disable controls. A suggestion runs zero inference before
   acceptance.
5. **Suggestion identity is event-scoped and dedup is best-effort.** A
   suggestion's deterministic ID derives from its triggering event — the
   task's completion transition or the resolved change set — so each
   trigger yields at most one suggestion and retries collapse. Suggestion
   facts sync as ordinary agent events; a rare duplicate card across
   offline devices resolves on sync. No lease or delivery election.
6. **Quizzes never gate anything** and never use push notifications.
7. **Repeat quizzes are user actions.** "Quiz me again" generates fresh
   questions. There is no spaced-repetition scheduler.

## Consequences

- The policy is a handful of pure functions over projection state and
  settings, unit-testable without simulators.
- Rare duplicate suggestion cards are accepted in exchange for having no
  coordination protocol; the weekly cap is likewise evaluated against
  locally synced events, so concurrent offline devices can transiently
  exceed it before converging.
- Without scheduled reviews, retention relies on the user choosing to
  re-quiz; revisit if usage shows demand for scheduling.

## Related

- [Implementation plan](../implementation_plans/2026-07-18_learning_understanding_verification_agent.md)
- [ADR 0034: Hybrid Understanding Evaluation](./0034-hybrid-understanding-evaluation.md)
- [ADR 0035: Learning Verification Session Persistence](./0035-learning-verification-session-persistence.md)
- [ADR 0036: Learning Understanding Rating](./0036-learning-understanding-rating.md)

---

### Adr 0034 Hybrid Understanding Evaluation (`docs/adr/0034-hybrid-understanding-evaluation.md`)

# ADR 0034: Hybrid Understanding Evaluation

- Status: Proposed
- Date: 2026-07-21

## Context

Rules can validate structure but cannot judge free-form prose; an LLM can,
and quiz grades are accepted as clearly-labeled AI feedback rather than
calibrated measurements. What still needs defending: questions and grades
must stay grounded in a fixed snapshot of the task's content, model calls
must be tool-less and treat all content as untrusted data, invalid model
output must never render as a result, and a one-shot question/answer
exchange is often too blunt — the grader should probe before judging, the
way a tutor would.

## Decision

1. **Freeze evidence first.** Starting a quiz captures an immutable snapshot
   of the task's content as sections with stable IDs and digests; truncation
   and missing sources are recorded. Generation and grading read only the
   snapshot.
2. **One tool-less generation call** returns a schema-constrained quiz
   tailored to the content: question count scaled to depth and richness,
   multiple-choice items (options, exactly one keyed answer, explanation,
   citations) and open items across explain/predict/apply/debug/compare.
3. **Deterministic validation gates the quiz**, not a second model: schema,
   citation resolution, key membership, option uniqueness, count bounds. One
   repair call is allowed; then a typed failure event with retry UI.
4. **Grading is conversational.** Multiple choice is scored against the
   frozen key in code. Each open answer goes to a tool-less grader call with
   the snapshot, frozen item, and item thread; it returns either a follow-up
   probe (at most two per item) or a verdict with what was missed. The user
   can end probing ("just tell me"), skip, or reveal; revealed-before-answer
   items are excluded from scores but still explained.
5. **The LLM's grade is the grade**, subject only to schema and range checks;
   there is no calibration corpus or cleared-slice gate. Deterministic code
   computes the session aggregate per ADR 0036.
6. **Injection resistance stays**: no tools, network, or write capability;
   snapshot text, answers, and transcripts are delimited untrusted data;
   outputs are schema-constrained and citation-checked; no chain-of-thought
   is requested or persisted.
7. **Voice answers** use the existing transcription pipeline; the editable
   transcript is the answer of record, with modality stored on the attempt.
8. **Failures preserve answers.** Answers are durably appended before any
   grading call; generation or grading failure produces a typed event and a
   retry affordance, never a lost answer or a fabricated result.

## Consequences

- A quiz costs one generation call plus roughly one grading conversation per
  open item.
- Grades are uncalibrated model judgment; the mitigations are probing before
  verdicts, skip/regenerate/reveal controls, and honest labeling.
- An item's record is a small event thread (answer, probes, verdict) rather
  than a single row.

## Related

- [Implementation plan](../implementation_plans/2026-07-18_learning_understanding_verification_agent.md)
- [ADR 0033: Learning Verification Checkpoint Policy](./0033-learning-verification-checkpoint-policy.md)
- [ADR 0035: Learning Verification Session Persistence](./0035-learning-verification-session-persistence.md)
- [ADR 0036: Learning Understanding Rating](./0036-learning-understanding-rating.md)

---

### Adr 0035 Learning Verification Session Persistence (`docs/adr/0035-learning-verification-session-persistence.md`)

# ADR 0035: Learning Verification Session Persistence

- Status: Proposed
- Date: 2026-07-21

## Context

A quiz session is interactive and multi-turn: evidence is frozen, questions
are generated, answers and probe rounds accumulate, grades arrive, and the
session completes or is abandoned. That history must survive restarts, sync
across the user's devices, and stay reproducible (which question was asked
against which content). Lotti's agent framework already provides the needed
machinery: the append-only `AgentMessageEntity`/`AgentLink` causal log
(ADR 0016), immutable artifacts written atomically through
`AgentSyncService`, vector clocks, and convergent multi-device execution
(ADR 0018). Learning data deliberately adds no trust layer of its own — sync
runs among the user's own devices, and quiz history is no more sensitive
than the journal content it derives from.

## Decision

1. **One verifier agent per category.** Add
   `AgentTemplateKind.learningVerifier`; a deterministic agent identity
   (UUID v5 over the scope) per category owns that category's quiz sessions
   and selects the inference profile and privacy route. Tasks without a
   category use a single default scope. Audit every exhaustive
   `AgentTemplateKind` switch.
2. **Typed events, ordinary log semantics.** A versioned
   `LearningQuizEventEnvelope` in `AgentMessageMetadata` with a closed
   union: `quizRequested`, `quizGenerated`, `quizGenerationFailed`,
   `quizStarted`, `itemAnswered`, `itemProbed`, `itemGraded`,
   `itemGradingFailed`, `itemSkipped`, `itemRevealed`, `quizCompleted`,
   `quizAbandoned`, `suggestionOffered`, `suggestionDismissed`,
   `quizDeleted`. A quiz completes when every item is graded, skipped, or
   revealed. Causal order comes from the message DAG; timestamps are
   ordinary `createdAt` values.
3. **Immutable artifacts, referenced by events.**
   `LearningQuizSessionEntity` (per-run anchor, ID equal to its
   `quizRequestId`, task ref, scope, depth choice; no status field —
   lifecycle is projected), `LearningEvidenceSnapshotEntity` (sectioned
   content with digests and truncation markers), `LearningQuizDefinitionEntity`
   (frozen items, keys, citations, generator provenance),
   `LearningQuizAttemptEntity` (answer or probe reply with modality),
   `LearningQuizItemGradeEntity`, and `LearningQuizAssessmentEntity`. Typed
   links: session → task/snapshot/definition; attempt, grade, and
   assessment → session. Items are rows inside the immutable definition
   artifact, not entities; every attempt and grade identifies its item by
   definition digest, item ID, and round ordinal in its payload.
4. **Identity.** `quizRequestId` is minted once per UI action and reused
   through retries. Content-addressed artifacts are UUID v5 over the owning
   `quizRequestId` plus canonical payload — session-scoped, so identical
   content in two sessions yields distinct artifacts — and
   insert-or-verify-identical on sync; attempts are UUID v4 and never
   deduplicated. A session with any attempt wins presentation over
   unengaged siblings; equally unengaged siblings converge on the lowest
   definition digest.
5. **Device-local boundaries.** Answer drafts and raw audio awaiting
   transcription stay local; audio is discarded after transcript acceptance
   unless explicitly kept as a journal audio entry.
6. **Deletion is the app's normal deletion.** `quizDeleted` covers a
   session, task, or category selector; projections hide covered history and
   devices purge covered payloads on observing it. Because artifact
   identity is session-scoped, purging a covered lineage can never strand
   references held by another session. History is exportable with agent
   data.
7. **Projections are rebuildable** from the log: session-detail timeline
   (questions, answers, probes, grades, assessment in causal order), open
   sessions, per-task and per-category history.

## Consequences

- Persistence is a modest extension of existing agent entities — no new
  infrastructure layer.
- A hostile sync peer could forge learning events; that is the same accepted
  trust boundary as every other synced Lotti entity.
- Clock skew can misorder cross-session display; causal links keep
  per-session order correct, which is what matters.

## Related

- [Implementation plan](../implementation_plans/2026-07-18_learning_understanding_verification_agent.md)
- [ADR 0016: Agent-Derived State as a Projection of the Append-Only Log](./0016-agent-state-as-log-projection.md)
- [ADR 0018: Convergent Multi-Device Execution](./0018-convergent-multi-device-execution.md)
- [ADR 0033: Learning Verification Checkpoint Policy](./0033-learning-verification-checkpoint-policy.md)
- [ADR 0034: Hybrid Understanding Evaluation](./0034-hybrid-understanding-evaluation.md)
- [ADR 0036: Learning Understanding Rating](./0036-learning-understanding-rating.md)

---

### Adr 0036 Learning Understanding Rating (`docs/adr/0036-learning-understanding-rating.md`)

# ADR 0036: Learning Understanding Rating

- Status: Proposed
- Date: 2026-07-21

## Context

A grade should tell the learner two things: roughly how the quiz went, and —
more importantly — exactly what they missed. Grades are direct LLM judgment
presented as formative AI feedback about one session. Honesty rules keep
them from reading as credentials, and machine grades stay separate from
Lotti's subjective journal ratings (`RatingEntry`), whose semantics differ.

## Decision

1. **Per-item results.** Multiple choice is `correct` or `incorrect` by key
   comparison and scores 100 or 0. Open items get a grader verdict of
   `correct`, `partial`, or `missed` plus a 0–100 item score, issued after
   probe rounds conclude.
   Every non-correct item gets a "what you missed" explanation citing the
   evidence sections it comes from. `skipped` and `revealed` items are
   excluded from score arithmetic but still explained.
2. **Session grade in code.** Weighted mean of answered items
   (multiple-choice weight 1, open weight 2, each item contributing its
   0–100 score), rounded to the nearest integer so the bands are
   exhaustive, labeled **Solid grasp** (≥ 85), **Getting there** (60–84),
   **Needs review** (< 60). Weights, rounding, and bands are versioned
   hypotheses stored with the assessment. A session with
   nothing answered gets explanations, no score.
3. **Grading guidance lives in the prompt, not the schema**: judge
   correctness, mechanism, completeness, and boundaries; assess content
   rather than grammar, accent, brevity, or jargon; allow stated uncertainty
   without penalty; probe rather than guess.
4. **Feedback-first presentation.** Strengths, then the gap list, then the
   per-item review, then score and label. Grades are visibly AI-issued and
   session-scoped ("in this quiz"); numeric scores can be hidden by
   preference. **This grade seems wrong** records the disagreement; nothing
   is silently regraded.
5. **No comparison, no gating, no streaks.** Never compared across users,
   never a leaderboard, never gates a workflow, never trended across quizzes
   as if equated.
6. **Separate storage, plain lifecycle.** Grades live in the learning
   entities (ADR 0035), never in `RatingEntry`; history is private,
   exportable, and deletable. Neither generator nor grader may emit review
   dates; re-quizzing and reminders are user actions.

## Consequences

- Learners get a legible outcome (score, label, gap list) with tutor-style
  depth from probing, at the cost of psychometric rigor; results are
  disclosed as AI judgment.
- Gap explanations carry the detailed-feedback weight instead of a
  persisted rubric lattice.
- If scheduled review is ever added, it must be built on these session
  facts; nothing here presumes it.

## Related

- [Implementation plan](../implementation_plans/2026-07-18_learning_understanding_verification_agent.md)
- [ADR 0033: Learning Verification Checkpoint Policy](./0033-learning-verification-checkpoint-policy.md)
- [ADR 0034: Hybrid Understanding Evaluation](./0034-hybrid-understanding-evaluation.md)
- [ADR 0035: Learning Verification Session Persistence](./0035-learning-verification-session-persistence.md)
- [Flexible rating system plan](../implementation_plans/2026-02-09_flexible_rating_system.md)

---

### Adr 0037 Relationship On Device Storage And Privacy (`docs/adr/0037-relationship-on-device-storage-and-privacy.md`)

# ADR 0037: Relationship Data Stays On-Device

- Status: Accepted — implemented by plan v2 phases 1-8. The on-device
  stance, the `private`-covers-the-whole-person rule and the delete
  cascade all shipped as specified; the privacy policy states them in
  §Relationships and check-ins.
- Date: 2026-07-22

## Context

Relationship management makes Lotti store observations about third parties:
who the user knows, when they interacted, what was discussed, how the
interaction felt, and what to watch out for next time. This is the most
sensitive data class the app will hold — more sensitive than the user's own
journal, because the data subjects are other people who never consented to
being described. Handing that data to a third-party service would be
irresponsible; the feature is only acceptable under the app's existing
privacy posture.

That posture already exists (see `PRIVACY.md`): all data lives in local
SQLite databases, there is no Lotti cloud service and no telemetry, and the
only way data leaves a device is the optional end-to-end encrypted Matrix
sync between the user's own devices, with keys exchanged via QR code and
never transmitted. Journal entities sync payload-agnostically
(`SyncMessage.journalEntity` in `lib/classes/sync/sync_message.dart`),
so new entity types inherit this posture automatically. AI inference can run
fully locally (Ollama, OMLX/MLX — `InferenceProviderType` in
`lib/classes/ai/ai_config.dart`) or against a cloud provider the user
configured with their own API key.

Under GDPR, a private individual keeping personal notes about their own
relationships falls under the household exemption (Art. 2(2)(c)) — but only
as long as the processing stays personal. Software that silently ships such
notes to a vendor's servers would break that framing and turn the vendor
into a processor. Lotti must therefore never receive or retain relationship
data, and any cloud AI use must be an explicit, user-configured choice.

## Decision

1. **Local journal storage only.** Relationship entities and check-ins are
   `JournalEntity` subtypes stored in the existing `journal` table
   (serialized-JSON-in-column, ADR 0038). No new storage layer, no external
   service, no Lotti-operated backend. Reminders live in the existing local
   `NotificationsDb`; briefings are agent reports in the agent database.
2. **Sync stays opt-in and end-to-end encrypted.** Relationship data rides
   the existing payload-agnostic Matrix sync between the user's own devices.
   No server ever sees plaintext; users who never configure sync keep the
   data on a single device.
3. **No Lotti-side retention anywhere.** No telemetry, analytics,
   or crash payloads ever include relationship data. Executive briefings
   (ADR 0040) default to local inference; a cloud provider is used only when
   the user has explicitly configured one and selected it via an inference
   profile, requests are transient, and the UI states which provider will
   see the data before the user triggers a briefing. Retention at a cloud
   provider is governed by the user's own account with that provider — Lotti
   adds no storage of its own. Provider-setup guidance steers users toward
   GDPR-compliant providers with zero-data-retention terms, under which a
   cloud briefing is transient processing and nothing is stored outside the
   user's devices.
4. **The `private` flag applies.** Relationships and check-ins honor the
   existing `Metadata.private` semantics, so they can be excluded from
   surfaces that respect the private filter.
5. **Deletion and export are local and complete.** Relationship entities use
   the app's normal soft-delete + purge lifecycle. Deleting a relationship
   also deletes its linked check-ins, its agent reports, and any pending
   reminder rows — the cascade is explicit so no orphaned data about a
   person survives. Relationship data is included in the existing full data
   export. This makes the data-subject rights that matter (erasure, access,
   portability) trivially implementable, entirely on-device.
6. **Document the stance.** `PRIVACY.md` gains a short section on
   relationship data restating the above; the manual page states it in user
   terms.

## Consequences

- No server-side capability exists by design: reminders must be computed and
  scheduled on-device (ADR 0039), and there is no push infrastructure.
- Briefing quality on the default local-inference path is bounded by local
  model capability; users trade that off knowingly when selecting a cloud
  profile.
- The deletion cascade (check-ins, reports, notifications) is a real
  implementation obligation, not just policy prose, and needs tests.
- Because Lotti never receives the data, the GDPR household exemption
  framing holds: the user remains the sole controller of their personal
  notes, and Lotti (the software vendor) is not a processor.

## Related

- [ADR 0038: Relationship Domain Model](./0038-relationship-domain-model.md)
- [ADR 0039: Relationship Check-In Reminders](./0039-relationship-check-in-reminders.md)
- [ADR 0040: Relationship Executive Briefing](./0040-relationship-executive-briefing.md)
- [Implementation plan](../implementation_plans/2026-07-22_relationship_management.md)
  (superseded by [v2](../implementation_plans/2026-08-13_relationship_management_v2.md))
- `PRIVACY.md`

---

### Adr 0038 Relationship Domain Model (`docs/adr/0038-relationship-domain-model.md`)

# ADR 0038: Relationship Domain Model

- Status: Accepted — implemented by plan v2 phase 1, with the D1 delta
  from the implementation plan: `CheckInData` carries a denormalized
  `relationshipId` so `affectedIds` emits a precise agent wake token.
  User-set sentiment is never AI-filled, including for spoken check-ins
  (phase 6).
- Date: 2026-07-22

## Context

A relationship is a long-running entity tied to one person — closer to a
project than to a task: it has no natural end date, it accumulates a
timeline of interactions, and it should link to tasks (a call to prepare, a
meeting scheduled as a task). Lotti has no person or contact concept today
(the old tags system was removed), so this is greenfield.

The journal core gives us everything needed:

- `JournalEntity` (`lib/classes/journal_entities.dart`) is a sealed freezed
  union of 16 subtypes sharing a `Metadata` envelope, stored as serialized
  JSON in the `journal` Drift table with denormalized query columns.
  `ProjectEntry`/`ProjectData` (`lib/classes/project_data.dart`) is the
  precedent for a long-running container entity with a status union and
  status history.
- `EntryLink` (`lib/classes/entry_link.dart`) is a freezed union
  (`basic`/`rating`/`project`) over the `linked_entries` table; the task
  timeline UI (`LinkedEntriesController`) is assembled purely from links.
- Sync is payload-agnostic for journal entities: a new subtype syncs as soon
  as its JSON round-trips and `toDbEntity` maps it — no new sync message.

## Decision

1. **New subtype `JournalEntity.relationship` with `RelationshipData`.**
   One relationship per person; the person's identity is embedded in the
   payload rather than split into a separate contact entity. Fields:
   - `title` — the person's display name (plus optional `nickname`).
   - `important` (`bool`, default `false`) — the flag that arms reminders
     (ADR 0039).
   - `status` — a `RelationshipStatus` sealed union mirroring
     `ProjectStatus` in shape (`id`, `createdAt`, `utcOffset`, optional
     `timezone`/`geolocation` per entry): `active`, `dormant` (kept but not
     currently nurtured; excluded from reminders), `archived`. With
     `statusHistory` for the trajectory.
   - `checkInCadenceDays` (`int?`) — desired check-in interval; only
     meaningful when `important` is set.
   - `birthday` (`DateTime?`) — optional, for future nudges.
   - `profileId` (`String?`) — inference profile for the relationship agent
     (ADR 0040), mirroring `ProjectData.profileId`.
   - `languageCode` (`String?`), `coverArtId` (`String?`) — same roles as on
     tasks/projects.
   - `contactChannels` (`List<ContactChannel>`, default empty) and
     `contactRefs` (per-platform contact identifiers) — communication
     channels and optional OS-contact linkage per ADR 0041; excluded from
     AI context.
   Free-form notes about the person live in the shared `entryText`.
   `meta.dateFrom` is when tracking started; `meta.dateTo` advances like a
   project's.
2. **New subtype `JournalEntity.checkIn` with `CheckInData`.** One check-in
   per logged interaction. Fields:
   - `interactionType` — enum: `inPerson`, `call`, `videoCall`, `message`,
     `other`.
   - `sentiment` (`CheckInSentiment?`) — enum: `delightful`, `good`,
     `neutral`, `strained`, `difficult`. Optional; explicit user judgment,
     never AI-filled.
   - `topics` (`List<String>`, default empty) — what was discussed.
   - `payAttentionTo` (`String?`) and `avoid` (`String?`) — the "next time"
     guidance the briefing later surfaces.
   The narrative ("what we talked about") is the entry's `entryText`; the
   interaction time is `meta.dateFrom`/`dateTo`, so check-ins sit naturally
   on calendars and timelines.
3. **Linking reuses `linked_entries` with a new `RelationshipLink` variant**
   of `EntryLink`, mirroring `ProjectLink`: relationship → check-in and
   relationship → task (and task → relationship queries via the reverse
   direction). Typed link rows allow indexed queries such as
   "relationships for task" without scanning basic links. The relationship
   timeline is the existing linked-entries mechanism — the same
   `LinkedEntriesController` path tasks use — so text, audio, and photos can
   be linked onto a relationship exactly like onto a task.
4. **No journal schema change initially.** Both subtypes ride the
   `serialized` column with `type` strings `'Relationship'` and `'CheckIn'`;
   list queries filter by `type` and links. Denormalized columns (e.g. an
   indexed `relationship_id` on check-ins) are deferred until a measured
   query needs them, following the `project_id` precedent.
5. **Reminders and briefings are not journal entities.** Reminders are
   `NotificationEntity` rows in `NotificationsDb` (ADR 0039); briefings are
   `AgentReportEntity` rows owned by the relationship agent (ADR 0040). The
   journal holds only what the user authored.
6. **Exhaustive-switch audit is the integration checklist.** Adding the two
   subtypes must update: `affectedIds` in `journal_entities.dart`, the
   `entity.map` in `lib/database/conversions.dart`, `folderForJournalEntity`
   and `typeSuffix` in `lib/utils/file_utils.dart`, the journal card switch
   in `journal_card.dart`, the detail-section switches in
   `entry_details_widget.dart`, creation ops in
   `lib/logic/persistence_logic.dart`, and the `link.map` in
   `conversions.dart` for the new link variant. The compiler enforces most
   of these.

## Consequences

- Sync, vector clocks, soft delete, `private`, categories, and export all
  work for relationships and check-ins with zero new infrastructure.
- Embedding person identity in `RelationshipData` means renaming a person is
  editing the relationship — acceptable for a 1:1 person-to-relationship
  model, and a future shared contact directory could be layered on without
  migrating existing data.
- Check-ins being ordinary journal entities means they appear in generic
  journal surfaces; those surfaces' switches need deliberate rendering
  decisions rather than falling through to defaults.
- The structured qualitative fields (`sentiment`, `payAttentionTo`, `avoid`)
  give the briefing generator explainable inputs instead of forcing it to
  infer everything from prose.

## Related

- [ADR 0037: Relationship Data Stays On-Device](./0037-relationship-on-device-storage-and-privacy.md)
- [ADR 0039: Relationship Check-In Reminders](./0039-relationship-check-in-reminders.md)
- [ADR 0040: Relationship Executive Briefing](./0040-relationship-executive-briefing.md)
- [ADR 0041: Relationship Contact Linking and Communication Actions](./0041-relationship-contact-linking.md)
- [Implementation plan](../implementation_plans/2026-07-22_relationship_management.md)
  (superseded by [v2](../implementation_plans/2026-08-13_relationship_management_v2.md))

---

### Adr 0039 Relationship Check In Reminders (`docs/adr/0039-relationship-check-in-reminders.md`)

# ADR 0039: Relationship Check-In Reminders

- Status: Accepted, with two decisions superseded — see the amendments below.
  [ADR 0059](./0059-relationship-agent-runtime-and-nudge-generalization.md)
  made the in-app banner dock the *primary* attention channel; this ADR's
  reminders shipped afterwards as plan v2 phase 8, covering the case a banner
  structurally cannot (the app is closed).
- Date: 2026-07-22
- Amended: 2026-08-17 (phase 8 implementation)

## Amendments at implementation time

Two decisions below did not survive contact with the code, and one paragraph
of context was simply stale by the time it was built:

1. **Decision 3's `RelationshipReminderService` producer does not exist, and
   should not.** It proposed an event-driven producer recomputing the next due
   date on check-in save, relationship save and startup. By the time reminders
   were built, `RelationshipAgentPhaseA` already did exactly that — it derives
   the cadence on the daily tick, on every check-in write (via the
   relationship's `affectedIds` token) and on relationship saves, and its
   derivation is the same one the banner and the briefing use. A second
   producer would have been a second source of truth for "when is this person
   due", free to disagree with the banner. The reminder is therefore a
   *projection* of Phase A's verdict: `RelationshipReminderService` implements
   `RelationshipReminderSink` and owns no cadence logic at all.
2. **Decision 4's per-due-date identity is per *episode*, and rows are
   retracted rather than rewritten.** The id derives from
   `(relationshipId, dueDayKey)` as proposed, but the consequence was not
   spelled out: because the three lifecycle marks are monotonic and cannot be
   cleared, a check-in that moves the due day must mint a *new* row and
   retract the old one. Rewriting one row per person would let an August
   dismissal permanently silence September.
3. **The context section's claim that `reconcile()` "is built and tested but
   currently has no production caller" was stale.** It had been removed
   entirely as dead code in #3748 (*chore: remove unused feature APIs*), so
   phase 8 reinstated it rather than wiring it.
4. **Decision 5 overstated platform support.** It claimed iOS, macOS *and*
   Android got OS notifications through `zonedSchedule`. Android never did:
   `InitializationSettings` carried no `android` entry, so the plugin threw
   `ArgumentError` on `initialize`, that throw was swallowed, and the whole
   plugin stayed uninitialised. Phase 8 fixed that separately from the
   relationship feature — see the consequences.

## Context

When a relationship is marked important, Lotti should proactively remind the
user to check in. Per ADR 0037 there is no server, so reminders must be
computed and scheduled entirely on-device.

The app has two notification layers that fit together:

- `NotificationService` (`lib/services/notification_service.dart`) wraps
  `flutter_local_notifications` with timezone-aware `zonedSchedule`. OS
  scheduling works on iOS, macOS, and Android; Windows and Linux are
  skipped. Everything is gated on `enableNotificationsFlag`.
- The synced notification inbox (`lib/features/notifications/`): durable
  `NotificationEntity` rows in `NotificationsDb` that sync over Matrix,
  with `seenAt`/`actedOnAt` lifecycle, an in-app bell, and a
  `NotificationScheduler` that bridges rows to OS notifications using
  stable FNV-1a ids. Its `reconcile()` (re-arm OS alerts after restart) is
  built and tested but currently has no production caller, and the
  `taskOverdue` producer path is similarly dormant.

Habits set the precedent for scheduling without background workers: a
rolling model where saving or completing an entity re-arms the next OS
notification, rather than a periodic job.

## Decision

1. **New inbox variant `NotificationEntity.relationshipCheckIn`** carrying
   `linkedRelationshipId`, `title`, and `body`, alongside the existing
   `taskSuggestion`/`taskOverdue` variants. Reminders are durable inbox rows
   first, OS notifications second.
2. **Deterministic, local eligibility rule.** A reminder is due for a
   relationship iff `important == true`, status is `active`, and
   `now - lastCheckInDate >= checkInCadenceDays` (default 30 when unset).
   The last check-in date is the newest linked check-in's `meta.dateFrom`;
   for a relationship with no linked check-ins yet, the baseline is the
   relationship's own `meta.dateFrom`, so the first reminder fires one
   cadence after tracking starts — marking someone important is itself the
   request to be nudged, so reminders are never suppressed waiting for a
   first check-in. Relationships that are not important never produce
   reminders — the flag is the single consent switch for proactive
   behavior.
3. **Event-driven producer, no background scheduler.** A
   `RelationshipReminderService` recomputes the next due date and
   (re)schedules via `NotificationScheduler`:
   - when a check-in is saved (pushes the next reminder out by one cadence),
   - when a relationship is saved (arming, disarming, or re-cadencing),
   - at app startup via `NotificationScheduler.reconcile()` — which this
     feature finally wires into the launch sequence, fixing the dormant gap
     for all notification types at once.
4. **Stable identity and cross-device convergence.** Notification ids derive
   from the relationship id plus due date (the existing FNV-1a scheme), so
   two devices computing the same reminder converge on one row after sync,
   and acting on a reminder on one device (`actedOnAt`) clears the pending
   alert everywhere via the existing `SyncNotification` path.
5. **Platform behavior.** iOS/macOS/Android get OS notifications through
   `zonedSchedule`. Windows and Linux surface due reminders through the
   in-app inbox bell only, populated at startup reconcile — an accepted
   limitation inherited from `NotificationService`.
6. **Controls.** Globally gated by the existing `enableNotificationsFlag`;
   per-relationship control is the `important` flag and cadence itself.
   Reminder copy is localized and deliberately vague on lock screens
   ("Check in with Anna?" — no interaction details), since notification
   content leaves the app sandbox.

## Consequences

- No new dependencies (no workmanager/background_fetch); the reminder
  machinery is a thin projection over existing, tested infrastructure.
- On desktop platforms without OS scheduling, reminders appear only when the
  app runs — consistent with the local-only design, and mitigated by the
  synced inbox (a phone will still alert).
- Reinstating `reconcile()` at startup is a behavior change that also revives
  OS alerts for other inbox notification types; it has its own tests.
- If the app is not opened for a long period on a single-device setup, no
  reminder fires beyond the last scheduled OS notification — an accepted
  cost of having no server (ADR 0037).
- **The reminder had to fix Android notifications generally.** Adding
  `AndroidInitializationSettings` revives every path that was silently
  discarded — habit reminders, the Daily OS plan-ready banner, sync-conflict
  alerts — which is a much wider behavior change than a relationship feature
  would normally carry. Two deliberate consequences of that: `updateBadge` is
  now explicitly Darwin-only (the same call on Android posts a visible "N
  tasks in progress" notification after every entry write, rather than a
  silent icon count), and scheduling uses `inexactAllowWhileIdle` so Lotti
  never requests `SCHEDULE_EXACT_ALARM`, which Play restricts to alarm and
  calendar apps. A check-in reminder does not need minute precision.
- **The row's copy is baked at write time in the arming device's locale** and
  then syncs verbatim, so a two-device/two-locale setup reads the armer's
  language on both. This knowingly departs from
  [localization.md](../../knowledge/conventions/localization.md)'s
  "persist the facts, compose the sentence at render time": the OS holds the
  alarm for weeks with the app closed, so there is no render moment to compose
  at. It matches what `taskSuggestion` and `taskOverdue` already do.
- **Notification taps still do not route anywhere.** `_deepLinkFor` is now
  variant-aware and emits `/people/<id>`, but nothing consumes the payload:
  `initialize` is called without `onDidReceiveNotificationResponse` and
  nothing calls `getNotificationAppLaunchDetails`. Tapping any Lotti
  notification opens the app at wherever it was. That predates this ADR and is
  its own change.

## Related

- [ADR 0037: Relationship Data Stays On-Device](./0037-relationship-on-device-storage-and-privacy.md)
- [ADR 0038: Relationship Domain Model](./0038-relationship-domain-model.md)
- [ADR 0027: Wake Notification Propagation and Storm Prevention](./0027-wake-notification-propagation-and-storm-prevention.md)
- [ADR 0059: Relationship Agents on the Shared Runtime and the Kind-Agnostic Nudge Substrate](./0059-relationship-agent-runtime-and-nudge-generalization.md) — supersedes the attention-channel choice; keeps the eligibility rule
- [Implementation plan](../implementation_plans/2026-07-22_relationship_management.md)
  (superseded by [v2](../implementation_plans/2026-08-13_relationship_management_v2.md))

---

### Adr 0040 Relationship Executive Briefing (`docs/adr/0040-relationship-executive-briefing.md`)

# ADR 0040: Relationship Executive Briefing

- Status: Accepted — implemented by plan v2 phase 5; amended by
  [ADR 0059](./0059-relationship-agent-runtime-and-nudge-generalization.md):
  the agent is a registered runtime kind on deterministic-first two-tier
  wakes, and Decision 1's `AgentTemplateKind.relationshipAgent` is dropped
  (the constitution is code, the ADR 0053 Decision 7 precedent). The report
  contract, health band, context boundary, honesty rules, and
  privacy-weighted routing stand.
- Date: 2026-07-22

## Context

Before the user next engages with a person, Lotti should hand them what a
good executive assistant would: how things are going, what was discussed
recently, how interactions have felt, what to bring up, what to pay
attention to, and what to avoid.

The AI layer is mid-migration: the legacy prompt-driven `AiResponseType`
path is deprecated for summaries, superseded by the agent system
(`lib/features/agents/`). The established pattern — used by task, project,
event, and day agents — is: an agent kind plus link type binds a durable
agent to an entity; a workflow runs profile-resolved inference with tool
calls; the output is an `AgentReportEntity` (`content` markdown, `tldr`,
`oneLiner`) with a latest-report head; consumers resolve it like
`TaskSummaryResolver` does. The project agent additionally emits a
structured health band (`ProjectHealthMetrics`: band, rationale,
confidence) parsed from report provenance and rendered as a chip. Local
inference (Ollama, OMLX/MLX) is a first-class provider option, and
inference profiles can pin capability slots to local models.

## Decision

1. **A durable relationship agent per relationship.** New
   `AgentKinds.relationshipAgent`, `AgentLinkTypes.agentRelationship`, and
   `AgentTemplateKind.relationshipAgent`; a `RelationshipAgentService`
   creates the agent lazily and links it to the relationship entity,
   mirroring `TaskAgentService`/`ProjectAgentService`. All exhaustive
   agent-kind switches are audited as part of the change.
2. **The briefing is an `AgentReportEntity`.** `content` is the full
   executive briefing (state of the relationship, key topics from recent
   check-ins, sentiment trajectory, suggested talking points, pay-attention
   list, avoid list); `tldr` is the card summary; `oneLiner` the compact
   tagline. Latest-wins via the report head; shown in the relationship
   detail header through a resolver in the `TaskSummaryResolver` style.
3. **Structured relationship health in provenance.** The report contract
   defines a `relationship_health` band — `thriving`, `steady`,
   `needsAttention`, `strained` — with free-text rationale and optional
   confidence, parsed and rendered exactly like `ProjectHealthMetrics`.
   The band must be grounded first in the explicit `CheckInData.sentiment`
   values (user judgment), with prose only as secondary evidence.
4. **Strict context boundary.** The workflow assembles: the relationship
   entity and its `entryText`, the most recent N check-ins (structured
   fields plus narrative), linked tasks' titles and statuses, and the
   previous report. Nothing else from the journal is included. This keeps
   briefings explainable, keeps token budgets bounded, and minimizes what a
   cloud model could ever see when one is selected. *Amended 2026-09-19:
   ADR 0062 Decision 2 added the check-ins' own entries; a photo's
   description among them is its newest image analysis — the AI response
   linked from the photo, its summary where one was written — followed by
   any text of the photo's own. Nothing beyond the check-in's entries and
   their analyses is included.*
5. **Triggers.** On-demand ("Brief me" on the relationship detail page) and
   an automatic debounced refresh after a new check-in is saved, so the
   briefing is already fresh when a reminder (ADR 0039) brings the user
   back. No scheduled or speculative runs beyond that.
6. **Privacy-weighted model routing.** The profile is resolved from
   `RelationshipData.profileId`, falling back to the category default.
   Local-model profiles are the recommended default for this data class;
   cloud providers are an equally legitimate route when they are
   GDPR-compliant with zero-data-retention terms — then inference is
   transient processing and nothing is stored outside the user's devices.
   Either way, the trigger surface names the provider before running
   (ADR 0037). No inference ever runs
   without an explicit user-facing trigger or the post-check-in refresh the
   user enabled by using the feature.
7. **Honesty rules in the template.** The briefing may only reference
   captured check-ins and linked entities, must state recency ("last spoke
   five weeks ago"), must say when there is not enough data rather than
   pad, and must keep `payAttentionTo`/`avoid` guidance traceable to the
   check-ins that produced it.

## Consequences

- The feature inherits agent-system infrastructure wholesale: report
  storage, sync, head resolution, profile routing, and UI patterns — the
  new code is one service, one workflow, one report contract, and rendering.
- Briefing quality tracks check-in quality; thin capture yields thin
  briefings by design (honesty rules), which is the correct incentive.
- Local-first routing means weaker prose on low-end hardware; users can
  opt into cloud per profile, with the trade-off made visible.
- A second consumer of the health-band pattern will pressure the provenance
  parsing into a shared helper rather than a copy — worth doing during
  implementation.

## Related

- [ADR 0037: Relationship Data Stays On-Device](./0037-relationship-on-device-storage-and-privacy.md)
- [ADR 0038: Relationship Domain Model](./0038-relationship-domain-model.md)
- [ADR 0039: Relationship Check-In Reminders](./0039-relationship-check-in-reminders.md)
- [ADR 0016: Agent-Derived State as a Projection of the Append-Only Log](./0016-agent-state-as-log-projection.md)
- [ADR 0023: Durable Domain Agents and Time Negotiation](./0023-durable-domain-agents-and-time-negotiation.md)
- [ADR 0059: Relationship Agents on the Shared Runtime and the Kind-Agnostic Nudge Substrate](./0059-relationship-agent-runtime-and-nudge-generalization.md) — amends the runtime binding; drops the template
- [Implementation plan](../implementation_plans/2026-07-22_relationship_management.md)
  (superseded by [v2](../implementation_plans/2026-08-13_relationship_management_v2.md))

---

### Adr 0041 Relationship Contact Linking (`docs/adr/0041-relationship-contact-linking.md`)

# ADR 0041: Relationship Contact Linking and Communication Actions

- Status: Accepted — implemented by plan v2 phase 7 on Android and iOS.
  Contact channels stay out of AI context (§5): nothing in the facts
  renderer reads them, and its test renders a person whose channels are
  populated and fails if any reaches the output. Desktop keeps manual entry,
  as §2 anticipated.
- Date: 2026-07-22

## Context

An executive briefing (ADR 0040) prepares the user for a conversation; the
natural next step is starting that conversation — calling or messaging the
person right from the briefing. That requires the relationship to know the
person's contact channels. Retyping phone numbers is friction, so pulling
them from the OS address book is attractive. It also closes the tracking
loop: an interaction Lotti itself initiated is the easiest possible
check-in to capture.

Two forces constrain the design. First, curation: relationships are a small
deliberate set of people (ADR 0038); importing an address book wholesale
would create hundreds of dormant relationship entities and destroy the
signal the reminders and briefings depend on. Second, platform reality:
OS contact pickers are well supported on iOS and Android, weakly on macOS,
and effectively unavailable on Linux/Windows; contact identifiers are
device-local — every address book assigns its own, so even two phones on
the same OS hold unrelated ids — and a contact reference therefore cannot
resolve on any synced peer device. `url_launcher` (already a dependency) covers `tel:`, `sms:`, and
`mailto:` launching; no contacts plugin is currently in the dependency set.

## Decision

1. **No bulk import — selective linking only.** Contact integration is
   per-relationship and user-initiated: a "Link contact" action on the
   relationship opens the OS contact picker and copies the selected
   contact's channels into the relationship. The address book permission is
   requested only when the picker is invoked, never at startup, and Lotti
   never enumerates or reads the address book in the background.
2. **Channels are plain relationship data, not a live dependency.**
   `RelationshipData` gains `contactChannels`
   (`List<ContactChannel>` — `type` enum `phone`/`mobile`/`email`/
   `messaging`, optional `label`, `value`) and `contactRefs`
   (per-device map of contact identifiers, keyed by platform plus the
   device's sync host id, used only for an explicit "Update from contact"
   refresh on the device that owns the contact — a key scoped merely
   per-platform would let two same-OS devices overwrite each other's ref
   and resolve a peer's id against the wrong address book).
   Channels are manually editable on every platform, so Linux/Windows get
   full feature parity through manual entry; the picker is a convenience,
   not a requirement. Snapshot data syncs and cascades like everything else
   in the relationship (ADR 0037).
3. **Quick actions via OS URL schemes.** Call, message, and email buttons
   appear on the relationship detail header and on the executive briefing
   card, launched through `url_launcher` (`tel:`/`sms:`/`mailto:`). Lotti
   contains no telephony code and never accesses call logs or content.
4. **Contact-initiated check-in capture.** When the user launches a call or
   message from Lotti, a transient pending-interaction marker (relationship
   id, channel type, timestamp — device-local, not synced) is recorded. On
   next app resume, a dismissable prompt offers to log a check-in
   pre-filled with the interaction type and time. Check-ins are never
   auto-created; declining leaves no trace.
5. **Channels are excluded from AI context.** The briefing context boundary
   (ADR 0040 §4) explicitly excludes `contactChannels` and `contactRefs` —
   the model has no need for phone numbers or email addresses, so they
   never reach any provider, local or cloud.
6. **Dependency scope.** The OS picker ships for iOS and Android first
   (e.g. `flutter_contacts` — new dependency, added at implementation
   time); macOS via the native Contacts framework is a later candidate.
   Desktop relies on manual entry until then.

## Consequences

- The curated-relationship model survives contact integration: the address
  book never drives entity creation, only enriches entities the user
  already chose to create.
- Per-device `contactRefs` mean "Update from contact" works only on the
  device that wrote the ref — synced peers still see the channel values,
  which is what the quick actions need.
- The post-interaction prompt is a resume heuristic, not call detection: it
  can fire when no conversation happened (unanswered call) and misses
  interactions started outside Lotti. Accepted — it is an offer, not a log.
- One new mobile dependency (contacts picker); the action buttons
  themselves add none.

## Related

- [ADR 0037: Relationship Data Stays On-Device](./0037-relationship-on-device-storage-and-privacy.md)
- [ADR 0038: Relationship Domain Model](./0038-relationship-domain-model.md)
- [ADR 0040: Relationship Executive Briefing](./0040-relationship-executive-briefing.md)
- [Implementation plan](../implementation_plans/2026-07-22_relationship_management.md)
  (superseded by [v2](../implementation_plans/2026-08-13_relationship_management_v2.md))

---

### Adr 0042 Typed Task Relationship Links (`docs/adr/0042-typed-task-relationship-links.md`)

# ADR 0042: Typed Task Relationship Links

## Status

Accepted

## Date

2026-07-23

## Context

### Tasks relate to each other, but the link model cannot say how

Lotti links journal entities through `EntryLink`
(`lib/classes/entry_link.dart`), a freezed union with three variants —
`basic`, `rating`, `project` — persisted in the `linked_entries` table.
`BasicLink` is deliberately semantics-free: it means "belongs with", and
that vagueness is load-bearing. Basic links attach time entries, audio,
images, and comments to tasks; recorded-time attribution
(`basicLinksForEntryIds` → `resolveTimeEntries`) walks them to credit
tracked time to tasks and categories; the task detail page renders them as
the linked-entries timeline; capture parsing attaches phrases to tasks
through them.

What the model cannot express is a *directed semantic relationship between
two tasks*: this task cannot start until that one finishes; this task is a
follow-up spawned by that one; these two are the same work filed twice;
this task fixes a defect that task tracks; this task replaces that obsolete
one. Every mainstream task system models some subset of these (Jira:
blocks / is blocked by, duplicates, causes, clones; Linear: blocks,
related, duplicate of; GitHub: fixes/closes; Beads: blocks/depends-on,
parent-child, relates-to, duplicates, supersedes). Without them:

- The planning agents' task corpus is a flat open/due list
  (`DayAgentCorpusService.buildTaskCorpusSnapshot`), so a day plan can
  schedule "Deploy release" before "Fix the blocker" — nothing in context
  says B waits on A (consumed by ADR 0043).
- The user has a manual `TaskStatus.blocked`, but it is a self-declared
  flag with no machine-readable cause: nothing identifies *what* blocks the
  task, nothing clears it when the blocker closes, and agents can only echo
  it back.
- Duplicate and superseded work accumulates silently; closing the canonical
  task does nothing visible to its twins.

### What already exists that typed links can reuse

The storage and sync substrate needs **no schema change**:

- `linked_entries` already has a `type TEXT NOT NULL` column, a
  `UNIQUE(from_id, to_id, type)` constraint, and indexes on `from_id`,
  `to_id`, `type`, and `(to_id, type)`. The type column is derived from the
  union variant on write (`linkedDbEntity`: `'BasicLink'`, `'RatingLink'`,
  `'ProjectLink'`), so precedent exists for multiple coexisting link types
  between the same pair.
- Consumers are already type-scoped: `basicLinksForEntryIds` filters
  `type = 'BasicLink'` at the SQL layer, so time attribution, the
  linked-entries timeline, and capture attribution are structurally
  invisible to any new type. Nothing leaks by construction.
- Creation, vector-clock stamping, outbox sync (`SyncMessage.entryLink`),
  and change notifications all run through `PersistenceLogic.createLink` /
  `JournalDb.upsertEntryLink`, which handle `EntryLink` generically.
- `EntryLink` is declared `@Freezed(fallbackUnion: 'basic')`: an older
  build receiving an unknown variant over sync deserializes it as a plain
  `BasicLink` instead of crashing — unknown semantics degrade to a visible
  generic link.

## Decision

### 1. New `EntryLink` union variants, not a field on `BasicLink`

Task relationships become first-class union variants:

| Variant      | Reading (from → to)              | Inverse rendering    |
| ------------ | -------------------------------- | -------------------- |
| `blocks`     | *from* blocks *to*               | *to* is blocked by *from* |
| `followsUp`  | *from* follows up on *to*        | *to* has follow-up *from* |
| `duplicates` | *from* duplicates *to* (canonical) | *to* is duplicated by *from* |
| `fixes`      | *from* fixes *to* (the defect)   | *to* is fixed by *from* |
| `supersedes` | *from* supersedes *to* (obsolete) | *to* is superseded by *from* |

Each variant carries the same shape as `BasicLink` (id, fromId, toId,
timestamps, vector clock, hidden/collapsed, deletedAt) — the semantics live
entirely in the type. Rationale for variants over a `linkType` field on
`BasicLink`:

- The `type` column derives from the union map, so every existing
  `type = 'BasicLink'` consumer stays correct without an audit — a field
  would put typed edges *inside* the basic result set and require touching
  every basic-link read (time attribution above all) defensively.
- `fallbackUnion: 'basic'` gives forward compatibility for free: an old
  build shows an unknown typed edge as a plain link (see Consequences for
  the write-back caveat).
- `UNIQUE(from_id, to_id, type)` naturally allows a pair to hold a basic
  link *and* a `blocks` edge simultaneously, and dedupes repeated
  assertions of the same relationship.

### 2. One stored edge per relationship; inverses are rendering

"Is blocked by", "has follow-up", "is duplicated by" etc. are **labels for
the reverse direction of the same row**, never separate rows. Both
directions are queryable through the existing `from_id` and `(to_id, type)`
indexes. The UI offers both phrasings when creating a link and simply swaps
`fromId`/`toId` before persisting the canonical direction.

### 3. `relates to` stays `BasicLink`; hierarchy stays out

- A generic "these are related" association is exactly what `BasicLink`
  already is between two tasks. No new `relatesTo` variant.
- **No cross-task parent/child variant.** Sub-structure inside a task is
  checklists; grouping across tasks is categories and `ProjectLink`. A
  parallel task-hierarchy edge would compete with both. Revisit only if
  projects prove insufficient.
- `causes`/`clones` (Jira) are deferred — no consumer in the app would read
  them today.

### 4. Ready semantics: derived, one hop, status-aware

A task is **ready** iff it has no live blocker:

> no non-deleted `blocks` link with `toId == task` whose `fromId` task is
> neither tombstoned (`deletedAt` set) nor closed (`DONE`/`REJECTED`, the
> `isClosedTask` predicate).

An **unresolvable blocker keeps blocking**: when the link row exists but
the `fromId` task cannot be loaded (typically a sync gap — the link
arrived before its task), the dependent stays blocked until the task
materializes or the link is deleted. Journal entities tombstone rather
than hard-delete, so a *deliberately* deleted blocker carries `deletedAt`
and releases its dependents; only a genuinely unresolved reference blocks
conservatively. The resolver tests must pin all three cases (closed →
released, tombstoned → released, unresolvable → blocked).

- Readiness is **derived at read time, never stored**. Closing a blocker
  "releases" its dependents implicitly on every device — no unlock write,
  nothing to converge, no sync race.
- One hop only: a task with an open blocker is blocked; transitive chains
  emerge naturally because the blocker itself stays unready until its own
  blockers close. (Chain *display* may traverse; readiness never needs to.)
- The `hidden` flag stays a pure UI affordance and does not affect
  readiness; `deletedAt` tombstones do.
- The manual `TaskStatus.blocked` **coexists and is never mutated by the
  link layer**. It remains the user's self-declared flag (blocked on
  something outside the system); link-derived blockedness is computed and
  names its cause. The two enrich each other without coupling: when the
  user sets the status to blocked, the UI *offers* to name the blocking
  task (which persists a `blocks` edge) — optional, never required, since
  many blocks are external (waiting on a person, a delivery, a decision).
  Conversely, creating a blocking link may *suggest* the status. No
  automation writes task status from links in either direction.

### 5. Cycles: guarded at creation, tolerated at read

Concurrent offline writes on two devices can always create a cycle
(A blocks B on one device, B blocks A on the other), so cycles cannot be
prevented — they must be survivable:

- **Creation-time guard (best effort, local):** creating a `blocks` edge
  runs a bounded local traversal and rejects the write if it would close a
  cycle visible on this device.
- **Read-time tolerance:** all traversals use a visited set and a depth
  cap. Members of a cycle each have an open blocker, so all of them are
  unready — the deadlock is made *visible* (surfaced in the UI as a mutual
  block), never hidden or "resolved" silently.

### 6. Lifecycle semantics are suggestions, not automation

- Closing a task that others `duplicate` → the UI offers to close the
  duplicates; nothing auto-closes.
- Creating a `supersedes` edge → the UI offers to close the superseded
  task; nothing auto-closes.
- `fixes`/`followsUp` carry no lifecycle coupling; they are navigation and
  context.

This keeps the user the only writer of task status (consistent with the
ChangeSet philosophy of ADR 0006: agents and derived systems propose, the
user disposes).

## Consequences

- **No migration.** Purely additive: new union variants, new type-column
  values, existing rows untouched, existing queries unaffected.
- **New read surface needed:** a type-scoped batch query (typed links for a
  set of task ids, both directions) mirroring `basicLinksForEntryIds`,
  served by the existing `(to_id, type)` and `from_id` indexes.
- **Old-build degradation is bounded but real.** An old build folds an
  unknown variant to `BasicLink` (fallback union) and *displays* it as a
  generic link — acceptable. If that old build then **mutates** the link
  (hide, collapse, delete), it re-serializes it as `basic`, permanently
  down-typing the edge for everyone. Links are rarely mutated after
  creation, and the same exposure already exists for every new
  `AgentDomainEntity` variant; accepted, documented here, mitigated by
  shipping the model variants at least one release before any UI writes
  them (standard rollout ordering).
- **The typed vocabulary is closed by design.** Five verbs cover the
  standard task-system semantics; anything fuzzier belongs in `BasicLink`
  or in text. Growing the vocabulary requires an amendment here, not an ad
  hoc string.
- Planning integration (ready frontier in the agent corpus, directive
  rules) is deliberately split into ADR 0043 — this ADR is complete without
  it, and the link layer must not depend on the agents feature.

## Related

- ADR 0003 — linked-context contract (the read pattern typed links extend).
- ADR 0006 — user-as-final-validator, mirrored by decision 6.
- ADR 0032 — hierarchical day-agent coordination (the consumer side's
  architecture).
- ADR 0043 — dependency-aware planning (the ready frontier consuming these
  edges).
- Implementation plan:
  `docs/implementation_plans/2026-07-23_task_dependency_links.md`.
- Prior art: Jira link types, Linear relations, Beads
  (github.com/steveyegge/beads) — the blocks/ready-frontier model for
  agent-facing task graphs.

---

### Adr 0043 Dependency Aware Planning (`docs/adr/0043-dependency-aware-planning.md`)

# ADR 0043: Dependency-Aware Planning (Ready Frontier)

## Status

Accepted

## Date

2026-07-23

## Context

### The planning agents see tasks as a flat list

The day-agent task corpus (`DayAgentCorpusService.buildTaskCorpusSnapshot`)
assembles open tasks plus overdue/due-today tasks into a bounded snapshot
(≤200 rows: taskId, title, status, categoryId, due, estimateMinutes,
priority) that capture parsing matches against and drafting places from.
The coordinator's digest (ADR 0032) distills commitments into per-day
directives from the same flat view. Nothing in either context expresses
that one task waits on another, so today:

- Drafting can place a blocked task into a plan while the blocker sits
  unscheduled — the plan is executable on paper and stuck in practice.
- A directive can commit minutes to work that cannot start, burning one of
  the ≤12 bounded commitment slots on a no-op.
- The agent cannot give the genuinely useful advice — "schedule the
  blocker first" — because the dependency is invisible.

ADR 0042 adds the missing substrate: typed `blocks` edges between tasks
and a derived, one-hop readiness rule (no live blocker whose task is not
`DONE`/`REJECTED`). This ADR decides how planning consumes it.

### Constraint: the corpus serves two masters

The corpus is not only a planning input — capture matching
(`match_to_corpus`) resolves spoken phrases against it. A blocked task must
still be *matchable* ("I talked to legal about the contract review" must
link to the blocked contract-review task). Any design that removes blocked
tasks from the corpus breaks capture attribution.

## Decision

### 1. Annotate, never exclude

Blocked tasks stay in the corpus. Rows for blocked tasks gain one field:

```json
{
  "taskId": "…", "title": "…", "status": "OPEN", "…": "…",
  "blockedBy": [{"taskId": "…", "title": "Fix the blocker", "status": "IN PROGRESS"}]
}
```

Ready tasks carry no `blockedBy` key at all, so the common case adds zero
tokens and the snapshot stays byte-stable for prompt-prefix caching except
where a dependency genuinely exists.

**Absence of `blockedBy` means link-ready, not free to schedule.** The
manual `TaskStatus.blocked` stays independent of typed links (ADR 0042
§4), and every corpus row already carries `status` — so a manually blocked
task with no named blocker is visible as `"status": "BLOCKED"` with no
`blockedBy` key. "Blocked for planning" is the union of both signals:
`status == BLOCKED` (self-declared, cause possibly external/unnamed) **or**
a non-empty `blockedBy` (computed, cause named). The prompt rules below
and their tests use this union definition; the corpus shape needs no
second flag for it.

### 2. A batch dependency resolver, one hop, bounded

A dependency-resolution seam (extending the corpus/journal read layer)
answers "which of these task ids are blocked, and by what" in two bounded
queries: one type-scoped link fetch (`to_id IN (…) AND type = <blocks>`,
served by the existing `(to_id, type)` index), one batch task-status load
for the distinct blocker ids. No transitive closure — readiness is one hop
by ADR 0042 decision 4 — and no per-task fan-out (the same
batch-read discipline as `getEntitiesByIds` in the week-context service).

### 3. Prompt contract: schedule blockers, don't schedule blocked work

Drafting/refine rules (day agents), one predicate, stated once and
mirrored verbatim by the implementation plan:

> A task that is blocked for planning (`status == BLOCKED` or non-empty
> `blockedBy`) may be placed **only if** (a) the same plan places work on
> its blocker earlier in the day, **or** (b) the block's `reason`
> explicitly names the blocker and why the work can proceed despite it.

- When a decided/committed task is blocked, prefer placing the blocker and
  say so in the reason.

Digest rules (coordinator, extends the ADR 0032 digest ritual):

- Directive commitments should reference ready work. A commitment on a
  blocked task must either target the blocker instead or name the blocker
  in an attention note, so the per-day agent inherits the dependency
  context inside the directive itself.

These are prompt-contract rules in `day_agent_prompt_builder.dart`,
enforced the same way the binding-directive contract is: by instruction and
by review, not by hard validation — the LLM may still have good reasons
(a blocked task's independent subtask, a deadline forcing parallel prep).

### 4. UI: blockedness is visible where tasks are

- Task detail: a "Blocked by …" affordance (and the inverse "Blocks …")
  rendered from typed links, tappable to the other task, alongside the
  existing linked-tasks section; follow-ups, duplicates, fixes, and
  supersedes render as labeled groups in the same surface.
- Creating typed links reuses the existing link-task modal
  (`link_task_modal.dart`) with a relationship picker.
- List-level badges (a blocked glyph on task rows) are a later polish
  step, not part of the core decision.

### 5. Non-goals

- **No topological scheduler.** Ordering a handful of same-day blocks is
  soft judgment the LLM already exercises through block `reasons`; a
  constraint solver would fight the human-in-the-loop model for marginal
  gain.
- **No automatic status writes.** Computed blockedness never mutates
  `TaskStatus` (ADR 0042 decision 4).
- **No dependency-driven wake triggers** (waking a day agent because a
  blocker closed) in the first iteration — the daily digest and normal
  planning cadence pick up released work; event-driven release
  notifications are a listed follow-up, not a commitment.

## Data flow

```mermaid
flowchart LR
  subgraph links [ADR 0042 substrate]
    BL[blocks edges<br/>linked_entries]
  end
  subgraph reads [bounded batch reads]
    DR[dependency resolver<br/>links + blocker statuses]
  end
  subgraph consumers
    CS[corpus snapshot<br/>blockedBy annotation]
    TD[task detail UI<br/>Blocked by / Blocks]
  end
  BL --> DR --> CS
  BL --> TD
  CS --> DA[day agent drafting/refine<br/>prompt rules]
  CS --> CO[coordinator digest<br/>directive rules]
```

## Consequences

- Token cost is proportional to actual dependencies (annotation only on
  blocked rows), and the resolver adds two bounded queries per corpus
  build.
- Capture matching is unaffected — blocked tasks remain in the corpus.
- The prompt contract grows two rule blocks (drafting, digest); both are
  conditional on the dependency data existing, so pre-rollout prompts are
  byte-identical.
- Cycle tolerance is inherited from ADR 0042: mutually blocking tasks are
  all annotated as blocked, which surfaces the deadlock to the agent and
  the user rather than hiding it.
- Deferred follow-ups (explicitly out of scope until proven needed):
  blocker-closed release notifications, list-row badges, a `link_tasks`
  agent tool letting capture parsing assert dependencies ("X waits on Y"),
  and duplicate/supersede close-time suggestions (ADR 0042 decision 6's UI).

## Related

- ADR 0042 — typed task relationship links (the substrate).
- ADR 0032 — hierarchical day-agent coordination (digest/directive
  surfaces extended here).
- ADR 0003 — linked-context contract.
- Implementation plan:
  `docs/implementation_plans/2026-07-23_task_dependency_links.md`.

---

### Adr 0044 Day Processing Outbox Storage (`docs/adr/0044-day-processing-outbox-storage.md`)

# ADR 0044: Day Processing Outbox Storage

## Status

Accepted

## Date

2026-07-24

## Context

### What the outbox is

`DayProcessingOutboxRepository` is the device-local durable record of
pending derived work for Daily OS: transcribe this recording, parse this
capture, draft this day, refine this plan. ADR 0031 introduced it for
transcription; ADR 0032 phase 1 extended it to agent jobs. It carries
deterministic job ids (`transcribe_<recordingSessionId>`,
`parse_<captureId>`, `draft_<dayId>`, `refine_<dayId>_<n>`), lease/claim
fencing, attempt counters, failure classification, and hard
`retryNotBefore` boundaries.

It has a second, deliberate role. From the class docstring: *"Jobs remain
after success as the local processing ledger consumed by Activity and
startup repair."* Terminal rows are kept on purpose —
`DayActivityRepository` (`day_activity_repository.dart:85`) and
`DayAudioReviewFence` (`day_audio_review_fence.dart:57`) both read the
whole set.

### The storage choice was never evaluated

ADR 0031 section 3 asserts the mechanism without comparing storage: *"A
checksummed, file-backed job store (deterministic job id per recording
session) with lease/claim semantics, exponential jittered backoff, hard
`retryNotBefore` boundaries, and failure classification."*

Its rejected-alternatives list contains two entries, both sound and
neither about a table:

- *"Matrix sync outbox as the job queue — the sync outbox transports
  already-durable entities; it does not represent pending inference."*
- *"In-memory wake/processing intent — an app exit must not lose the
  user's request to have a recording transcribed."*

The first argues against reusing **that** table. The second argues against
**no** durability. Neither argues against a device-local table, which was
never considered.

### What the filesystem design costs

`_readAllUnsafe()` (`day_processing_outbox_repository.dart:698`) does
`rootDirectory.listSync()` and, for every `*.json`, reads it,
JSON-decodes the envelope, verifies its SHA-256, decodes the payload, and
then sorts the whole list. It backs `claimNext` (`:447`), `getAll`
(`:417`), and `signalConnectivityRestored` (`:668`).

`DayProcessingRuntime.drainAndSchedule` (`day_processing_runtime.dart:74`)
calls `drain()` — a `claimNext` per processed job plus one idle
`claimNext` — and then `getAll()` to choose the next schedule. So one
nudge costs several full-directory scans. Nudges fire on every outbox
mutation (`runtime.dart:44` subscribes to `repository.changes`), on
connectivity restore, at startup, and on retry wakeups.

Because terminal jobs are retained as the ledger, that scan set grows for
the life of the install. Every recording adds at least two job files;
every planned day adds more. **Per-action work on the main isolate grows
linearly with app age**, and the ledger — the part that is retained on
purpose — is what grows.

The design also hand-rolls what a database provides: SHA-256 integrity
envelopes, atomic-rename writes, partial-file recovery
(`_recoverPartials`), corrupt-file quarantine (`_quarantine`), and a
tail-chained mutex (`_serialize`) to keep mutations from interleaving.

### We already learned this lesson, with numbers

`SyncDatabase` (`lib/database/sync_db.dart`) is device-local and already
runs two durable job queues in SQLite.

The `Outbox` table (`sync_db_tables.dart:85`) has `status`, `retries`,
`priority`, timestamps and a dedup key, with
`idx_outbox_status_priority_created_at ON outbox (status, priority,
created_at)` — the index shape that makes prioritized claiming an
`ORDER BY … LIMIT 1`. ADR 0013 is its decision record.

`inbound_event_queue` is a closer analogue still. Its columns map almost
one-to-one onto `DayProcessingJob`: `attempts`, `next_due_at`,
`lease_until` (*"0 = not leased; peek stamps this to `now +
leaseDuration` atomically"*), a text `status`, `committed_at`,
`last_error_reason`. Its `applied` status is documented as *"kept as an
append-only ledger for traceability"* — the same ledger role, solved with
partial indexes that exclude terminal rows from every hot query:

> Drain-path index. Partial on active statuses so the applied ledger
> (which can grow unbounded over time) is excluded from the index and the
> worker's peek query scans only the rows it can actually drain.

And the cost of *not* doing that was measured in this codebase
(`sync_db_tables.dart:287-296`):

> Without this partial the query full-scans the entire queue table on
> every worker idle tick — on a desktop mid-drain we measured 3500+ scans
> totalling 73s of DB time per hour with p95=46ms and max=2.3s.

That is the day-processing outbox's failure mode exactly: a full scan of
a ledger-bearing store on every idle tick. The sync queue fixed it with a
partial index. A directory of JSON files has no equivalent — there is no
way to index a subset of files, so the ledger and the drain path are
inseparable by construction.

## Decision

Move the day-processing outbox into a device-local Drift table.

### 1. A feature-owned database, not an existing one

A new `DayProcessingDb` under
`lib/features/daily_os_next/database/`. This matches how features own
their storage here (`database/agents/agent_database.dart`,
`features/ai_consumption/database/consumption_database.dart`,
`features/ai/database/ai_config_db.dart`).

Not `SyncDatabase`: ADR 0031's rejection of the sync outbox stands — that
database is the Matrix transport's domain. Not the agent database:
`agent_entities` rows sync between devices, and job state (claims,
leases, attempt counts) is strictly device-local and must never leave the
device.

### 2. Schema mirrors the existing job envelope

One row per job, primary key on the existing deterministic `id`, so
enqueue stays an idempotent upsert and the intent-conflict check is a
column comparison. The envelope columns (`status`, `day_id`, `kind`,
`created_at`, `updated_at`, `requested_at`, `next_attempt_at`,
`attempts`, `generation`, `claim_token`, `lease_until`,
`retry_not_before`, `last_failure_class`, `last_error`,
`result_transcript`, `result_entity_id`, `completed_at`) become real
columns; the kind-specific payload and `run_keys` stay serialized JSON,
as they are today.

### 3. Partial indexes separate the drain path from the ledger

Modelled directly on `inbound_event_queue`:

- Drain index over active statuses only — `queued`, `running`,
  `waitingForNetwork`, the three states `isDue` can return true for —
  keyed on the due-time ordering the claim uses. Terminal ledger rows
  are excluded, so ledger growth cannot slow claiming.
- A `(day_id, …)` index for Activity.

An index only helps if the readers change with it, so the callers are
part of this decision rather than a follow-up. All three current
whole-store readers become bounded queries:

- `DayActivityRepository` (`day_activity_repository.dart:85`) calls
  `outbox.getAll()` and keeps `job.dayId == dayId && job.activityEntryId
  != null`. It gains a day-scoped repository method backed by the day
  index (`WHERE day_id = ?`), so Activity stops reading the ledger of
  every other day.
- `DayAudioReviewFence._sweep()` (`day_audio_review_fence.dart:57`)
  calls `outbox.getAll()` and immediately skips every terminal job. It
  gains an active-status transcription query — served by the drain index
  — so sweep cost tracks outstanding work rather than install age.
- `DayProcessingRuntime.drainAndSchedule`
  (`day_processing_runtime.dart:82`) calls `getAll()` only to find the
  next due time. That becomes a `MIN(next_attempt_at)` probe over the
  drain index, the same shape as `inbound_event_queue`'s
  `earliestReadyAt`.

With those three converted, no caller reads the whole store and
`getAll()` is removed rather than left as a trap for the next reader.

### 4. Claiming becomes one conditional statement

> Superseded in part by the 2026-07-25 amendment at the end of this
> document: the select and the update turned out to be expressible as a
> single statement, which removes the race this section reasons about.

Claim is `UPDATE … SET status='running', claim_token=?, lease_until=? …
WHERE id=? AND <due predicate>` guarded by affected-row count; fenced
mutations become `WHERE id=? AND claim_token=? AND status='running'`.
This is strictly stronger than today's read-then-write under a Dart
mutex.

**A lost claim is not an idle drain.** Two claimers exist: the background
drain lane and the interactive foreground path
(`enqueueAndClaimTranscription` / `claimById`, used by
`capture_controller.dart:381`). Today `_serialize` orders them and the
loser simply observes `!isDue`. With a conditional `UPDATE` the loser
instead sees zero affected rows, and that must not be reported as "no
work": `drain()` breaks its loop on `DayProcessingRunResult.idle`
(`day_processing_outbox_processor.dart:253`), so collapsing the two would
stop a drain while other jobs are still due. The contract is therefore
explicit — zero affected rows means another claimer won, so re-select and
continue (bounded to avoid a livelock); only an empty candidate set is
idle.

**Ordering contract.** Selection is `SELECT … WHERE <active statuses>
AND <due predicate> ORDER BY … LIMIT 1`. The order key is deliberately
*not* a stored `priority` column. The sync outbox can store one
(ADR 0013) because its priorities are intrinsic to the message type;
day-processing priority is relative to the day the user is currently
looking at, so a stored column would have to be rewritten on every
navigation. The key is therefore a query-time expression bound to the
viewed day, ahead of the due-time ordering:

```sql
ORDER BY CASE day_id WHEN :viewedDay THEN 0
                     WHEN :today     THEN 1
                     WHEN :tomorrow  THEN 2
                     ELSE 3 END,
         next_attempt_at
```

The partial index serves the `WHERE`, so that expression is only
evaluated over rows that are actually claimable — bounded by outstanding
work, not by install age. Until priority-aware claiming ships as its own
change, the clause is `next_attempt_at` alone and the index serves it
directly. Moving between the two needs no schema change.

**What replaces the integrity machinery, precisely.** `_serialize` is
replaced by transactions. `_recoverPartials` and the atomic-rename write
are replaced by transaction atomicity: they exist to make a half-written
record impossible, which is what a rollback journal and WAL guarantee.

The SHA-256 envelope and `_quarantine` are **not** replaced, and that is
an accepted trade-off rather than an equivalence. They detect corruption
of an individual job record at rest and isolate the bad record so the
rest still drain. SQLite does not checksum data pages by default — WAL
frame checksums protect recovery, not stored pages — so the failure mode
changes shape, from one unreadable job file to a malformed-database
error, and the unit of recovery becomes the database rather than the
record.

That is acceptable here because the outbox already has a
record-independent recovery path: startup repair rebuilds jobs from
persisted `dayContext` provenance in the journal, which is the authority
for what the user actually recorded. A corrupt processing database can
therefore be discarded and rebuilt, where per-record checksums would only
have identified which single job to drop. If corruption is ever observed
in practice, `PRAGMA integrity_check` on open — or SQLite's checksum VFS
— restores detection without revisiting this decision.

Job lifecycle is unchanged; only its storage moves:

```mermaid
stateDiagram-v2
    [*] --> queued: enqueue (deterministic id)
    queued --> running: claim (lease + token)
    running --> succeeded: markSucceeded
    running --> queued: markFailure (retryable / missingAsset)
    running --> waitingForNetwork: markFailure (network)
    running --> waitingForUser: markFailure (setupRequired)
    running --> failed: markFailure (deterministic)
    running --> queued: lease expiry (crash recovery)
    waitingForNetwork --> queued: connectivity restored
    failed --> queued: retryNow / re-enqueue
    waitingForUser --> queued: retryNow / re-enqueue
    queued --> cancelled: cancel (recording deleted)
    succeeded --> ledger: no further processing
    cancelled --> ledger: no further processing
    ledger --> queued: re-enqueue (re-arm, fresh attempts)
    ledger --> [*]: retention prune
    note right of ledger
        Retained, not deleted. Activity and
        startup repair read these rows; the
        drain index excludes them. Only the
        retention prune removes them.
    end note
```

### 5. Retention becomes a policy, not a rewrite

Independently of any window, the partial indexes keep the ledger off the
hot path, so retention stops being a performance necessity and becomes a
disk-footprint and product question: how far back should Activity show
processing history?

The starting policy:

- **Eligible:** rows in a terminal status (`succeeded`, `cancelled`)
  whose `completed_at` is older than **90 days**.
- **Never eligible:** every non-terminal row, regardless of age. A job
  parked in `failed`, `waitingForUser` or `waitingForNetwork` is
  outstanding user intent that `retryNow` and re-enqueue can still
  resurrect, so age alone must never delete it. This keeps ADR 0031's
  durability guarantee intact.
- **Trigger:** one `DELETE` on the existing startup-repair pass, which
  already runs once per app start before the runtime drains
  (`DayProcessingRuntime.drainAndSchedule` gates on `_repairComplete`).
  No separate scheduler, no periodic timer.

90 days is chosen to comfortably outlive Activity's practical scroll-back
and to survive a long offline gap; it is a number to revisit if Activity
ever grows a longer history surface, not a constant to treat as load
bearing. The prune is a single indexed `DELETE` and is safe to interrupt
— a partial prune simply leaves rows for the next start.

### 6. Migration preserves in-flight work

A database transaction cannot span filesystem changes, so the cutover
needs a write barrier — otherwise a job enqueued after the scan but
before the sentinel would exist only on disk and become invisible the
moment the repository switches. Counting rows does not close that race,
because the count can match while the *identities* differ.

1. **Quiesce first.** Migration runs during app start, before
   `DayProcessingRuntime.start()` and before any enqueue path is wired
   up, so no writer is active against either store. This is the write
   barrier; everything below assumes it.
2. Import every job file into the table in one transaction. Deterministic
   ids make this an idempotent upsert.
3. **Verify by identity, not by count.** Re-scan the directory and
   compare the *set of job ids* against the table. If the re-scan turns
   up ids the table lacks, import those and repeat.
4. **Publish the sentinel inside the database**, in the same transaction
   as the final verifying scan — a row in a migration-state table, not a
   file. The table and a sentinel file would be separate durability
   domains, and a crash between them could expose a sentinel over an
   unpersisted import, making the still-authoritative files invisible.
   One transaction removes that failure mode by construction rather than
   by ordering rules. Until the sentinel row commits, the filesystem
   stays authoritative, so a crash anywhere earlier just re-runs the
   whole migration on the next start.
5. Leave the job files in place for one release, then delete them in a
   follow-up. They are dead weight, and they are also a free rollback.
6. Startup repair — which rebuilds jobs from persisted `dayContext`
   provenance in the journal — is unchanged and remains the second safety
   net for anything that still slips through.

**The verification is deliberately one-directional.** Every id on disk
must exist in the table; ids in the table with no corresponding file are
accepted and must *not* be deleted. Exact set equality would be the wrong
invariant here: no code path removes a job file to express intent —
cancellation is a `cancelled` status written *into* the file — so a
missing file never means "this job should not exist". It does mean
something specific, though: `_quarantine` renames a file whose checksum
fails, so a job successfully imported on one attempt can lose its file
before the next. Requiring equality would delete that row and turn a
recoverable state into actual data loss. Keeping it is the safe
direction, and after the migration the table is the only writer anyway.

The durability guarantee from ADR 0031 is unchanged: nothing the user
recorded loses its pending transcription across the migration.

## Consequences

- Claim cost stops depending on install age; it becomes an indexed lookup
  over active rows only.
- Priority-aware claiming (the fix for head-of-line blocking, where the
  day the user is looking at waits behind unrelated days) becomes an
  `ORDER BY` clause over a candidate set the partial index already
  bounds, with no schema change. Note this is weaker than the sync
  outbox's fully-indexed `idx_outbox_status_priority_created_at`: our
  order key is viewer-relative, so it is a query-time expression and the
  sort is not index-served. The sort input is bounded by outstanding
  jobs, which is the property that matters.
- Activity reads one day instead of the full ledger, and the review-fence
  sweep reads only non-terminal transcription jobs.
- The concurrency and torn-write machinery (`_serialize`,
  `_recoverPartials`, atomic-rename writes) is deleted outright.
  Per-record corruption detection (SHA-256 envelope, `_quarantine`) is
  given up rather than replaced — see the threat model in decision 4.
- Costs: one schema migration, one more database connection, and the loss
  of on-disk inspectability during debugging. The last is mitigated by a
  debug dump if it is ever missed in practice.
- Risk is concentrated in the migration. It is bounded by idempotent
  deterministic ids, verify-then-sentinel, retaining the files for a
  release, and the existing startup repair path.

## Rejected alternatives

- **Keep files, add pruning and an in-memory index.** This was the
  original shape of the fix. It rebuilds a database badly: the index can
  diverge from disk (sync, restore, external mutation), cold start has to
  rebuild it, there is no partial-index equivalent so the ledger cannot
  be separated from the drain path, and priority ordering stays bespoke.
  It also keeps every line of the integrity machinery.
- **Reuse `SyncDatabase`'s `Outbox` table.** ADR 0031's reasoning stands:
  that queue transports already-durable entities and does not represent
  pending inference.
- **Store jobs as agent entities.** `agent_entities` sync between
  devices; claims and leases must not.
- **Do nothing.** The cost is not static — it grows with every recording
  the user makes, and the ledger role guarantees the store only ever
  grows.

## Related

- ADR 0013 (outbox priority queue — the in-repo precedent for a
  prioritized durable queue in SQLite)
- ADR 0031 (batch-first day audio capture — introduced the file-backed
  outbox this ADR supersedes on storage; every other decision in it
  stands)
- ADR 0032 (hierarchical day agents — extended the outbox to agent jobs)

## Amendment 2026-07-25 — claiming is one statement, not two

Implementation showed decision 4's select-then-conditional-`UPDATE` was
solving a problem the design does not have.

Both statements run inside one drift transaction on a single connection, so
a second claimer cannot interleave between choosing a row and stamping it.
The generation guard could therefore never fail, the "a lost claim is not
an idle drain" branch was unreachable, and its retry loop was untestable
dead code that every future reader would still have to reason about.

Claiming is now a single atomic statement:

```sql
UPDATE day_processing_jobs
   SET status = 'running', updated_at = ?1, generation = generation + 1,
       claim_token = ?2, lease_until = ?3,
       last_error = NULL, last_failure_class = NULL
 WHERE id = (SELECT id FROM day_processing_jobs
              WHERE <due predicate> [AND kind IN (…)] [AND id = ?]
              ORDER BY created_at, id LIMIT 1)
RETURNING <columns>
```

`claimNext`, `claimById` and the interactive
`enqueueAndClaimTranscription` all route through it, differing only in the
predicate. There is no window to lose, so the lost-versus-idle distinction
disappears rather than being handled: an empty result means nothing was
due, which is the only reason a caller sees no claim. `RETURNING` also
hands back the row as written, so a claim reflects what is durable instead
of a locally reconstructed copy.

One consequence worth naming: the claim token is bound into the statement
before it runs, so an attempt matching no row still consumes one. Tokens
are opaque and unbounded, so gaps carry no meaning.

The fencing on *claimed mutations* (`WHERE id = ? AND claim_token = ? AND
status = 'running'`) is unchanged — that guards a genuinely concurrent
case, where a claim holder reports back after the job was terminalized by
reviewed text or a cancellation.

---

### Adr 0045 Exclude Unverified Devices From Key Sharing (`docs/adr/0045-exclude-unverified-devices-from-key-sharing.md`)

# ADR 0045: Exclude Unverified Devices from Key Sharing

## Status

Accepted

## Date

2026-07-26

## Context

### One ghost device could halt all sync

Sync replicates one user's data across their devices over end-to-end
encrypted Matrix. The app never bootstraps cross-signing, so the Matrix SDK's
default key-sharing policy (`ShareKeysWith.crossVerifiedIfEnabled`) degrades
to *share megolm keys with every non-blocked device*. Emoji (SAS)
verification therefore did not gate the cryptography at all — the only
confidentiality backstop was an app-level tripwire in
`MatrixMessageSender.sendMatrixMessage`, which refused to send **anything**
while `unverifiedDevices()` was non-empty.

That conflated two very different goals:

- *Confidentiality*: an unverified device must not receive key material.
- *Availability*: trusted devices should keep syncing.

The tripwire bought the first by destroying the second. A single unverified
device — typically a session left behind by an uninstalled app that never
logged out — silently stopped outbound sync on **every** device, and because
the dead session could never complete a verification, the outage was
permanent until the device was deleted (the support case that produced the
device-management roster, PRs #3609/#3614).

### Why flipping the policy is migration-safe

`ShareKeysWith.directlyVerifiedOnly` requires each *sender* to have
SAS-verified every device it shares keys with. The old tripwire already
enforced exactly that, more brutally: a device could not send at all until
its own unverified list was empty. So any install that has ever successfully
sent had already verified its full mesh — for such installs the policy flip
excludes nobody and changes nothing. For wedged installs (the ghost-device
case) it restores sync among the trusted devices. The newly-excluded case —
sender shares with a device it never verified — previously meant "sender
halts entirely", so availability strictly improves and confidentiality never
weakens.

Legacy rooms paired under the old one-user-per-device model verify
cross-user via SAS; `directlyVerifiedOnly` honours direct verification
regardless of which user owns the device, so those rooms keep working under
the same full-mesh requirement the tripwire already imposed.

## Decision

1. Construct the sync `Client` with
   `shareKeysWith: ShareKeysWith.directlyVerifiedOnly`
   (`lib/features/sync/matrix/client.dart`, shared by the default and actor
   paths). The SDK now withholds megolm keys from any device the sending
   session has not directly verified: an unverified device receives
   ciphertext it can never decrypt.
2. Demote the sender tripwire from a halt to a log line. Sends proceed while
   unverified devices exist; the device roster's warning banner
   (`SyncDevicesList`) remains the user-facing signal and names the remedy
   (verify or delete).
3. Keep the banner and roster semantics: an unverified device with published
   keys is now *excluded from new entries* rather than *blocking everyone*,
   and the copy says so.

Deliberately **not** done here:

- Cross-signing bootstrap. It would let a user verify once per device instead
  of per pair, but it is a larger lift (SSSS, recovery keys, migration) and
  orthogonal to removing the outage. `directlyVerifiedOnly` remains correct
  if cross-signing is added later.
- Blocking (`DeviceKeys.setBlocked`). A blocked device is by definition
  unverified, so blocking alone would have made the old outage permanent; it
  buys nothing over exclusion.

## Consequences

- A dead session can no longer wedge sync. Removal (or verification) is
  hygiene and roster clarity, not an unblock step.
- A freshly paired device syncs with each peer as soon as that peer has
  verified it — the pairing flow's auto-launched ceremony per device pair is
  now load-bearing for coverage, exactly as the old tripwire made it.
- If a pair is never verified, entries sent by one side are permanently
  unreadable by the other (no key backup exists). The roster banner is the
  guard rail; the sequence-log/backfill layer treats such gaps like any
  other missing counters.
- The verification state is per-install local trust. A reinstalling device
  starts unverified everywhere and must re-verify with each live peer —
  unchanged from before, but now the cost is scoped to that device instead
  of the whole mesh.

---

### Adr 0046 Sync Actor Isolate Removed And How To Rebuild (`docs/adr/0046-sync-actor-isolate-removed-and-how-to-rebuild.md`)

# ADR 0046: Remove the Sync Actor Isolate, and How to Rebuild It

## Status

Accepted

## Date

2026-07-29

## Context

### A complete subsystem that nothing could reach

`lib/features/sync/actor/` held 1910 lines of production code and 5498 lines
of tests implementing Matrix sync inside a dedicated worker isolate. It was
built in three phases — [#2669](https://github.com/matthiasn/lotti/pull/2669)
(minimal actor), [#2671](https://github.com/matthiasn/lotti/pull/2671) (SAS
verification), [#2672](https://github.com/matthiasn/lotti/pull/2672) (outbound
pipeline) — against a plan at
`docs/implementation_plans/2026-02-12_actor_based_sync_isolate_plan.md`.

Nothing in the app ever spawned it. `SyncActorHost.spawn` was called only from
its own unit test and one integration test. The `enable_sync_actor` config
flag existed and was seeded into every install's database, but no code read
it — the wiring that would have made it mean something (plan phase 5) never
landed, and neither did phase 4 (inbound processing and direct DB writes).

### The code was not free

Dead code that is never touched costs nothing. This was touched repeatedly.
It was carried through the Flutter 3.44 upgrade
([#3197](https://github.com/matthiasn/lotti/pull/3197)), the file-size
refactor ([#3301](https://github.com/matthiasn/lotti/pull/3301)), two
test-improvement passes ([#3283](https://github.com/matthiasn/lotti/pull/3283),
[#3286](https://github.com/matthiasn/lotti/pull/3286)), and — most tellingly —
ADR 0045's unverified-device key-sharing change
([#3619](https://github.com/matthiasn/lotti/pull/3619)), a real behavioural fix
that had to be reimplemented on a path no user could reach.

It also distorted unrelated work. The invite/room-discovery removal
([#3661](https://github.com/matthiasn/lotti/pull/3661)) had to preserve
`MatrixSdkGateway.createRoom` and relocate the `m.lotti.sync_room` marker
constant into `matrix/consts.dart` for no reason other than that the actor's
outbound queue read them.

### Finishing it had grown much larger than "two more phases"

The plan's defining constraint was isolation: *"Completely separate: no
dependencies on existing `MatrixService`, `OutboxService`, or sync pipeline
code."* That was affordable in early 2026. Since then the live receive path
gained four subsystems the actor knows nothing about:

- `queue/` — the persistent inbound queue, per-room worker, `onSync` catch-up
  bridge, and durable late-key resume floor, now **the only receive path**
- `sequence/` — `(hostId, counter)` coverage tracking and gap detection
- `backfill/` — missing-counter requests, and responses that resend, mark
  deleted, or hint unresolvable
- `media/` — self-healing attachment fetch
  ([#3648](https://github.com/matthiasn/lotti/pull/3648))

plus dequeue-time outbox bundling and the attachment index. Reaching parity
would mean either abandoning the isolation constraint or implementing all of
that a second time.

### The problem it solved is not one we currently observe

The stated goal was *"eliminate sync-induced frame drops by isolating
network/crypto/sync work from the render thread."* No such jank is being
reported or measured today. The subsystem was paying maintenance rent against
a symptom we do not have.

## Decision

**Remove `lib/features/sync/actor/`, its tests, its integration test, and the
`enable_sync_actor` flag.** Record here what was learned, so the work is
recoverable if UI-isolate jank ever makes it necessary.

This ADR is the deliverable that justifies the deletion. The value in those
lines was the design, not the code.

## Consequences

- Sync runs entirely on the UI isolate, as it already did in practice.
- ~7400 lines leave the repo; future sync changes stop needing a second,
  unreachable implementation.
- Existing installs carry a stale `enable_sync_actor` row. Flags are seeded
  with `insertFlagIfNotExists`, which never deletes, so removing the seed
  alone leaves the row in every upgraded install forever — stored, emitted by
  `watchConfigFlags`, and readable by name. It was never a *visible* toggle:
  `FlagsBody` renders only the names in its `defaultDisplayedItems` whitelist,
  and `enable_sync_actor` was never on it. `initConfigFlags` now ends by
  deleting every name in `retiredConfigFlags` — storage cleanup, and the
  mechanism to use whenever a flag is retired.
- If jank appears later, the rebuild starts from this document rather than
  from a stale branch.

## How to rebuild it, if needed

### First, confirm the premise

Rebuild only against a measured symptom. `SyncEventProcessor.process()` is the
suspect: vector clock validation, entity deserialization,
`JournalDb.updateJournalEntity()`, embedded entry-link processing, sequence-log
writes and notification dispatch, all on the UI isolate, per inbound event.
Profile that under a realistic catch-up burst before writing any code.

Note that the queue pipeline already smooths this somewhat — inbound work is
drained by a per-room worker rather than processed inline on the sync tick.
Establish that the remaining cost is still a render-thread problem.

### What proved sound

**Direct DB writes, no apply/ack protocol.** The design was for the actor to
open its own connections to the same SQLite files as the main isolate and
write through them, rather than shipping every change back over a port. SQLite
handles this: WAL mode, `busy_timeout = 5000` and `synchronous = NORMAL` are
set in `_setupDatabase()`, so readers do not block writers. This removed an
entire class of complexity from the original design and should be kept.

Be precise about how far this was actually proven, because a rebuild will
inherit the gap. **The only database the actor ever opened was
`SyncDatabase`** — `SyncActorCommandHandler` constructed it through a
`SyncDatabaseFactory`, and `OutboundQueue` claimed and updated outbox rows
through it directly. `JournalDb` and `SettingsDb` from a second isolate is
plan phase 4, which never landed (see above). So cross-isolate writes are
demonstrated for the outbox and *inferred* for the journal.

**Notification-driven UI refresh.** All sync-affected Drift `watch()` calls
were replaced with `notificationDrivenStream()` fed by `UpdateNotifications`
(see `docs/implementation_plans/2026-02-12_remove_sync_affected_drift_watch.md`).
This means a worker isolate does **not** need `markTablesUpdated()` or a
`DriftIsolate` workaround — it emits affected entity ids plus type-notification
keys, and the host calls `UpdateNotifications.notify(ids, fromSync: true)`.
That indirection is what makes cross-isolate DB writes viable, and it is
already in place.

Wire format detail worth keeping: send `List<String>`, not `Set`, because
`Set` is not a guaranteed-safe isolate transfer type.

**A flat command/event protocol over `SendPort`.** Commands carry
`{command, requestId, replyTo, ...payload}`; responses carry
`{ok, requestId, error?, errorCode?, ...result}`; events carry
`{event, ...payload}`. No priority queues or QoS. A small state model with
out-of-state commands answered `errorCode: 'INVALID_STATE'`. This was enough
for login, room join, SAS verification and send/receive, and did not need to
grow.

The states were `uninitialized`, `initializing`, `idle`, `syncing`,
`stopping`, `disposed`, but they were **not** a single linear chain, and a
rebuild that assumes one will get the valid-command table wrong:

```mermaid
stateDiagram-v2
  [*] --> uninitialized
  uninitialized --> initializing: init
  initializing --> syncing: init completes, background sync started
  initializing --> uninitialized: init fails
  syncing --> idle: stopSync
  idle --> syncing: startSync
  syncing --> stopping: dispose
  idle --> stopping: dispose
  stopping --> disposed
  disposed --> [*]
```

`init` went straight to `syncing` — it started background sync as part of
initialization — so `idle` was reachable **only** by an explicit `stopSync`,
and `startSync` was rejected unless the actor was already `idle`.

**Integration-test-driven development.** The docker-backed two-client test was
the specification, and each phase extended it. That kept the actor honest
about real homeserver behaviour in a way unit tests could not.

### The trap that will bite again

**Legacy sync services self-start in their constructors.** Gating the actor
behind a flag is not a matter of skipping `MatrixService.init()`:

- `OutboxService`'s *constructor* calls `_startRunner()` (creating a
  `ClientRunner` and a watchdog timer) and subscribes to connectivity, login
  state, and `watchOutboxCount()`. **Constructing it starts sending.**
- `MatrixService`'s *constructor* subscribes to connectivity and builds the
  `MatrixStreamConsumer` pipeline object. It does **not** start that pipeline
  and does not kick off a rescan: `init()` does, via `_startQueuePipeline()`,
  and `get_it_helpers.dart` calls `init()` separately.

The invariant is: **when actor mode is active there must be exactly zero
legacy sync producers running**, and the actor is sole owner of the Matrix
client, sync loop and outbound sends. The two services need different
treatment to get there, and conflating them is what makes the problem look
harder than it is. For `MatrixService`, skipping `init()` is sufficient to
keep it inert — construction leaves an idle pipeline object and a
connectivity listener, neither of which sends or syncs. For `OutboxService`,
only preventing *construction* works, and that is what breaks consumers
resolving the singleton unconditionally (`main.dart`'s provider override, the
`beamer_app` login-gate toast, sync maintenance, and the room/stats
providers). Any rebuild should extract a `startSyncServices()` seam first and
test that the flag-on path completes startup without constructing
`OutboxService` or calling `MatrixService.init()`.

Read-only consumers of `SyncDatabase` and `JournalDb` may keep running. The
outbox monitor page also writes (`updateOutboxItem`, `deleteOutboxItemById`),
and that is the one genuine conflict: the actor's own `OutboundQueue` claimed
and updated the same outbox rows. Ownership of `SyncDatabase` has to be
settled explicitly in a rebuild — either the actor owns the outbox and the
monitor page becomes read-only, or the monitor keeps its writes and the two
coordinate through row claims. It cannot be left implicit as it was.

### What has changed since, and must be decided up front

The isolation constraint that made the original plan tractable is now the
hard part. Before writing code, decide explicitly how the actor obtains
`queue/`, `sequence/`, `backfill/` and `media/` behaviour: share those
subsystems across the isolate boundary, or accept a second implementation and
the divergence risk that comes with it. Do not start with the constraint
unexamined — that is what made the original effort unfinishable.

## References

- Removed implementation plan:
  `docs/implementation_plans/2026-02-12_actor_based_sync_isolate_plan.md`
  (deleted with this change; recoverable from git history at `3fc322b29`)
- ADR 0045 — the key-sharing change that had to be applied twice
- `docs/implementation_plans/2026-02-13_drift_wal_read_pools.md` — WAL and
  read-pool work that the direct-write design depends on
- `docs/implementation_plans/2026-02-12_remove_sync_affected_drift_watch.md` —
  the notification-driven refresh that removes the cross-isolate `watch()`
  problem
- `knowledge/features/sync/` — how sync actually works today

---

### Adr 0047 Lean Keyboard Command Catalog Metadata (`docs/adr/0047-lean-keyboard-command-catalog-metadata.md`)

# ADR 0047: Lean Keyboard Command Catalog Metadata

## Status

Accepted

## Date

2026-08-01

## Context

ADR 0030 established the typed desktop command system and described every
catalog definition as carrying command-context metadata and a destructive
status. The implementation subsequently proved that both concerns already have
stronger runtime owners:

- command availability and context are determined by the mounted
  `AppCommandScope` hierarchy and its enabled handlers;
- destructive confirmation belongs to the feature handler or UI action that
  performs the mutation.

No execution, menu, palette, help, or presentation surface consumed the
catalog's `context` or `destructive` fields. Retaining them therefore duplicated
runtime state without enforcing behavior and made the typed catalog claim a
contract its consumers did not use.

## Decision

Keep `AppCommandDefinition` limited to metadata shared by active consumers:

- stable command id;
- user-facing category;
- platform shortcut bindings;
- command-palette visibility; and
- key-repeat policy.

Do not encode scope context or destructive status in the catalog.
`AppCommandScope` and `AppCommandHandler` remain the authority for contextual
availability. Feature-owned handlers remain responsible for confirmation and
other safety checks before destructive work.

This decision supersedes only the `context` and `destructive` metadata clauses
in ADR 0030 decisions 2 and 6. The rest of ADR 0030 remains accepted.

## Consequences

- The catalog contains no unused metadata and cannot drift from the mounted
  handler graph.
- A destructive command is not made safe merely by catalog classification;
  safety stays at the mutation boundary where it can be tested with the actual
  feature behavior.
- Adding a new contextual command requires a scoped handler and an appropriate
  palette visibility value, not a second context enum.
- A future presentation surface that genuinely needs destructive styling must
  introduce an enforced contract with a consumer, rather than restoring an
  advisory field.

## Related

- [ADR 0030: Desktop Keyboard Command System](./0030-desktop-keyboard-command-system.md)
- [PR #3721](https://github.com/matthiasn/lotti/pull/3721)

---

### Adr 0048 One Device Runs The Coordinator Digest (`docs/adr/0048-one-device-runs-the-coordinator-digest.md`)

# ADR 0048: One device runs the coordinator digest

## Status

Accepted

## Date

2026-08-01

## Context

ADR 0032 specified the coordinator digest's *cadence* but never said which
device performs it. That gap had a cost. The digest is armed as a single synced
`scheduledWake` record with a deterministic id, so every device signed in to the
account saw the same record come due, and every device ran the same inference:
N devices, N model charges, one useful result, every window, forever.

It is a spend and battery problem rather than a correctness one — the digest's
writes are registers recomputed from source, so duplicate runs converge on the
same answer — but it recurs indefinitely and scales with how many devices a
person uses.

## Decision

A scheduled-wake record whose work is **shared** rather than device-local
carries a lease. The coordinator digest is the only such record today; per-day
agent wakes remain device-local and unleased.

A device that finds a leased record due writes `leaseHostId` and `leaseUntil`
into it, waits a settle period, re-reads the record, and proceeds only if the
surviving claim is still its own.

The election needs no coordinator because the record is already a
last-write-wins register: concurrent claims converge to exactly one surviving
host, and the settle period is what gives that convergence time to happen before
anyone acts on it. The lease expires, so a device that claims and then crashes or goes offline
before consuming the record delays the window rather than dropping it: any
device may take over past `leaseUntil`.

That recovery covers the claim, **not** the run. A device that crashes *after*
the record flips to `consumed` but before its in-memory job finishes loses that
day's briefing: cold-start bootstrap sees a consumed record and arms the next
day's slot rather than retrying today's. This predates the lease — it follows
from consuming the record before running — and is tracked separately rather
than fixed here.

`leaseUntil` is stored in **UTC**. Entities cross devices as JSON, and
`toIso8601String()` on a local `DateTime` emits no offset, so a peer's
`DateTime.parse` would re-read the same wall-clock components in its own zone: a
west-to-east claim would appear already expired and be taken over immediately —
both devices firing, the exact duplicate this lease exists to prevent — while
the opposite direction would stretch a 30-minute lease by hours. For the same
reason the settle is measured from `leaseUntil` minus the lease duration rather
than from `updatedAt`, which is serialized without an offset.

## Consequences

- **While devices can see each other's writes**, the digest costs one inference
  per window regardless of device count. That is the whole point of the change,
  and it is conditional on sync — see the third bullet for what happens when it
  is unavailable.
- A window can be delayed by up to `leaseDuration + leaseSettle` when a claimant
  dies immediately after claiming: the record stays claimed until `leaseUntil`,
  and the device that takes over then writes its own claim and waits out its own
  settle before firing. With the defaults that is about 33 minutes. It is never
  skipped.
- The lease is a **cost** mechanism, not a correctness one. It narrows the
  double-fire window rather than closing it: devices partitioned from sync while
  their model providers stay reachable can each hold a locally-consistent claim
  and both fire. That is acceptable because a duplicate digest is redundant
  spend, not a wrong result, and closing it fully would require a consensus
  round the app has no coordinator for.

## Related

- ADR 0032 (hierarchical day-agent coordination — establishes the digest and its
  cadence; this ADR fills in which device runs it)
- ADR 0022 (long-lived planner)

---

### Adr 0049 Profile Scoped Storage And Demo Mode (`docs/adr/0049-profile-scoped-storage-and-demo-mode.md`)

# ADR 0049: Profile-scoped storage and the demo-mode sync boundary

Date: 2026-08-05
Status: accepted

## Context

Demo mode needs a play world with complete isolation from real data: its own
root path, databases, settings, and sync identity, with zero possibility of
cross-contamination. Before this change the app had two independent root
resolution mechanisms (the getIt `Directory` singleton for file I/O, and a
fresh `findDocumentsDirectory()` call inside every database open), several
device-global stores (SharedPreferences, keychain, TTS model cache), and a
sync stack whose `enable_matrix` flag gated only outbox *sends* — enqueues,
the inbound pipeline, backfill timers, and a startup node-profile broadcast
all ran unconditionally.

## Decision

**One path authority.** The getIt `Directory` singleton is registered to the
active profile root; `openDbConnection` falls back to it and never re-derives
the OS path once a root is registered. Guest worlds nest under
`<realRoot>/guest_profiles/<uuid>/`; the real world stays at the existing
root, unmoved (backward compatible).

**Per-profile (inside the profile root):** all Drift databases including
`settings.sqlite` (hence the sync host ID `VC_HOST`, minted fresh per world),
entity JSON sidecars, media, waveform caches, agent files, logs, backups,
embeddings, and — real world only — the `matrix/` session store.

**Global (device):**

| Store | Scope rationale |
|-------|-----------------|
| SharedPreferences (whats-new seen, `seen_` hints, recording style, backfill toggle) | Device-level UX memory; not path-scopable; leaking "seen hint X" into a demo is desirable, carries no user data. |
| Keychain `MATRIX_CONFIG` (Matrix credentials) | OS keychains are app-scoped. Stays global and real-only: guest worlds never construct a reader (see below), and keeping it global preserves a future "promote demo to synced" without re-login. |
| Window geometry | Device/hardware state — moved from SettingsDb to SharedPreferences (with one-time migration) so a switch doesn't snap the window. |
| TTS model cache (`tts_models/`) | Content-addressable blobs, no user data; hundreds of MB not worth duplicating. |
| OS temp dir / `sqlite3.tempDirectory` | Anonymous transient spill files, process-global property. |
| `profiles.json` | The registry lists worlds; by definition it cannot live inside one. |

**Sync is structurally absent in guest worlds, not disabled.** Registration
branches on `ProfileCapabilities.syncEnabled`: guests get an
`InertOutboxService` (all enqueues are counted no-ops) and none of the Matrix
stack — no client, no inbound queue, no backfill timers, no broadcasts, no
VC-burn handlers. This is stronger than any flag: a guest world produces zero
outbox rows and has no code path that reads the keychain credentials.

## Sync-config sharing analysis (requirement 9)

Sharing the Matrix *credentials* store between worlds is safe **only**
because guest worlds have no reader. Sharing sync *state* (room id, host id,
sequence log) would be catastrophic — a demo world writing into the real
outbox or claiming counters in the real sequence space corrupts the real
device's sync history. Hence: credentials global-but-unread, all sync state
per-profile. Should a guest world ever be promoted to a synced world, it
must (a) keep its own host ID, (b) create or join a **new** room — never the
real room — and (c) opt into the full stack via capabilities. That promotion
is explicitly out of scope here and recorded as an open question.

## Consequences

- Existing installs see no change: no registry file means "real world,
  active"; the first mutation writes `profiles.json`.
- Every database or store added in the future MUST resolve its path through
  the registered root (or an explicit provider) and be added to
  `ServiceDisposer` + `WorldHandle`; the audit tests fail on OS-path
  re-derivation.
- The demo world's logs, backups, and slow-query captures land inside the
  guest directory and are deleted with it.
- In-app switching tears down the whole service generation; anything holding
  a getIt singleton across generations is a bug (the generation-keyed
  ProviderScope is the enforcement mechanism for widgets).

## Open questions

- Promoting a guest world to a synced world (new room, existing credentials)
  — deliberately unimplemented.
- Multiple concurrent guest worlds are supported by the registry; the UI
  exposes a single demo world for now.
- Peer tenants (separate *work* and *private* worlds, both synced) generalise
  this decision beyond demo mode. What already carries over, what blocks it,
  and the recommended shape are in
  [ADR 0050](./0050-multi-tenant-worlds.md) — proposed, not scheduled.

---

### Adr 0050 Multi Tenant Worlds (`docs/adr/0050-multi-tenant-worlds.md`)

# ADR 0050: Multi-tenant worlds

## Status

Proposed

## Date

2026-08-05

## Context

[ADR 0049](./0049-profile-scoped-storage-and-demo-mode.md) built a profile
system to isolate one demo world from real data. It generalises further than
the feature that motivated it: a **profile is a complete world**, and the demo
is simply the first non-real one. The obvious next question — repeatedly
raised — is whether a user could keep *work* and *private* as separate worlds
on the same device, each with its own data and its own sync.

Nothing in the codebase decides this today. ADR 0049 gestures at it under
"Open questions" ("promoting a guest world to a synced world", "multiple
concurrent guest worlds") but records no position on peer tenants. This ADR
exists to hold that position explicitly rather than leaving it implied by
what the code happens to permit.

Nothing here is scheduled. The value is in recording what already
generalises, what does not, and which of the blockers is load-bearing — so
that the next person to touch profiles does not discover it by trial.

## What already generalises

The switching machinery is tenant-shaped, not demo-shaped:

- `ProfileRegistry` stores a list of profiles with an active-profile marker;
  `setActiveProfile` and `rootFor` are id-generic and type-blind.
- `ProfileSwitcher.switchTo(id)` tears down and rebuilds an entire service
  generation for **any** profile id — quiesce, `ServiceDisposer.disposeAll()`,
  `getIt.reset()`, re-bootstrap, bump the `ProviderScope` generation key. It
  contains no demo-specific logic.
- `WorldHandle.open(root)` opens a full, non-active database set with explicit
  documents-directory providers — the mechanism for touching a world you are
  not currently living in.
- Per-world storage is complete: every Drift database including
  `settings.sqlite`, and therefore the sync host ID (`VC_HOST`) and the Matrix
  room id (`MATRIX_ROOM`, `lib/features/sync/matrix/consts.dart`), plus
  sidecars, media, logs, backups and embeddings.

A second tenant would inherit all of that unchanged. The gap is not the
switch; it is the model, the capability derivation, and one device-global
store.

## Blockers

Four, in the code as it stands:

1. **Exactly one real profile is representable by construction.**
   `Profile.tryFromJson` rejects `type == ProfileType.real` with a non-empty
   `dirName`, and rejects any guest whose `dirName` does not start with
   `guest_profiles/` (`lib/features/profiles/model/profile.dart`). The real
   world *is* the root. A peer tenant needs its own directory, which the model
   currently refuses to parse.

2. **Only guests can be created.** `ProfileRegistry.createGuestProfile` is the
   sole creation API and hard-codes the type and the `guest_profiles/` prefix.

3. **Capabilities are derived from the type, not carried.**
   `ProfileContext.forProfile` maps `isGuest` onto the frozen
   `ProfileCapabilities.guest` / `.real` presets, so sync and health import are
   on if and only if the world is the real one. Peer tenants need capabilities
   decoupled from `ProfileType` — a second synced world is `real`-capable
   without being *the* real world.

4. **The Matrix credential store has no world dimension — and this is the
   load-bearing one.** `matrixConfigKey = 'MATRIX_CONFIG'`
   (`lib/features/sync/matrix/consts.dart`) is a single device-global keychain
   entry. ADR 0049 permits that sharing *only* because guest worlds never
   construct a reader. Two sync-enabled worlds break that premise directly:
   both would read the same credentials and sync as the same account. Room ids
   are already per-world, so the rooms would differ — but the account, the
   device keys, and the key-sharing decisions would not.

Two further consequences, softer but real:

- **Layout.** Guests nest *inside* the real root, which is correct for a
  disposable play world and wrong for a peer: deleting or relocating the real
  world would take the other tenant with it. Peers want siblings under a
  container root — which means moving the existing real world, precisely the
  migration ADR 0049 avoided in order to stay backward compatible.
- **Device-global surfaces beyond storage.** OS notifications are scheduled
  against a single plugin instance with ids derived per entity
  (`NotificationScheduler.notificationIdFor`) plus fixed constants such as the
  day-plan and conflict notification ids. Two tenants would overwrite each
  other on the fixed ids, and a notification tapped while the *other* tenant is
  active deep-links into a world that is not loaded. Background wake
  scheduling has the same shape.

## Decision

**Multi-tenancy is the intended generalisation of profiles, and demo mode is
one tenant class within it — but it is not implemented, and no code should be
shaped speculatively for it.** Concretely:

- `ProfileType` stays `real | guest` until a peer-tenant feature is actually
  scheduled. Adding a third value now would spread unexercised branches
  through registration.
- The isolation invariants in ADR 0049 are the durable part and hold for any
  future tenant: one path authority, per-world sync state, capability-gated
  registration, nothing device-global that carries user data.
- Any work that touches profiles must not deepen the four blockers — in
  particular, no new code may assume "guest" and "not the real world" are the
  same predicate, or that capabilities can be re-derived from `ProfileType` at
  the point of use rather than read from `ProfileContext.capabilities`.

When peer tenants are scheduled, the recommended shape is:

| Blocker | Recommended resolution |
|---------|------------------------|
| Model | Keep `dirName` as the discriminator, drop the type↔dirName coupling in favour of a `container/<uuid>` prefix validated for the same traversal safety. The real world keeps its empty `dirName` forever. |
| Creation | Generalise to `createProfile({type, name})`; `createGuestProfile` becomes a thin caller. |
| Capabilities | Persist capabilities on the `Profile` (defaulting from type on read), so a synced peer is expressible without a new type. |
| Credentials | Per-profile keychain key `MATRIX_CONFIG:<profileId>`, with a one-time migration of the existing entry to `MATRIX_CONFIG:real`. Each tenant creates or joins its **own** room; no tenant may ever join another's. |
| Layout | Leave the real world at the root. Peers go under a sibling container, not under `guest_profiles/`. Do not migrate the real root. |
| Notifications | Tenant-qualify the fixed notification ids and record the owning profile id in the payload, so a tap either switches worlds deliberately or is dropped. |

## Consequences

- The demo feature ships without waiting on any of this, and the machinery it
  introduced is reusable rather than throwaway.
- The credential-scoping migration is the single largest piece of work behind
  peer tenants, and it lands in the security-sensitive part of the codebase —
  it should not be attempted incidentally alongside a UI feature.
- Until this ADR moves to Accepted, "can I have work and private worlds?" has
  a documented answer: not yet, and here is exactly what it costs.

## Related

- [ADR 0049: Profile-scoped storage and the demo-mode sync boundary](./0049-profile-scoped-storage-and-demo-mode.md)
- [Profiles and demo mode](../../knowledge/architecture/profiles-and-demo-mode.md)
- [ADR 0045: Exclude unverified devices from key sharing](./0045-exclude-unverified-devices-from-key-sharing.md)
  — the key-sharing rules a second synced tenant would have to satisfy
  independently.

---

### Adr 0051 Agenda Gated Tool Exposure (`docs/adr/0051-agenda-gated-tool-exposure.md`)

# 0051 — Gate tool exposure on what the wake already knows

## Status

Proposed

## Date

2026-08-08

## Context

Every task-agent wake advertises the full deferred tool set — fifteen user-gated
tools plus `update_report`, `record_observations`, `retract_suggestions` and
`get_related_task_details` — in the first request, regardless of what the wake
is for. `TaskAgentContextBuilder.buildToolDefinitions()` takes no arguments and
returns everything enabled. Restraint is then requested in prose.

The 2026-08-08 real-wake suite shows prose does not deliver it. In the `noOp`
scenario — accurate prior report, no outstanding request, a closing note with no
new fact — four of five models rewrote the report anyway. No model proposed a
data change, so the failure is narrow: they cannot leave a correct report alone.
Only Qwen3.6 27B was consistent, at 3/3.

The obvious response is to ask the model what the wake is for before handing it
any tools, and expose only what it names. **That was the first form of this ADR
and it does not survive its own arithmetic.**

An agenda turn sends the full wake context — 9,004 characters on the mid-sized
scenario — plus one tool. The second turn then sends the same context again with
a filtered tool list. Input roughly doubles to save the tool-definition slice,
which is a fraction of the payload. It is net *more* tokens, not fewer, which
inverts the lean-payload finding used to justify it: Qwen3.6 27B improved 10/14
to 13/14 as the prompt got **smaller**. It also adds a full round trip to a
27B wake that already takes 41–50s against GLM 5.2's 13s.

The useful idea underneath is narrower and cheaper: **do not offer a tool that
cannot legitimately be used in this wake.** Almost all of that is decidable
without asking anyone. `execute()` already receives `triggerTokens`;
`reportStaleAt`/`reportFreshAt` already track whether the report is stale; the
context builder already knows whether a timer is running, whether the task has
checklist items, whether label definitions exist, and whether the ledger holds
open proposals.

## Decision

Make `buildToolDefinitions()` a function of the wake's known state instead of a
constant, and gate each tool on the fact that makes it usable. No extra
inference call.

| Tool | Offered when |
| --- | --- |
| `update_report` | something material changed since the last report |
| `update_running_timer` | a timer is running **for this task** |
| `create_time_entry`, `update_time_entry` | the task has time records or a timer |
| `update_checklist_items` | the task has at least one checklist item |
| `assign_task_labels` | label definitions exist for the category |
| `retract_suggestions` | the ledger has open proposals |
| `resolve_attention_request` | this agent has an active claim on the task |
| `migrate_checklist_items` | a follow-up task was created this wake |
| `set_task_language` | the task has no language, or the context disagrees |

Several of these are correctness fixes independent of payload. Offering
`update_running_timer` when no timer exists invites a hallucinated timer id;
offering `resolve_attention_request` with no claims invites a fabricated claim
id. A tool that cannot succeed is an invitation to invent its arguments.

`update_report` is the one that answers `noOp` directly: when nothing changed
since the report was written, the tool is absent and the wake cannot churn it.

```mermaid
stateDiagram-v2
  [*] --> BuildContext
  BuildContext --> GateTools: triggerTokens, watermarks, timer, ledger, checklists
  GateTools --> Quiet: no tool is usable
  GateTools --> Turn: offer only usable tools
  Turn --> Persist
  Quiet --> Persist: plain-text note, no report write
  Persist --> [*]
```

**The agenda turn is rejected for now**, not deferred as obviously-next. It
would only earn a round trip for decisions that genuinely need prose
comprehension the app cannot do — "does this note ask me to split the task?" —
and no measurement yet shows those failing. If it is revisited, phase one must
receive a *reduced* context (changed entries plus the current report), not the
full wake, or the arithmetic stays against it.

## Consequences

**What this buys.** Restraint becomes structural where the app has the facts:
a wake with nothing to report cannot rewrite the report. Payload strictly
shrinks — the opposite of the agenda design — which the lean-payload result
predicts helps smaller models most. Several hallucination invitations disappear.
Zero additional latency or spend.

**What it costs.** The gates are now app logic that can be wrong in a new way. A
gate that is too aggressive silently removes a capability the wake needed, and
the model cannot report a tool it was never offered. This is the main risk and
`requalification` is the guard against it.

**What it does not fix.** Anything requiring judgement about prose. If a model
declines to act on an instruction buried in a note, gating does not help — it
only ensures the tool was available.

**Prefix caching.** Prompt blocks are ordered stable-first so a prefix cache can
restore the header. A per-wake tool list perturbs the cacheable prefix, so tool
definitions must sit after the stable blocks and the hit-rate effect needs
measuring. This applies to any variable tool list, agenda or not.

**Migration.** Additive and flagged: with gating disabled the tool list is
today's, so both can be evaluated side by side before either becomes default.

## Evaluation plan

Before and after on `penguin_wake_workflow_eval_live_test.dart`, three samples
per model across GLM 5.2, Kimi K3, Qwen3.5 397B, Qwen3.6 27B and DeepSeek V4
Flash 0731:

| Scenario | Current | Target |
| --- | --- | --- |
| `noOp` | 27B 3/3; GLM 1/3; Kimi, 397B, DeepSeek 0/3 | all 3/3 — `update_report` withheld |
| `requalification` | Kimi, 27B, DeepSeek 3/3; GLM, 397B 2/3 | no regression |
| `pendingProposal` | Kimi does not repeat; three others do | unchanged (see below) |

`requalification` outweighs `noOp`: it is the scenario where the wake genuinely
has work, and a gate that makes a model miss it is worse than report churn.

Payload size per wake is recorded alongside correctness, since shrinking it is
the second reason to do this and should be shown rather than assumed.

`pendingProposal` is not a target. `ChangeSetBuilder` already dedups identical
proposals against still-open items and consolidates pre-wake sets, so a repeat
never reaches the user; it costs turns, not correctness. Gating cannot remove
`set_task_status` there either, since the status genuinely may need changing.

## Related

- ADR 0042 — typed task relationship links (part of the tool surface gated here)
- `knowledge/features/agents/task-agents.md` — wake flow, prompt composition,
  tool policy, freshness watermarks, proposal ledger
- `knowledge/features/agents/wake-orchestration.md` — the content gate, which
  applies the same principle before a wake starts at all
- `docs/evaluations/task_agent_models/README.md` — the real-wake suite
- PR #3851 — real-database eval harness
- PR #3852 — `noOp` and `pendingProposal` scenarios

---

### Adr 0052 Agent Directive Constitution (`docs/adr/0052-agent-directive-constitution.md`)

# 0052 — An agent's constitution is code, not an evolvable directive

## Status

Proposed

## Date

2026-08-08

## Context

Template evolution rewrites an agent's directives. `propose_directives` takes
`general_directive` and `report_directive` as complete strings — the session
prompt says so explicitly: *"When proposing directives, output the COMPLETE new
directives text, not a diff."* Approval writes both fields verbatim into a new
template version. The only structural validation is that at least one is
non-empty.

That shape is what this ADR is about. Two questions follow from it: which rules
may a rewrite touch, and how does an agent accumulate durable guidance without
rewriting anything?

**What is already safe.** The role, the wake-finishing contract, the job steps,
every tool definition and its authority boundaries, the evidence-synthesis
protocol and the model-tuned report contract are code-owned constants in
`TaskAgentPromptBuilder` and `AgentToolRegistry`. Evolution cannot reach them.
So "this is what you are, these are your tools" is not at risk today.

**What was mixed up.** The seeded `taskAgentGeneralDirective` restates rules the
scaffold already asserts:

| Seeded directive section | Already code-owned in the scaffold |
| --- | --- |
| never re-open a user-checked item | `**Checklist sovereignty**` — overriding needs a `reason` naming later evidence |
| never override a manual field change | the no-op rule — *"the user wins — make no call at all"* |
| never change a user-set estimate | `**Estimates**` — never adjust retroactively |
| never change a user-set title | `**Title**` — only when the task has none |
| review recent user decisions first | `**Past decisions**` — the proposal ledger |
| don't call tools speculatively | `**Confidence**` |
| never change a user-set priority or due date | **nothing** |
| handle rough transcripts, ask rather than assume | **nothing** |

So the risk was not that evolution could delete the sovereignty rules — the
scaffold keeps asserting almost all of them regardless. The real defects were
smaller and duller: **two wordings of one rule**, one of them editable, costing
payload on every wake and free to drift apart; and **two rules that lived only in
the editable copy**, which a rewrite genuinely could drop.

The compact scaffold used by the evaluated Qwen and Mistral profiles had already
resolved this for itself: it carries its own constitution (`## Authority and
Evidence`, `## Tool Discipline`) and *suppresses* a general directive that is
byte-for-byte the seeded constant, appending only a genuinely customised one.
The common scaffold never adopted that, so the same template produced a
duplicated prompt on one path and a single one on the other.

**The defect that decides who any of this reaches.** "Are these our directives?"
was answered by comparing the stored text against today's seeded constant. That
is an equality test against a moving target: `taskAgentReportDirective` was
edited on 2026-04-19 (#2971) and 2026-06-07 (#3286), `taskAgentGeneralDirective`
on 2026-03-02 (#2737) and 2026-06-07 (#3286). **Every install seeded before the
last edit stores the older text, fails the comparison, and is classified as
customised** — without anyone having customised anything.

For the general directive that only means the constitution work below skips
those installs. For the report directive the consequence is live today and worse:
`usesBuiltInReportContract` returns false, the model-tuned evidence-synthesis
contract is never substituted, and the agent instead receives the superseded
seeded text headed `## MANDATORY FINAL TOOL CALL` — which mandates
`update_report` on *every* wake. That is exactly the behaviour the `noOp`
scenario penalises, and the eval harness cannot reproduce it, because the harness
seeds the current constant and passes the comparison. An aged install can
therefore churn reports for a reason the suite reports as fixed.

The signal that answers the question directly is already stored:
`AgentTemplateVersionEntity.authoredBy` is `system` for seeding,
`evolution_agent` for an approved proposal, `user` for a hand-edit in the
template detail page.

**What is missing entirely** is the additive layer. An agent has no way to
accumulate a standing rule — "this project's estimates are always in ideal
days", "never propose a due date for this recurring task" — other than by
rewriting its whole general directive. The planner already has exactly this
mechanism (ADR 0022 Decisions 9–10): `PlannerKnowledgeEntity` keyed statements
with a ≤120-character always-injected hook, a `proposed → confirmed → retracted`
lifecycle, per-key supersession and global/category/project scope, confirmed by
the user in a panel. Task agents do not read it.

## Decision

Three layers, ordered by mutability. Each layer may add to the ones above it and
may never contradict or remove them.

| Layer | Home | Who writes it | Lifetime |
| --- | --- | --- | --- |
| **Constitution** | code constants in `TaskAgentPromptBuilder` | Lotti releases | changes when the app ships |
| **Template directive** | `AgentTemplateVersionEntity.generalDirective` / `reportDirective` | evolution, user-approved | one version, rollback-able |
| **Standing rules** | keyed knowledge entries | evolution, user-confirmed per rule | per rule, retractable |

Concretely, and in this change:

1. **The constitution is complete and single-sourced.** The two rules that lived
   only in the seeded directive — user-set priority and due date are sovereign,
   and input handling — move into the code-owned scaffold. Every rule an agent
   must never lose is now a constant.
2. **The seeded general directive is no longer rendered.** `buildSystemPrompt`
   resolves it through `effectiveGeneralDirective`, which returns empty for the
   seeded value and the text verbatim for anything else — the same
   compatibility-sentinel pattern as `usesBuiltInReportContract`. Both scaffolds
   now behave the way the compact one already did. A stock wake gets one wording
   of each rule; an evolved directive is appended *after* the constitution, so it
   adds rather than replaces.
3. **Provenance decides whether directives are ours, not string equality.**
   `AgentAuthors.isSystemAuthored` — exactly `system` — settles both
   `usesBuiltInGeneralDirective` and `usesBuiltInReportContract` before any text
   is compared, so a template seeded under any release is recognised. The
   equality test stays as the fallback for versions whose author cannot settle
   it. Two deliberate narrowings:

   * **`system:config_change` is not system authorship.** It is stamped on
     versions that *copy* directives forward after a model or profile change, so
     on an install that evolved a template and then switched models it sits on
     evolved text. Reading it as seeding would delete a user-approved directive
     from the prompt — a worse failure than the one being fixed.
   * **That copy-forward now preserves the directive's author** rather than
     restamping it, because a model swap does not write a directive. The config
     change stays visible in version history through the `modelId`/`profileId`
     difference. Rows already stamped `system:config_change` keep falling back to
     the text comparison, which is exactly today's behaviour for them.

4. **The evolution session sees what is in effect.** For a stock template the
   general directive shows as *"None. This template adds nothing on top of the
   built-in task-agent constitution, which is code-owned…"*, mirroring the
   report-directive fix. Silence would invite a proposal that restates rules the
   agent already has and cannot lose.

```mermaid
stateDiagram-v2
  [*] --> Constitution: code constants, every wake
  Constitution --> Directive: template adds guidance?
  Directive --> StandingRules: confirmed keyed rules
  Constitution --> StandingRules: stock template, nothing to add
  StandingRules --> Prompt
  Directive --> Prompt
  Prompt --> [*]
  note right of Constitution
    Evolution cannot reach this layer.
  end note
  note right of Directive
    Rewritable, user-approved, rollback-able.
    Appended after the constitution.
  end note
```

**The constant itself does not change.** `taskAgentGeneralDirective` keeps its
exact text: templates seeded on earlier versions store it byte-for-byte and are
recognised by that match, so editing it would reclassify every one of them as
customised and start rendering it again. Its value is now its stability, exactly
as for `taskAgentReportDirective`.

**The compact scaffold text is not touched.** It already carries the
constitution, and the 27B and Mistral numbers were measured against that exact
wording. Changing a measured prompt needs an eval run, not an ADR. A test now
pins that a stock template produces the compact scaffold plus the evidence
protocol and nothing else.

## Consequences

**What this buys.** One authoritative wording per rule, owned by code, updated
by shipping the app — including for templates that have already been evolved,
which previously forked from the shipped baseline permanently
(`seedDirectiveFields` backfills only when a field is *empty*). Stock wakes get a
smaller prompt on the common scaffold. The two previously-unprotected rules
become unloseable. And the evolution session can no longer be shown a directive
the agent never received.

**What it costs.** An evolved directive that duplicates constitution rules keeps
its copy — the app cannot safely edit user-approved text — so those templates
still pay for a second wording until their next evolution session. The
`## Input Handling` and priority/due-date additions grow the common scaffold
slightly; net payload for a stock template still falls, because the seeded
directive it replaces was longer than both.

**Precedence is stated, and it favours the user — with one narrow exception.**
Ordering alone was the wrong mitigation: the template directive is appended
*last*, the position a model reads as the final word, so a contradiction
resolved by accident. But the fix is not "the scaffold wins" either, which was
this ADR's first instinct and is wrong. Nearly everything in the scaffold is
**default behaviour** — when to set an estimate, how a report is shaped, which
observation category to use, how terse to be — describing what the agent does
when no instruction covers the case. Changing a default is not a conflict to
resolve; it is the reason the evolvable layer exists, and a blanket precedence
rule would have a model discard a legitimate customisation the moment it brushed
against any scaffold line.

So the statement now says the template's instruction takes precedence, and names
the two things that are not preferences at all and therefore stand regardless:

* **No fabrication.** No wording makes an invented id or an unearned claim valid.
* **The agent does not undo the user's own actions on its own judgement.** A
  directive may lift this only by saying when to act on the user's behalf —
  that is the user deciding, not the agent.

An instruction that cannot be carried out safely produces the closest thing that
can, plus an observation naming the gap, so a quietly impossible directive
surfaces instead of being dropped.

**An override declares what it overrides.** A directive that departs from a
default is expected to name it and give the reason — *"Default: X. Here: Y,
because Z."* — and a declared override is followed exactly. The wake holds both
texts, so a stated departure gives the model the baseline *and* the argument for
leaving it, instead of two paragraphs that disagree. An undeclared contradiction
is still followed — user rules win, and every directive written before this
convention contains undeclared departures — but it is recorded as an observation,
which is what carries it into the next evolution session to be stated properly.
The evolution prompt asks for the same declaration when a proposal is written.

A *customised* report directive gets a narrower statement: it governs the
report's shape and voice, not whether to publish at all. That one exists because
evolved report directives in the wild descend from the seeded text that demanded
`update_report` on every wake, and would otherwise read as licence to republish
an unchanged report. This is a scoping rule rather than an exception to
user primacy: wanting a report on every wake is a legitimate preference, it is
simply a *behaviour* change, so it belongs in the general directive as a declared
override — which the evolution prompt says explicitly.

All of these are emitted only where a template actually contributes text, so a
stock prompt — and every measured eval prompt built from one — is byte-for-byte
what it was.

**What it still does not fix.** Nothing checks a proposal before it is stored, so
a directive can still be vague, contradictory or undeclared; the prompt only
decides what a wake does with it afterwards. Structural enforcement would mean
constraining what a directive may say — plausibly a typed override (which default,
what replaces it, why) rather than prose, which is a larger change and belongs
with the standing-rules work.

**What an existing install gets**, by what its active template version holds:

| State | Before | After |
| --- | --- | --- |
| Seeded on the current release | seeded constitution rendered on top of the scaffold's | constitution once, from the scaffold; ~1.5 kB smaller |
| Seeded on an older release | read as customised: stale constitution rendered, model-tuned report contract **disabled** | recognised by author; same as a current seed |
| Evolved or hand-edited | rendered verbatim | rendered verbatim, after a complete constitution |
| Evolved, then model changed (`system:config_change`) | rendered verbatim | rendered verbatim — provenance deliberately declines to claim it |
| Legacy, no split fields | `directives` blob rendered | unchanged |

Personality is untouched in every row: soul versions have no sentinel and no
substitution, so an evolved soul is rendered exactly as before.

**Migration.** None. No stored data is rewritten and no version is created; the
change is in what gets rendered and how provenance is read. Re-seeding stale
directive text onto old templates — as `seedDayAgentCaptureReconcileDirective`
does for the day agent — would additionally repair installs whose stored text is
genuinely outdated rather than merely misclassified. That is a separate decision,
because it mints a version per template on upgrade and changes what an evolved
template inherits.

## Follow-ups

Not in this change, in the order they earn their keep:

1. **Make the report directive additive.** A custom report directive currently
   flips `usesBuiltInReportContract` to false, which permanently disables the
   model-tuned contract substitution for that template — the contract behind
   Qwen3.6 27B's 10/14 → 13/14. Normal evolution output triggers this, and the
   proposal card does not say so. An *addendum* appended after the model-tuned
   contract removes the cliff.
2. **Give task agents standing rules.** Reuse `PlannerKnowledgeEntity`: a
   `propose_knowledge` evolution tool writing one keyed rule with a hook, a
   scope and a rationale; the wake injects the confirmed Head set. Directive
   rewrites become the escape hatch rather than the default move, and the session
   prompt's contradiction between *"make the smallest directive changes"* and
   *"output the COMPLETE new directives text"* dissolves, because an additive
   proposal is a diff.
3. **Constrain the rewrite itself** — section-scoped proposals, or a check that a
   proposal does not contradict the constitution — only if 1 and 2 leave a real
   gap.

## Related

- ADR 0022 — daily-OS planner: Decisions 9–10 define the knowledge lifecycle
  this ADR proposes reusing for task agents
- ADR 0051 — agenda-gated tool exposure; the same principle applied to tools
  rather than directives
- `knowledge/features/agents/templates-souls-evolution.md` — the evolution
  ritual, version lifecycle and rollback
- `knowledge/features/agents/task-agents.md` — prompt composition and the
  directive substitution rules

---

### Adr 0053 Goal Driven Agents Per Goal Producers (`docs/adr/0053-goal-driven-agents-per-goal-producers.md`)

# ADR 0053: Goal-Driven Agents — Per-Goal Durable Producers

- Status: Proposed
- Date: 2026-08-08

## Context

The product wants long-running coaches for long-term personal goals — "average 10,000 steps a
day", "gym 3×/week", composite fitness goals — viable over a ten-year horizon. Each is mostly
dormant, wakes on time- and data-triggers, nudges the user visually when off-track (ADR 0055),
holds an ongoing voice-capable conversation, and revises its goal through that dialogue while
always being able to state the current goal and success criteria.

ADR 0023 already specifies the closest ancestor: durable, self-scheduled *domain agents*
(fitness, sleep) that produce attention claims and standing agreements for the day planner to
arbitrate. It is Proposed and unimplemented. Its Decision 1 picks one agent per
`StandingAgreementScope`; its Open Question 1 explicitly leaves granularity open.

### What already exists (verified in code)

- `StandingAgreementEntity` (`lib/classes/agents/agent_domain_entity.dart:516`) fully
  models "exercise 3×/week" — scope (`fitness`, `sleep`, …), cadence, `minCount`/`minMinutes`
  quotas, enforcement (`preference`/`target`/`nonNegotiable`), approval mode, evidence refs —
  and has **no writer and no UI**. The day-planner context builder reads agreements for its
  planning window (`day_agent_context_builder.dart`).
- `AutoCompleteRule` (`lib/classes/entity_definitions.dart:68-114`) models health/measurable
  thresholds with `and`/`or`/`multiple` composition — and has **no evaluator anywhere**.
- Versioned configuration with head pointers and `authoredBy` provenance exists twice (agent
  templates, souls) and is battle-tested with sync and vector clocks.
- `AgentKinds` are free strings (`agent_constants.dart:5`) — a new kind is non-breaking.
  `AgentTemplateKind` is a closed enum whose decode has no fallback
  (`agent_domain_entity.g.dart`); v1 goal agents sidestep it by using no template at all.
- The runtime plug-in seam (`agentWakeRunnersProvider` + `AgentRuntimeMaintenance`,
  `agent_runtime_registry.dart`) was built for new agent kinds and is exercised by Daily OS.

## Decision

1. **A new agent kind, one durable identity per goal.** `AgentKinds.goalAgent = 'goal_agent'`;
   the agent *is* the goal's surrogate. This deliberately refines ADR 0023's per-scope
   granularity, using 0023's own principle — "memory coherence, not claim volume, sets the
   granularity": a goal is one narrative thread (one conversation, one evolving spec, one
   attainment series) over a decade. Per-scope agents would interleave several narratives in one
   message log, making compaction summaries mushy and "state your current goal" plural. Goals
   also end individually: per-goal identity retires cleanly via `AgentLifecycle` with history
   intact. The arbitration side is unaffected — claims and agreements carry scope on themselves.

2. **The goal is versioned structured state, not prose.** Two new `AgentDomainEntity` variants:
   `goalSpecVersion` (immutable: `title`, a speakable `statement`, a `GoalCriterion` criteria
   tree, `authoredBy`, provenance, optional start/target dates, rationale) and `goalSpecHead`
   (deterministic id `goal_spec_head:<agentId>`, LWW). "State your current goal and success
   criteria" is a head read — zero inference, immune to context drift. Version history is the
   ten-year story: every revision is a new version; nothing is edited in place.

3. **Criteria are a purpose-built tree, not a reuse of `AutoCompleteRule`.** A new freezed union
   `GoalCriterion` with leaves `metric{dataType, window, aggregation, target, direction}`,
   `habit{habitId, window, targetCount}`, `measurable{…}`, and composites
   `allOf`/`anyOf`/`atLeastCount{successes}`, every node carrying a stable `criterionId`.
   `AutoCompleteRule` leaves are point-in-time, same-day thresholds owned by habit
   autocompletion; goals need rolling windows, aggregation, direction, and per-window quotas.
   Grafting those onto the habit feature's class would couple two features' evolution
   permanently. A `GoalCriterion.fromAutoCompleteRule` importer seeds a goal from an existing
   habit rule in one tap; the goal evaluator is the codebase's first rule-tree evaluator, making
   a later `AutoCompleteRule` adapter trivial.

4. **Deterministic attainment is a keyed register.** `goalProgress` rows keyed
   `goal_progress:<agentId>:<periodKey>`, recomputed from source and never accumulated (the
   `weekRollup` convergence pattern), carrying `trackStatus`
   (`onTrack | atRisk | offTrack | recovering | achieved | insufficientData` — the full
   `GoalTrackStatus` vocabulary, one enum for evaluator, agent and evals, mirrored into `subtype` for
   indexed scans), `attainment 0..1`, per-criterion results, and the `specVersionId` the numbers
   were computed against — so a decade of charts stays honest across goal revisions. The register
   is retention-exempt: it is both the chartable history and the agent's cheap wake context.

5. **Goal revision is proposal-only.** The single mutation path is a `propose_goal_revision`
   tool call producing a ChangeSet (ADR 0006) with a human-readable old-vs-new diff; on user
   approval a new `goalSpecVersion` (authoredBy `goal_agent`, `sourceSessionId` provenance) is
   written and the head moves. There is **no auto-accept tier**: a ten-year coach must never
   quietly move its own goalposts. User-authored versions (creation, direct edits) write
   directly.

6. **The goal agent is `StandingAgreementEntity`'s first writer — as a derived projection.**
   When the head spec contains a quota criterion implying calendar time (gym 3×/week), the agent
   proposes `upsert_standing_agreement` (ChangeSet-gated, deterministic id
   `standing_agreement:goal:<agentId>`, `targetKind: 'goal'`, evidence refs pointing at
   `goalProgress` rows). The spec remains the source of truth; the agreement is planner-facing
   output. Metric-only goals imply no agreement. Attention *claims* and planner arbitration
   remain ADR 0023's future seam — deliberately not built here.

7. **v1 goal agents use no template.** The goal constitution (role, wake contract, tool
   protocol, grounding and no-op rules) is fully code-owned — the ADR 0052 posture; goal agents
   are the first kind born under it. This also avoids extending the frozen `AgentTemplateKind`
   enum. Persona arrives via soul documents attached through agent links (link types are free
   strings — non-breaking) in a later increment.

## Consequences

- The feature lands as ADR 0023's producer side at finer granularity; 0023 is amended (granularity
  note referencing this ADR), not superseded. If scope-level coaching is ever wanted, it composes
  over goal agents through the claim/agreement log — the interface 0023 already defines.
- Four new entity variants ride the existing single-table union with `fallbackUnion: 'unknown'`
  forward compatibility and no schema-version bump. Mixed-version fleets are not a supported
  configuration — the project assumes all of a user's devices stay current, so no
  store-and-forward compatibility work is done for peers running older builds.
- An orphaned, fully-modeled entity (`StandingAgreementEntity`) gains its first producer, and the
  never-evaluated criteria idea (`AutoCompleteRule`) gains a working evaluator lineage.
- One agent per goal multiplies agent instances; wake cost is bounded by ADR 0054's
  deterministic-first design, and memory cost by ADR 0057.

## Non-Goals

- Mutating the calendar or negotiating with the planner (ADR 0023's arbitration path stays
  future work).
- Per-scope "domain coach" agents.
- Auto-accepted goal revisions of any size.
- Push notifications (ADR 0055 is banner-only).

## Related

- [ADR 0006: Change Set — Deferred Tool Confirmation Workflow](./0006-change-set-deferred-tool-confirmation.md)
- [ADR 0023: Durable Domain Agents and Time Negotiation](./0023-durable-domain-agents-and-time-negotiation.md) — amended by this ADR (granularity)
- [ADR 0052: Agent Directive Constitution](./0052-agent-directive-constitution.md)
- [ADR 0054: Deterministic-First Two-Tier Wakes](./0054-deterministic-first-two-tier-wakes.md)
- [ADR 0055: Banner-Nudge Attention Channel](./0055-banner-nudge-attention-channel.md)
- [ADR 0057: Decade-Scale Agent Memory](./0057-decade-scale-agent-memory.md)
- Assessment: `docs/implementation_plans/2026-08-08_goal_agents_phase1_assessment.md`

---

### Adr 0054 Deterministic First Two Tier Wakes (`docs/adr/0054-deterministic-first-two-tier-wakes.md`)

# ADR 0054: Deterministic-First Two-Tier Wakes for Goal Agents

- Status: Proposed
- Date: 2026-08-08

## Context

Task agents wake on evidence and their no-op wakes are rare. Goal agents invert that: step-count
imports, habit completions, and cadence ticks arrive many times a day, and on most of them
*nothing decision-worthy has changed*. Model evaluation showed what LLMs do with such wakes: in
the task-agent `noOp` scenario, four of five models rewrote a correct report anyway
(ADR 0051), and "a tool that cannot succeed is an invitation to invent its arguments"
(`task_agent_tool_gate.dart`). Paying an inference round-trip to conclude "nothing to do" is the
failure mode this ADR exists to prevent — for cost, energy, and correctness alike.

Two infrastructure facts constrain the design:

- `WakeOrchestrator` deliberately consumes only `updateNotifications.localUpdateStream`
  (`agent_providers.dart`), so a synced entry never wakes an agent on the receiving device.
  Health data **originates on mobile only** and is **pull-only**
  (`health_import.dart` — desktop returns `unsupportedPlatform`; deltas fire when dashboard
  charts mount, throttled to 10 minutes; no background fetch). Without new routing, a desktop
  goal agent would never learn about phone-imported steps.
- Single-device execution of scheduled work already exists: `ScheduledWakeEntity` carries
  `leaseHostId`/`leaseUntil` with a claim–settle–re-read election
  (`scheduled_wake_manager.dart`), proven by ADR 0048.

## Decision

1. **The invariant: a tick that changes nothing costs €0 and writes no messages.** No capture,
   no compaction, no agent messages, no inference — only (idempotent) register upserts.

2. **Phase A — deterministic, every wake, every device.** Each goal-agent wake first runs pure
   Dart: load the spec head, re-arm the cadence wake, run `GoalProgressEvaluator` over journal
   aggregates per criterion (steps by `dataType`, completions by `habitId`), upsert the
   `goalProgress` register for the current period, and compute `GoalWakeFacts` (status
   transition? nudge stale? user message pending? scheduled check-in due?). Registers are
   recomputed-never-accumulated, so concurrent Phase A runs on several devices converge by
   construction.

3. **Phase B — the LLM — runs only on facts, never directly from a data trigger.** When Phase A
   finds an LLM-worthy condition (status transition, nudge staleness, pending dialogue, scheduled
   check-in), it upserts an *immediate* escalation `ScheduledWakeEntity`
   (`workspaceKey: 'goal-escalation:<periodKey>'`) and nudges the manager. The existing lease
   election picks exactly one device to run Phase B; if the arming device dies, another picks it
   up within the hourly scan. User-initiated chat is Phase B directly — the typing device is
   inherently the single runner.

4. **Sync-origin signals wake Phase A on receiving devices.** A `GoalSignalSyncListener`/
   `GoalSignalSyncDispatcher` pair (modeled 1:1 on `synced_audio_inference_listener.dart` /
   `_dispatcher.dart`) listens to `syncUpdateStream`, intersects batches with goal-subscribed
   tokens, guards against self-echo via vector clocks, and enqueues Phase-A-only wakes. Phase A
   being idempotent makes this convergence, not duplication; Decision 3 keeps token spend
   single-flighted.

5. **Subscriptions are per-goal and precise.** `matchEntityIds` = the union of the criteria's
   `dataType` strings (`QuantitativeEntry.affectedIds` already emits them — e.g.
   `cumulative_step_count`), the criteria's `habitId`s (`HabitCompletionEntry.affectedIds` emits
   them; the global `HABIT_COMPLETION` sentinel is deliberately not used), and a per-agent
   nudge-dismissal token. Registered and restored by a `GoalRuntimeMaintenance` implementing
   `AgentRuntimeMaintenance`, contributed in `app_bootstrap.dart` like Daily OS's.

6. **Recurrence by re-arm, not by schema.** No recurrence field is added to
   `ScheduledWakeEntity`. Phase A re-arms the next cadence wake at a deterministic id
   (`workspaceKey: 'goal-cadence'`) at its *start* (crash-safe), and
   `GoalRuntimeMaintenance.beforeWakeScan()` self-heals any active goal agent missing a pending
   cadence record — the day-agent `set_next_wake` precedent. Hourly poll granularity is ample
   for daily/weekly goal cadences. A first-class recurrence model is deferred until a third
   agent kind needs one.

7. **The tool gate is designed in, not retrofitted.** `GoalWakeFacts` gates tool exposure from
   day one: `update_goal_report` is only offered when status transitioned or a report-worthy
   fact exists — a wake that should no-op *cannot* churn, structurally. Ad and agreement tools
   are likewise fact-gated (fresh-ad present ⇒ no `create_goal_ad`; see ADR 0055/0056).

8. **Cost is monitored, not capped.** Every Phase B call lands as an `AiConsumptionEvent`
   carrying `agentId` and `wakeRunKey` (credits and energy on Melious), so per-goal spend is a
   query; the goal UI surfaces it, and the eval harness reports cost per call plus an
   extrapolated €/goal-month with its wakes/day assumption printed — observed estimates, never
   targets. Spending caps are documented as a future option only; the efficiency guarantees are
   architectural (Phase A gating, ≤8K-token Phase B prompts with cold-prefill-sized compaction
   budgets, lease-elected single execution).

```mermaid
flowchart TD
  T1[local data token] --> A
  T2[sync-origin dispatcher] --> A
  T3[hourly cadence record] --> A
  T4[nudge dismissed] --> A
  U[user message] --> B
  A["Phase A — deterministic, every device<br/>evaluator → registers → facts → re-arm"] -->|nothing LLM-worthy| Z[return: €0, no messages]
  A -->|LLM-worthy| E["escalation ScheduledWakeEntity<br/>lease election picks ONE device"]
  E --> B["Phase B — LLM wake<br/>fact-gated tools, ≤8K in"]
```

## Consequences

- Every device stays fresh (banners re-evaluate wherever the user is looking); exactly one device
  spends tokens. Worst-case remote pickup latency is one hourly scan; a rare lease-race duplicate
  costs fractions of a cent and is idempotent (LWW report head, deduped nudge creation).
- Health-data latency is bounded by the pull-only importer, not by this design; a banner channel
  tolerates that (documented in ADR 0055).
- The no-op discipline that task agents request in prose (flag-off ADR 0051) is structural here.
- An unregistered agent kind falls through to the task-agent executor **silently**
  (`agent_wiring.dart`); the runtime PR must carry a regression test asserting `goal_agent`
  resolves to its registered runner.

## Related

- [ADR 0010: Scheduled Wake Infrastructure](./0010-scheduled-wake-infrastructure.md)
- [ADR 0018: Convergent Multi-Device Execution](./0018-convergent-multi-device-execution.md)
- [ADR 0027: Wake Notification Propagation and Storm Prevention](./0027-wake-notification-propagation-and-storm-prevention.md)
- [ADR 0048: One Device Runs the Coordinator Digest](./0048-one-device-runs-the-coordinator-digest.md)
- [ADR 0051: Agenda-Gated Tool Exposure](./0051-agenda-gated-tool-exposure.md) — the measured lesson this design codifies
- [ADR 0053: Goal-Driven Agents — Per-Goal Durable Producers](./0053-goal-driven-agents-per-goal-producers.md)

---

### Adr 0055 Banner Nudge Attention Channel (`docs/adr/0055-banner-nudge-attention-channel.md`)

# ADR 0055: The Banner-Nudge Attention Channel

- Status: Proposed
- Date: 2026-08-08

## Context

ADR 0019 and ADR 0023 frame agent attention as **scheduled calendar time, not interruption**: a
fitness agent asks the planner for workout blocks; nothing pushes at the user. Goal agents add a
deliberately different second channel: when the user is off-track, the agent shows a visual "ad"
— potentially humorous, persona-flavored — prominently inside the app. This is persuasion at the
moment the user is already looking, not an interrupt. That departure deserves its own record.

Two facts make the boundary easy to hold today: OS push is off by default behind
`enable_notifications`, and notification-tap deep links are written but never consumed
(`notification_service.dart` initializes without a response callback) — there is no push-to-chat
routing to be tempted by.

## Decision

1. **Banner-only, in-app, never push (v1).** The ad channel renders only inside the app.
   Revisiting push later requires reopening this ADR and building tap routing; the durable
   synced notification inbox would be the substrate.

2. **An ad is data: the `goalNudge` entity.** One append-only row per generated ad; status is
   mutated in place through a typed lifecycle:
   `draft → ready → active → dismissed | retired | expired | superseded | failed` — the *user
   dismisses*, the *agent retires* (goal back on track, habit checked off), the *clock expires*
   (default lifetime 72 h or goal-satisfying completion, whichever first), a newer ad
   *supersedes*, generation/verification *fails*. Each terminal status keeps its timestamp.
   Dismissal is an LWW status write that syncs like any entity — **dismissal is data the agent
   reads** deterministically at its next wake (dismissal counts, time-to-dismiss, cool-down
   state).

3. **Staleness is a contract, not a hope.** `staleAt` bounds how long an ad may claim to be
   current; goal-relevant events pull it forward — checking off the gym habit re-wakes the agent
   (ADR 0054 subscription) whose wake facts then retire the now-stale "go to the gym" ad. A
   wrong banner that lingers is treated as a defect of the contract, not of the model.

4. **Respect mechanics, not budget mechanics.** Dismissing an ad suppresses new ads for that
   goal for 24 h (wake-fact enforced). *Amended 2026-08-09 (maintainer decision during the
   visible-layer build): the suppression window is the **rest of the local calendar day**, not
   a rolling 24 h — "not today" should not silence most of tomorrow after an evening dismissal.
   Enforced via the repo's DST-safe day key (`GoalWindow.dayUtc`).* Near-identical regeneration
   is prevented by a `briefDigest` dedupe key. There are **no spending caps** (cost policy is
   monitoring-per-goal, ADR 0054 Decision 8); these mechanics exist so the channel stays
   respectful, which is what keeps it effective.

5. **Quiet-by-default surfaces.** The banner widget renders nothing when no active ad exists
   (the `KnowledgeNudge` contract). v1 mounts: the Daily OS day page nudge stack and the habits
   tab; multiple active ads render as a manual-swipe carousel with position dots (no
   auto-advance; reduced-motion respected). *Amended 2026-08-10: the carousel was specified for
   ADR-0055-era fixed-height IMAGE cards. With ADR 0058's pivot to compact procedural text
   banners, multiple ads render as a bounded vertical stack (at most two visible; the rest stay
   reachable on the goal's detail page) — a swipe carousel over variable-height text rows would
   hide the second ad behind a gesture without saving meaningful space. Revisit if banners ever
   regain fixed-height media.* An app-shell structural band (the demo-banner
   pattern) is documented as an escalation surface and deliberately not built in v1.

6. **Tap opens the conversation; dismissal is explicit.** Tapping the ad opens the goal agent's
   chat (pushed over the bottom nav); a separate 44 px dismiss affordance (and swipe) writes the
   dismissal. The two intents are never conflated on one gesture.

7. **Tap-through asks for a rating; top-rated ads are reusable.** Opening an ad's conversation
   presents a lightweight rating prompt (the tap already proved engagement — that is the moment
   to ask). Ratings are appended to the `goalNudge` row as a history (`{rating, ratedAt}` per
   run), which turns the ad archive into a labeled library of what actually lands with this
   user. Two uses:
   the agent's wake facts summarize top-/bottom-rated briefs so future `create_goal_ad` calls
   steer toward proven concepts, and a sufficiently high-rated ad may be **re-run as-is** —
   re-activating the existing entity and its already-generated image at zero image-generation
   cost — instead of generating a new one. Reuse is a first-class lifecycle move
   (`active → retired → active` re-entry with a fresh `staleAt`), not a copy; the row keeps its
   full rating and display history. **Every run is rated**: a re-run prompts for a fresh rating
   on its next tap-through — the rating trajectory is what detects wear-out (an ad that slides
   from 5 to 2 across re-runs retires from the library; a single frozen rating would hide
   that). Skipping a prompt is always allowed; within the same run the skipped prompt is not
   nagged again, but the next re-run asks anew.
   Alongside the explicit rating, **exposure is measured implicitly**: the banner widget reports
   visibility sessions, accumulated onto the row as `totalVisibleMs`, `impressionCount`,
   `firstShownAt`/`lastShownAt` (LWW-merged per device, summed for display). An ad dismissed
   after 40 minutes of accumulated visibility failed differently from one dismissed in two
   seconds — visible-time-to-action is the denominator every effectiveness ratio needs, and it
   also weights the rating library (a five-star ad seen once means less than a four-star ad
   that earned its rating over many impressions).

8. *[Superseded by ADR 0058 — ads are procedural text banners; no image is
   generated. Original decision preserved below as the point-in-time record.]*
   **The ad is a designed banner — headline and CTA render IN the image.** (Revised same day:
   text-free images read too tame; a real ad has type.) The composed prompt instructs a
   polished advertising-banner layout and passes the model-authored `headline` and optional
   `cta` verbatim as the only sanctioned text — both are leakage-checked tool arguments, so no
   personal data rides along (ADR 0056 holds: the boundary is *which fields* travel, and these
   two carry no user data by construction). All *other* readable text, digits, logos and
   watermarks stay banned. `headline`/`altText` remain stored on the entity regardless, so
   history rendering, semantics labels and any future theming never depend on pixels.

9. **Past ads are part of the conversation history.** Ads render inline (compact card + status
   badge) in the goal chat's timeline projection, permanently — the scrollable history of all
   interactions includes every banner the agent ever ran.

## Consequences

- The product gains a second attention channel with an explicit boundary to the first: claims
  buy *calendar time* through the planner (ADR 0023, future); nudges spend *screen presence*
  inside the app, bounded by staleness, dismissal cool-downs, and quiet-by-default surfaces.
- Because ads are synced entities referencing a `JournalImage`, cross-device display is free;
  the image file may land after the entity on a second device, so banner rendering keeps the
  gradient-fallback + file-watcher repaint pattern.
- Ad effectiveness becomes measurable later (dismissal latency, tap-through, status at expiry)
  without new instrumentation — the lifecycle timestamps are the instrument, and explicit
  ratings (Decision 7) add a labeled signal on top of the behavioral one.
- The rating library shifts image spend downward over time: the more history a goal accumulates,
  the more often a wake can re-run a proven ad instead of paying for a new generation.
- **Cold-start blandness is expected and acceptable.** A fresh goal agent produces generic
  (if snarky) ads because it knows nothing about this user's taste yet — that is the design,
  not a defect to be prompt-engineered away. Personality comes from the feedback loop
  (per-run ratings, dismissal latency, visible time, recorded tone preferences), which is
  where investment belongs; the prompt only sets the floor.

## Non-Goals

- Push notifications, OS notification-tap routing, badges.
- Auto-advancing or animated attention-grabbing carousels.
- Cross-app or web delivery of ads.

## Related

- [ADR 0019: Attention Negotiation Protocol](./0019-attention-negotiation-protocol.md)
- [ADR 0023: Durable Domain Agents and Time Negotiation](./0023-durable-domain-agents-and-time-negotiation.md) — the "attention = calendar time" stance this channel deliberately complements
- [ADR 0053: Goal-Driven Agents — Per-Goal Durable Producers](./0053-goal-driven-agents-per-goal-producers.md)
- [ADR 0054: Deterministic-First Two-Tier Wakes](./0054-deterministic-first-two-tier-wakes.md)
- [ADR 0056: The Need-to-Know Visual Brief Boundary](./0056-need-to-know-visual-brief-boundary.md)
- [ADR 0058: Procedural Text Banners — No Generative Imagery](./0058-procedural-text-banners-no-generative-imagery.md) — supersedes Decision 8

---

### Adr 0056 Need To Know Visual Brief Boundary (`docs/adr/0056-need-to-know-visual-brief-boundary.md`)

# ADR 0056: The Need-to-Know Visual Brief Boundary

- Status: Proposed (dormant — ADR 0058 removed generative imagery from the ad
  channel the same day; this boundary is the door any future non-ZDR feature
  must re-enter through. Every decision below is conditional on there being a
  non-ZDR recipient: with no image provider in the path, banner copy never
  leaves the device and nothing here imposes a runtime obligation on it. See
  the amendment note under Decision 3.)
- Date: 2026-08-08

## Context

Goal-agent text inference runs on the user's configured zero-retention-posture provider (today:
Melious.ai — EU jurisdiction, no-training claims; `PRIVACY.md` records that these are the
provider's claims on the provider's terms). Ad images are generated by **Nano Banana Pro**
(`models/gemini-3-pro-image-preview`, direct Gemini) — a provider for which zero data retention
**cannot** be enforced. The user's ruling (2026-08-08): we shall not share anything with the
image provider beyond the actual image request — zero background information, strict
need-to-know.

Prior art in-repo: the "Generate Cover Art (Flux)" skill already composes a compact visual scene
prompt with a no-readable-text contract (`built_in_skills.dart`); ADR 0034 established the
deterministic-validation + one-repair-call + typed-failure shape for AI output gating.

## Decision

1. **Non-ZDR providers receive a self-contained typed brief — nothing else.** The outbound image
   request is built from a `GoalNudgeBrief` value object (`sceneConcept`, `mood`, enum
   `stylePreset`, `paletteHint`, `aspectRatio`, `composition`) plus a fixed style-contract system
   message (16:9, centre-safe, **no readable text, captions, UI, logos, or watermarks**). The
   brief must be understandable by someone with zero knowledge of the user.

2. **The parameter type enforces the channel; evals police the content.** The type guarantees
   what it can: the request builder's entire input *is* the brief —
   no repository handle, no entity, no conversation context exists in its signature or call
   path. Personal data cannot be attached because no parameter can carry it. The shared image
   service (extracted from `SkillInferenceRunner.runImageGeneration`) is capability-shared with
   task cover art, but need-to-know lives at each caller: cover art legitimately builds its
   prompt from task context; the ad path structurally cannot. What the type cannot prevent is
   the model writing personal data *into* a free-text brief field — that residual channel is
   Decision 4's linting plus the leakage evals (Decision 6), never the type alone.

3. **Only leakage-checked fields leave the device.** (Revised 2026-08-08 with ADR 0055
   Decision 8.) The `headline` and optional `cta` ARE part of the outbound request — rendered as
   banner typography — because they are model-authored brief fields covered by the same
   constitution rules, handler linting and leakage evals as `sceneConcept`; by construction they
   carry no personal data ("3,200 steps to go" is exactly what the lint rejects). `caption`,
   `altText` and any goal-referencing copy remain entity-only and are never sent. The boundary
   is the *field allowlist*, not the absence of text.

   **Amended 2026-08-10 (post-ADR 0058).** The sentences above describe a world
   with an outbound image request; ADR 0058 Decision 2 removed that request
   entirely. There is no longer any recipient for `headline` or `cta`: the text
   provider that *authors* them already holds the FACTS block they are drawn
   from, the banner is composed on-device by Flutter, and nudge rows sync only
   between the user's own devices over end-to-end encryption. "Leave the
   device" therefore has no referent in the text-banner channel, and this
   decision imposes no obligation on banner copy while that remains true. It
   revives verbatim the moment any non-ZDR provider re-enters the path.

4. **Defense-in-depth behind the type.** The agent authors the brief via a schema-constrained
   tool call; the goal constitution forbids names, health readings, locations, dates, or numbers
   from context in any brief field; and the tool handler lints briefs (digit+unit patterns,
   terms from the goal title, entries from the private-strings inventory) and rejects rather
   than sanitizes. The model writing personal data into a brief is the residual channel — which
   is why it is evaluated (Decision 6).

   **Amended 2026-08-10 (post-ADR 0058).** This lint is an *egress* control, not
   a display control, and it is dormant with the rest of this ADR. Applying it
   to text-banner copy would reject the user's own step count on the way to the
   user's own screen — privacy machinery pointed at no third party. What governs
   banner copy today is the goal constitution's tone rules (still live) and
   `sanitizeAgentReportText`, which strips model annotation artifacts from every
   rendered copy field. Restore the lint together with the outbound request.

5. **Reference images are provenance-gated.** For persona/series consistency the request may
   attach prior *AI-generated* anchors only: any referenced `JournalImage` must carry non-null
   `aiAttribution`. User photographs structurally cannot enter the ad path.

6. **Verified by evaluation, continuously.** The goal-agent eval suite includes
   leakage-pressure scenarios: the wake context is deliberately stuffed with tempting private
   detail (names, health readings, appointments), and the composed brief is asserted to contain
   **zero** strings from the fixture's private inventory, plus no self-referential fragments
   ("her goal", "as discussed"). A model that leaks fails the suite regardless of how good its
   images are.

7. **Image verification is cheap and bounded.** One flash-class vision call scores
   `{matchesBrief, mismatches[]}` against the brief (the brief is already provider-safe, so the
   verifier may run anywhere); on mismatch, exactly one regeneration with the mismatches
   appended as corrections; on second failure the ad is not published — typed failure, status
   `failed`, agent observation recorded. The ADR 0034 shape, applied to pixels.

## Consequences

- Provider choice becomes a quality decision, not a privacy decision: Nano Banana Pro (reference
  images, best quality) by default; Melious `flux-2-klein-9b` as a fallback (no reference
  images) — both sit behind the same boundary.
- The boundary generalizes: any future non-ZDR capability (video, music) adopts the same rule —
  self-contained typed artifacts out, nothing else; personal text composited locally.
- Costs: the boundary adds at most one verification call and one retry per ad — cents, recorded
  per-goal via the existing consumption attribution.
- The residual risk is the model embedding personal data in `sceneConcept` despite constitution,
  lint, and evals; the lint rejects the obvious cases and the eval suite keeps the pressure
  visible per model. This residual is accepted and documented.

## Related

- [ADR 0034: Hybrid Understanding Evaluation](./0034-hybrid-understanding-evaluation.md) — the validate/repair/typed-failure shape
- [ADR 0055: The Banner-Nudge Attention Channel](./0055-banner-nudge-attention-channel.md)
- [ADR 0058: Procedural Text Banners — No Generative Imagery](./0058-procedural-text-banners-no-generative-imagery.md) — removed this ADR's only recipient; the reason every decision here is dormant
- [ADR 0053: Goal-Driven Agents — Per-Goal Durable Producers](./0053-goal-driven-agents-per-goal-producers.md)
- `PRIVACY.md` — provider-claims stance this ADR operates within

---

### Adr 0057 Decade Scale Agent Memory (`docs/adr/0057-decade-scale-agent-memory.md`)

# ADR 0057: Decade-Scale Agent Memory

- Status: Proposed
- Date: 2026-08-08

## Context

Goal agents are open-ended: they live for years, plausibly well beyond a decade — ten years is
the design horizon we size for, not a lifetime cap. The existing memory substrate is genuinely good — content-
addressed capture (ADR 0020), never-destructive prefix-coverage compaction (ADR 0017), keyed
durable knowledge (`PlannerKnowledgeEntity`), author-time memory links (ADR 0026) — but several
of its *policies* were tuned for task agents that live weeks, and are actively hostile to a
decade-long identity (verified in code, 2026-08-08):

- Every task-agent wake loads **all** observations then keeps the newest 20; the critical-
  observation self-review scans only those 20 (`task_agent_execute.dart`,
  `task_agent_context_builder.dart`).
- Observations are pruned raw at 180 days (`agent_retention_policy.dart`) — "you always stall in
  November" is precisely the observation that dies.
- `maxAgentMessages: 20000` makes the retention sweep **skip the agent entirely**; a daily-waking
  agent crosses the threshold around year eight and then grows unbounded *and* unpruned.
- Compaction is a single rolling prose summary; `AgentMessageEntity.summaryDepth` exists and
  nothing builds a hierarchy — a decade compresses into one blob of unbounded lossiness.
- The 50k/20k compaction watermarks assume a warm provider prefix cache; a once-daily goal agent
  is almost always a cold prefill.
- Memory is write-only in practice for non-day agents: `search_memory` is wired only for the day
  agent, planner knowledge is read only by the day agent (ADR 0052: "Task agents do not read
  it"), memory links are never traversed.

## Decision

1. **Fix the read side first — by generalization, not new entities.** Goal agents get
   `search_memory` via a shared helper extracted from the day-agent tool handlers, and read
   `PlannerKnowledgeEntity` scoped to their own `agentId` (hooks ≤120 chars always injected;
   compaction-exempt — unchanged semantics). A `remember` tool writes user-stated facts straight
   to `confirmed`, agent-inferred facts to `proposed`.

2. **Observation reads are bounded and priority-aware.** Never read-all: a repository method
   returns "recent N plus all critical-priority", and the context builder passes an explicit
   limit from day one. (The task-agent read-all site receives the same one-line fix as an
   unrelated cleanup.)

3. **Epoch summaries make the hierarchy real.** Quarterly, the agent's raw quarter (observations,
   dialogue, report evolution) is folded into one depth-1 epoch summary message; yearly, depth-1
   epochs fold into a depth-2 year summary — using the existing `summaryDepth` field and the
   ADR 0017 checkpoint machinery unchanged underneath. This ADR **amends 0017** by adding a
   hierarchy above its rolling summary; the rolling mechanism itself is untouched. Epochs are
   collapsible dividers in history UI and retrievable via `search_memory`.

4. **Bounded reads are the invariant; pruning is optional.** What makes a decade viable is that
   no wake ever re-reads the entire history — every read path goes through the epoch chain,
   keyed knowledge, bounded observation windows and the `goalProgress` register. Once that
   holds, keeping the full raw log forever is perfectly viable (a decade of daily wakes is
   megabytes, not gigabytes, and storage is the user's own device): raw history behind the
   summary frontier is simply *cold* — never loaded into context, still searchable and
   browsable. Deletion, if ever wanted, is a user-facing space decision, and then strictly
   **distill-then-prune**: raw observations become prunable only after their quarter's epoch
   summary exists and durable facts are promoted to keyed knowledge. Pruning without
   distillation is a policy violation, not a space optimization. The default is to prune
   nothing. The `goalProgress` register (ADR 0053) is retention-exempt either way — at ~1 MB
   per goal-decade it *is* the quantitative history.

5. **The 20000-message skip is fixed, not repurposed.** Today crossing `maxAgentMessages` makes
   the retention sweep skip the agent entirely while the task-agent policy still expects
   pruning. For goal agents the sweep must simply not be the thing that bounds context (
   Decision 4 does that); the skip-threshold deadlock is repaired so that *if* a prune is ever
   requested it operates on the summary-covered prefix only (checkpoint-frontier aware,
   ancestor-closed, protected heads untouched) instead of silently doing nothing.

6. **Cold-prefill-sized context.** Goal-agent Phase B wakes pass per-call compaction budgets
   (`budget: 12000, retainTokens: 4000` — the parameters already exist on
   `compactAndAssemble`) and target ≤8K input tokens: spec head render, the last ~8
   `goalProgress` periods as a table, active-nudge state, knowledge hooks, compacted tail. The
   50k/20k defaults remain for task agents, whose warm-cache assumption holds.

## Consequences

- A ten-year goal agent's *context* stays bounded (epoch chain + keyed facts + bounded windows +
  register) while its *log* can remain complete: nothing is lost by default, everything old is
  merely cold. "What did I conclude last January?" is a search over epochs and knowledge — and
  the raw source is still there underneath if the user scrolls. Lossiness, where it exists,
  happens only at explicit fold boundaries into context, never by silent deletion.
- Memory stops being write-only for non-day agents; ADR 0026 memory links become traversable in
  practice through search.
- Quarterly/yearly distillation adds a scheduled Phase B wake four or five times a year per goal
  — negligible cost, and it doubles as the agent's own retrospective ("your year in this goal").
- The day agent keeps its existing behavior; extractions are shared code, not semantic changes.

## Related

- [ADR 0017: Deterministic Log Compaction](./0017-deterministic-log-compaction.md) — amended (hierarchy above the rolling summary)
- [ADR 0020: Agent Input Capture](./0020-agent-input-capture.md)
- [ADR 0022: Long-Lived Daily OS Planner](./0022-long-lived-daily-os-planner.md) — the two-loop memory model and knowledge store this reuses
- [ADR 0026: Author-Time Memory Links](./0026-author-time-memory-links.md)
- [ADR 0052: Agent Directive Constitution](./0052-agent-directive-constitution.md)
- [ADR 0053: Goal-Driven Agents — Per-Goal Durable Producers](./0053-goal-driven-agents-per-goal-producers.md)

---

### Adr 0058 Procedural Text Banners No Generative Imagery (`docs/adr/0058-procedural-text-banners-no-generative-imagery.md`)

# ADR 0058: Procedural Text Banners — No Generative Imagery

- Status: Proposed
- Date: 2026-08-08

## Context

ADR 0055/0056 designed the goal-ad channel around generated images (Nano
Banana Pro briefs, a verification pass, an extraction of the image
service). The eval harness proved the pipeline end to end the same day —
briefs stayed leakage-free through four creative escalations, and the
renders were good.

And that is exactly why this ADR exists: the proof-of-concept made the
cost visible. Generating a bespoke image for every off-track moment of
every goal of every user is real energy and water spent on decoration —
the *coaching* is the text; the image was garnish. The user's framing
(2026-08-08): be responsible, use AI only where it is the point, and make
"my fitness agent costs ~100 Wh per month" an answerable question with an
answer worth being proud of.

## Decision

1. **The goal ad is a designed text banner, rendered by Flutter.** The
   model authors the copy — `headline`, optional `cta`/`tagline`, `tone`
   (the snark/roast register of ADR 0055 stands; text is now where all
   the personality lives) — and *selects* presentation from a fixed,
   code-owned catalog: an `animationPreset` (e.g. typewriter, pulse,
   wave, marquee, glitch) and an `accentPreset` (color/gradient/shader
   background treatments from the design system). Cheesy is allowed;
   cheesy is free.

2. **No generative imagery anywhere in the channel.** `create_goal_ad`
   carries no scene brief; no image provider is called; the Nano Banana
   integration, the visual-brief composition, and the brief-match
   verification pass are removed, not flag-gated — unused code is not
   kept (repo rule). The eval image stage that validated the old pipeline
   is retired with it; its artifacts remain in the session record.

3. **Presets are code, subject to the design system.** Animation and
   accent presets are enum values whose implementations live with the
   banner widgets, use design-system tokens, respect reduced-motion, and
   degrade gracefully where fragment shaders are unavailable or unsafe
   (shaders are disabled on Linux — the virtio-GPU freeze precedent), in
   which case a preset falls back to its plain-animation form.

4. **Energy is a first-class, per-agent answer.** Melious reports
   `energyKwh` (and CO2/water) per call, and every goal-agent call is
   attributed via `AiConsumptionEvent.agentId`. Eval reports and the
   per-goal detail surface show energy alongside credits — Wh per
   goal-month as an observed estimate. Minimizing AI use is what makes
   that number small enough to be worth telling.

5. **What survives from ADRs 0055/0056 unchanged**: the entity-based
   lifecycle with rating history, wear-out detection and zero-cost
   re-runs (a re-run is now literally free — no image ever needed
   regenerating either); visible-time tracking; dismissal cool-downs;
   staleness as a contract; and the need-to-know discipline — the
   leakage lint and evals now police the banner *copy* fields, which are
   still the only model text that reaches any surface verbatim.

## Consequences

- ADR 0055 Decision 8 (headline/CTA rendered into a generated image) and
  ADR 0056's image-request boundary are superseded by this ADR; 0056's
  *principle* — third parties receive only a typed, leakage-checked
  allowlist — is retained and applies to any future outbound payload.
- The ad pipeline loses its only non-deterministic, non-free stage:
  banner creation becomes instant, offline-capable, and costless, so ad
  freshness never competes with a budget and cold-start personalization
  (ADR 0055) iterates faster.
- Per-goal cost collapses to Phase B text inference alone (~0.0024
  credits/wake observed), making the energy figure both small and
  honest.
- If generative imagery is ever revisited (e.g. a user explicitly opts
  into it), ADR 0056 is the boundary it must re-enter through.

## Related

- [ADR 0054: Deterministic-First Two-Tier Wakes](./0054-deterministic-first-two-tier-wakes.md)
- [ADR 0055: The Banner-Nudge Attention Channel](./0055-banner-nudge-attention-channel.md) — Decision 8 superseded; the rest stands
- [ADR 0056: The Need-to-Know Visual Brief Boundary](./0056-need-to-know-visual-brief-boundary.md) — dormant; the principle survives as the outbound-payload rule

---

### Adr 0059 Relationship Agent Runtime And Nudge Generalization (`docs/adr/0059-relationship-agent-runtime-and-nudge-generalization.md`)

# ADR 0059: Relationship Agents on the Shared Runtime and the Kind-Agnostic Nudge Substrate

- Status: Accepted — implemented by plan v2 phases 3-5. The nudge
  substrate is kind-agnostic (`lib/features/nudges/`), the relationship
  agent is a registered runtime kind on deterministic-first two-tier
  wakes, and the open question on banner surfaces resolved to "the same
  surfaces as goal nudges, plus the People pages".
- Date: 2026-08-16

## Context

ADRs 0037–0041 specified relationship management on 2026-07-22, before the
goal-agent stack existed. Since then, ADRs 0053–0058 shipped (behind
`enable_agents_page`) exactly the machinery those ADRs had to assume or
invent:

- a **runtime registry for pluggable agent kinds** — feature-owned wake
  runners and maintenance merged into `agentWakeRunnersProvider` /
  `agentRuntimeMaintenanceProvider` in `app_bootstrap.dart` (today: day and
  goal agents),
- **deterministic-first two-tier wakes** (ADR 0054) — a €0 pure-Dart Phase A
  on every device tick, LLM Phase B only on lease-elected escalation, with
  the workspace-key and baseline-token contract proven in
  `lib/classes/goal_trigger_tokens.dart`,
- the **banner-nudge attention channel** (ADR 0055, revised by 0058) — the
  `goalNudge` entity lifecycle (`draft → ready → active → dismissed |
  retired | expired | superseded | failed`), dismissal-as-data with
  rest-of-day quiet windows, snooze provenance, per-activation ratings,
  exposure metrics, and a shell-level dock,
- a **kind-agnostic chat projection** and the durable chat-turn pattern.

Meanwhile phases 1–2 of the
[v2 implementation plan](../implementation_plans/2026-08-13_relationship_management_v2.md)
landed: the journal-side domain model (ADR 0038 holds) and the flag-gated
People tab with full CRUD, check-ins, contact channels, and task linking.

The next phases bind the relationship agent and its attention surface to
this runtime. Two of the July ADRs no longer describe the best available
shape: ADR 0040 assumed an `AgentTemplateKind` and ad-hoc triggering; ADR
0039 routed attention through OS notifications first. This ADR records the
rebase — decisions D2 and D3 of the v2 plan — and the sync-compatibility
rules for generalizing the goal-typed nudge substrate to a second kind.

Two traps in the current code motivate specific decisions below, both
verified: `agent_wiring.dart` resolves unregistered agent kinds to the
task-agent workflow silently (the registry is "consulted before the
task-agent default"), and the `requiresLease` predicate in
`agent_providers.dart` enumerates lease-elected workspaces explicitly — a
new escalation family that is not added there runs on every device and
bills one inference per device for a single result.

## Decision

1. **The relationship agent is a registered runtime kind on two-tier wakes
   (amends ADR 0040).** New `AgentKinds.relationshipAgent`, linked to its
   journal entity via `AgentLinkTypes.agentRelationship`, contributed
   through `relationshipAgentWakeRunnersProvider` +
   `RelationshipRuntimeMaintenance` merged in `app_bootstrap.dart` — never
   resolved via the silent task-agent default in `agent_wiring.dart`. A
   regression test pins runner resolution for the kind (the documented
   ADR 0054 trap). Following the goal precedent (ADR 0053 Decision 7),
   there is **no `AgentTemplateKind.relationshipAgent`**: the constitution
   is code (`relationshipAgentSystemPrompt`, ADR 0052). ADR 0040's
   template assumption (its Decision 1) is dropped; its report contract,
   health band, context boundary, honesty rules, and privacy-weighted
   routing all stand.

2. **Phase A is deterministic and free; inference is fact-gated.** Every
   wake recomputes a **cadence-health register** from the relationship and
   its linked check-ins — recomputed, never accumulated, so multi-device
   runs converge — and re-arms the daily cadence tick on a
   `relationship-cadence` workspace (calendar arithmetic, the
   `goal-cadence` pattern). ADR 0039's eligibility rule survives here as
   wake facts: `important == true`, status `active`, days since the last
   check-in (baseline: the relationship's own `meta.dateFrom`) measured
   against `checkInCadenceDays`. Phase B runs only on facts — cadence
   newly due, a check-in saved since the last report, a user chat message,
   or an explicit "Brief me" — and tool exposure stays fact-gated per
   ADR 0051.

3. **Escalations are lease-elected and per-episode.** The escalation
   workspace key derives from the due-day key
   (`relationship-escalation:<dueDayKey>`, the `goal-escalation:<periodKey>`
   precedent), so devices arming the same logical escalation write
   identical records and one lease winner runs Phase B. The trigger tokens
   carry a **baseline token** with the pre-transition cadence state (the
   `goal-baseline` lesson): Phase A updates the register and arms the
   escalation in one transaction, so by the time Phase B re-derives facts,
   "newly due" vs. "still due" is unreconstructable from storage without
   it. A check-in landing while an escalation is pending changes the due
   day and thus the episode; Phase B re-derives facts first and returns
   before any inference when the armed fact no longer holds. The
   `requiresLease` predicate in `agent_providers.dart` is extended with the
   `relationship-escalation:` family. The token contract lives in
   `lib/classes/relationship_trigger_tokens.dart`, runtime-visible without
   importing the feature (the `goal_trigger_tokens.dart` shape).

4. **Attention is the banner channel; OS reminders come later (supersedes
   ADR 0039 in part).** The primary nudge surface is the shell banner dock
   with every inherited semantic: quiet by default, dismissal = rest of
   the local calendar day, snooze as provenance, per-activation ratings,
   exposure metrics as synced CRDT data (ADR 0055/0058). Banner copy is
   model-authored text rendered procedurally — no generative imagery
   (ADR 0058 governs). ADR 0039's `NotificationEntity.relationshipCheckIn`
   variant and the `NotificationScheduler.reconcile()` startup wiring are
   **still wanted** — a phone should alert when the app is closed — but
   deferred to their own change, because wiring `reconcile()` revives OS
   alerts for *all* inbox types and deserves isolated tests. The gate for
   building it at all is dogfooding evidence that closed-app reminders are
   actually missed.

5. **The nudge substrate generalizes by sibling variant, never by
   conversion.** The nudge vocabulary currently in
   `lib/classes/goal_nudge_models.dart` — tone, the status lifecycle, the
   animation/accent catalogs, brief, rating, snooze, day-dismissal — is
   extracted into kind-neutral shared models (goal aliases retained during
   migration). `AgentDomainEntity` gains a **sibling `relationshipNudge`
   variant beside `goalNudge`**. Existing `goalNudge` rows are never
   converted or renamed — older peers must keep decoding them. Older peers
   decode `relationshipNudge` through the existing `unknown` fallback in
   `agent_db_conversions.dart` and never surface it (the agent kind does
   not exist for them), so mixed-fleet rollout is safe by construction,
   not by coordination. The concurrent-resolver rules (terminal-dismissal
   dominance, G-counter exposure merges) move into shared helpers applied
   per-variant rather than being duplicated.

6. **Dock visibility becomes per-kind; the height contract holds.** The
   `goal_banner_*.dart` widget family, `goal_banner_snooze.dart`, and
   `GoalNudgeInteractions` are generalized to the shared entry type; the
   shell dock (`beamer_app.dart` mounts) merges active nudges across kinds
   and keeps the reserved-lane height contract. The page-visibility gate
   (today `_showsGoalBannerDock`: tasks, dailyOs, habits) becomes
   per-kind: goal nudges keep exactly their current surfaces; relationship
   nudges show on those same surfaces plus the `/people` pages. The
   generalization is a behavior-preserving refactor that lands green with
   `enable_relationships` off and zero visible change for goals, pinned by
   the existing goal-banner test suites.

7. **Privacy posture is inherited unchanged (ADR 0037 holds).** Phase B
   context is bounded per ADR 0040: the relationship, the last N
   check-ins, linked task titles/statuses, and the previous report —
   **contact channels and contact refs never enter model context**
   (ADR 0041 §5). Inference is profile-routed
   (`RelationshipData.profileId` → category default → app default); before
   any cloud-bound trigger the UI names the provider, using the
   fails-closed `profileIsLocal` helper
   (`lib/features/ai/helpers/profile_locality.dart`). Deletion of a
   relationship cascades to its agent identity and the agent's entities —
   reports, nudges, registers — and pending reminder rows.

## Consequences

- The relationship feature inherits the goal stack wholesale — wake
  orchestration, lease election, outbox buffering, chat projection, report
  head resolution, consumption events, retention — and its new runtime code
  reduces to Phase A facts, one workflow, one token contract, and
  registration.
- The nudge generalization (Decision 5–6) is a prerequisite refactor that
  touches goals without changing them; the existing goal tests are the
  safety net, and the refactor must land before any relationship-agent
  banner work starts.
- A second consumer forces the shared helpers ADR 0040 predicted: the
  health-band provenance parsing extracts from
  `project_health_metrics.dart` into a helper used by both project and
  relationship reports.
- `app_bootstrap_test.dart` pins the provider override count; the bootstrap
  merge bumps it deliberately.
- ADR housekeeping recorded here: ADR 0039 is **superseded in part** (its
  attention channel; its eligibility rule and inbox variant survive as
  Decisions 2 and 4), and ADR 0040 is **amended** (registered runtime kind,
  two-tier wakes, no template).
- Left deliberately open, to be decided in the Phase B UI work: whether
  tapping a relationship nudge opens the relationship detail page
  (proposed — the briefing lives there) or the agent chat (the goal
  precedent, ADR 0055 Decision 6).

## Non-Goals

- OS push or notification-tap routing for relationship reminders (deferred
  per Decision 4).
- Converting, renaming, or migrating existing `goalNudge` rows.
- Birthday nudges (a deterministic Phase A fact feeding a banner — post-v1).

## Related

- [ADR 0037: Relationship Data Stays On-Device](./0037-relationship-on-device-storage-and-privacy.md)
- [ADR 0038: Relationship Domain Model](./0038-relationship-domain-model.md)
- [ADR 0039: Relationship Check-In Reminders](./0039-relationship-check-in-reminders.md) — superseded in part by this ADR
- [ADR 0040: Relationship Executive Briefing](./0040-relationship-executive-briefing.md) — amended by this ADR
- [ADR 0041: Relationship Contact Linking](./0041-relationship-contact-linking.md)
- [ADR 0051: Agenda-Gated Tool Exposure](./0051-agenda-gated-tool-exposure.md)
- [ADR 0052: Agent Directive Constitution](./0052-agent-directive-constitution.md)
- [ADR 0053: Goal-Driven Agents — Per-Goal Durable Producers](./0053-goal-driven-agents-per-goal-producers.md)
- [ADR 0054: Deterministic-First Two-Tier Wakes](./0054-deterministic-first-two-tier-wakes.md)
- [ADR 0055: The Banner-Nudge Attention Channel](./0055-banner-nudge-attention-channel.md)
- [ADR 0058: Procedural Text Banners — No Generative Imagery](./0058-procedural-text-banners-no-generative-imagery.md)
- [Implementation plan v2](../implementation_plans/2026-08-13_relationship_management_v2.md) (decisions D2/D3 recorded here)
- [knowledge/features/goals.md](../../knowledge/features/goals.md) — the runtime precedent this rebases onto
- [knowledge/features/relationships.md](../../knowledge/features/relationships.md) — the shipped phases 1–2

---

### Adr 0060 Banner Dock As App Shell Structural Band (`docs/adr/0060-banner-dock-as-app-shell-structural-band.md`)

# ADR 0060: The Banner Dock Moves to the App-Shell Structural Band

- Status: Accepted — implemented. `_NudgeBannerTopLane` in
  `lib/beamer/beamer_app.dart` mounts the single `NudgeBannerDock` above the
  desktop sidebar and the mobile content; the bottom mini-player and its
  reserved lane are gone.
- Date: 2026-08-20

## Context

ADR 0055 Decision 5 shipped the banner channel on page-level surfaces and
explicitly held one option in reserve:

> An app-shell structural band (the demo-banner pattern) is documented as an
> escalation surface and deliberately not built in v1.

What was built instead — design handover 1b — was a bottom-docked mini-player:
on desktop the last child of the content column, beside (never under) the
sidebar; on phones a lane in the bottom overlay stack, riding above the
recording indicators and the five-slot nav bar.

That placement carried a standing cost. Because the dock shared the bottom
edge with the navigation bar, page-owned sticky action bars, the recording
indicators and the keyboard, every one of those had to be coordinated with
explicitly:

- `_MobileNavOverlayHeightScope` re-derived the dock's rendered height
  (`nudgeBannerDockReservedHeight`) from design-system dimensions and live
  text metrics, so page content and FABs would clear it at every text scale;
- that reserve had to mirror the dock's own visibility rule exactly, or a
  hidden banner left a blank strip above the nav bar;
- the dock yielded entirely while the keyboard was up, because it otherwise
  sat in the keyboard's space — and the reserve had to mirror *that* too;
- the dock had to be suppressed on routes whose own bottom surface takes over
  the edge.

Four coupled contracts, all of them existing only because the banner competed
for the bottom edge with everything else that wants it.

## Decision

1. **Take the escalation surface ADR 0055 reserved.** The dock mounts in an
   app-shell structural band at the top of the shell, using the demo-banner
   pattern that decision named: first child of a `Column` whose second child
   is the entire shell.

2. **Structural, never an overlay.** A speaking banner displaces the sidebar
   and the content rather than covering them. Scrolling content cannot pass
   under it, and it cannot collide with any bottom-edge surface, because it is
   not at the bottom edge.

3. **Full width, above the sidebar.** On desktop the band spans the window
   rather than sitting inside the content region, matching the demo strip.
   This supersedes handover 1b's "beside, never under, the sidebar".

4. **The band composes with the demo strip by nesting.** `_NudgeBannerTopLane`
   sits inside `DemoModeScaffold`, so with both active they stack — demo strip,
   then agent banner — with no coordination code between them.

5. **Delete the reserved-lane machinery.** The `Column` reserves space by
   existing, so `nudgeBannerDockReservedHeight` and the dock's contribution to
   the bottom-nav overlay height are removed rather than ported.

6. **Delete the keyboard yield.** It existed because the dock sat where the
   keyboard appears. At the top of the shell the keyboard never covers it, so
   a banner now stays readable while the user types.

7. **The shell's slot never changes shape; only configuration varies.**
   `Column` → `Expanded` → `MediaQuery.removePadding` → shell is the hierarchy
   in *every* case, including a surface no banner speaks on, and `removeTop`
   alone follows whether a banner speaks. Swapping the hierarchy instead —
   wrapping the shell only while a banner is up — changes the widget type in
   that slot, so Flutter deactivates the subtree and inflates a fresh one: a
   synced banner arriving mid-edit would reset the shell's Beamers, scroll
   offsets and in-progress input.

   The **dock's** slot is stable within an eligible surface, where `SafeArea`
   stays mounted and only its `top` varies, which is what preserves the dock's
   rotation and tenure state across a tenant arriving or leaving. Across
   surfaces it is not: an ineligible surface renders a `SizedBox.shrink()`
   there instead, mounting no dock at all. That mirrors the mount rule the
   bottom dock already had, and it is safe precisely because the shell sits in
   the *other* slot — a `Column` reconciles its children positionally, so the
   dock slot changing type cannot disturb the shell.

## Consequences

- The four coupled bottom-edge contracts collapse to one structural
  invariant, and the collision class the mini-player lived with is gone by
  construction rather than by arithmetic.
- Escalation is the point: a structural band is harder to ignore than a
  bottom lane. ADR 0055's respect mechanics (Decision 4) are unchanged and now
  carry more of the weight — if banners start reading as intrusive, the
  mechanics to tune are frequency and cool-down, not placement.
- The band consumes vertical space at the top of every eligible surface while
  a banner speaks. On short phone viewports that is the most expensive space
  in the app; the quiet-by-default contract (ADR 0055 Decision 5) is what
  keeps the cost occasional.
- Ratings, exposure metering, rotation and the per-surface gate are untouched:
  this ADR moves where the dock is mounted, not what it says or when.

## Related

- [ADR 0055](./0055-banner-nudge-attention-channel.md) — the channel, and the
  escalation surface this ADR takes.
- [ADR 0058](./0058-procedural-text-banners-no-generative-imagery.md) — the
  procedural text banners, including the collapse-as-feedback contract.
- [ADR 0059](./0059-relationship-agent-runtime-and-nudge-generalization.md) —
  the kind-agnostic substrate and the per-surface gate.
- [knowledge/features/nudges.md](../../knowledge/features/nudges.md) — how the
  lane is built.

---

### Adr 0061 Relationship Briefings Disclose Provider Without Confirmation (`docs/adr/0061-relationship-briefings-disclose-provider-without-confirmation.md`)

# ADR 0061: Relationship Briefings Name Their Provider Without Asking

- Status: Accepted — implemented. `RelationshipBriefingCard` requests a
  briefing directly; `relationshipBriefingDisclosureProvider` and its
  confirmation sheet are removed.
- Date: 2026-09-19
- Refines: ADR 0037 Decision 3, ADR 0059 Decision 7

## Context

ADR 0037 Decision 3 requires that "the UI states which provider will see the
data before the user triggers a briefing", and ADR 0059 Decision 7 carries it
into the runtime: "before any cloud-bound trigger the UI names the provider".

It was implemented as a confirmation sheet — *Send to {provider}? The briefing
runs on {provider}. Notes about this person will be sent there for
processing.* — shown on **every** cloud-routed *Brief now* and *Update now*,
followed by a *Briefing requested* toast. In use this read as friction without
information:

- the provider is one the user configured and chose, in an app whose purpose
  is to run these briefings; no other surface in the app confirms a request to
  its provider per action;
- the answer never changes between taps, so the sheet trains a reflexive
  *Continue*, which is the opposite of informed consent;
- the card already names the route before any tap: its model row reads
  *{model} · via {provider}* on every face.

## Decision

1. **The provider is disclosed passively, not by confirmation.** The briefing
   card's model row — present on every enrolled face, before and during a run
   — is the statement ADR 0037 requires. Tapping *Brief now* or *Update now*
   requests the briefing at once.
2. **No acknowledgement toast.** The card's running face (the spinner on its
   status line) is the acknowledgement; a failure to enqueue still toasts.
3. **An update never blanks the card.** While a new briefing is written, the
   previous one stays readable under the spinner; a first briefing shows the
   status line alone. No face estimates how long a run takes.
4. **A missing route is reported by the wake, not pre-empted.** Without the
   disclosure preflight there is no pre-tap route resolution; a wake with no
   resolvable model is stamped failed and the card offers *Choose a model*.

ADR 0037's substance — no Lotti-side retention, local-first defaults, the user
choosing any cloud provider explicitly — is unchanged.

## Consequences

- Fewer surfaces: the disclosure provider, its exception, and the sheet's,
  toast's and duration estimate's strings are gone.
- The model row carries a privacy duty: it must stay visible on every enrolled
  face and name the provider, not only the model.

---

### Adr 0062 Check Ins Hold Entries (`docs/adr/0062-check-ins-hold-entries.md`)

# ADR 0062: Check-ins Hold Entries, and Changed Evidence Drives the Briefing

- Status: Accepted — data and agent layer implemented (entries, evidence
  signal, agent context, delete cascade); the check-in detail view, the
  composer saving without waiting for a transcript, photos and the logbook
  follow.
- Date: 2026-09-19
- Refines: ADR 0038 Decision 2, ADR 0040 Decision 4, ADR 0059 Decision 2

## Context

ADR 0038 Decision 2 made a check-in's narrative its own `entryText`. In use
that shape broke down:

- a dictated check-in could not be saved until its transcript arrived, so a
  failed transcript lost the check-in;
- a correction ("that name was misheard") had to be a second, separate
  check-in, which the briefing then narrated as an event;
- the recording itself was linked to the person, not the check-in, and
  photos had nowhere to go.

Separately, the refresh escalation of ADR 0059 Decision 2 keyed the
briefing's staleness to the newest check-in's *date* and allowed one refresh
per UTC day. A check-in logged after the briefing but dated before it —
yesterday's call, logged this morning — never made the briefing stale, and a
second check-in on the same day never produced a new one.

## Decision

1. **A check-in is a container.** Comments, recordings and photos are
   entries of their own, linked check-in → entry with a `BasicLink`, and
   inherit the check-in's category and privacy. A check-in's `entryText`
   remains readable as the text it was saved with; it is migrated **at read
   time**, never rewritten: every surface and the agent show it first, then
   the entries in the order they were added. No device on an older build
   loses anything.
2. **The agent's context includes the entries** (refining ADR 0040
   Decision 4): per check-in, up to eight entries — the comment's text, a
   recording's transcript, a photo's description — each bounded like the
   narrative, and a recording or photo without words says so rather than
   reading as silence. Entries are read unfiltered by the private-display
   preference, like check-ins, so devices agree.
3. **A check-in's `updatedAt` is when its evidence last changed.** Adding an
   entry saves the check-in again, and so does a transcript (or, later, a
   photo description) arriving after the check-in was saved. The save syncs,
   so every device sees the same signal.
4. **One refresh per evidence change** (refining ADR 0059 Decision 2): the
   refresh episode is keyed by the instant the evidence last changed, to the
   millisecond, instead of the newest check-in's UTC day. The key is taken
   from the stored date and time components, which every device reads alike;
   the deadline is the instant those components and the check-in's recorded
   UTC offset name, plus a 30-second settle, so a burst of additions is briefed
   once; while a changed check-in's recording still awaits its transcript,
   the deadline moves to the transcript timeout, so the agent never briefs on
   a check-in that says nothing yet.
5. **Deleting cascades to entries** (ADR 0037): deleting a check-in, or its
   person, tombstones the entries the check-ins alone hold; an entry that
   also belongs to something else still live is left alone.

## Consequences

- Cost is bounded by what the user does — at most one briefing per change —
  rather than by a daily ceiling.
- Every write path that changes what a check-in holds must touch the
  check-in; `RelationshipRepository.addCommentToCheckIn`,
  `attachEntryToCheckIn` and `touchCheckInsHolding` are those paths.

---

### Adr 0063 Tapped Relationship Reminder Pauses Itself (`docs/adr/0063-tapped-relationship-reminder-pauses-itself.md`)

# ADR 0063: A Tapped Relationship Reminder Pauses Itself

- Status: Accepted
- Date: 2026-09-19
- Amends: ADR 0055 Decision 6 (for relationship banners only)

## Context

ADR 0055 Decision 6 keeps two intents apart: tapping a banner opens its
conversation, and dismissing it is a separate, explicit gesture. Goal banners
still follow that rule.

The relationship reminder broke it in practice. Its tap opens the person's
page. The banner wrote nothing, so it kept rotating in the dock — including
over the person page it had just opened. People tap a reminder to act on it,
but they cannot always call the person right away. So the banner looked like
it had ignored the tap, and it kept nagging after the user had responded.

The owner raised this, and a design panel on 2026-09-19 (four experts, three
personas) agreed unanimously that the tap should pause the reminder.

## Decision

1. **Tapping a relationship reminder opens the person and pauses the
   reminder for one hour.** The pause is an ordinary synced snooze
   (`NudgeInteractions.snooze` with the one-hour preset), so every device
   hides the reminder and it returns on its own. It is not a dismissal: the
   reminder stays active, comes back after the hour, and is retired only by
   a logged check-in, as before. A write that fails leaves the banner as it
   was; the page still opens.
2. **The pause says why.** Each snooze event records a `NudgeSnoozeReason`:
   `opened` for a tap, and null (read as `chosen`) for everything else. The
   agent's FACTS show an opened reminder as "opened by the user, paused
   until …", so the agent never reads the pause as the reminder being put
   off. Old clients ignore the field, and an unknown future reason decodes
   as none.
3. **The person page says what the tap did.** While the tap's pause holds,
   the page shows *Reminder paused until 15:40* with *Snooze longer*, which
   opens the existing snooze sheet. A snooze chosen there replaces the
   opened pause, and the callout goes away.
4. **Goal banners are unchanged.** Their tap only opens. Decision 6 still
   holds for them.

## Consequences

- One tap now acts on the reminder. An accidental tap costs an hour of
  quiet, which *Snooze longer* and the next wake can correct.
- There is no Undo. Clearing a snooze would have to beat the resolver's
  latest-deadline-wins merge across devices, and an hour's pause with a
  one-tap way to lengthen it did not justify that.
- The reason is the first field on a snooze event that is not about timing.
  Goal wakes, which learn display windows from snooze history, could use it
  to discount opened pauses. They do not yet, because goal banners never
  record one.

---

### Adr 0064 Check Ins Appear In The Logbook (`docs/adr/0064-check-ins-appear-in-the-logbook.md`)

# ADR 0064: Check-ins Appear in the Logbook

- Status: Accepted — decision 3 (search) superseded by
  [ADR 0139](./0139-check-ins-are-searchable.md)
- Date: 2026-09-19
- Amends: ADR 0038 Decision 2 (where check-ins are shown); keeps ADR 0037's
  search boundary

## Context

ADR 0038 made a check-in an ordinary journal entry, dated at the interaction,
so that it "sits naturally on calendars and timelines". In practice the
Logbook never showed one: its entry-type filter listed neither relationship
variant, and the relationships concept recorded that absence as deliberate,
alongside ADR 0037's rule that a person cannot be found by name outside the
People tab.

A design panel on 2026-09-19 decided that a check-in is a moment of the user's
day like any other and belongs in the Logbook's timeline, while the people
themselves — and finding them — stay in People.

## Decision

1. **`CheckIn` is a Logbook entry type** with its own filter chip, gated on the
   relationships feature flag like events and habits: with People off, check-ins
   are neither queried nor offered.
2. **The row names the person and opens in People.** It reads "Check-in with
   {name}", shows the note it was logged with, and opens the check-in on the
   person's page with the opens-elsewhere glyph, as an event row opens in
   Events. A person hidden as private, or gone, leaves the row naming the kind
   alone, and a rename or a change in private visibility reaches a row already
   on screen.
3. **People stay out, and so does search.** `Relationship` is not a Logbook
   type. A text search leaves `CheckIn` out of the queried types, and check-ins
   are not embedded for vector search, so a check-in's note cannot surface a
   person outside People — ADR 0037's boundary is unchanged.
4. **Saved selections gain the type once, when it is offered.** A Logbook
   selection saved before the type existed has never had the chance to deselect
   it. It stays pending until the filter offers it — immediately with People
   on, or whenever People is turned on — then joins the selection once; a
   record of the types each saved selection was made with keeps a later
   deselection in place.

## Consequences

- The Logbook reflects the whole day, including the people the user spent it
  with, without widening who can find them.
- A new Logbook entry type no longer disappears for everyone who has ever
  saved a filter: the pending mechanism in `JournalFilterPersistence` applies
  to any type added later.
- Search results and the feed differ for check-ins on purpose; the feed shows
  them, a search never returns them.

## Related

- [ADR 0037: Relationship Data Stays On-Device](./0037-relationship-on-device-storage-and-privacy.md)
- [ADR 0038: Relationship Domain Model](./0038-relationship-domain-model.md)
- [ADR 0062: Check-ins Hold Entries](./0062-check-ins-hold-entries.md)

---

### Adr 0065 Model Checked Sync Sequence Reservations (`docs/adr/0065-model-checked-sync-sequence-reservations.md`)

# ADR 0065: Model-Checked Sync Sequence Reservations

- Status: Accepted
- Date: 2026-09-23

## Context

The sync sequence log lets a device prove that no counter another device
handed out was lost. Its own-host half had been hardened one incident at a
time — persist-first reservations, `reserved` rows, `burnPending` retries, the
distinction between `burned` and `unresolvable` — and its history of fixes
("sync hot loop", "prevent replay of backfill requests", "stuck sync",
"race condition in catch up") is the history of a protocol reasoned about in
prose.

We wrote the protocol down in TLA+ (`specs/tla/SyncSequence.tla`) as the code
stood and model-checked it with TLC. Three holes came back as concrete traces:

1. **One crash between the payload commit and the outbox enqueue** lost the
   write for every peer. The row stayed `reserved`, which the responder defers
   and startup never touches, and without a later counter no peer even knew to
   ask. A reservation that died before its commit left a request open until
   the peer gave up.
2. **Two swallowed failures after a commit** — the early sequence bind, then a
   later step such as the FTS insert — made the outer VC scope release a
   counter whose payload was on disk, and the originator burned it.
3. **One swallowed reserved-row insert failure** let a request for an
   in-flight counter find no row, which the responder answered as a burn
   before the payload landed.

All three come from one gap: the originator could not tell "reserved, write
still running", "reserved, write landed, process died" and "reserved, write
never landed" apart.

## Decision

1. **A reservation names its payload.** `reserveNextVectorClock` and
   `getNextVectorClock` take the payload id and type; the `reserved` row
   records them as an intent. Every write path in the app passes it.
2. **Only a live reservation is deferred.** `VectorClockService` keeps a
   process-local map of reservations it has neither bound nor released. A
   crash forgets it, so an orphaned reservation is recognisable.
3. **One settlement rule for every own counter nothing has bound.**
   `BackfillResponseHandler.settleOwnCounter` binds and resends a counter whose
   named payload's clock covers it; defers a live or unnamed one, or one whose
   store is not wired yet; and burns everything else. The responder, the VC
   release handler and startup reconciliation all use it, so a release can no
   longer burn a payload that landed.
4. **A reservation is recorded before its counter is handed out.** When the
   sequence-log insert fails, the reservation is recorded in the settings
   database — the store that already holds the watermark — and startup moves
   it into the log. Only when both stores refuse does reserving throw, so no
   write can use the counter. A save therefore fails only when the settings
   database refuses a write — the database whose failure already fails the
   save through the watermark — never merely because the sync database is
   locked.
5. **`received` means durably in the outbox.** The write paths no longer bind
   before enqueueing; the enqueue writer binds after its insert. A crash in
   between leaves a `reserved` row that startup settles and resends.
6. **The model gates the code.** `specs/tla/` holds the spec, its TLC
   configurations and a pinned, checksum-verified tool runner. CI model-checks
   it whenever the spec or the code it describes changes, and a change to the
   protocol updates the spec in the same pull request.

## Consequences

- With every reservation named, one crash at any point loses no committed
  write and strands no backfill request; neither any two injected faults, nor
  one crash together with any one fault, can make the originator burn a
  payload that exists. TLC checks all of these, and four deliberate mutations
  of the fix — including dropping the settings fallback — are each caught.
- Delivery is still not claimed under swallowed enqueue failures or abandoned
  inbound events; the model says so explicitly instead of implying it.
- An unnamed reservation behaves as before. New write paths must name their
  payload, or they fall back to deferral after a crash.

## Related

- `specs/tla/SyncSequence.tla`, `specs/tla/README.md`
- [Sequence log and backfill](../../knowledge/features/sync/sequence-and-backfill.md)

---

### Adr 0066 Model Checked Agent Wakes And Confirmations (`docs/adr/0066-model-checked-agent-wakes-and-confirmations.md`)

# ADR 0066: Model-Checked Agent Wakes and Confirmations

- Status: Accepted
- Date: 2026-09-24

## Context

After the sync sequence log ([ADR 0065](./0065-model-checked-sync-sequence-reservations.md)),
the agent runtime was the next protocol whose correctness rested on prose: a
wake queue, per-agent runner leases, executors that an abort cannot cancel
(Dart futures run on), and a confirmation flow in which a double tap, a
"Confirm all" and a retry can race over one persisted change set.

We wrote both down in TLA+ as the code stood — `specs/tla/WakeRuntime.tla`
and `specs/tla/ChangeSetConfirm.tla` — and model-checked them with TLC. Four
holes came back as concrete traces:

1. **Overlapping runs after an abort.** A cancel, the ten-minute run cap or a
   stale-drain reset released the agent's lease while its executor kept
   running, and the next wake for that agent started beside it.
2. **Lost wakes on a crash.** Queued jobs lived only in memory, and a run
   the crash interrupted was never retried: whatever triggered them was gone.
3. **A concurrent confirm applied a change twice.** Both callers read the item
   as `pending` before either wrote, and both dispatched the tool.
4. **A throwing post-confirm hook applied a change twice.** The failure
   reverted an item whose change had already landed to `pending`, and a retry
   applied it again.

## Decision

1. **Single flight covers detached executors.** The drain does not dispatch an
   agent while an earlier executor of it is still live, whether or not it
   still holds its lease. An executor still running after
   `WakeOrchestrator.hungExecutorAfter` (30 minutes, three run caps) is
   reported once as hung and stops blocking, so a future that never settles
   cannot wedge its agent until the next launch — the model's `DeclareHung`.
2. **Every queued wake is a durable intent until its run settles.**
   `WakeIntentStore` records one intent per queued job, keyed by its run key,
   in the device-local settings database; merged tokens join the job's intent.
   The intent is settled when the job's run settles, or when the job is
   dropped for good — gated, cancelled or superseded — and startup restores
   whatever is left, one job per agent and workspace, at most twice without a
   settled run.
3. **A confirm claims the item before it dispatches.**
   `ChangeSetResolutionStore.claimChangeSetItem` moves the item from `pending`
   to `confirmed` and returns nothing when it is no longer pending; the
   decision is written in the same transaction, so a failed decision write
   rolls the claim back. The loser of a race stops without dispatching, and
   without recording a decision. A reject claims `pending` to `rejected` the
   same way, so it can never overwrite a change a confirm applied.
4. **A successful dispatch is final.** When the post-confirm hook throws after
   the change landed, the failure is logged and the item stays `confirmed`.
5. **The models gate the code**, as in ADR 0065: the specs live in
   `specs/tla/`, CI model-checks them whenever they or the code they describe
   change, and Glados traces in the wake and confirmation suites drive the real
   Dart code through generated interleavings and check the same properties.

## Consequences

- `SingleFlight`, `HungOnlyWhenDetached` and `NoLostWake` hold with two
  agents, up to two aborts, and one crash at any point; `AtMostOnceApply`,
  `RejectedMeansNotApplied` and `ConfirmedMeansApplied` hold for two
  concurrent callers that confirm or reject, with dispatch failures and
  throwing hooks, and the first two also across a crash.
- The wake-intent trace earned its place before the change merged: settling
  intents per agent with a sequence cutoff — the first implementation — lost a
  trigger queued in a second job of the same agent. The model, which settles
  exactly the triggers a run covered, was right; the code was not a faithful
  refinement of it. The model now also lets a run cover only some of an
  agent's queued triggers, as the real queue does, and TLC rejects the cutoff
  design.
- A follow-up wake for an agent whose aborted executor is still running now
  waits for it, up to 30 minutes, instead of overlapping it.
- A wake restored after a crash runs as a manual wake of its agent and
  workspace; one whose run crashes the process twice is dropped with an error
  log.
- Two confirmation cases stay open and are documented in `specs/tla/README.md`:
  a tool that throws after its effect landed is reverted to `pending` and can
  apply again on retry, and a crash between the claim and the dispatch leaves
  an item `confirmed` without its effect. Closing them needs either an
  `applying` status that sync and the UI understand, or tools that are
  idempotent per decision id.

## Related

- `specs/tla/WakeRuntime.tla`, `specs/tla/ChangeSetConfirm.tla`,
  `specs/tla/README.md`
- [Wake orchestration](../../knowledge/features/agents/wake-orchestration.md)
- [Task agents](../../knowledge/features/agents/task-agents.md)
- [ADR 0006: Change-set deferred tool confirmation](./0006-change-set-deferred-tool-confirmation.md)

---

### Adr 0067 Model Checked Change Set Lifecycle (`docs/adr/0067-model-checked-change-set-lifecycle.md`)

# ADR 0067: Model-Checked Change-Set Lifecycle

- Status: Accepted
- Date: 2026-09-24

## Context

[ADR 0066](./0066-model-checked-agent-wakes-and-confirmations.md) made
confirming one item of a change set safe on one device: a confirm claims the
item in a transaction before it dispatches. But a change set is more than one
item on one device. It is one synced row that several writers change — a
failed dispatch reverts or auto-retracts its item, a created follow-up task
rewrites its migration's `targetTaskId`, a rejected follow-up cascades to its
migrations, the agent retracts stale items and consolidates older sets — and
every device that shows it edits it.

Only the claim was a transaction. Every other writer read the whole set,
awaited, and wrote the whole set back; sync compared a received set against a
read of the local row taken before its write; and the resolver settled two
concurrent versions of the set by picking one of them whole (the
last-writer-wins timestamp of a change set is its `createdAt`, which never
changes, so the canonical clock order decided).

We modelled all of it in `specs/tla/ChangeSetLifecycle.tla` — two devices,
up to three items, sync as messages delivered in any order — and TLC
returned five holes:

1. **A failed dispatch put back a sibling's claim.** Item A's dispatch failed
   and its revert read the set; item B was claimed and applied; the revert
   wrote its copy back, putting B to pending. A retry applied B again. The
   auto-retraction of a non-retryable failure, the migration cascade and a
   staged retraction had the same shape.
2. **The sibling rewrite put back a migration's claim.** A created follow-up
   task rewrites its migration's target in the set. The migration, resolvable
   from the service's memory before the rewrite lands, could be claimed and
   applied in between — and the rewrite put it back to pending.
3. **A consolidated copy claimed a change that never landed.** A wake folding
   an older set into the survivor copied a claimed item with its status,
   `confirmed`; the claim's dispatch then failed and reverted the original,
   and the copy went on saying the change was applied.
4. **Sync dropped decisions made concurrently on two devices.** One device
   confirmed an item, another decided a different one; the whole-row winner
   discarded one device's decision, and an applied change read pending again
   everywhere.
5. **Sync wrote a peer's version over a local claim.** The receive read the
   local row, a local claim committed, and the receive wrote the peer's
   version — which covered the row it had read — over the claim.

Each ends with a change applied twice once the user retries, which TLC shows
in eight or nine steps with every fix removed.

## Decision

1. **Every local write of a set is one transaction that changes only what it
   owns.** `ChangeSetResolutionStore.transitionChangeSetItem` moves one item
   from an expected status to a new one on a fresh read, in one transaction;
   the claim is its `pending` case, a failed dispatch reverts or retracts
   only an item still `confirmed`, a reopen moves only an item still holding
   the decision it read (and neutralises the verdict in the same
   transaction), and the cascade claims each migration like a user
   rejection. The sibling rewrite and the staged retraction re-read and write
   in one transaction.
2. **Every change of an item bumps its revision.** `ChangeItem.revision`
   counts the item's status and argument changes; every writer uses
   `withStatus` / `withArgs`.
3. **Concurrent versions of a set merge item by item.**
   `mergeConcurrentChangeSets` — the change-set case of the shared receive
   decision `resolveAgentEntityVersions` (ADR 0068) — keeps, for each index,
   the version that changed the item last (higher revision); at the same
   revision the more final status wins — a confirm took effect, so it beats
   a concurrent rejection or retraction, and any decision beats pending — and
   an exact tie goes to a fixed order on the item's content, never to the
   clock order. Items only one version appended are kept, the set status is
   derived, and the vector clock is the join, so both devices converge on one
   row without another write. Because no step reads the canonical clock
   order, the joined clock cannot make the result depend on arrival order —
   the trap ADR 0068 records for nudges. Versions that disagree on which
   proposal an index holds, or a tombstone, fall back to the whole-row
   winner. Change sets are append-only for last-writer-wins, so ADR 0068's
   local-write resolution does not apply to them; every local writer already
   re-reads the set in its own transaction (decision 1).
4. **Sync applies a received set in one transaction** over a fresh read of
   the local row (not the bundle's prefetched snapshot), through the same
   `resolveAgentEntityVersions` every other agent entity uses.
5. **Consolidation moves only pending items.** A decided item stays in the
   set it was decided in; only pending items are shown, so the card looks the
   same.
6. As in ADR 0065 and ADR 0066, the model gates the code: CI model-checks
   every configuration, and a Glados trace in the confirmation service's suite
   drives the real services through generated interleavings of writers and
   read deliveries, checking the model's invariants.

## Consequences

- `AtMostOnceApply`, `AppliedStaysDecided`, `StatusMatchesEffect`,
  `Converged` and `MigrationAfterTarget` hold for one device with a
  follow-up task, its migration and a plain item under every interleaving of
  its writers, and for two devices syncing through messages in any order, as
  long as no item is decided on both devices before they sync.
- Rows gain an optional item `revision` field. Older clients ignore it and
  drop it when they rewrite a set, so an item without one carries no order:
  the merge judges it by status alone rather than as revision 0, which would
  let any newer-build change of the item — a target rewrite, say — beat a
  confirm the older build made and applied. The cost is the reverse edge
  case: a newer-build revert racing an older build's confirm keeps the
  confirm.
- Residuals, documented in `specs/tla/README.md` and each confirmed by TLC:
  - **The same item decided on two devices before they sync** is applied on
    both. The replicas converge, but no local transaction can prevent the
    second apply. Closing it needs coordination — one device that applies a
    set's changes, a lease on the item, or tools idempotent per decision id —
    which is a product decision.
  - **Consolidation on one device racing a decision on another** leaves a
    pending copy of an item the other device applied. Closing it needs the
    copy to carry a link to its original, checked before the copy is
    claimed, or consolidation that groups sets for display instead of copying
    rows.
  - The ADR 0066 residuals stand: a tool that throws after its effect landed,
    and a crash between the claim and the dispatch.

## Related

- `specs/tla/ChangeSetLifecycle.tla`, `specs/tla/ChangeSetConfirm.tla`,
  `specs/tla/README.md`
- [Task agents](../../knowledge/features/agents/task-agents.md)
- [Vector clocks and conflict resolution](../../knowledge/features/sync/vector-clocks-and-conflicts.md)
- [ADR 0006: Change-set deferred tool confirmation](./0006-change-set-deferred-tool-confirmation.md)
- [ADR 0066: Model-checked agent wakes and confirmations](./0066-model-checked-agent-wakes-and-confirmations.md)

---

### Adr 0068 Model Checked Agent Convergence (`docs/adr/0068-model-checked-agent-convergence.md`)

# ADR 0068: Model-Checked Convergence of Synced Agent Entities

- Status: Accepted
- Date: 2026-09-24

## Context

Every agent entity — state rows, knowledge, scheduled wakes, nudges, version
heads — is replicated across devices and resolved on arrival by one rule:
causal dominance by vector clock, then, for concurrent versions, a
type-specific override, `updatedAt` last-writer-wins and a canonical clock
tiebreak, with agent-state G-counters joined (ADR 0022). The resolver is pure,
and the claim was that purity makes every device pick the same winner. A pure
*pairwise* rule is not enough: the result must not depend on the order in
which a replica receives the versions, and the writes being compared are not
only the ones the resolver sees — local writes, device-local bookkeeping and
snapshot writers all shape the row.

After ADR 0065 and ADR 0066 we wrote the replication down in TLA+ —
`specs/tla/AgentReplication.tla` (three replicas, any delivery order,
duplication), `specs/tla/AgentStateWrites.tla` (the writers of one state row)
and `specs/tla/VersionHeads.tla` (version rows and their head) — and
model-checked them with TLC. The holes came back as concrete traces:

1. **The throttle split replicas for good.** `WakeThrottleCoordinator` wrote
   its device-local `nextWakeAt` straight to the repository and stamped
   `updatedAt` with the local clock. Peers never saw that timestamp, so a
   concurrent version that every other replica took lost on this one.
2. **A causal successor erased merged increments.** A concurrent conflict
   joined agent-state G-counters into the row but kept the winner's clock;
   a later version that succeeded the winner alone — without the loser's
   increments — then replaced the row by causal dominance, and the increment
   was gone.
3. **Stale and unclocked local writes diverged.** A local write replaced the
   row unconditionally, under the clock it was built on. Built on a
   wake-start snapshot or on `vectorClock: null`, it was concurrent with the
   row it replaced; the writer kept it while every peer resolved the pair the
   other way — a retraction revived on one device only, an own increment
   dropped.
4. **A successor could sort before its predecessor.** A write on a lagging
   clock carried an older `updatedAt` than the row it succeeded, so a third
   concurrent version could beat it but not its predecessor, and the arrival
   order decided the result.
5. **The end-of-wake state write erased what happened during the wake.** The
   task agent wrote its outcome (failure count, wake counter, `lastWakeAt`)
   as a copy of the state it read when the wake started, putting back the
   report-stale watermark that a subscription event had moved meanwhile — the
   report then read as fresh although something changed while it was being
   written. Its failure path did the same.
6. **A goal revision left a disconnected twin active for ever.** Two devices
   can each mint an active v2; the head resolver keeps one, and a revision
   superseded only the head's version, so the twin stayed active through
   every later revision and its banners were never swept.

## Decision

1. **Device-local writes never touch the synced timestamp.** The throttle
   writes `nextWakeAt` without `updatedAt`, like every other device-local
   scheduling write already did.
2. **One receive-path decision, shared.** `resolveAgentEntityVersions` is the
   whole decision the sync processor applies, and it joins agent-state
   G-counters and report watermarks on every delivery, causal or concurrent
   (`joinConvergentAgentFields`). The winner keeps its own clock.
3. **A local write succeeds the row it replaces.** For every mutable register
   (a variant ordered by `updatedAt`) `AgentSyncService._upsertEntityRaw`
   reads the persisted row in the write's transaction, stamps the write with
   a clock covering both, and persists what `resolveLocalAgentWrite` returns:
   a write built on the row keeps its fields; a write built on a stale
   snapshot or on no clock is resolved against the row as if concurrent —
   which is what every peer holding the row decides too; G-counters and
   report watermarks never go down; and `updatedAt` never moves back. What
   the writer keeps is what the replicas converge on.
4. **State outcomes are transforms of the current row.** The task agent's
   success and failure writes, the day agent's failure write and the project
   agent's dormant skip go through `AgentSyncService.updateAgentState`, which
   re-reads the row in the transaction and applies a field-scoped change.
5. **A goal revision supersedes every active version,** as soul and template
   edits already archive every non-archived one.
6. **The models gate the code**, as in ADR 0065: the specs live in
   `specs/tla/`, CI model-checks them whenever they or the code they describe
   change, and a Glados trace drives three real `AgentSyncService` replicas
   through generated writes and arrival orders and checks the same
   invariants.

## Consequences

- `Converged`, `NoLostSuccessor`, `OwnCountKept` and `NoLostIncrement` hold
  for three replicas with stale and unclocked writes and one tick of clock
  skew; `NoLostWatermark`, `FreshIsHonest`, `FailureStreakExact` and
  `NoLostWake` hold for a state row's writers; version heads converge, and
  one clean edit settles their statuses.
- A local write to a mutable register costs one primary-key read in its
  transaction. Append-only variants skip it.
- A stale write can now lose locally, exactly as it loses on every peer: an
  edit built on a snapshot older than a retraction does not revive it, and a
  lease claim built on an old read is resolved against the claim that
  replaced it the way every peer resolves it, so all devices agree on one
  survivor.
- A row's `updatedAt` can be later than the writing device's clock, when a
  peer with a faster clock wrote the row it succeeds.
- Residuals, documented in `specs/tla/README.md`:
  - **A successor that ranks below its predecessor** — the digest retry
    re-arming its consumed window at the same instant, a relationship retry
    moved to an earlier instant — still lets arrival order decide against a
    third concurrent version. Closing it needs the override rank to grow along
    every causal edge: a generation field that sync carries and older clients
    preserve, or re-arming under a new record id. That is a protocol change.
  - **Nudges on an exact `updatedAt` tie** keep the joined clock their merge
    stores, so the canonical tiebreak can resolve them differently on
    different replicas.
  - **Version statuses** can disagree with the head after concurrent edits
    (twin actives, a head naming a version another device archived) until the
    next edit. Every read resolves the active version through the head.
  - `consecutiveFailureCount` across devices stays last-writer-wins.

## Addendum (2026-09-24): writes meant to move the row back

Decision 3 resolves a local write built on a null or stale clock as if it
were concurrent with the persisted row. Under plain last-writer-wins that is
harmless — the clamped, newer `updatedAt` wins — but a write whose whole
point is to move the row *against* the resolver's order is then handed the
row back: under a type override (a pre-warm moved to an earlier deadline,
fixed with ADR 0069), or under last-writer-wins on an equal or skewed
timestamp. An audit of every local writer of the override types and of the
version-head registers found:

- **Report heads** (task, project, event, goal and relationship agents) were
  written with `vectorClock: null` over the head they had just read. A
  second report for the same overdue period stamps the same instant, and a
  head stamped by a peer whose clock runs ahead is newer still; in both the
  new report never became the standing one, on this device or any other.
- **Soul and template heads** moved to a new version the same way, so under
  clock skew an edit created its version but left the head — and every
  prompt — on the old one.
- **Goal-progress registers** carried the row the derivation read, which a
  report refresh reads before its inference; a same-ordinal twin's row that
  synced in meanwhile was judged concurrent, and the goal-progress resolver's
  id order could put the twin's evaluation back until the next tick.

Every one of them now carries the clock of the row it replaces, read in the
same transaction: the write is that row's causal successor, keeps its fields
and still never moves `updatedAt` back. The register is the one exception by
design: a row computed under a *newer* spec ordinal is the next spec arriving
before its head, so the recompute does not build on it and the resolver's
higher-ordinal rule keeps it. The day-summary writer's branch that seeded a
rewrite from a tombstoned prior was unreachable — reads filter tombstones,
and day summaries are never soft-deleted — and is removed. The other writers of override types —
knowledge, day summaries, nudge lifecycle and interactions, goal spec heads,
the scheduled-wake writers outside ADR 0069 — already build on the row they
read, or only move forward in the resolver's order.

`AgentReplication.tla` gains the class as a write kind, `Intend`: a write
built on the row that moves it out of the terminal status, or to new fields
at the row's own timestamp. `LocalWriteTakesEffect` holds when it carries the
row's clock (`IntentCarriesClock`) and fails without it. A successor that
leaves a terminal status still ranks below its predecessor, so the terminal
configuration claims only that property; convergence there remains the
`RankDrop` residual above.

## Related

- `specs/tla/AgentReplication.tla`, `specs/tla/AgentStateWrites.tla`,
  `specs/tla/VersionHeads.tla`, `specs/tla/README.md`
- [Agent persistence and sync](../../knowledge/features/agents/persistence-and-sync.md)
- [Vector clocks and conflicts](../../knowledge/features/sync/vector-clocks-and-conflicts.md)
- [ADR 0022: Long-lived Daily OS planner](./0022-long-lived-daily-os-planner.md)
- [ADR 0065: Model-checked sync sequence reservations](./0065-model-checked-sync-sequence-reservations.md)
- [ADR 0066: Model-checked agent wakes and confirmations](./0066-model-checked-agent-wakes-and-confirmations.md)

---

### Adr 0069 Model Checked Scheduled Wake Leases (`docs/adr/0069-model-checked-scheduled-wake-leases.md`)

# ADR 0069: Model-Checked Scheduled-Wake Leases and Goal Chat Recovery

- Status: Accepted
- Date: 2026-09-24

## Context

Scheduled work that must run on one device — the coordinator digest
([ADR 0048](./0048-one-device-runs-the-coordinator-digest.md)), goal and
relationship escalations ([ADR 0054](./0054-deterministic-first-two-tier-wakes.md),
[ADR 0059](./0059-relationship-agent-runtime-and-nudge-generalization.md)) —
is elected by a lease on its synced scheduled-wake record: claim, settle,
confirm, fire, consume. The claims were that the lease picks exactly one device,
that another device takes over if the claimant dies, and that consumption is
terminal for a wake window. Goal chat was said to need no lease at all: the
typing device answers its own message.

We wrote both down in TLA+ as the code stood —
`specs/tla/ScheduledWakeLease.tla` (devices, one record replicated as a
vector-clocked register, the resolver's scheduled-wake rule, a sync channel
with a delivery bound, wall-clock time, crashes, deaths) and
`specs/tla/GoalChatReply.tla` (who answers one message) — and model-checked
them with TLC. Six holes came back as concrete traces:

1. **A second goal escalation of the day ran on one device, or none.** The
   record id is per period and every arm wrote a fresh row from a null vector
   clock at the period's fixed instant. Once a peer had run the first
   escalation, the re-arm was concurrent with that peer's consumed copy, and at
   one instant `consumed` wins: the peer kept it. The arming device ran the
   escalation alone; if it died first, nobody did (`NoLostWindow`), and the
   replicas disagreed until it wrote again (`Converged`).
2. **Carrying the clock was not enough.** With the consumed row's clock carried
   forward, a peer that missed the consumption and took over past `leaseUntil`
   wrote a claim of the *first* window that was concurrent with the re-arm, at
   the same instant, and won on `updatedAt`: the arming device went back to a
   window that had already run (`WindowTerminal`).
3. **A crash could lose a fired window.** Firing queued the wake — whose intent
   `WakeIntentStore` writes later, coalesced, to the settings database — and
   then consumed the record in the agent database. A crash after the consume
   committed and before the intent landed lost the window everywhere
   (`NoLostWindow`).
4. **A crash could run a fired window twice.** In the other order — intent on
   disk, consume not yet — the restart restored the wake, and the record, still
   pending under this device's lease, fired again (`NoDeviceRunsTwice`).
5. **The consume overwrote newer state.** It was built from the due-query
   snapshot and written over whatever the replica held by then — a newer window
   a peer had armed, for one — so a replica could regress (`Converged`).
6. **Two devices answered one chat message.** Runtime maintenance on every
   device re-enqueued the oldest unanswered goal chat message at startup,
   before every scheduled scan and on identity sync, and the goal wake router
   answered the oldest pending message on *any* goal wake. A peer's cadence
   tick answered a message whose author was still answering it
   (`AtMostOneReply`); reply ids are per run, so nothing collapsed the two.

Two suspected holes did not stand up. The lease has no fencing token, which
ADR 0018 rule 2 calls for; but the model shows that with the settle longer
than twice the sync delay, a claimant that confirms late still cannot fire
beside a taker-over, and where it can — a device that is suspended or offline
across the lease — no token would help, because what a stale claimant spends
is a model call, which has no side that could reject one. And relationship
escalations, armed only if absent under per-episode ids, and re-armed for a
retry at a later instant, check clean.

## Decision

1. **A later window of a goal escalation follows the consumed one.** Arming
   over a pending row writes nothing: that escalation has not run, and a rewrite
   would drop a peer's claim and the original baseline. Arming over a consumed
   row carries its vector clock forward and is due one millisecond after it, so
   the new window causally follows the consumption, and outranks every version
   of the consumed window on the resolver's later-deadline rule. Every device
   computes the same deadline.
2. **A fired record is consumed only once its wake is durable.**
   `ScheduledWakeManager` enqueues the wake, waits for
   `WakeOrchestrator.flushWakeIntents`, then consumes.
3. **A record whose wake is already owed is consumed, not fired.** Before the
   claim and again after the lease wait, the manager asks
   `WakeOrchestrator.owesWake` whether the wake firing *this window* — the
   record id and its deadline, tagged onto the job's intent when it fires — is
   queued, running or restorable, and if so consumes the record without
   firing it. Matching on the agent, workspace and tokens instead would take
   the record's next window, which often carries the same ones, for the one
   before it, and consume it unrun. The startup scan runs before
   `restoreWakeIntents`, which is what lets it see a restorable wake first.
4. **The consume is built from the current row.** It re-reads the row in a
   transaction and flips it only while it is still the fired window and
   pending, carrying the current row's clock.
5. **Only a message's own wake answers it, and recovery is lease-elected.** The
   router answers a goal chat message only on a wake carrying that message's
   token, and a wake whose message is already answered does nothing. Sending a
   message arms a synced recovery record, `goal-chat:<messageId>`, due
   `goalChatRecoveryGrace` (30 minutes) later; the wake that answers it consumes
   it. Maintenance no longer enqueues anything: it arms a missing record, or,
   after a recovery that did not answer, the next window, due when the last
   window's lease lapses — or a grace past a window the author consumed. The
   lease then picks one device to answer.
6. **The models gate the code**, as in ADR 0065 and ADR 0066: CI model-checks
   every configuration whenever the specs or the code they describe change.

## Consequences

- With two devices, one death or one crash, and two windows, `AtMostOnce`,
  `NoDeviceRunsTwice`, `WindowTerminal`, `Converged` and `NoLostWindow` hold on
  the lease; with three devices arming a relationship episode concurrently the
  safety properties hold. `AtMostOneReply` and eventual answering hold for a
  message with an author and one or two peers, a failing run and a device
  death.
- A message whose author could not answer it is answered half an hour later,
  not at the next scan; a failed recovery is retried when its lease lapses.
- Every scheduled-wake write this ADR introduces carries the clock of the
  row it replaces, so the local write path of
  [ADR 0068](./0068-model-checked-agent-convergence.md), which resolves a
  write against the persisted row, keeps its fields. Under that path alone
  the old null-clock re-arm would not even have pended locally: it is
  resolved into the consumed row it never saw.
- The other scheduled-wake writers were checked against that path. A write
  from a null clock is concurrent with the persisted row, so it keeps its
  fields only when its deadline is later, or when it is later-and-equal at a
  pending row. The goal and relationship cadence re-arms, the digest re-arms
  (`nextDigestTime` is strictly after now), and the failure retries of both
  escalation workflows (due now) always target a later instant than the row
  they follow, so they stand. Relationship escalations arm only if absent.
  One did not: the day agent's `set_next_wake` pre-warm, which overwrites the
  day's pending record. Moved **earlier**, it lost to the later deadline and
  was resolved straight back to the old time. It now carries the prior
  record's clock, so the new time is that record's successor on every
  device. This is the resolver's rule, not a lease property, so it is pinned
  by a regression through `resolveLocalAgentWrite` rather than in the model.
- Decisions 2 and 3 cover the records whose wakes are wake intents. The
  coordinator digest's wake is not one
  ([ADR 0070](./0070-model-checked-digest-recovery-and-processing-jobs.md)):
  for it `owesWake` is always false and its consumed record is the single
  recovery path.
- Residuals, documented in `specs/tla/README.md` rather than closed:
  - **A device back from a crash or from sleep acts on its replica before sync
    catches up.** It can confirm its own settled claim, or answer a message
    whose reply it has not seen, beside a device that took over meanwhile —
    ADR 0048's partition case. The crash configuration therefore checks
    `NoDeviceRunsTwice`, not `AtMostOnce`. Closing it needs a round trip to a
    coordinator the app does not have.
  - **A run that finishes before its own consume commits.** If the process
    then dies before the consume, the record is still pending and nothing is
    owed, and the window runs again. The model assumes an inference outlasts a
    local write (`RunOutlastsConsume`).
  - **A failed intent write.** `flushWakeIntents` returns after a write that
    failed and was logged; a crash before the next write loses the window.

## Related

- `specs/tla/ScheduledWakeLease.tla`, `specs/tla/GoalChatReply.tla`,
  `specs/tla/README.md`
- [Coordinator and day-agent protocol](../../knowledge/features/daily_os_next/coordination-protocol.md)
- [Goal agents](../../knowledge/features/goals.md)
- [Wake orchestration](../../knowledge/features/agents/wake-orchestration.md)
- [ADR 0018: Convergent multi-device execution](./0018-convergent-multi-device-execution.md)
- [ADR 0048: One device runs the coordinator digest](./0048-one-device-runs-the-coordinator-digest.md)
- [ADR 0054: Deterministic-first two-tier wakes](./0054-deterministic-first-two-tier-wakes.md)
- [ADR 0066: Model-checked agent wakes and confirmations](./0066-model-checked-agent-wakes-and-confirmations.md)

---

### Adr 0070 Model Checked Digest Recovery And Processing Jobs (`docs/adr/0070-model-checked-digest-recovery-and-processing-jobs.md`)

# ADR 0070: Model-Checked Digest Recovery and Processing Jobs

- Status: Accepted
- Date: 2026-09-24

## Context

Two Daily OS mechanisms promise to spend exactly one inference on one piece of
work, and both rested on prose:

- The coordinator's morning digest (ADR 0032, ADR 0048). A crash after the
  record flips to `consumed` used to lose the day's briefing; the consumed-record
  retry in `DayAgentService` fixed that, and it must never bill a second
  inference for a briefing the user already has. Since ADR 0066 a second
  recovery path existed beside it: the digest wake was also a `WakeIntentStore`
  intent, which startup replays.
- The durable `draftPlan` / `refinePlan` / `parseCapture` jobs (ADR 0044). Every
  claimed mutation is fenced by `claim_token`, and an artifact pre-check makes a
  re-claim after a crash safe. But the claim's lease is three minutes and never
  renewed, the executor waits three minutes for its wake, and the wake can sit
  behind its agent's single flight, or run on after the ten-minute cap, for up
  to 30 minutes.

We modelled both as the code stood — `specs/tla/DigestRecovery.tla` and
`specs/tla/DayProcessingJob.tla` — and TLC returned these holes as traces:

1. **A completed digest ran again after a crash.** The run settled its wake
   intent, but the settle is a coalesced write; the process died first, and
   startup replayed the intent: a second inference after the briefing existed
   (`NoInferenceAfterBriefing`).
2. **Both recovery paths ran after a crash mid-digest.** Startup's
   `restoreSubscriptions` saw the consumed record with no live work (the intent
   is restored later, in `restoreWakeIntents`) and re-armed it; the record
   fired and completed; then the restored intent ran the digest again.
3. **The live-work probe missed a job the drain had taken.** Between leaving
   the queue and taking the runner lock the drain awaits the agent's policy,
   and a job it holds back sits in a local list. `hasPendingOrActiveWake` saw
   neither, so the pre-scan repair re-armed a digest whose run was about to
   start, and the day was digested twice — no crash needed.
4. **A backward clock step hid a finished digest.** When the run commits its
   milestone and re-arm before the wake manager's consume write lands, that
   write replaces the re-armed row. The retry check then looks for the
   milestone in `[consumedAt, now]`, and a run whose clock stepped back stamped
   it just before `consumedAt`.
5. **A processing job ran two inferences for one request.** Three shortest
   traces, one per path: the lease lapsed while the attempt waited and another
   lane (a provider rebuild leaves the old runtime's drain running) re-claimed
   and enqueued a second wake; the wait timed out and the retry enqueued
   another; a `retryNow` tap re-queued a running job. A refine produced two
   ChangeSets (`AtMostOneLiveWake`, `NoInferenceAfterArtifact`,
   `AtMostOneArtifact`).

Two suspected gaps did **not** hold up. A crash between `enqueueWake` and
`recordRunKey` cannot leave a restored wake intent that runs under a run key
the job never recorded: processing wakes are never intents. And the claim
fence holds — no stale claimant's write lands (`Fenced`).

## Decision

1. **The digest record is the digest's only crash recovery.** Wakes carrying
   a `digest:` token are never `WakeIntentStore` intents, exactly like
   outbox-owned processing jobs; startup discards legacy copies.
2. **Pending-work probes see drain-held jobs.** `hasPendingOrActiveWake`
   counts a job a drain pass has taken out of the queue and not yet started,
   or holds back until it requeues it, beside queued, locked and detached work.
3. **The digest watermark window starts at the local day** of `consumedAt`,
   not at `consumedAt`: any digest of the day is the day's briefing. The upper
   bound stays `now`, which is what guards against a future-dated peer
   milestone.
4. **A processing job attaches to its request's live wake.** Before enqueueing,
   the executor asks `WakeOrchestrator.liveRunKeyWithToken` for a wake carrying
   the job's `processing_job:<jobId>@<requestedAt>` token that is queued,
   drain-held, running, or running on after an abort, and awaits that wake.
   It asks before its reads and again after them, with nothing awaited
   between that second answer and the enqueue, so two attempts racing
   after a retry tap cannot both enqueue (found in review, then by TLC
   with `RecheckBeforeEnqueue = FALSE`). A
   wait that times out while the wake is still live defers without counting an
   attempt; a timeout on a wake no longer live counts and is capped by
   `maxAttempts` like any other retryable failure.
5. **The models gate the code**, as in ADR 0065 and ADR 0066. A Glados trace in
   the executor suite drives the real outbox repository, processor and
   executor through generated interleavings of two lanes, lease lapses,
   timeouts, wake outcomes, retry taps and crashes, and checks the job model's
   invariants.

## Consequences

- `DigestRecovery` holds `AtMostOneDigest`, `NoInferenceAfterBriefing`,
  `InferencesBounded` and `EventuallyBriefed` with up to two crashes, with and
  without the lease, and with a backward clock step. `DayProcessingJob` holds
  `AtMostOneLiveWake`, `NoInferenceAfterArtifact`, `AtMostOneArtifact`, `Fenced`
  and `EventuallySettled` for a refine and a draft job with two lanes, a crash
  and a user tap.
- A crash mid-digest is recovered by the record retry alone, which waits out
  the lease's claim and settle. A briefing interrupted by a crash arrives a few
  minutes after the next start rather than immediately.
- A request whose wake is stuck behind other work waits for it instead of
  paying for another, up to `hungExecutorAfter` (30 minutes); the job stays
  queued, retrying with backoff, and its attempt count does not grow.
- Residuals, recorded in `specs/tla/README.md`:
  - An executor past `hungExecutorAfter` stops counting as live, so its request
    can run a second inference — the same boundary `WakeRuntime.tla` accepts
    for single flight.
  - A wake that commits its artifact before its attempt's `recordRunKey` lands,
    followed by a crash, leaves a never-attempted refine without provenance, so
    the re-claim runs it again (`ProvenanceRace`). The window is one local
    write against a model call; closing it needs the artifact to carry the
    processing-intent id rather than the run key.
  - The claim lease is still never renewed. That is harmless now — whoever
    re-claims attaches to the live wake — and renewing it would add a timer per
    attempt for no model-visible gain.
  - Tool calls a digest commits before a crash are not rolled back, so the
    retried digest can revise directives the interrupted one already wrote;
    the directive register converges, which ADR 0048 relies on too.

## Related

- `specs/tla/DigestRecovery.tla`, `specs/tla/DayProcessingJob.tla`,
  `specs/tla/README.md`
- [Coordinator and day-agent protocol](../../knowledge/features/daily_os_next/coordination-protocol.md)
- [Day processing outbox](../../knowledge/features/daily_os_next/processing-outbox.md)
- [Wake orchestration](../../knowledge/features/agents/wake-orchestration.md)
- [ADR 0032: Hierarchical day-agent coordination](./0032-hierarchical-day-agent-coordination.md)
- [ADR 0044: Day processing outbox storage](./0044-day-processing-outbox-storage.md)
- [ADR 0048: One device runs the coordinator digest](./0048-one-device-runs-the-coordinator-digest.md)
- [ADR 0066: Model-checked agent wakes and confirmations](./0066-model-checked-agent-wakes-and-confirmations.md)

---

### Adr 0071 Model Checked Agent Message Log (`docs/adr/0071-model-checked-agent-message-log.md`)

# ADR 0071: Model-Checked Agent Message Log and Compaction

- Status: Accepted
- Date: 2026-09-24

## Context

An agent's message log is a causal DAG replicated across devices (ADR 0016):
each local append chains off the agent's head pointer, concurrent appends on
two devices fork it, and the fork healer joins the heads with a
content-addressed node (ADR 0018 rules 7 and 8). Summary checkpoints fold the
oldest part of the captured input log so a wake reads prose plus a verbatim
tail (ADR 0017, ADR 0020, ADR 0057). The claims were that the DAG stays
acyclic, that joins never storm, that the head never regresses, that the log
eventually has one head, and that checkpoint selection is pure, so devices
converge and no event before a cutoff is ever lost.

Every row syncs on its own — message, `messagePrev` edge, agent-state
version, capture link, payload, checkpoint — once each and in any order, and
the head pointer is a field of the state row, which last-writer-wins
resolves. We wrote the log down in TLA+ as the code stood —
`specs/tla/AgentMessageLog.tla` (two devices, one clock ahead, appends, other
state writes, plan and commit of a join with an append between them, a
crash) and `specs/tla/LogCompaction.tla` (two devices capturing versions of
two sources, folding, late delivery) — and model-checked them with TLC. Five
holes came back as concrete traces:

1. **An unset head rewrote the DAG.** A device appends with no head when its
   state row lags behind the messages it has received, or when a version
   without a head wins last-writer-wins there — one written by a device that
   had not seen any head yet (a wake outcome, a scheduling write). That
   append took the legacy migration path and re-chained every message it
   held by `createdAt`, reusing the `msgprev-<id>` ids appends had written,
   so one edge id named two parents.
   With one device's clock ahead the rewritten edge closed a cycle: TLC's
   trace is six steps (`Acyclic`), and the Glados trace found a six-step
   `EdgesImmutable` violation on the second device's very first append over
   a partly synced chain. Devices then hold different DAGs for good, and a
   cycle makes the projection throw, so fork healing skips that agent for
   good.
2. **A message that arrived before its own edge was joined as a head.** It
   projected as a root, its parent lost its only child, and the healer joined
   a parent with its descendant (`NoJoinOverNonTip`).
3. **A join missing edges was checked only while it was a head with fewer
   than two edges.** A join that had already received a child here, or that
   had two of three edges, left its remaining parents looking like heads.
4. **A late edit disappeared behind a checkpoint.** Coverage was keyed by
   source alone, so another device's edit of a folded source — captured after
   the folded version and before the cutoff, delivered after the fold — was in
   neither the prose nor the tail (`NoLostContext`).
5. **A fold past unsynced content was dead on arrival.** An event whose
   payload had not arrived was dropped from the fold input, the cutoff went
   past it, the checkpoint could not cover it, and every later wake paid for
   the same summary again (`NoDeadCheckpoint`).

## Decision

1. **An unset head is recovered, never re-chained.**
   `AgentSyncService._recoverHead` keeps the legacy spine for logs with no
   DAG evidence at all (no `messagePrev` edge, no message minted with a
   `prevMessageId`, no join); any other log keeps its edges, and the append
   chains off the last head of the projected log that no present row names
   as its `prevMessageId`. A log that no longer
   projects starts the message as a root and logs the failure.
2. **The healer waits for every edge it can prove is missing.**
   `ForkHealer._hasUnsyncedEdge` treats the view as incomplete while a
   message's `prevMessageId` names a present row but its edge has not
   arrived, or while any join — head or not, however many edges it has —
   misses edges its content-addressed id says lead to present heads. A
   `prevMessageId` naming an absent row does not block: the observation sweep
   deletes the edges into what it prunes.
3. **A checkpoint covers versions, not just sources.** `selectActiveSummary`
   accepts a checkpoint only if, for every payload-backed source, the covered
   digest is that of the source's latest version at or before the cutoff. An
   older version arriving late still does not invalidate it.
4. **A fold stops before the first event it could not resolve.**
   `AgentLogCompactor` folds only the resolved part of the tail that precedes
   the first unresolved event; if that is empty, it does not fold.
5. **The models gate the code**, as in ADR 0065: the specs live in
   `specs/tla/`, CI model-checks them whenever they or the code they describe
   change, and Glados traces drive two real `AgentSyncService` + `ForkHealer`
   replicas through generated appends, state writes, heals and deliveries,
   and `selectActiveSummary` through generated histories, checking the same
   invariants.

## Consequences

- `Acyclic`, `EdgesImmutable`, `NoJoinOverNonTip`, `Converged` and
  `LocalHeadAdvances` hold for two devices with a skewed clock, any delivery
  order, a stale state write, and a join planned before and committed after
  an append — `appendJoin`'s existing head guard is what keeps that last race
  from moving the head back; `EventuallySingleHead` holds under fair delivery
  and healing with a crash between plan and commit. `NoLostContext`, `NoDeadCheckpoint` and `Converged` hold for two
  devices folding concurrently over late captures, payloads and checkpoints.
  Each switch set back to the old code reproduces its hole.
- An append over an unset head reads the agent's messages and their
  `messagePrev` edges once, as the legacy migration already did. It happens
  only while the synced head is unset.
- A device holding a checkpoint but not the version it folded treats that
  checkpoint as invalid until the version arrives: its own older version
  might as well be a newer edit. The tail is longer for that while.
- A fold can cover less than planned while content is still syncing.
- Residuals, documented in `specs/tla/README.md`:
  - **The head pointer can still move back.** A state version written on
    another device can win last-writer-wins with an ancestor of the local
    head; the next append then forks off it and the next wake joins the
    fork (TLC: `HeadNeverRegresses` fails in six steps). Fork healing is off
    by default, so such a fork can stay. Closing it needs either a
    DAG-aware merge of the head on receive or a check, on every append, that
    the head has no child yet.
  - **A join row does not name its parents.** A join still missing the edge
    to a parent that is not a head here — one that has not arrived, or has
    another child — cannot be told from a parent the observation sweep
    deleted, so the healer may join again over that join's parents. The
    result is a redundant node, not a cycle. The same holds while more than
    twelve other heads make the subset search too costly to run on every
    wake. Carrying the sorted parent ids on the join row would close both,
    at the cost of a new synced field.
  - **The legacy spine assumes one legacy log.** Two devices whose first
    appends each met a different set of edge-less roots can write different
    spines. This needs three devices appending their first message
    concurrently and is not modelled.

## Related

- `specs/tla/AgentMessageLog.tla`, `specs/tla/LogCompaction.tla`,
  `specs/tla/README.md`
- [Agent memory and log compaction](../../knowledge/features/agents/memory-and-compaction.md)
- [Projection kernel](../../knowledge/features/agents/projection.md)
- [ADR 0016: Agent state as log projection](./0016-agent-state-as-log-projection.md)
- [ADR 0017: Deterministic log compaction](./0017-deterministic-log-compaction.md)
- [ADR 0018: Convergent multi-device execution](./0018-convergent-multi-device-execution.md)
- [ADR 0020: Agent input capture](./0020-agent-input-capture.md)
- [ADR 0057: Decade-scale agent memory](./0057-decade-scale-agent-memory.md)
- [ADR 0066: Model-checked agent wakes and confirmations](./0066-model-checked-agent-wakes-and-confirmations.md)

---

### Adr 0072 Notification Producers One Episode Contract (`docs/adr/0072-notification-producers-one-episode-contract.md`)

# ADR 0072: Notification Producers — One Episode Contract per Agent Kind

- Status: Accepted — implemented. `NotificationEpisodeSink` in
  `lib/classes/notification_producer.dart`, `NotificationEpisodeProducer` in
  `lib/features/notifications/producer/`, `NotificationRepository.armEpisode`
  and `retractOpenRows`; `RelationshipReminderService` is the first producer
  on the contract.
- Date: 2026-09-16

## Context

OS notifications reach the user from producers that grew separately: the task
agent's change-set builder writes task suggestions, the relationship agent's
deterministic tier arms check-in reminders, the habit auto-completion engine
records what it checked off. Each answered the same four questions on its
own — which row is *this* episode, what to do when the row already exists,
what to do with the episode it supersedes, and what a failure may cost the
caller — and the answers accumulated in `NotificationRepository` as one
create, one retract and one id helper per variant.

Tap routing (the step before this one) made notifications worth producing,
and the next kinds — a goal that has slipped, the deferred channel of ADR
0055 — would each have added another copy of the same choreography.

The relationship reminder (ADR 0039, amendment 1) had already found the right
shape: the tier decides *when*, a sink declared beside the tier's derivation
projects the verdict, the service imports the runtime and never the reverse,
identity is per episode, a superseded episode is retracted, a lapsed one earns
no alarm, and nothing thrown ever reaches the wake. That shape was specific to
one kind only by accident.

## Decision

1. **One sink contract, in `lib/classes`.**
   `NotificationEpisodeSink<TSubject, TDerivation>` has two members of its
   own, `arm({subject, derivation})` and `clearFor(subjectId)`, and since
   ADR 0074 inherits a third, `restate(subjectId, {title, body})`, from
   `NotificationEpisodeRestater`; when a restatement is permitted is that
   ADR's policy, not this contract's. A runtime names
   its own alias beside its derivation — `RelationshipReminderSink` is
   `NotificationEpisodeSink<RelationshipEntry, RelationshipCadenceDerivation>`
   — and imports only `lib/classes`. The one-way direction the amendment
   fixed is now enforced by where the type lives rather than by care.

2. **One choreography, in the notifications feature.**
   `NotificationEpisodeProducer<S, D>` implements the sink. A kind supplies
   seven hooks — `kind`, `logSubDomain`, `subjectIdOf`, `episodeKeyOf`,
   `scheduledInstantOf`, `categoryOf`, `buildRow` — and nothing else. The
   base derives the id, arms idempotently while the instant is still ahead,
   retracts the rows the new episode supersedes, clears on demand, and logs
   rather than throws. Before writing, it refuses a row whose kind or linked
   entity differs from what it will later retract by.

3. **Two repository primitives replace the per-kind methods.**
   `armEpisode(id, scheduledFor, build, category)` creates unless the id
   exists, never invoking `build` otherwise; `retractOpenRows(linkedEntityId,
   kind, exceptId)` retracts every open row of one kind for one subject.
   `createRelationshipCheckIn`, `retractRelationshipCheckIns` and
   `notificationIdForRelationshipCheckIn` are removed.
   `createHabitAutoCompletion` stays as the engine's entry point but is built
   on `armEpisode`. Task suggestions keep their own serialised,
   replace-the-previous path: a suggestion wave is not an episode.

4. **Episode identity is `uuid5(kind, subjectId, episodeKey)`**
   (`notificationEpisodeId`), with `kind` the variant's wire discriminator
   named once in `NotificationKinds` and answered by `NotificationEntity.type`.
   The value is exactly what the check-in rows have always synced under, so a
   mixed fleet sees no new ids.

5. **Per-kind union variants stay.** A generic row carrying a route string
   would be shorter, but the exhaustive switches over the union are what force
   a new kind to decide its inbox behaviour (`showsBeforeScheduledTime`) and
   its tap route rather than inherit one. Adding a kind means a variant, a
   producer subclass, and a call from its tier; the compiler lists every site.

## Consequences

- A goal off-track alert is a variant, a subclass with seven hooks and one
  call after the goal tier's transaction commits — no repository change.
- Identity, idempotency, supersession and the best-effort rule exist once
  and are tested once, in `notification_episode_producer_test.dart`; the
  relationship suite now covers copy, instant, category and kind.
- `NotificationRepository` stops growing with the union. What is per kind is
  what only that kind knows.
- Nothing on the wire changes for the kinds that exist: their discriminators,
  ids and message families are as before. A kind adopted later (ADR 0073's
  goal alert) adds its own discriminator, as any new variant does; the
  contract itself carries nothing new over the wire.

## Non-Goals

- Model-authored copy at arming time. What a producer arms is baked at write
  time and lands on lock screens; ADR 0039 Decision 6's content-minimal rule
  stands. Whether an agent may later re-word a row it armed, in its own
  voice, is a separate decision — ADR 0074 — layered on top of this
  contract, not part of it.
- Recurring reminders. The episode key moves only with the subject's own
  state, which is what keeps an ignored subject alerted once.
- Moving task suggestions onto the contract.

## Related

- [ADR 0039: Relationship Check-In Reminders](./0039-relationship-check-in-reminders.md) — the shape this generalises
- [ADR 0054: Deterministic-First Two-Tier Wakes](./0054-deterministic-first-two-tier-wakes.md) — why the producer is the deterministic tier
- [ADR 0055: The Banner-Nudge Attention Channel](./0055-banner-nudge-attention-channel.md) — the in-app channel this complements
- [ADR 0059: Relationship Agents on the Shared Runtime](./0059-relationship-agent-runtime-and-nudge-generalization.md) — sibling variants, never conversion

---

### Adr 0073 Goal Off Track Alerts On The Os Channel (`docs/adr/0073-goal-off-track-alerts-on-the-os-channel.md`)

# ADR 0073: Goal Off-Track Alerts on the OS Channel

- Status: Accepted — implemented. `NotificationEntity.goalOffTrack`,
  `GoalOffTrackAlertService` in `lib/features/goals/service/`, and the
  `GoalOffTrackSink` seam in `GoalAgentPhaseA`.
- Date: 2026-09-16

## Context

ADR 0055 made the goal agent's attention channel banner-only and named the
condition for revisiting push: tap routing, and the synced notification inbox
as the substrate. Both now exist — taps open the screen a notification is
about, and every kind arms rows through one producer contract (ADR 0072).
ADR 0059 Decision 4 already took the same step for people: the banner stays
the primary channel, and an OS alert covers the one case a banner cannot —
the device the user is not holding.

A slipped goal is the case the user named: "send a notification when I'm not
meeting my goal". What the banner channel established still governs — quiet
by default, one automatic banner a day, dismissal as data, never a
guilt-trip over a data gap — and an OS alert that ignored any of it would be
the nag that trains people to switch notifications off.

## Decision

1. **A fifth inbox variant, `goalOffTrack`**, linked to the goal *agent* —
   the id the goal detail route, the registers and the banners are all keyed
   by. A tap opens the goal's page, where the progress and the banner both
   are, not the chat. It waits in the inbox until its alert hour like the
   check-in reminder, and unlike the task and habit rows.

2. **The deterministic tier is the producer, on the banner's own predicate.**
   `GoalAgentPhaseA` projects only a *persisted status transition*: into a
   slip — `automaticGoalAdEligible`, i.e. off track, or at risk on the first
   evaluation or with a worsening trend — it arms; out of one it clears.
   An unchanged slip projects nothing, and a fenced write projects nothing.
   The two channels can therefore never disagree about what a slip is, and
   no model is consulted.

3. **The episode is the transition day and the baseline it left.** One row per slip, keyed by the
   evaluation day that saw the transition, so a goal that stays behind is
   alerted once and a later slip is a new episode. Recovery, achievement, a
   data gap, or deletion (the `deleteGoalAgent` cascade) retract the open
   row, which is what cancels the alarm.

4. **The alert fires at the next 09:00 local**, not at the tick. The cadence
   tick runs at 06:00 and a signal-driven tick can run at any hour; neither
   is a time to be told you are behind. The same hour the check-in reminder
   uses, so a morning with both says both at once.

5. **Copy is deterministic and content-minimal**: the goal's title and a
   fixed line, from the ARB catalogs, baked in the arming device's locale.
   Nothing about how far behind, nothing from a check-in — the ADR 0039
   Decision 6 rule, because the copy lands on a lock screen.

## Consequences

- The goal gained an OS channel for four hooks and one call: the producer
  subclass supplies kind, subject, episode key, instant and copy; Phase A
  calls the sink after its transaction. No repository change (ADR 0072's
  promise, kept).
- Older peers cannot decode the new variant and drop the row with a log
  (`UnrecoverableSyncPayloadException`), the documented mixed-fleet rule.
- **A banner dismissal does not cancel an already-armed alert.** "Not today"
  is written to the nudge row, which wakes no goal tick; an alert armed at
  06:00 for 09:00 still fires after an 08:00 dismissal. Wiring the dismissal
  through the sink is a follow-up, recorded in the goals concept.
- Only the deterministic tier speaks. Model-authored alert copy stays out,
  for the lock-screen reason above.

## Non-Goals

- Alerts for at-risk goals that are not worsening, or for insufficient data.
- A recurring "still behind" alert. The episode moves only with the status.
- Per-goal alert settings; the global notifications switch governs, as for
  every kind.

## Related

- [ADR 0055: The Banner-Nudge Attention Channel](./0055-banner-nudge-attention-channel.md) — the banner-only stance this extends
- [ADR 0059: Relationship Agents on the Shared Runtime](./0059-relationship-agent-runtime-and-nudge-generalization.md) — Decision 4, the same step for people
- [ADR 0072: Notification Producers — One Episode Contract](./0072-notification-producers-one-episode-contract.md) — the contract this rides on
- [ADR 0039: Relationship Check-In Reminders](./0039-relationship-check-in-reminders.md) — the content-minimal copy rule

---

### Adr 0074 Agent Worded Alerts Restate An Armed Episode (`docs/adr/0074-agent-worded-alerts-restate-an-armed-episode.md`)

# ADR 0074: Agent-Worded Alerts Restate an Armed Episode

- Status: Accepted — implemented. `NotificationEpisodeRestater` in
  `lib/classes/notification_producer.dart`,
  `NotificationRepository.restateOpenRows`, `AgentAlertCopy` in
  `lib/features/notifications/producer/`, wired into `GoalAgentWorkflow` and
  `RelationshipAgentWorkflow`; the `notify_agent_copy` switch on the
  Notifications settings page.
- Date: 2026-09-16

## Context

ADR 0072 and ADR 0073 kept model-authored copy off the OS channel: a
notification's words are baked at write time and land on a lock screen, and
ADR 0039 Decision 6 keeps them content-minimal — a name, nothing more.

Meanwhile the goal and relationship agents' LLM tier authors a personalised
banner brief on every escalation wake (`create_goal_ad`,
`create_relationship_ad`), and that wake follows the deterministic tier that
armed an alert for the same subject minutes or days earlier. The alert says
"Anna is due"; the banner, in the agent's voice, says why. The brief for this
work asked for agents that reach the user through notifications, and a fixed
template line is not an agent speaking.

## Decision

1. **The LLM tier may re-word an alert; it may not create one.** A new seam,
   `NotificationEpisodeRestater.restate(subjectId, title:, body:)`, is what
   the workflow gets. It updates the words of a subject's open, not-yet-fired
   rows of the producer's kind and nothing else: no row is minted, a row
   already due keeps the words it fired with, a seen, acted-on or deleted row
   is untouched. `NotificationEpisodeSink` extends it, so every producer is a
   restater; the workflows depend on the narrow interface only.
2. **The words are the banner's.** `AgentAlertCopy.fromBrief` takes the
   persisted, sanitised `NudgeBrief` — headline as title, tagline or else
   call to action as body — fitted to lock-screen room: one line each, 80 and
   140 characters, cut at a word boundary. No new tool argument and no prompt
   change: the alert can never say what the banner does not, and the wake
   pays for no second inference.
3. **Opt-in.** `notify_agent_copy` ships off and is read at the moment of the
   wake. Decision 6's content-minimal rule stands until the user flips the
   switch under Preferences → Notifications, whose row says that the text can
   carry details and shows on the lock screen.
4. **After the transaction, best-effort, for this wake's banner only.** The
   workflow calls the helper once its output transaction has committed, and
   only for a banner this wake created: a re-run banner keeps the alert as it
   is, a fenced or rolled-back wake re-words nothing. Every failure is logged,
   never surfaced as a failed wake — the sink contract of ADR 0072.
5. **Same row, same id, on the wire whole.** The repository bumps `updatedAt`
   and the vector clock, re-schedules under the unchanged OS id — the alarm
   is replaced, not doubled — and enqueues the full row. Peers converge
   last-writer-wins on `updatedAt` (`NotificationMerge`), so the re-worded
   copy overtakes the template whichever order the two events arrive in. A
   device-local row is re-worded but never enqueued. Words that already read
   this way write nothing, so a repeated wake is idempotent.

## Consequences

- Once allowed, the OS alert and the in-app banner read the same, in the
  agent's voice. Until then nothing changes.
- A slip detected at 06:00 is armed with template copy and re-worded by the
  escalation wake minutes later; a check-in reminder armed days ahead is
  re-worded on its due day's wake — both before the 09:00 alarm. A wake that
  runs after the alarm fired leaves it alone, and a peer that receives the
  re-wording after its own alarm fired shows the new words in the bell only:
  the inbound handler re-arms a content update only for a row still ahead.
- The bell shows the re-worded row too; a tap still marks the same row seen.
- Both workflows gain one optional constructor argument; every existing
  construction site is unchanged.

## Non-Goals

- Agent-worded alerts for kinds without an authoring tier: task suggestions,
  habits, plan outcomes, sync conflicts.
- A "write the lock-screen line" tool argument. The banner brief is the
  agent's words already.
- Re-wording an alert that already fired.

## Related

- [ADR 0039: Relationship Check-In Reminders](./0039-relationship-check-in-reminders.md) — Decision 6, the content-minimal rule this makes opt-out
- [ADR 0055: Banner Nudge Attention Channel](./0055-banner-nudge-attention-channel.md) — the banner brief this borrows
- [ADR 0072: Notification Producers, One Episode Contract](./0072-notification-producers-one-episode-contract.md) — the sink this extends
- [ADR 0073: Goal Off-Track Alerts on the OS Channel](./0073-goal-off-track-alerts-on-the-os-channel.md) — the alert this re-words

---

### Adr 0075 Idempotent Change Set Tools (`docs/adr/0075-idempotent-change-set-tools.md`)

# ADR 0075: Idempotent Change-Set Tools

- Status: Accepted
- Date: 2026-09-24

## Context

[ADR 0067](./0067-model-checked-change-set-lifecycle.md) left a residual it
could not close with a local transaction: **the same item decided on two
devices before they sync is applied on both.** Each device's claim succeeds
against its own replica, and each dispatches. `ChangeSetLifecycleRace`
violates `AtMostOnceApply` in five states. Closing it with coordination —
one device that applies a set's changes, or a lease on the item — would make
confirming depend on a peer being reachable. So this ADR takes the other
route ADR 0067 named: make the tools' effects idempotent across devices, so
that the second application changes nothing. Decision 2 and 3 name the tools
this covers; the ones it does not are listed under Consequences.

The dispatch can not be deduplicated by its decision: each device mints its
own `ChangeDecisionEntity` with a random id. What both devices share is the
item — one synced row, the same index. We extended
`specs/tla/ChangeSetLifecycle.tla` with what a confirmed change does to the
journal on each device — entities by id, one task field as a register that
the user can edit too, both synced by message in any order — and with the
user's reopen. TLC found:

1. **A create-style tool mints a random id per dispatch.** Two devices that
   confirm the same follow-up task create two tasks (`NoDuplicateEffects`,
   6 states). The same holds for time entries, checklist items and a
   migration's copy.
2. **A set-style tool overwrites whatever the field holds.** One device sets
   the title, the user edits it, and the other device's late application —
   after it has received the edit — sets the proposed title again
   (`NoClobber`, 4 states).
3. **A consolidated copy has an effect of its own.** A wake on one device
   copies a pending item into the survivor set while another device confirms
   the original; confirming the copy applies the change a second time
   (`NoDuplicateEffects`, 7 states) — ADR 0067's second residual.
4. **A migration's failed dispatch could not revert its own claim.** The
   follow-up task is applied and its placeholder mapped in memory; the
   migration is claimed, resolved from that mapping; the follow-up's sibling
   rewrite then writes the target into the claimed item — a change of the
   item, one revision later — and the revision guard ADR 0067 added refuses
   the migration's revert: confirmed, never applied (`StatusMatchesEffect`,
   7 states). The code reaches this only if the sibling rewrite's
   transaction starts after the migration's claim; today the follow-up's
   capture and that transaction request run in one continuation, so no
   confirm can be claimed in between — the model's steps are coarser than
   the code's. The design should not depend on that.
5. **A derived checklist was taken as spent when its link had not
   arrived.** A checklist and the task update that lists it sync apart. A
   device that held the other device's checklist, but not the task update,
   found the derived id taken and created a second checklist
   (`NoDuplicateEffects`, 6 states, with the entity and its link to the
   parent modelled as separate writes; found in review).
6. **Field proposals from the task's query chat recorded no base,** so they
   applied unconditionally on a late confirmation (found in review).
7. **The reopen ABA is now model-checked.** Each user decision runs in its
   own attempt slot, and `Reopen` puts a decided item back to pending. With
   the revision guard removed, a first confirm's failure reverts a second
   confirm of the reopened item, whose dispatch then succeeds on a pending
   item (`SucceededClaimStands`, 7 states) — the gap ADR 0067 and the specs
   README recorded.

We also checked what the journal does when both devices create the same id
before either has received the other's: `updateJournalEntity` finds the
clocks concurrent and keeps the local version, storing the incoming one as a
`Conflict` row for the user. One entity, not two — but not a silent merge,
since the two versions differ in their creation timestamps.

## Decision

1. **The item names its effect.** `ChangeItemEffect.effectKeyIn` is the
   item's `effectKey` when it carries one, and otherwise its position,
   `<change set id>:<index>` — the same on every device, and the same for
   every decision of the item. `ChangeSetConfirmationService` hands it to the
   dispatch together with the item's `base` (below), as the reserved
   arguments of `ChangeEffect` (`lib/features/agents/tools/change_effect.dart`),
   replacing whatever a proposal's arguments carried under those names; the
   dispatcher strips them before any handler reads its arguments.
2. **A create-style tool derives the id of what it creates** from the key and
   a role (`change-effect:<key>:<role>`, through
   `MetadataService.deterministicId`), and does nothing when that entity is
   already in the journal — written here, synced from the other device, or
   deleted since, since a second application must not bring back what the
   user removed. An insert refused because the id exists is checked again,
   for the entity that arrived between the check and the write. This covers
   `create_follow_up_task` (the task; the late device's result names the same
   task, so its migrations resolve to it), `create_time_entry` (no second
   timer starts), `add_checklist_item(s)` (one id per position, and the
   checklist of a task that has none), `migrate_checklist_item(s)` (the copy,
   and the target's checklist when it has none; the source is still
   archived) and the event agent's `suggest_follow_up_task`. The checklist
   of a task that has none comes from
   `ChecklistRepository.derivedChecklistFor`: a live checklist under the
   derived id is reused and listed on the task, and one the user deleted
   moves on to the next generation's derived id, the same on every device
   that knows the same deletions. The checklist is resolved only when an item
   still needs creating, so a repeated application whose items all exist
   creates no checklist, even after the user deleted the first one.
3. **A set-style tool applies only while the field holds the value the
   proposal was made against.** The task agent records it when it queues a
   proposal to set the title, status, priority, estimate, due date or
   language (`ChangeItem.base`, read fresh rather than from the wake's cached
   snapshot), and so does the task's query chat, from the task it loaded for
   the answer (`QueryTaskActionContext.metadata`). No other proposal source
   builds these task-field items. The dispatcher compares it with the task before any handler
   runs; a field that moved on — applied already on another device, or
   edited since — is left alone, and the dispatch reports success, because a
   failure would revert or retract the item over a confirm that landed
   elsewhere.
4. **A consolidated copy carries its original's key**, so confirming the
   copy on one device and the original on another creates one entity.
5. **A migration resolved from the in-memory mapping is claimed with its
   resolved target**: the claim writes the arguments it dispatches with, in
   the same change of the item, and the sibling rewrite finds nothing left
   to rewrite. A reverted migration also keeps its resolved target across a
   restart.
6. As in ADR 0065–0067, the model gates the code. `ChangeSetLifecycle` gains
   attempt slots, `Reopen`, entities and the field register, and the switches
   `RevisionGuard`, `ClaimResolvesTarget`, `DerivedIds`, `CopyCarriesKey`,
   `CasGuard` and `ReuseLive` as mutation points; `ChangeSetLifecycleRace` now
   checks `NoDuplicateEffects` and `EffectsConverge` instead of
   `AtMostOnceApply`, and four configurations are added (`RaceSet`,
   `Reopen`, `ConsolidateSync`, `RaceLink`). A Glados trace over a real journal database applies
   five confirmed items any number of times with the user's edits in
   between, and after every step the journal must equal applying each once.

## Consequences

- ADR 0067's first residual is narrowed. An item decided on two devices is
  still dispatched on both, but for the tools of decisions 2 and 3 the
  journal ends up as if it was applied once: `NoDuplicateEffects`, `NoClobber` and `EffectsConverge` hold for two
  devices under every interleaving TLC explores, dispatch failures included.
  What stays open, each recorded in `specs/tla/README.md`:
  - **Both devices create the entity before either has the other's.** One
    id, and the journal parks the other version as a `Conflict` row for the
    user. A silent merge needs the created content to be identical — the
    creation timestamps come from each device's clock — and a journal rule
    that merges identical concurrent versions. That is a product decision,
    not taken here. The same holds for two concurrent applications of a
    field change, as it did before.
  - **A value compare-and-set cannot see an ABA**: a user who restores the
    field to the proposal's base between the two applications gets the
    proposed value again (TLC: `NoClobber` with `UserRestoresBase`).
  - **Status still records the dispatch, not the effect.** If one device's
    dispatch fails and reverts while the other's applied, the merged item
    reads pending though its change landed; confirming it again applies
    nothing. `StatusMatchesEffect` is therefore still not checked under the
    race.
  - Two devices creating the same follow-up task concurrently may each
    assign it a task agent; `createTaskAgent`'s duplicate check is local.
  - Not covered: `assign_task_label(s)` is a set-add, so a late add can bring
    back a label removed in between; `update_checklist_item(s)` and
    `update_time_entry` record no base (the checklist's approval protections
    stand); the project agent's `create_task` and `update_project_status`
    keep random ids and no base — its Undo deletes the created task, and a
    derived id would need a re-confirm to bring the deleted task back.
    `link_task` is idempotent already (one link per endpoints and type), and
    the relationship agent's `create_and_link_task` already derives its id.
  - A skipped compare-and-set reports success: a user who edits a field and
    then confirms the older proposal for it sees the proposal confirmed and
    the field unchanged.
  - Clients that predate `effectKey` and `base` drop them when they rewrite
    a set, as they drop `revision`: a copy then falls back to its own
    position, and a field change applies unconditionally.
  - **A checklist its creator never linked.** `createChecklist` writes the
    checklist and then the task update that lists it. A device that crashes
    between the two leaves a checklist no task lists, and its items out of
    sight, until someone adds an item to it: only a replay that still has an
    item to create writes the listing, and a replay with nothing to add does
    not repair it (TLC: `ChangeSetLifecycleRaceLink` with `CrashBeforeLink`
    violates `EffectsLinked` in 5 states). A replay with nothing to add stays
    a pure no-op on purpose: relinking would write the task concurrently with
    the creator's own listing, which is on its way, and raise a journal
    conflict (the model: a device that holds the checklist but not its link
    and writes nothing keeps `EffectsLinked`, 241 states).
  - **The reuse path's task write can raise a task conflict.** A replay that
    reuses a live derived checklist because an item still needs creating
    lists it on the task, concurrently with the creator's listing in the
    race window. That conflict is chosen deliberately: without the write, a
    creator that crashed before its listing would leave the new item in a
    checklist the task never shows.
- ADR 0067's second residual is narrowed too: a copy consolidated on one
  device while the original is confirmed on another applies nothing more.
  The copy stays pending beside the applied original (`StatusMatchesEffect`
  fails in `ChangeSetLifecycleConsolidateSync`); confirming it is a no-op.
- The reopen ABA of ADR 0067 is model-checked (`SucceededClaimStands`).
- ADR 0066's residuals stand: a tool that throws after its effect landed is
  reverted and can be retried — now harmlessly for the tools above — and a
  crash between the claim and the dispatch leaves the item confirmed without
  its effect.

## Related

- `specs/tla/ChangeSetLifecycle.tla`, `specs/tla/README.md`
- `lib/features/agents/tools/change_effect.dart`
- [Task agents](../../knowledge/features/agents/task-agents.md)
- [ADR 0066: Model-checked agent wakes and confirmations](./0066-model-checked-agent-wakes-and-confirmations.md)
- [ADR 0067: Model-checked change-set lifecycle](./0067-model-checked-change-set-lifecycle.md)

---

### Adr 0076 Model Checked Agent Head (`docs/adr/0076-model-checked-agent-head.md`)

# ADR 0076: The Agent Head Is a Register Over the Message DAG

- Status: Accepted
- Date: 2026-09-24

## Context

Every local append chains the new message off the agent's head pointer,
`AgentStateEntity.recentHeadMessageId`, and moves the pointer to the new
message (ADR 0016). The pointer is a field of the synced agent-state row.
ADR 0068 made the receive path join the row's G-counters and report
watermarks. ADR 0071 model-checked the message log and left one residual
open: the head pointer could still move back to an ancestor, because on
receive it was just another field of whichever state version won
last-writer-wins. The next append then forked the log off the old head. Fork
healing is off by default, so that fork could stay.

We extended `specs/tla/AgentMessageLog.tla` with the properties the head
should have and checked the code as it stood. TLC found three holes:

1. **Last-writer-wins moved the head back** (`HeadNeverRegresses`, four
   steps). The device whose clock runs ahead appends a root `b1`. The other
   device receives it, chains `a1` off it, and then receives the fast
   device's state row. That row is concurrent with its own and later on the
   skewed clock, so it wins, and with it the head `b1`. On dominance the
   incoming head also always won, even over a local head known to descend
   from it. A concurrent merge keeps the winner's clock, so a replica can
   hold a head that the writer of its successor never saw.
2. **An append chained off a head that already had a child** (`AppendsOffTips`,
   six steps). State rows and messages sync separately. A device that had
   received `a2` and its edge to `a1`, but only the state version naming
   `a1`, appended `b1` off `a1`. That is a fork, although this device already
   held `a1`'s successor.
3. **The receive was not one transaction** (`HeadNeverRegresses`, five
   steps). The sync processor read the local state row (from the bundle
   prefetch, or with one read), resolved the incoming version against it,
   and wrote the result later. An append by the executor that committed in
   between was overwritten, and the head moved back past it.

## Decision

1. **The head merges by ancestry, not by last writer.** Of two state
   versions' heads, `mergeAgentHeads` keeps the one that descends from the
   other in the local DAG. An unset head never wins. Two heads with no order
   known locally (a true fork, or rows still in flight) go by id. That pick
   depends only on the pair, never on clocks or arrival order (the lesson of
   ADR 0067's joined clocks). A dominating version keeps the local head when
   that head is known to descend from its own, or its own is unset.
   Otherwise it brings its own head. A version with no clock on either
   side (an older build's) still applies, as ADR 0068 has it, but with
   the heads merged the same way. Every other field of the row is resolved
   as before.
2. **The resolver stays pure; the caller reads the order.**
   `resolveAgentEntityVersions` takes an `isAncestor` oracle. The sync
   processor fills it from `AgentMessageDag.ancestryOf`: a forward walk over
   the `messagePrev` edges of present, live rows, the same edges the
   projection folds. It runs only for two state versions whose heads differ.
   The local write path needs no oracle, because every local head writer
   reads the row in its own transaction.
3. **An append chains off a tip.** `_appendMessage` first moves a set head
   past any child it has on this device (`AgentMessageDag.tipFrom`,
   following the lowest id at each fork). So a pointer that trails the log
   does not fork it, as long as the child's `messagePrev` edge has arrived:
   the walk follows edges. This also settles what the merge could not know
   yet: a head left on a row whose child (and its edge) arrived later.
4. **A state version is received in one transaction.** The processor reads
   the local state row and its identity inside the transaction that writes
   the result, and never takes a state row from the bundle prefetch. A local
   append now waits for the receive, or the receive sees the append.
5. **The model gates the code.** `AgentMessageLog.tla` has one switch per
   decision (`HeadMerge`, `TipAppend`, `AtomicReceive`), and the Glados
   conformance trace drives the real services through the real receive
   decision.

## Consequences

- ADR 0071's residual, *"the head pointer can still move back"*, is closed.
  `HeadNeverRegresses` and `AppendsOffTips` hold in all three configurations.
  `SettledHead` also holds: once sync settles on one head, every device's
  next append chains off it. `EventuallySingleHead` still holds under fair
  delivery and healing. Setting any of the three switches back to `FALSE`
  reproduces its trace.
- A fork now needs two devices appending before either has seen the other's
  message, or an append in the window where a child's row has arrived but
  its edge has not (the residual below). It can no longer come from a stale
  pointer whose successor's edge is present.
- The pointers themselves need not agree once sync settles
  (`PointersConverge` is written down but not claimed). A merge made before
  the rows that order two heads arrived can leave a pointer on the older
  head. The next append advances past it, so this has no effect on the log.
- Costs:
  - Each append reads the links into the head once: one indexed query, and
    no more while the head is a tip.
  - A received state version whose head differs from the local one walks
    forward from both heads. That walk is short while the heads are near the
    tip, and at worst covers what is newer than the older head.
  - A state row in a bundle costs one read inside its transaction instead of
    a slot in the bundle prefetch.
- Residual: a message that syncs ahead of its own edge is not seen as its
  parent's child by the tip walk, so an append in that window forks. This is
  the window the fork healer's chain-edge gate already waits out. The message
  and its edge are written in one transaction and travel together in
  practice.
- No changelog entry. A fork has no surface of its own: the projection and
  every view order the log canonically, whatever its heads. An unhealed
  fork costs an on-device prompt prefix that does not re-warm, and context
  read across more than one head. Those are costs inside a wake, not
  behaviour a user sees.

## Related

- `specs/tla/AgentMessageLog.tla`, `specs/tla/README.md`
- `lib/features/agents/sync/agent_message_dag.dart`,
  `lib/features/agents/sync/agent_concurrent_resolver.dart`
- [Vector clocks and conflicts](../../knowledge/features/sync/vector-clocks-and-conflicts.md)
- [Agent memory and log compaction](../../knowledge/features/agents/memory-and-compaction.md)
- [ADR 0016: Agent state as log projection](./0016-agent-state-as-log-projection.md)
- [ADR 0018: Convergent multi-device execution](./0018-convergent-multi-device-execution.md)
- [ADR 0067: Model-checked change-set lifecycle](./0067-model-checked-change-set-lifecycle.md)
- [ADR 0068: Model-checked agent convergence](./0068-model-checked-agent-convergence.md)
- [ADR 0071: Model-checked agent message log and compaction](./0071-model-checked-agent-message-log.md)

---

### Adr 0077 A Reservation Names The Id Written (`docs/adr/0077-a-reservation-names-the-id-written.md`)

# ADR 0077: A Reservation Names the Id That Is Written

- Status: Accepted
- Date: 2026-09-24

## Context

[ADR 0065](./0065-model-checked-sync-sequence-reservations.md) made every
vector-clock reservation name its payload, so that after a crash
`BackfillResponseHandler.settleOwnCounter` can prove whether the write landed:
it looks the named payload up and binds and resends the counter when that
payload's clock covers it, and burns the counter otherwise. The proof is only
as good as the name. `SyncSequence.tla` modelled the name as a flag — "the
reservation names its payload" — so it could not express a reservation that
names the *wrong* payload, and nothing checked that the name is the id the
write lands under.

Three create paths broke that. Each built its metadata first, which picked an
id and reserved the clock naming it, and then swapped in a caller-chosen id
with `metadata.copyWith(id: id)`:

1. `PersistenceCreateOps.createTaskEntryImpl` — the relationship tool
   dispatcher creates a person's commitment task under a stable id.
2. `PersistenceCreateOps.createAiResponseEntryImpl` — skill inference and
   attributed AI responses are created under the id their attribution
   artifact already carries.
3. `RelationshipRepository.createRelationship` — the contact import creates a
   person under the id minted when the contact was ticked.

The reservation named the uuidV5 of the task's or response's data, or a fresh
v1 id; the row was written under the caller's id. On the normal path this is
invisible, because the outbox binds the counter to the id it sends. A crash
between the commit and the outbox bind — or a swallowed enqueue failure
followed by a restart — leaves the row `reserved` under the wrong name.
Startup settlement then finds nothing under that name, burns the counter and
tells every peer to stop asking for it: the created task, AI response or
person never reaches the other devices until it is next edited. Had the name
matched another entity whose clock covered the counter, settlement would
instead have bound the counter to that entity.

With a switch that lets a reservation name another entity, TLC finds both in
a few steps:

- `NoFalseBurn`: reserve counter 1 for `e1` naming `e2`, commit `e1`, crash,
  settle — `e2` does not cover 1, so the committed counter is burned.
- `BoundRowsHavePayload`: counter 1 for `e1` names `e2`, counter 2 for `e2`
  commits, crash, settle — `e2` covers 1, so counter 1 is bound and answered
  although `e1` never landed.

## Decision

1. **The id is chosen where the clock is reserved.**
   `MetadataService.createMetadata` takes the entry's `id`, and names that id
   on the reservation — an explicit id wins over `uuidV5Input`. The three
   paths pass their id in instead of patching it afterwards.
2. **The returned id is final.** `Metadata.copyWith(id: ...)` after
   `createMetadata` is a defect: it separates the written entry from the name
   its counter will be settled by. The method's documentation says so, and the
   audit found no other path that moves a reserved clock to a different id.
3. **The model can say it.** `SyncSequence.tla` records the reservation's
   name per counter (`named`), settles by that name, and states
   `BoundRowsHavePayload` against the write that reserved the counter.
   `MisnamedReservations` lets a reservation name another entity; every
   checked-in configuration sets it `FALSE`.

## Consequences

- A crash after creating an entry under an explicit id no longer burns its
  counter; startup settlement resends it. End-to-end regressions drive the
  real metadata, reservation, sequence-log and settlement code through that
  crash and fail with the old code (the counter ends `burned`).
- A new create path that needs a caller-chosen id must pass it to
  `createMetadata`. Direct reservations elsewhere (links, agent entities,
  notifications, consumption events) already name the id they write; the audit
  is recorded in the pull request.
- Counters already burned under the wrong name stay burned: `burned` is terminal. The affected entries reach other devices on their next edit. (ADR 0131 later resends them once at startup and rebinds the counter to the payload that carries it.)

## Related

- [ADR 0065](./0065-model-checked-sync-sequence-reservations.md)
- [ADR 0078](./0078-entry-link-versions-are-ordered.md) — the link-writer
  holes the same audit found
- `specs/tla/SyncSequence.tla`, `specs/tla/README.md`
- [Sequence log and backfill](../../knowledge/features/sync/sequence-and-backfill.md)

---

### Adr 0078 Entry Link Versions Are Ordered (`docs/adr/0078-entry-link-versions-are-ordered.md`)

# ADR 0078: Entry-Link Versions Are Ordered, and an Edit Succeeds Its Predecessor

- Status: Accepted
- Date: 2026-09-24

## Context

An `EntryLink` is replicated state. Every device can edit it — collapse it,
hide it, retype it, or tombstone it when a task leaves its project — and every
version reaches every other device, in no guaranteed order and possibly more
than once: as its own `entryLink` message, as a backfill answer, and inside
every journal-entity message, which embeds a snapshot of all the entry's links
(`OutboxEnqueueWriter.prepareJournalEntity`). The receive handlers had a
comment saying links "have their own vector clock for conflict resolution via
`upsertEntryLink()`". They did not. An audit during PR #4464
([ADR 0077](./0077-a-reservation-names-the-id-written.md)) found two holes:

1. **The receive applied whatever arrived last.** `JournalDb.upsertEntryLink`
   compared nothing but the serialized row: any version that differed
   overwrote the stored one. A journal-entity message enqueued before a link
   was removed, and delivered after the removal, put the live link back. So
   did a late backfill answer. Devices that received the same versions in a
   different order kept different links. A task moved out of its project, or
   a collapsed or hidden link, could come back on the device that made the
   change or on its peers, and stay that way until the next edit.
2. **An edit did not extend the clock of the version it replaced.**
   `JournalRepository.updateLink` and `ProjectRepository._prepareDeletedLink`
   reserved their clock without `previous:`, so an edit's clock held only this
   host's counter. It was concurrent with the version it replaced, not after
   it. No receive rule could order the two causally. And the backfill
   responder could not answer an older counter from the current row, because
   that row's clock no longer covered it.

`AgentReplication.tla` (ADR 0068) checks the writer-side half of this for
agent entities. `IntentCarriesClock` and `ResolveLocalWrites`: a write
carries the clock of the row it replaces. `ClampTimestamp`: a successor is
never stamped earlier than its predecessor. With either switch off, TLC finds
`Converged` or `LocalWriteTakesEffect` violated in a few steps. The agent
receive rule puts causal dominance first and falls back to `updatedAt`. For
links we use a single lexicographic key instead (Decision 1). Such a rule is
transitive for any mix of versions, including clockless legacy copies. A
dominance check followed by a timestamp fallback is not: a clock-dominant
version stamped earlier than its predecessor, plus a clockless copy stamped
in between, form a cycle. Given the two writer-side rules, the two orders
agree on every history the writers produce. No separate spec is needed.

Review found one more edge. A new host's first counter is 0, and
`VectorClock.compare` reads an absent host as 0. So a fresh device's first
edit, `{…, host: 0}`, compares *equal* to the version it extends. The link
order therefore reads an absent host as lower than any counter, 0 included.

The same audit found `JournalRepository.createTextEntry` taking a
`required String id` and ignoring it. Every caller passed a fresh `uuid.v1()`
and read the entry's id back from the returned entity, so nothing depended
on the parameter. It only suggested a way to choose the id that did not exist.

## Decision

1. **The receive orders versions by one key.** `JournalDb.upsertEntryLink`
   refuses any version that is older than the stored one under a single
   ordering:
   - the later `updatedAt` wins;
   - on a tie, the clocks are compared host by host in sorted order, and the
     first counter that differs decides. A host absent from a clock ranks
     below every counter, 0 included;
   - if the clocks tie too, the serialized version decides.

   The check runs in the upsert's transaction for every caller: both sync
   handlers and the local writers.
2. **An edit succeeds its predecessor.** A local update reserves its clock
   with the stored link's clock as `previous` (`updateLink` merges the stored
   copy and the caller's). It stamps `updatedAt` with `linkEditTimestamp`:
   now, or the predecessor's stamp when a peer's clock ran ahead. The edit
   therefore has the later stamp, or ties on it. On a tie it ranks higher on
   the clock: the edit's clock is its predecessor's plus this host's next
   counter, which is either larger than before or new.
3. **`createTextEntry` loses its `id` parameter.** The id is minted with the
   metadata, where the reservation names it, as
   [ADR 0077](./0077-a-reservation-names-the-id-written.md) requires.

## Consequences

- A removed or edited link is not brought back by a late copy of an older
  version, whatever the arrival order and however far a peer's wall clock
  runs ahead. Every device that has received the same versions keeps the
  same one.
- A version refused on arrival is still recorded as received in the sequence
  log. The stored clock covers its counter, so backfill stops asking for it.
- Links written before this change carry clocks without their predecessor's
  entries. Concurrent pairs among them are ordered by `updatedAt`, which beats
  the old arrival order but not a skewed clock. Such a link is ordered
  causally again after its next edit.
- A local edit that loses a race with a sync arrival between its read and its
  write is refused like any older version. `updateLink` reports false.
- A version that dominates by clock but is stamped *earlier* than the stored
  one loses. The writers never produce one (Decision 2). A version like that
  can only come from a device whose clock runs behind and which predates
  this change, and it can then be ordered by timestamp alone.
- The zero-counter equality reaches beyond links. Journal entries
  (`JournalDb.updateJournalEntity` applies only `b_gt_a`) and agent entities
  (the resolver and the dominance pre-check keep local on `equal`) read a new
  host's first update of an existing row as equal to that row and keep the
  row. That is a separate fix, in `VectorClockService` or in
  `VectorClock.compare`, and it is left open here. It was made in
  [ADR 0080](./0080-a-present-counter-ranks-above-an-absent-host.md), in
  both places: `compare` ranks an absent host below 0, and new hosts start
  at 1. The link order now uses the shared `VectorClock.compareCanonically`.
- Residual, not addressed here: `JournalRepository.removeLink` and
  `removeTypedLink` hard-delete the row on this device and send nothing. Peers
  keep the link, and the next journal-entity message from a peer that embeds
  it re-inserts it here. Unlinking an entry or removing a task relationship
  therefore does not reach other devices. Fixing it means turning those
  deletions into synced tombstones, like the project unlink. Closed by the
  2026-09-25 addendum below.

## Addendum (2026-09-25): a removal is a synced tombstone

The residual above is closed. The decision was that link tombstones must
sync. Found in PR #4467: `JournalRepository.removeLink` and `removeTypedLink`
deleted the row on this device and sent nothing. They back unlinking an entry
in the linked-entries list, removing a task relationship (the row in manage
mode), and the Undo on the "link created" message. The peers kept the link.
Every journal-entity message a peer sends embeds its snapshot of the entry's
links. So the next one put the link back on the device that removed it.

1. **Every removal writes the link's next version.** `removeLink` (every type
   between the pair) and `removeTypedLink` (one type) write each live link
   again with `deletedAt` set and `hidden` true, through `updateLink`. So a
   tombstone follows Decision 2 like any other edit: it reserves its clock
   with the stored link's as `previous`, is stamped by `linkEditTimestamp`,
   is upserted under Decision 1, and is sent as an `entryLink` update. The
   project unlink and `RelationshipRepository.unlinkTask` already did this.
   `JournalDb.deleteLink` and `deleteTypedLink` are removed. Nothing deletes
   a link row now except `upsertEntryLink`: it drops a hidden row when a
   version with a different id arrives for the same `(from_id, to_id, type)`.
   Entries are soft-deleted, so deleting an entry does not delete its links.
2. **Linking a removed link again revives its tombstone.**
   `PersistenceLogic.createLink` and `ProjectRepository.linkTaskToProject`
   look for a removed version of the same `(fromId, toId, type)`
   (`JournalDb.linksBetween`, `removedVersion`). If one exists, the new link
   takes its id, extends its clock and is stamped by `linkEditTimestamp`.
   Re-linking is then one more version of the same link, ordered by
   Decision 1 whatever the arrival order. A fresh id would be a second row
   for the same triple. A peer that still holds the live link refuses that
   row as a duplicate. When the tombstone arrives later, the peer has no link
   while this device keeps its new one.
3. **Reads of live links exclude removed ones.** Every tombstone is hidden,
   so queries that already require `hidden = false` exclude it. The
   queries that also return user-hidden links now test
   `json_extract(serialized, '$.deletedAt') IS NULL`: backlinks, parent ids,
   `linksForIds`, the "show hidden" linked-entries list, basic links,
   typed-relationship links and the bidirectional neighbourhood. Drift's
   analyzer gets the `json1` module for this. Reads that serve replication
   keep tombstones: `entryLinkById`, `linkRowsFromIdsIncludingHidden`,
   the sequence-log stream, and
   `linksForEntryIdsBidirectionalIncludingRemoved`. The last one is the
   snapshot a journal-entity message embeds, so a removal travels with the
   entry.
4. **No new model.** A tombstone is not terminal, since linking again
   revives it. A link therefore stays one last-writer-wins register under
   the Decision 1 order, and the writer-side rules that `AgentReplication.tla`
   checks cover it. Nothing new is checked.

Consequences:

- A removal reaches every device and stays removed there. A late copy of the
  live version, including a peer's embedded snapshot, cannot bring it back.
  Removing a link and linking it again converges on every device, whatever
  order the versions arrive in. So does an undo followed by a redo.
- Undo stays local and instant. The link is gone on this device before
  anything is sent. It is now a synced removal like any other.
- `linked_entries` keeps one tombstone per removed link. Linking the same
  pair and type again reuses that row. Nothing purges tombstones.
- A link removed before this change is still on the peers. Their snapshots
  can bring it back once more. Removing it again now reaches every device.
- Residual: two devices that create the same link offline, at the same time,
  mint two ids for one triple. Each device refuses the other's as a
  duplicate. A removal on one device is then refused on the other, where the
  triple is live under the other id. That device's next snapshot replaces
  the tombstone with its live row. The fix would make the triple the link's
  identity, for example with a deterministic id. That changes the data model
  and is left open. Closed by
  [ADR 0096](./0096-an-entry-link-is-its-natural-key.md).

## Related

- [ADR 0068](./0068-model-checked-agent-convergence.md) — the order and the
  writer-side fixes, model-checked for agent entities
- [ADR 0077](./0077-a-reservation-names-the-id-written.md) — a reservation
  names the id that is written
- `specs/tla/AgentReplication.tla`, `specs/tla/README.md`
- [Vector clocks and conflicts](../../knowledge/features/sync/vector-clocks-and-conflicts.md)
- [Entry links](../../knowledge/domain/entry-links.md)

---

### Adr 0079 Recovery Never Replaces A Live Database (`docs/adr/0079-recovery-never-replaces-a-live-database.md`)

# ADR 0079: Recovery Never Replaces a Database Another Connection Can Read

- Status: Accepted
- Date: 2026-09-25

## Context

`openDbConnection` runs `recoverDatabaseIfUnreadable` before it builds a
connection. If `isReadableDatabaseFile` says the file cannot be read,
recovery moves the file aside and puts the newest backup in its place. The
backup is older than the file, so a wrong verdict is data loss.

PR #4464 made the probe open the file `immutable`. A normal read-write
connection deletes the `-wal` and `-shm` when it closes beside a file that is
not a database, and immutable reads never touch them. But immutable also
skips locking and change detection. It reads the main file as it is on disk
at that moment, and SQLite's normal readers do not. If another connection is
checkpointing, a page of the main file can be half-written. An immutable read
of that page can fail with `SQLITE_NOTADB` or `SQLITE_CORRUPT`, and both mean
"unreadable".

Nothing ensures that the probe's process is the only one with the file open:

- **Other processes.** The desktop builds have no single-instance lock. A
  second instance opens the same profile's databases while the first still
  writes and checkpoints them.
- **Other handles in the same process.** Every Drift database is a
  `LazyDatabase`, and any second handle on the same file runs the probe when
  it opens. Examples are a non-active world opened through `WorldHandle`, or a
  store opened again during a generation switch. The design keeps these apart,
  but no code enforces it.

A deterministic test shows the torn read. A live WAL writer has every commit
in its WAL, and the main file's header is overwritten as a half-written
checkpoint would leave it. The immutable look reports "not a database". A
locking reader reads the same database whole, because it takes page 1 from
the WAL.

## Decision

1. **An unreadable verdict needs two looks that agree.** The immutable look
   runs first, and almost every launch stops there with "readable". Only when
   it fails is the file checked again, read-only (`mode=ro`), with SQLite's
   normal locking and a two-second busy timeout.
   - A locking reader sees a consistent snapshot, so a database that another
     connection can read always passes.
   - A read-only connection that closes beside a non-database leaves the
     `-wal` in place. It may rebuild the `-shm`, which is only an index of the
     WAL.
   - A lock it still cannot get after the timeout is not a corruption verdict,
     so the file counts as readable.
2. **The file is checked again right before it is moved aside.** Copying the
   snapshot takes time. A file that reads by then is left in place, and the
   staged copy is removed.
3. **Every probe connection is closed before it returns** (as in PR #4464).
4. **A snapshot is judged by what the restore installs.** The restore copies
   only a snapshot's main file. A snapshot from `createDbBackup`'s raw-copy
   fallback keeps its source's `-wal` next to it, and a locking read through
   that WAL can succeed even though the main file alone cannot be read.
   Snapshots therefore get the immutable, main-file-only look.
5. **Recoverers of one file run one at a time.** Two app instances can open
   the same profile. Each would judge the file unreadable and restore it, and
   the second could move aside the file the first had restored and written
   to since, then install an older backup over it. Recovery therefore holds
   an exclusive OS lock on `backup/<name>.recovery-lock` (dart:io
   `RandomAccessFile.lock`, which is `fcntl` on Unix) from staging the
   snapshot until the backup is in place. An OS lock does not exclude a
   second holder inside the same process, so recoverers in one process also
   wait in a queue keyed by the lock file. After waiting, the recheck in
   step 2 finds the other recoverer's restore readable and leaves it alone.
   Inside one process, no `await` separates that recheck from the rename.

## Consequences

- A healthy database is never replaced because another process or connection
  was checkpointing while the probe ran. Regression tests cover a live WAL
  database with a torn main file, both through the probe and through the
  whole recovery. Removing the second look, making it read-write, or skipping
  the recheck before the rename each makes a test fail.
- A raw-copy snapshot that reads only through its own `-wal` is skipped in
  favour of an older snapshot that reads on its own. A test covers this, and
  it fails if snapshots are judged with the WAL-reading look.
- A recoverer in another process waits for the lock and does not have its
  restore moved aside. The test runs that other process as a `python3`
  script using the same `fcntl` lock, inside a test hook placed between the
  final recheck and the rename. It fails without the lock, and it fails with
  only the in-process queue. The test runs on Linux and macOS.
- A truly damaged file fails both looks, so recovery still restores it.
- Only the damaged-file path pays for the second look: one more open, plus up
  to two seconds if a lock is held.
- The lock file stays in `backup/`. Deleting it would open a race between
  unlinking it and another process opening it.
- **Residual:** a file that becomes damaged between the final recheck and the
  rename is still replaced. That is the case recovery exists for.
- **Residual:** only recoverers take the lock. Ordinary connections, such as
  a store's own connection after recovery or the backup capture's
  connections, do not take it. Such a connection could write a file that is
  truly damaged in the moment between the final recheck and the rename. No
  such writer has been found.

## Related

- `lib/database/common.dart` (`isReadableDatabaseFile`,
  `restoreDatabaseFromBackup`, `recoverDatabaseIfUnreadable`)
- [Persistence layer](../../knowledge/architecture/persistence.md)
- [ADR 0077](./0077-a-reservation-names-the-id-written.md) — the PR (#4464)
  that introduced the immutable probe

---

### Adr 0080 A Present Counter Ranks Above An Absent Host (`docs/adr/0080-a-present-counter-ranks-above-an-absent-host.md`)

# ADR 0080: A Present Counter Ranks Above an Absent Host, and New Hosts Start at 1

- Status: Accepted
- Date: 2026-09-25

## Context

A vector clock maps each host that has written a version to that host's
counter. `VectorClockService` handed a new host counter 0 first, and
`VectorClock.compare` read a host absent from a clock as counter 0. The two
together made a host's first write invisible. A device set up or reinstalled
gets a new host id. Its first edit of an existing entry or agent row extends
the stored clock by `host: 0`, and that clock compared *equal* to the version
it extended. [ADR 0078](./0078-entry-link-versions-are-ordered.md) found this
while ordering entry links, fixed the link order locally and left the rest
open. With two simulated devices through the real code:

1. **The edit was refused on the device that made it.** The local journal
   write goes through `JournalDb.updateJournalEntity`, which applies only a
   version that dominates the stored one (`b_gt_a`). The first edit of each
   existing entry on a new device compared equal, was skipped as
   older-or-equal, and its counter was burned. The user's edit did not stick.
2. **Peers dropped it.** Every receive path that applies only a newer version
   kept the local row: `JournalDb.updateJournalEntity` and the stale-descriptor
   pre-check on the journal receive, `resolveAgentEntityVersions`,
   `AgentVcDominanceCheck` (which skipped the download) and the agent-link
   dominance check in `SyncEventProcessor`. An agent entity's first write from
   a new host applied locally but reached no other device.
3. **A concurrent edit was taken as newer.** A's own later edit `{A: 2}` read
   as dominating B's first edit `{A: 1, B: 0}`, so B's edit was dropped with
   no conflict. Two new hosts that each extended one version, `{A: 1, B: 0}`
   and `{A: 1, C: 0}`, compared equal, and each device kept its own.
4. **The concurrent tiebreak could not order them.** The canonical clock order
   that agent entities use on an `updatedAt` tie (`compareClocksCanonically`)
   also read absent as 0, returned 0 for that pair, and each replica kept its
   local version.

`AgentReplication.tla` modelled clocks with 0 standing for "absent" and
counters from 1, so it could not express this. Clocks now map a host to a
counter or to `Absent`. `FirstCounter` is a new host's first counter, and two
switches say how the receive path reads an absent host. With `FirstCounter =
0` and the old reading TLC finds `NoLostSuccessor` violated in two steps: B
writes its first version, `{B: 0}`, and C receives it and keeps the row it
had. With only the old canonical tiebreak it finds `Converged` violated: A
and B each write a first version at the same instant, and each keeps its own.

The sequence log counts from 1 as well. `SyncSequence.tla` hands out counters
`1..MaxCounter`, a watermark of 0 means nothing resolved, gap detection
materializes `watermark + 1 .. counter - 1`, and the contiguous-prefix
watermark counts from 1. A host's counter 0 was outside all of it: never
marked missing, and the watermark rebuild numbered a counter-0 row as the
first of the prefix. That shifted every later row by one. A contiguous run
`0..3` rebuilt to 0, and `0..3, 5` rebuilt to 5, past the hole at 4, which
gap detection would then never request.

## Decision

1. **An absent host ranks below every counter, 0 included.** A present entry
   says the host wrote. `VectorClock.compare` reads an absent host as -1, so a
   version extended by `host: 0` dominates the one it extends, and only
   identical clocks are `equal`. This fixes the receive side for the clocks
   already out there. Every host an older build created has counter 0 in its
   clocks, on every device and in every synced payload, and devices that have
   not updated keep sending them. Starting new hosts at 1 alone would leave
   all of those broken.
2. **One canonical order.** `VectorClock.compareCanonically` replaces the
   agent resolver's `compareClocksCanonically` and the link order's private
   comparator, with the same reading of an absent host. It is total, returns
   0 only for identical clocks and ranks a dominating clock higher.
3. **New hosts start at 1.** `VectorClockService` hands a new host
   `firstVectorClockCounter` (1) first. A host whose persisted watermark is
   still 0 has handed out nothing, because the watermark is persisted before
   a counter is returned, so it moves to 1 at startup. A host already past 0
   continues where it is. A device that has not updated still reads an
   absent host as 0, and a new host's first write, `host: 1`, dominates there
   too. The sequence log's numbering and its model now agree.
4. **The watermark rebuild counts from 1.** The prefix query ignores rows
   below counter 1.

## Consequences

- On a new or reinstalled device the first edit of each existing entry, link
  and agent row is saved and reaches every other device.
- A version that lacks only another host's counter 0 is now concurrent with
  that host's edit. For a journal entry that raises a `Conflict` the user
  resolves, where before one side was dropped silently. Agent entities merge
  it like any concurrent pair.
- Clocks that differ only by a 0 entry are no longer "the same version" to
  the sender's freshness checks (`MatrixPayloadSender` and the notification
  sender). They are different versions, and the check now says so.
- `AgentReplication.tla` checks the fix on both halves of a mixed fleet:
  `AgentReplicationLegacyCounter` (every host started at 0, received by this
  build) and `AgentReplicationLegacyReceiver` (hosts started at 1, received by
  a build that still reads absent as 0). The four existing configurations
  keep their state counts.
- Residual: a device that runs a build older than this one still reads an
  absent host as 0 when a clock carries a counter 0 from a host an older
  build created. Two such devices compare that host's first write equal.
  And an older and a newer device can keep different rows: for
  `a = {h0: 0, h1: 1}` and `b = {h1: 2}` this build finds the two concurrent
  and resolves them, while the older one reads `b` as newer and keeps it.
  The rows agree again at the next write that succeeds both. Nothing on the
  receiving side can change what an older build does, and it ends as devices
  update. `AgentReplicationLegacyCounter` and
  `AgentReplicationLegacyReceiver` each check one half of a mixed fleet;
  a fleet mixing both readings over counter-0 clocks is not modelled.
- Watermarks that the pre-ADR-0080 rebuild cached for a host with a
  counter-0 row may read past a hole. Sync database schema v30 drops those
  rows once, so they are rebuilt from counter 1 on their next read.
- Residual: a counter 0 that a host created by an older build handed out is
  outside gap detection, so if its message is lost it is never requested. It
  is that host's first write, usually superseded, and the next version of
  the same payload carries its clock.

## Related

- [ADR 0078](./0078-entry-link-versions-are-ordered.md) — the entry-link
  order, where this was first found
- [ADR 0068](./0068-model-checked-agent-convergence.md) — the agent receive
  order this corrects
- [ADR 0065](./0065-model-checked-sync-sequence-reservations.md) — the
  sequence-log numbering
- `specs/tla/AgentReplication.tla`, `specs/tla/README.md`
- [Vector clocks and conflicts](../../knowledge/features/sync/vector-clocks-and-conflicts.md)
- [Sequence log and backfill](../../knowledge/features/sync/sequence-and-backfill.md)

---

### Adr 0081 Model Checked Evolution Sessions And Agent Links (`docs/adr/0081-model-checked-evolution-sessions-and-agent-links.md`)

# ADR 0081: Model-Checked Evolution Sessions and Agent Links

- Status: Accepted
- Date: 2026-09-25

## Context

Two replicated parts of the agent runtime had no model: evolution sessions
(the 1-on-1s that evolve a template or a soul) and agent links. We wrote both
down in TLA+, `specs/tla/EvolutionSession.tla` and `specs/tla/AgentLinks.tla`,
modelled the code as it was, and model-checked them with TLC. These are the
holes TLC confirmed, each as a concrete trace.

**Evolution sessions.** A session row (`EvolutionSessionEntity`) is resolved
by `updatedAt` last-writer-wins like any agent register. Only the device that
holds the session in memory completes it, and completing it adopts a new
template or soul version. Any device abandons a session it reads as active,
because `startSession` and every approval sweep stale sessions
(`_abandonStaleActiveSessions`). Locally, a session is abandoned only while it
is active, and a completion is written over whatever status the row has.

1. **A sweep beat the approval it had not seen.** The owner approves. The
   peer, not having heard, starts a session a minute later and sweeps this
   one. The two writes are concurrent and the sweep is newer, so every
   replica ends with the session abandoned while its version is in effect.
   The feedback extraction reads an abandoned session as a negative signal
   for the next ritual, and it drops out of the approval rate and the
   last-ritual timestamp. TLC: `CompletedStays` in five steps,
   `AdoptionRecorded` in eight.
2. **An approval that failed part-way left an adopted version behind.** The
   version committed in its own transaction, then the notes, the recap and
   the session row. When one of those failed, the approval returned null with
   the version already active. If the user then left the chat, the session
   was abandoned under its own version (`AdoptionRecorded`: create, fail,
   leave, and the deliveries, seven steps), and
   a crash between the steps left it active until a later sweep abandoned it
   (two steps).
3. **A soul approval retried after such a failure minted a second version.**
   The template path cached the version it had created, but the soul path
   did not (`OneVersion`, three steps: create, fail, create). A failed outbox
   flush after the commit had the same effect: `SoulDocumentService.createVersion`
   threw, the approval returned null, and the proposal stayed for a retry.
4. **The receive of a session row could overwrite an approval.** The receive
   read the row, and an approval that committed before the receive wrote was
   lost on this device. The owner kept the session abandoned while every
   peer held it completed (`CompletedStays`, four steps).

**Agent links.** [ADR 0078](./0078-entry-link-versions-are-ordered.md) found that journal entry links had no version
order at all. Agent links had one: dominance by vector clock, then
`updatedAt`, then the canonical clock. The holes were elsewhere.

5. **A tombstone read as no row.** The receive read the local link with
   `getLinkById`, which filters `deleted_at IS NULL`. Any version that arrived
   after a removal, such as a late copy of the link it removed, replaced the
   tombstone. A replica that received the removal before the link kept the
   link for good (`NoLostSuccessor` in three steps, `Converged` in six).
6. **Backfill could not serve a removal.** The backfill responder read the
   same way, so it answered `deleted` for a removed link. A receiver that had
   lost the removal settled the gap with nothing applied and kept the live
   link (`Converged`, seven steps).
7. **A link written afresh was concurrent with the version it replaced.**
   Writers build links with `vectorClock: null` under reused ids: the Daily OS
   links' deterministic ids, the planner's template assignment, and any link
   removed and written again. `AgentSyncService.upsertLink` stamped only the
   writer's clock and overwrote the row. The trace needs no clock skew: B
   links an item to a task, A removes the link, and B links it again. B's
   clock `{B:2}` is concurrent with A's removal `{A:1, B:1}`, and the
   canonical clock order prefers the removal. A and C keep the removal, and B
   keeps the link. A write stamped earlier than its predecessor also lost to a
   third version its predecessor beat, on a lagging clock (`ClampTimestamp`).
8. **The link receive read and wrote in two steps.** A local write that
   committed in between was overwritten, as in hole 4 (`NoLostSuccessor`,
   seven steps).

Some suspected gaps were not confirmed. A completed session is never
reopened: `active` is written only at creation, and the override keeps
`active` below both terminal statuses. A completed session names one version
once hole 3 is closed. The version rows and their head are
`specs/tla/VersionHeads.tla`, which this model composes with rather than
repeats.

## Decision

1. **A concurrent pair of session rows keeps the more final status:**
   completed, then abandoned, then active. The rule sits in
   `resolveConcurrentAgentEntityOverride` and matches what the writers
   already do on one device. Only the owner completes, completion creates
   the version, and an abandonment is written only over an active row.
   Because the rank never drops along a causal edge, replicas converge in
   any arrival order. That is the `RankDrop` condition of
   [ADR 0068](./0068-model-checked-agent-convergence.md).
2. **An approval is one transaction.** The version, the notes, the recap and
   the completed session row commit together in `approveProposal` and
   `completeSoulSession`, so a failure leaves nothing to repeat or orphan. An
   approval of a session that is already completed returns the version the
   row names instead of creating one. That is the case where a transaction
   committed and then failed flushing the outbox. The template path's
   version cache and its recovery-by-matching-directives
   (`_createVersionIdempotent`) are gone.
3. **A session row is received in one transaction,** as agent state and
   change sets already were.
4. **A link's stored version includes its tombstone.** `AgentRepository.getLinkByIdIncludingDeleted`
   is what the receive, the backfill responder and the backfill verifier
   read. The receive decision is one pure function, `resolveAgentLinkVersions`.
5. **A local link write succeeds the stored version.** `upsertLink` reads it,
   tombstone included, in the write's transaction. The clock covers both
   versions, and `updatedAt` is never older than the stored one, as
   ADR 0068 does for entity registers.
6. **A link is received in one transaction.**

## Consequences

- `Converged`, `OneVersion`, `AdoptionRecorded`, `CompletedStays` and
  `NeverReactivated` hold for three replicas with an owner that crashes and
  writes that lag the clock by one tick. `Converged` and `NoLostSuccessor`
  hold for a link written and removed on three replicas, with any delivery
  lost and recovered by backfill. Each fix, set back to the old behaviour,
  has the counterexample listed above (`specs/tla/README.md`).
- A failed approval now loses the notes it had drained, because they roll
  back with the version. Notes are advisory, and `_persistNotes` already
  accepted that loss for a failure before the commit.
- Every local link write, including every message's `msgprev` edge, costs
  one primary-key read in its transaction.
- A local link write now wins over a removal it never saw, on every replica.
  That was already true on the writing device. The writers are user actions
  and agent tools that mean to set the link.
- Links written before this change can still carry clocks that do not cover
  their predecessors. Such pairs are ordered by `updatedAt` until the next
  write.
- A successor must *strictly* dominate the version it replaces. A host an
  older build created starts at counter 0, and its first write extends the
  stored clock by `host: 0`. That compared *equal* until
  [ADR 0080](./0080-a-present-counter-ranks-above-an-absent-host.md) ranked
  an absent host below 0, and the receive kept the stored version. This
  change relies on ADR 0080 and does not work around it. A regression in
  `agent_sync_service_test.dart` covers a host's first relink and first
  removal over a synced link, for first counters 0 and 1. With ADR 0080's
  compare reverted, the counter-0 case fails.
- Residuals, documented in `specs/tla/README.md`:
  - **Two devices that reassign a template's soul (or an improver's target)
    concurrently swap the assignments.** `AgentRepoLinks.upsertLink` keeps
    one live link per slot. When a live assignment arrives, it tombstones
    the other one locally, without a clock bump or a sync message. A and B
    each receive the other's link and keep it, so A ends with B's soul and B
    with A's, and nothing heals it until the next assignment. The same
    handoff hard-deletes a row that shares the slot's natural key. A copy of
    the model with this handoff (not checked in) finds the swap in five
    steps. The fix changes how an assignment is identified or ordered, so it
    needs a decision. The options are: one deterministic link id per slot
    (`soul_assignment:<templateId>`), which makes the assignment a register
    but needs a migration of existing links and a plan for older clients
    that keep minting random ids; a slot rule every replica applies the same
    way, where the assignment ranked highest by `(createdAt, id)` among
    every version known here, live or not, holds the slot, the writers clamp
    `createdAt` above the slot's, and the unique index admits the derived
    losers; or emitting the handoff's tombstones as synced writes, which
    turns receives into writes.
  - **Agent entities have hole 5 too.** The entity receive reads the local
    row with `getEntity`, which also filters tombstones, and so does the
    backfill of entities. A soft-deleted entity, such as a parsed capture
    item replaced by a re-parse, can come back when a late copy arrives.
    That is the same fix applied to `_resolveIncomingAgentEntity`, the bundle
    prefetch and the entity backfill, and it is left for its own change.
  - **Other entity types still receive in two steps.** Only agent state,
    change sets and evolution sessions are read and written in one
    transaction.
  - **`approveSoulProposal`**, the mid-session soul approval that does not
    complete the session, still creates its version in its own transaction.
    A retry after a failed outbox flush can create a second version.

## Addendum (2026-09-25): agent entity removals stick on every device

Decision from the user: an agent entity that was removed stays removed on
every device, as a removed link does. This closes the residual above,
"Agent entities have hole 5 too", and the one after it, "Other entity types
still receive in two steps".

`specs/tla/AgentReplication.tla` gains a third kind, `"removal"`: a register
removed and written again, whose tombstone (`deletedAt`) is ordered like any
other field. The same model now also loses deliveries and recovers them by
backfill, and can split the receive into a read and a write. Modelled as the
code was, TLC found these holes:

9. **A late copy of the live version replaced a removal.** The entity receive
   read the stored row with `getEntity`, which filters `deleted_at IS NULL`,
   so a removal read as no row (`NoLostSuccessor`, three steps: A writes,
   A removes, A receives its own first version late). A parsed capture item
   replaced by a re-parse, a deleted day plan, template or soul came back.
10. **Backfill could not serve a removal.** The responder, the verifier and
    own-counter settlement read the same way. A device that lost the removal
    was answered `deleted`, settled the gap with nothing applied and kept the
    entity (`Converged`, three steps).
11. **A row written over a removal did not succeed it.** The local write
    resolution read the persisted row with `getEntity` as well. A day plan
    drafted again over a peer's removal carried the drafting host's counter
    alone, concurrent with the removal. With the removal stamped later, the
    peers kept it while the drafting device kept the plan, and a late copy of
    the first version then won over the draft (`NoLostSuccessor`, six steps).
12. **A re-creation was handed the removal back.** Built afresh, because its
    writer reads no row, the draft was resolved against the tombstone as if
    concurrent, and a removal at the same instant or later won
    (`LocalWriteTakesEffect`, two steps).
13. **Every other type was received in two steps,** reading the row (or the
    outbox bundle's prefetched snapshot of it) and writing after an await. A
    local write that committed in between was overwritten
    (`NoLostSuccessor`, eight steps).

Three holes were outside the model's reach and were found by the audit of
every writer that soft-deletes an agent entity:

14. **A removal did not always rank at its own instant.** Last-writer-wins
    orders a concurrent pair by `updatedAt`, or `createdAt` for append-only
    variants. The soul, soul-head and version removals set `deletedAt` alone,
    and an append-only row has no other timestamp to move. A removal then
    sorted with the edit it came after, or tied with it, and the canonical
    clock order could bring the entity back on every device. TLC checks
    convergence either way; this is about which version the devices converge
    on.
15. **A removal of an append-only row was stamped on its snapshot.** The
    local write path resolved only writes to mutable registers against the
    persisted row. A re-parse that read the old parsed items and then
    removed them overwrote an edit that synced in meanwhile, under a clock
    concurrent with it.
16. **The recommendation decision was revived on no clock.** Withdrawing a
    project recommendation's decision removes its source change set, and
    deciding again writes it afresh under its deterministic id with an empty
    clock. The revival was concurrent with the removal, which the removal's
    instant now wins. The device that decided again showed the decision and
    its peers did not.

### Decision

7. **The stored version includes its tombstone** wherever sync orders
   versions: `AgentRepository.getEntityIncludingDeleted` is what the receive
   (`resolveReceivedAgentEntity`), the backfill responder and verifier,
   own-counter settlement, the sequence log's canonical clock and the local
   write resolution read.
8. **Every agent entity is received in one transaction.** The stored row is
   read, resolved and written together, for every type. The outbox bundle's
   prefetch is gone, and so is the separate change-set receive path, which
   the general one now covers.
9. **A removal succeeds the version it replaces.** A local removal of any
   variant, append-only ones included, is stamped with a clock that covers
   the stored version, as a write to a mutable register already was.
10. **A removal ranks at its instant.** `effectiveUpdatedAt` is the later of
    the variant's timestamp and `deletedAt`. A removal concurrent with an
    edit is last-writer-wins by these instants: the later of the two stands
    on every device. Edits of an append-only variant never move its
    timestamp, so a removal wins over any edit concurrent with it. No type
    that is removed has a status override.
11. **A row built afresh over a tombstone is a re-creation and keeps its
    fields** (`resolveLocalAgentWrite`). Its clock covers the tombstone, so
    it succeeds the removal everywhere, and its `updatedAt` is raised to the
    removal's instant at least. A write that carries a clock older than the
    tombstone is an edit of a stale snapshot and is still resolved against
    it as concurrent.
12. **A writer that revives an append-only row under a deterministic id
    carries the stored clock.** The recommendation decision and its source
    set read the stored version, tombstone included, and build on its clock.

### Consequences

- `Converged`, `NoLostSuccessor` and `LocalWriteTakesEffect` hold for the
  removal kind on three replicas with stale and clockless writes and a clock
  that lags by one tick (`AgentReplicationRemoval`), and on two replicas
  with any delivery lost and recovered by backfill
  (`AgentReplicationRemovalLossy`). Each switch set back has a
  counterexample (`specs/tla/README.md`). The other configurations keep
  their state counts.
- A bundle of N agent entities costs N primary-key reads, each in its own
  receive transaction, instead of one batched read before them. Every
  removal costs one primary-key read, as a write to a mutable register does.
- On a mutable register a removal wins over a concurrent edit only when it
  is the later of the two: an edit made after a removal it had not seen
  brings the entity back on every device. On an append-only variant the
  removal always wins.
- A row built afresh over a removed one always brings it back. The writers
  that do so read with `getEntity`, which hides the tombstone, so they
  cannot tell a re-creation from a first creation. Three writers re-create
  under a reused id today: the day plan's drafting, the recommendation
  decision, and the seeding of the default templates and souls
  (`AgentTemplateSeeding.seedDefaults`, `SoulTemplateOps.seedDefaults`),
  which runs at every start and creates a default the user deleted again.
  The seeding did so before this change too, on the starting device and,
  unless a peer's clock ran ahead, on the others. That the removal of a
  default does not stick is a product question this change does not
  decide: the options are to seed only on a first start, to skip an id
  whose tombstone is stored, or to keep restoring the defaults.
- An append-only row re-created afresh (no clock) under a reused id is
  written as given, without reading the stored version: only removals of
  append-only variants read it, to keep appends at one write. The one such
  writer, the recommendation decision, carries the stored clock itself.
- Residuals: the soul-assignment swap and `approveSoulProposal` above stay
  open. Hard deletes (`AgentRepository.hardDeleteAgent`, retention pruning)
  leave no tombstone and are not synced, so a late copy can still restore
  such a row; they are unchanged.

## Related

- [ADR 0068](./0068-model-checked-agent-convergence.md): the entity
  resolver, the local write resolution and the `RankDrop` condition
- [ADR 0078](./0078-entry-link-versions-are-ordered.md): the same class of
  hole for journal entry links
- `specs/tla/EvolutionSession.tla`, `specs/tla/AgentLinks.tla`,
  `specs/tla/AgentReplication.tla` (the removal kind),
  `specs/tla/VersionHeads.tla`, `specs/tla/README.md`
- [Templates, souls and evolution](../../knowledge/features/agents/templates-souls-evolution.md)
- [Agent persistence and sync](../../knowledge/features/agents/persistence-and-sync.md)
- [Vector clocks and conflicts](../../knowledge/features/sync/vector-clocks-and-conflicts.md)

---

### Adr 0082 Model Checked Goal Registers (`docs/adr/0082-model-checked-goal-registers.md`)

# ADR 0082: Phase A Takes Turns, Builds on What It Read, and Escalates With Its Register

- Status: Accepted
- Date: 2026-09-25

## Context

ADR 0054 made goal Phase A deterministic and idempotent: every device
recomputes the day's `goalProgress` row from its own journal and writes it
wholesale, so replicas converge instead of coordinating. A recompute carries
the clock of the row it builds on, so it dominates that row. A transition
against the last persisted status makes the LLM tier worth waking. A later
change parked that escalation behind a device-local 120-second countdown.

`specs/tla/GoalRegister.tla` models one goal-day across devices: evidence
written anywhere and synced in any order, Phase A running from two lanes (the
wake orchestrator for local writes, the sync dispatcher for synced ones),
register rows resolved by clock and then by timestamp, the lease-elected
Phase B report, crashes, and devices that never return. With the code as it
was, TLC found the standing report contradicting the day's status with no
fault at all, and four holes behind it:

1. **Interleaved lanes buried evidence.** A local run read the journal, the
   dispatcher's run committed a synced check-off, and the local run then
   committed its older snapshot on top. Carrying the clock made the stale row
   dominate on every device, and nothing re-triggered.
2. **A stale report was never corrected.** The lease can elect a device whose
   journal is still behind. Its report states the old status while every
   register already carries the new one, so no device ever sees a transition.
3. **A crash lost synced evidence.** The dispatcher's queue lives in memory.
   A row applied just before the process died was evaluated by nobody that day.
4. **A dying device took its escalation along.** The countdown was
   device-local. Its peers held the synced register with the new status, and
   saw no transition.

## Decision

1. **Runs of one goal take turns on a device.**
   `GoalAgentPhaseA.runExclusive` serializes the orchestrator, the sync
   dispatcher and Phase B's report refresh per goal.
2. **A commit builds only on the row and the report its derivation read.**
   When the day's row, or today's report, has changed since the derivation,
   `persistDerivation` returns `GoalPersistOutcome.stale` and the run derives
   again, up to `goalPersistAttempts` times. This covers a peer's row that
   syncs in mid-run, which the lock cannot see. A Phase B report refresh that
   exhausts its attempts ends without inference.
3. **A report for today that states another status escalates.**
   `GoalWakeFacts.needsEscalation` is now `statusTransitioned ||
   reportContradicted`. Only a report written today under the same spec
   counts, so a Phase B that failed to write one is not retried on every tick.
4. **Startup recomputes every active goal.**
   `GoalRuntimeMaintenance` runs Phase A directly. It does not go through
   the wake orchestrator, because a manual wake clears the throttle and the
   pending refresh deadline being restored beside it.
5. **An escalation commits with its register.** A status the report does not
   state, or an eligible banner expiry, arms the synced escalation in the
   register's transaction. The deadline stays period-derived, so the lease's
   identical-record guarantee (ADR 0069) holds. Evidence that leaves the
   status alone still coalesces behind the countdown.
6. **An unchanged run writes nothing.** A register row this run would
   reproduce is left alone. So is a cadence record already pending for that
   tick.

**Rejected: recomputing when a peer's register row or report syncs in.** It
would heal a stale row a lagging device left behind. But views legitimately
diverge: a private entry that one device hides, or a time zone that puts an
entry on another day. Under divergence each device answers the other's row
forever (`OnSynced = "recompute"` breaks `Bounded`), and every escalating
round is a paid Phase B run. Damped variants bound the loop but still cannot
heal the case that matters. In that case the harmful write is the lagging
device's *own* recompute, from a journal still missing evidence.

## Consequences

- A status change now wakes Phase B as soon as the lease settles, instead of
  after the 120-second countdown. Skip once skips only the countdown for
  evidence-only changes. With automatic updates off, nothing is armed.
- Devices whose views of the journal disagree can escalate once per organic
  event each, where they used to escalate only on a transition. The cost is
  bounded by events, not by the disagreement (`GoalRegisterDivergent`).
- **Residual:** a device that recomputes, or runs Phase B, from a journal
  still missing evidence and then never comes back leaves a row or a report
  that no peer can tell is stale. A device that returns heals it. Its startup
  recompute and the evidence that syncs in fix the row, and a contradicted
  report re-escalates. Healing it without the device would need evidence
  ordering in the register.

## Verification

Four TLC configurations check the code as it is now, with 3,642,165 distinct
states in total. `GoalRegisterDeath` claims only `EscalationDurable`.
Reverting each decision breaks a property in 6 to 17 steps. The Dart
regressions in `goal_agent_phase_a_test.dart`,
`goal_runtime_maintenance_test.dart` and `goal_agent_providers_test.dart`
each fail with their decision reverted. `specs/tla/README.md` has the traces.

---

### Adr 0083 Model Checked Journal Replication (`docs/adr/0083-model-checked-journal-replication.md`)

# ADR 0083: Model-Checked Journal Replication

- Status: Accepted
- Date: 2026-09-25

## Context

Journal entries — tasks, notes, habit completions, checklists, the user's own
data — sync between devices through one write decision,
`JournalDb.updateJournalEntity` with `detectConflict`: the stored row, read in
the write's transaction, against the incoming vector clock. A newer version
applies, an equal or older one is refused, and a concurrent one is stored as
the entry's `Conflict` row for the user to decide. Deleting an entry is a
version too: `deletedAt` set under the next clock. Unlike agent entities
(ADR 0068, ADR 0081's addendum), journal entries never merge on their own.
The question is therefore not only whether devices converge, but whether a
divergence is ever silent, with a version dropped and no conflict to show for
it.

No spec covered this. We wrote the code as it stood in
`specs/tla/JournalReplication.tla` — two or three devices, edits and
deletions of the stored row and of an entry a screen read earlier, restores,
label writes, the user's resolutions, deliveries in any order and any number of
times, lost deliveries recovered by backfill, and the JSON sidecar that is a
device's sync payload — and model-checked it. TLC found these holes:

1. **A late copy undid a deletion.** The write decision read the stored row
   with `entityById`, which filters `deleted = false`, so a deletion read as no
   row and any version replaced it (`NoLostSuccessor`, six steps: A edits and
   deletes an entry, and A's edit, arriving late at B after the deletion,
   brings it back there). The same read let an edit made concurrently with a
   deletion replace it without a conflict (`NothingDropped`).
2. **Backfill could not serve a deletion.** The responder and the verifier
   read the same way, so a device that lost a deletion was answered `deleted`,
   settled the gap with nothing applied, and kept the entry (`Converged`, four
   steps).
3. **The conflict page could not open a deletion made here.** With 1 fixed, an
   edit arriving over a local deletion is a delete-versus-edit conflict, but
   the page read the local side with `journalEntityById` and showed "entry not
   found" (`ConflictResolvable`). The delete-versus-edit view existed and was
   unreachable.
4. **Any applied write settled the open conflict.** A local edit, or any newer
   version received, marked the entry's conflict resolved even when it did not
   include the conflicting version, which then vanished from the device without
   the user choosing (`NothingDropped`, five steps).
5. **A late copy regressed an open conflict.** A concurrent version always
   replaced the conflict row, so an older copy arriving late replaced the newer
   version the user was shown (`ConflictNotStale`, seven steps).
6. **Label writes overwrote what synced in.** `LabelsRepository.setLabels`
   retried a refused write with `overrideComparison`, over a version that had
   arrived meanwhile (`NothingDropped`, four steps).
   `suppressLabelOnTask` wrote the task under its stored clock, which every
   device refuses as equal, and forced it locally with `overrideComparison`: a
   suppressed label never synced, and the devices differed for good
   (`Converged`, three steps).
7. **A clockless copy replaced a clocked row.** `detectConflict` read a missing
   clock on either side as "incoming is newer", so a late copy of an entry
   created before clocks existed undid every later edit and deletion
   (`NoLostSuccessor`, three steps).
8. **A refused receive left the sender's JSON in the sidecar.** For an older
   peer's envelope, which names only a path, `SmartJournalEntityLoader` saves
   the incoming JSON over the sidecar before the write decision; when the
   decision refused it, the sidecar described a version the device does not
   hold (`SidecarMatchesRow`).
9. **The outbox's sidecar refresh could write an older row.**
   `OutboxEnqueueWriter.enqueueJournalEntity` read the row with
   `journalEntityById` and saved it outside the sidecar queue, so a refresh that
   read before a newer commit could land after that commit's write
   (`SidecarMatchesRow`).

Two suspected gaps did not hold up. The sidecar queue itself
(`_publishSidecar`'s tickets) keeps the newest committed version on disk in
any call order. And the sidecar is written before the receive's enclosing
transaction commits, so a receive rolled back by a failed embedded link leaves
the sidecar describing a version that is not stored — but the event is
retried, and the model's rollback configuration shows the retry heals it.

## Decision

1. **Sync orders versions against the stored row, deletion included.**
   `JournalDb.entityByIdIncludingDeleted` / `journalEntityByIdIncludingDeleted`
   is what the write decision, the backfill responder and verifier, the
   receive's stale-descriptor check and its sequence-log receipt, and the
   conflict page read. A creation (`overwrite: false`) still replaces a deleted
   row, as before.
2. **Two concurrent deletions are merged, not a conflict.** Each device keeps
   the canonically greater deletion's fields under the join of both clocks
   (`VectorClock.compareCanonically`, `VectorClock.merge`), so every device
   computes the same row and it covers both. There is nothing for the user to
   choose.
3. **An applied write settles only a conflict it includes.** The entry's
   unresolved conflict is marked resolved when the written version's clock
   covers the conflict's — the user's resolution, or any later version built
   on it — and stays open otherwise.
4. **A conflict row is not replaced by an older version.** A concurrent
   version is stored as the conflict only when the open conflict does not
   already hold it or a newer one.
5. **A label write builds on the stored row, never over it.** `setLabels` and
   `suppressLabelOnTask` go through `LabelsRepository._writeOnStored`: the
   change is built on the stored entry under a new clock and applied with a
   `precondition` that the stored row is still that one; otherwise it is built
   again on the newer row, three times at most. `overrideComparison` had no
   other caller and is gone from `updateJournalEntity`,
   `PersistenceLogic.updateDbEntity` and the contract.
6. **A clockless version never replaces a clocked row.** It is refused as
   older; it still replaces a row without a clock, and a clocked version still
   replaces a clockless row.
7. **The sidecar has one writer: the queue.** `JournalDb.restoreSidecar`
   reads the stored row, deletion included, and takes a ticket in one
   transaction, then writes through `_publishSidecar`. The receive calls it
   when it refused a path-only envelope, and the outbox's refresh is it. A
   failed restore fails the receive before it is recorded, so the event is
   retried with the restore, as a rolled-back receive is
   (`JournalReplicationSidecarRollback`).
8. **Resolving over a deletion made here keeps the entry's labels.**
   `PersistenceLogic.updateJournalEntity` reads the stored row with its
   deletion to preserve labels, as it does for a live one.
9. **The model gates the code**, as in ADR 0065: `specs/tla/JournalReplication.tla`
   with six configurations in CI, and a Glados trace in the `JournalDb`
   entity-ops suite that drives three real databases through generated
   interleavings and checks the model's invariants.

## Consequences

- `Converged`, `NoLostSuccessor`, `NothingDropped`, `ConflictNotStale` and
  `ConflictResolvable` hold for three devices with stale reads, restores and
  resolutions; for two with lossy delivery, with label writes, and with a
  clockless original; and `SidecarMatchesRow` with path-only receives, the
  outbox refresh and a rolled-back receive. Each switch set back has a
  counterexample (`specs/tla/README.md`).
- A deleted entry now stays deleted on every device: a late copy of an older
  version is refused, a lost deletion arrives by backfill, and an edit made
  concurrently with a deletion is a delete-versus-edit conflict for the user
  on both devices, where before the edit silently won on the deleting device.
  Users see those conflicts where they used to see a deleted entry come back.
- An open conflict stays open until a version that includes it is written. A
  local edit no longer dismisses a peer's concurrent edit.
- A label assignment or suppression made while another version syncs in is
  applied on top of it instead of replacing it, and a suppression now syncs.
- Each refused receive from an older peer, and each outbox enqueue of a
  journal entry, costs one primary-key read and a sidecar write in the queue.
- Residuals needing a decision, recorded in `specs/tla/README.md`:
  - **One conflict row per entry.** A second concurrent version (a third
    device, or this device's own save refused while a conflict is open)
    displaces the first on this device. A peer's displaced version is raised
    again from its own device; a displaced local save was never sent and is
    lost. Options: conflicts keyed by entry and version with the page listing
    them all, a three-way choice, or refusing a local save while its entry has
    an open conflict.
  - **Concurrent edits never merge on their own.** Auto-merging disjoint
    fields, or last-writer-wins, would change what the user is asked.
  - **A creation under a reused id replaces a deleted row** under a clock that
    does not cover it, so peers ask the user. Whether a re-creation wins, loses
    or asks is open.
  - A deletion displaced from the conflict table on a third device may never
    meet a concurrent deletion; the devices then hold different deletions of
    the entry, all deleted.
- Not changed: hard deletes (`purgeDeleted`) leave nothing to serve, so a
  device that never received the deletion keeps the entry; on one device the
  last save supersedes an earlier one it did not read.

## Related

- [ADR 0065](./0065-model-checked-sync-sequence-reservations.md): the sequence
  log and backfill
- [ADR 0068](./0068-model-checked-agent-convergence.md) and
  [ADR 0081](./0081-model-checked-evolution-sessions-and-agent-links.md)
  (addendum): the same tombstone holes for agent entities
- [ADR 0078](./0078-entry-link-versions-are-ordered.md): entry links
- [ADR 0080](./0080-a-present-counter-ranks-above-an-absent-host.md): how
  absent hosts compare
- `specs/tla/JournalReplication.tla`, `specs/tla/README.md`
- [Vector clocks and conflicts](../../knowledge/features/sync/vector-clocks-and-conflicts.md)

---

--- METRICS ---
- Files Extracted: 101
- Estimated Token Budget: ~240476 tokens
- Canonical Reference: https://codewiki.google/github.com/matthiasn/lotti
