diff --git a/changelog.d/2026-11-29-agent-history-summary-bounded.md b/changelog.d/2026-11-29-agent-history-summary-bounded.md new file mode 100644 index 0000000000..74a981a33b --- /dev/null +++ b/changelog.d/2026-11-29-agent-history-summary-bounded.md @@ -0,0 +1,7 @@ +### Changed +- **An agent's summary of a long-running project or task no longer grows + without end, and its older parts are no longer rewritten.** The summary is + kept in sections: a finished one is set aside as written, and only the + newest is ever updated, so earlier decisions cannot be dropped by a later + rewrite. The agent reads the most recent sections and can search the older + ones. diff --git a/docs/adr/0174-a-log-summary-is-frozen-sections-and-one-open-one.md b/docs/adr/0174-a-log-summary-is-frozen-sections-and-one-open-one.md new file mode 100644 index 0000000000..33486c2187 --- /dev/null +++ b/docs/adr/0174-a-log-summary-is-frozen-sections-and-one-open-one.md @@ -0,0 +1,80 @@ +# ADR 0174: A Log Summary Is Frozen Sections and One Open One + +- Status: Accepted +- Date: 2026-11-29 +- Concepts: [agent memory and compaction](../../knowledge/features/agents/memory-and-compaction.md) +- Amends: [ADR 0017](./0017-deterministic-log-compaction.md) — the shape of a + checkpoint's text; its coverage and selection are untouched +- Replaces, for the event log: the hierarchy + [ADR 0057](./0057-decade-scale-agent-memory.md) decision 3 proposed + +## Context + +A summary checkpoint held one running text. Every fold handed the whole of it +back to the model, with the newly folded entries, to be written again. + +Two things follow, and the long-log run measured both +([agent log summary](../evaluations/agent_log_summarizer.md)). The text grows +with the log — 56 to 97 words a fold on a busy one, with nothing to stop it — +and a rewrite of everything is where history is lost: cut at the completion +cap, or collapsed to a fraction of what it was given. ADR 0172 refuses those +results, which turns loss into a stall: a summary that has outgrown the cap +is refused on every wake and nothing more is compacted. + +ADR 0057 proposed a hierarchy above the running summary: quarters folded into +epoch summaries, epochs into years. That is more rewriting of summaries by +models, which is the step that fails. + +## Decision + +1. **A summary is sections.** Frozen ones, oldest first, and one open + section. A checkpoint's payload stores them (`summarySections`, + `summaryOpen`, `summaryOpenFrom`) beside the text a prompt shows. +2. **A fold rewrites only the open section.** The model is given the open + section's text and the folded entries, a batch of at most 12,000 tokens at + a time. Frozen sections are carried from checkpoint to checkpoint by code. + No model is handed one again, so it cannot be cut, collapsed or drift. +3. **An open section past 600 words is frozen**, with the days its entries + entered the log, and the next fold starts a new one from the entries + alone. 600 is the size every model in the run rewrote without loss. The + days are capture time, not when an entry was written: that is what + `search_memory` filters a period by, so a section's days are days a recall + can ask for, and they never run backwards when an old note is captured + late. +4. **A prompt shows the newest sections it has room for.** Frozen sections + newest first within 3,000 tokens — the newest always — then the open one, + each under its days. When older ones do not fit, one line says how many + there are, what days they cover, and that `search_memory` reaches + everything in them (ADR 0173). +5. **Nothing changes until a section is frozen.** With none, the summary is + its open text, byte for byte the single running summary it was. +6. **One checkpoint, as before.** A checkpoint still covers a log prefix up + to a cutoff, is still selected by the longest valid prefix, and still dies + when a late event sorts before its cutoff (ADRs 0017, 0071). Only its text + has structure. `summaryText` remains the rendered text, so a build from + before this reads a new checkpoint as it always has, and a checkpoint from + before this is one open section of its whole text. + +## Consequences + +- What a wake reads of its older history is bounded: about 3,000 tokens of + frozen sections, an open section of at most 600 words and a fold's growth, + and one line. Before, it grew without limit. +- A fold costs the same however old the log is: it reads one section, not + the whole summary. +- **Old sections leave the prompt.** A decision from a section no longer + shown is in the agent's view only if it searches. The index line tells it + there is something to search; nothing keeps an early decision always in + view. If that proves to matter, the answer is a small keyed store of + standing decisions (ADR 0057 decision 1 has one for goal agents), not a + summary of summaries. +- A checkpoint invalidated by a late arrival is rebuilt from the whole log, + as before, and its sections with it: a batch at a time, freezing as they + fill. Rebuilding only the sections after the late event would be cheaper + and is not done. +- The stall ADR 0172 left is gone: the model never rewrites more than one + section, so the summary cannot outgrow the completion cap. +- Run on three models, twelve folds and 120 planted decisions each: every + model holds all 120, with the first section frozen at the seventh to tenth + fold. Twelve folds freeze one section, which fits the prompt, so sections + leaving the prompt is held by unit tests, not by a live run. diff --git a/docs/evaluations/agent_log_summarizer.md b/docs/evaluations/agent_log_summarizer.md index a6dabdfb87..f3f6670a54 100644 --- a/docs/evaluations/agent_log_summarizer.md +++ b/docs/evaluations/agent_log_summarizer.md @@ -64,14 +64,30 @@ Gemini and Ollama were not run. Their adapters dropped the reason a completion stopped; they now report a cut the same way, held by unit tests on each adapter, not by a live run. +## 2026-11-29 — with ADR 0174: the summary as sections + +The same log, folded as production now folds it: frozen sections the model +never sees again, and one open section each fold extends. Two counts a fold: +decisions the summary still holds, and decisions in the text a wake is shown. + +| Model | Decisions held after 12 folds | Shown to a wake | First section frozen | Folds refused | +| --- | ---: | ---: | --- | ---: | +| glm-5.3 | 120 of 120 | 120 of 120 | eighth fold | 0 | +| DeepSeek Flash v4.1 | 120 of 120 | 120 of 120 | seventh fold | 0 | +| Mistral Large 4 | 120 of 120 | 120 of 120 | tenth fold | 0 | + +Each model keeps everything, and no fold rewrites more than one section. The +shown and held counts are the same because twelve folds freeze one section, +which fits the 3,000 tokens a wake is shown: this run does not reach the +point where an old section leaves the prompt. That is held by +`summary_sections_test.dart`, deterministically; a live run of it needs a +log three or four times this long. + ## What this does not settle -- **The summary still grows with the log.** 56 to 97 words a fold here, and - nothing bounds it. At 8,000 tokens a log this busy reaches the cap after - some fifty folds; from then on every fold is refused and nothing more is - compacted. That is visible rather than silent, and it is not a fix. A - bounded summary — frozen pieces, an index, and recall for the rest, as the - goal agents' digests have — is the work this leaves. +- **Sections leaving the prompt.** Once they do, a decision in one is in the + agent's view only if it searches (ADR 0173). Whether the models then search + when they should has not been run. - One sample a cell, two for DeepSeek. The 2,048 failures repeated in every run; their exact fold did not. - No model was run past twelve folds. diff --git a/knowledge/features/agents/memory-and-compaction.md b/knowledge/features/agents/memory-and-compaction.md index 8bbc2bddbb..7b16ea37e3 100644 --- a/knowledge/features/agents/memory-and-compaction.md +++ b/knowledge/features/agents/memory-and-compaction.md @@ -248,6 +248,48 @@ in the summary prose and are never reloaded. compaction this wake") rather than persisting an empty checkpoint that would erase folded memory. +## The summary is sections + +A checkpoint's text is not one running summary but **sections** (ADR 0174, +`lib/features/agents/projection/summary_sections.dart`): frozen ones, oldest +first, and one open section. + +```mermaid +stateDiagram-v2 + [*] --> Open: first fold writes it from the folded entries + Open --> Open: a later fold rewrites it with the next entries + Open --> Frozen: past 600 words — stamped with the days its entries entered the log + Frozen --> Frozen: carried to the next checkpoint by code, never rewritten + Frozen --> [*]: checkpoint invalidated by a late arrival — rebuilt from the log +``` + +- **`foldIntoSections`** hands the model only the open section and the folded + entries, a batch of at most `summaryFoldBatchTokens` (12,000) at a time, + and freezes the open section once it passes `summarySectionFreezeWords` + (600). A frozen section is never sent to a model again, so the failures a + rewrite of everything had — a cut, a collapse, a text that grows with the + log — cannot reach it. A fold costs the same however old the log is. A + section is dated by when its entries entered the log (`EventPosition.at`), + not by when they were written: the date `search_memory` filters a period + by, so the days a section names are days a recall can ask for. +- **`renderSummarySections`** is the text a prompt shows, stored as the + checkpoint's `summaryText`: the newest frozen sections that fit + `summaryShownSectionTokens` (3,000) — the newest always — then the open + one, each under the days it covers. When older sections do not fit, one + line ahead of them says how many there are, what days they cover, and that + `search_memory` reaches everything in them. +- **With nothing frozen the summary is its open text alone**, byte for byte + the single running summary it was; a log changes shape only once it has + outgrown one section. +- **The payload stores the structure** (`summarySections`, `summaryOpen`, + `summaryOpenFrom`) beside `summaryText`. A build from before sections reads + `summaryText` as it always has; a checkpoint from before sections is one + open section of its whole text, frozen by the fold that takes it past the + limit. +- **Coverage is untouched.** One checkpoint still covers a log prefix up to + its cutoff, and `selectActiveSummary` neither knows nor cares what shape + the text has. + ## Cadence and prefix caching `AgentLogCompactor.compactAndAssemble` uses two watermarks: diff --git a/lib/features/agents/projection/summary_sections.dart b/lib/features/agents/projection/summary_sections.dart new file mode 100644 index 0000000000..3e567527f3 --- /dev/null +++ b/lib/features/agents/projection/summary_sections.dart @@ -0,0 +1,271 @@ +/// The bounded form of an agent log's summary (ADR 0174). +/// +/// A summary checkpoint used to hold one running text, and every fold handed +/// the whole of it back to the model to be written again. It grew with the +/// log, and a rewrite could cut or drop what it was given (ADR 0172). Here +/// the summary is **sections**: frozen ones, written once and carried from +/// checkpoint to checkpoint by code, never sent to a model again, and one +/// open section that the next fold extends. A prompt shows the newest +/// sections it has room for and says what the rest cover. +library; + +import 'package:equatable/equatable.dart'; +import 'package:lotti/features/agents/projection/compaction_summary.dart'; +import 'package:lotti/features/agents/projection/input_capture.dart'; +import 'package:lotti/features/ai/service/text_chunker.dart'; + +/// Words past which the open section is frozen and a new one begun. A +/// section is what one model call can be trusted to rewrite whole: the +/// long-log run kept every decision in summaries of this size on every +/// model, and lost them in longer ones. +const int summarySectionFreezeWords = 600; + +/// Tokens of frozen sections a prompt shows, newest first. With the open +/// section this bounds the summary a wake reads, whatever the log's age. +const int summaryShownSectionTokens = 3000; + +/// Tokens of entries one fold call is given. A fold larger than this — the +/// first of a long-lived log, or one rebuilt after a late arrival — is cut +/// into batches so its sections freeze as they fill, instead of one batch +/// writing a single section of everything. +const int summaryFoldBatchTokens = 12000; + +/// One finished stretch of a log's summary. +class SummarySection extends Equatable { + const SummarySection({ + required this.from, + required this.to, + required this.text, + }); + + /// Parses a stored section, or null when it is not one. + static SummarySection? fromJson(Object? raw) { + if (raw is! Map) return null; + final from = DateTime.tryParse(raw['from']?.toString() ?? ''); + final to = DateTime.tryParse(raw['to']?.toString() ?? ''); + final text = raw['text']; + if (from == null || to == null || text is! String || text.trim().isEmpty) { + return null; + } + return SummarySection(from: from, to: to, text: text); + } + + /// When the first entry it covers entered the log. + final DateTime from; + + /// When the last entry it covers entered the log. + final DateTime to; + + final String text; + + Map toJson() => { + 'from': from.toUtc().toIso8601String(), + 'to': to.toUtc().toIso8601String(), + 'text': text, + }; + + @override + List get props => [from, to, text]; +} + +/// A log's summary as sections: the [frozen] ones, oldest first, and the +/// [open] one the next fold extends. +class SummarySections extends Equatable { + const SummarySections({ + this.frozen = const [], + this.open = '', + this.openFrom, + }); + + /// A summary written before sections existed: its whole text is the open + /// section, and the next fold that takes it past the limit freezes it. + const SummarySections.legacy(String text) + : frozen = const [], + open = text, + openFrom = null; + + /// Reads the sections a checkpoint payload stores, or its legacy + /// [summaryText] when it stores none. + factory SummarySections.fromPayload( + Map content, { + required String summaryText, + }) { + final rawFrozen = content[frozenKey]; + final rawOpen = content[openKey]; + if (rawFrozen is! List && rawOpen is! String) { + return SummarySections.legacy(summaryText); + } + return SummarySections( + frozen: [ + if (rawFrozen is List) + for (final raw in rawFrozen) ?SummarySection.fromJson(raw), + ], + open: rawOpen is String ? rawOpen : '', + openFrom: DateTime.tryParse(content[openFromKey]?.toString() ?? ''), + ); + } + + /// Payload key of the frozen sections. + static const frozenKey = 'summarySections'; + + /// Payload key of the open section's text. + static const openKey = 'summaryOpen'; + + /// Payload key of when the open section's first entry entered the log. + static const openFromKey = 'summaryOpenFrom'; + + final List frozen; + final String open; + + /// When the open section's first entry entered the log; null while it is + /// empty, and on a legacy summary, whose start was never recorded. + final DateTime? openFrom; + + /// What a checkpoint payload stores beside its rendered `summaryText`. + Map toPayload() => { + frozenKey: [for (final section in frozen) section.toJson()], + openKey: open, + if (openFrom != null) openFromKey: openFrom!.toUtc().toIso8601String(), + }; + + @override + List get props => [frozen, open, openFrom]; +} + +/// One folded entry and when it entered the log (`EventPosition.at`). +/// +/// A section is dated by that, not by when the entry was written: it is the +/// date `search_memory` filters a period by and the one a hit shows, so the +/// days a section names are days a recall can ask for. It also only ever +/// moves forward through a fold, where an old note captured late would give +/// a section a range that runs backwards. +typedef FoldedSource = ({RenderedSource source, DateTime at}); + +/// Writes one section's text from [sources], extending [priorSummary] when +/// there is one — the summarizer, which a fold calls once per batch. +typedef SummarySectionWriter = + Future Function({ + required List sources, + String? priorSummary, + }); + +int _words(String text) => + text.trim().isEmpty ? 0 : text.trim().split(RegExp(r'\s+')).length; + +/// Folds [sources] (oldest first) into [prior]'s open section and freezes it +/// whenever it passes [freezeWords]. +/// +/// The frozen sections of [prior] are returned as they are: no model is +/// handed them. Only the open section is rewritten, a batch of at most +/// [batchTokens] at a time. A [write] that throws ends the fold with nothing +/// changed for the caller — the existing "no compaction this wake". +Future foldIntoSections({ + required SummarySections prior, + required List sources, + required SummarySectionWriter write, + int freezeWords = summarySectionFreezeWords, + int batchTokens = summaryFoldBatchTokens, +}) async { + final frozen = [...prior.frozen]; + var open = prior.open.trim(); + var openFrom = prior.openFrom; + + for (final batch in _batches(sources, batchTokens)) { + open = (await write( + sources: [for (final folded in batch) folded.source], + priorSummary: open.isEmpty ? null : open, + )).trim(); + openFrom ??= batch.first.at; + if (_words(open) > freezeWords) { + frozen.add( + SummarySection(from: openFrom, to: batch.last.at, text: open), + ); + open = ''; + openFrom = null; + } + } + return SummarySections(frozen: frozen, open: open, openFrom: openFrom); +} + +List> _batches( + List sources, + int batchTokens, +) { + final batches = >[]; + var current = []; + var tokens = 0; + for (final folded in sources) { + final cost = TextChunker.estimateTokens( + renderCompactedSourceLine(folded.source), + ); + if (current.isNotEmpty && tokens + cost > batchTokens) { + batches.add(current); + current = []; + tokens = 0; + } + current.add(folded); + tokens += cost; + } + if (current.isNotEmpty) batches.add(current); + return batches; +} + +String _day(DateTime at) => at.toUtc().toIso8601String().substring(0, 10); + +String _span(DateTime from, DateTime to) => + _day(from) == _day(to) ? _day(from) : '${_day(from)} to ${_day(to)}'; + +/// The summary text a prompt shows for [sections]: the newest frozen +/// sections that fit [shownTokens], oldest of them first, then the open one — +/// each under the days it covers — and, ahead of them, one line saying how +/// many older sections there are, what days they cover, and that +/// `search_memory` reaches them. +/// +/// With nothing frozen the summary is its open text alone, byte for byte +/// what a single running summary was: a log changes shape only once it has +/// outgrown one section. +String renderSummarySections( + SummarySections sections, { + int shownTokens = summaryShownSectionTokens, +}) { + final open = sections.open.trim(); + if (sections.frozen.isEmpty) return open; + + final shown = []; + var spent = 0; + for (final section in sections.frozen.reversed) { + final cost = TextChunker.estimateTokens(section.text); + // The newest frozen section is always shown: it is what the open one + // continues from. + if (shown.isNotEmpty && spent + cost > shownTokens) break; + shown.insert(0, section); + spent += cost; + } + final hidden = sections.frozen.length - shown.length; + + final buffer = StringBuffer(); + if (hidden > 0) { + final first = sections.frozen.first; + final last = sections.frozen[hidden - 1]; + buffer + ..writeln( + '($hidden earlier ${hidden == 1 ? 'section' : 'sections'} of this ' + 'summary, covering ${_span(first.from, last.to)}, ' + '${hidden == 1 ? 'is' : 'are'} not shown. search_memory reaches ' + 'everything in them, by words or by period.)', + ) + ..writeln(); + } + for (final section in shown) { + buffer + ..writeln('[${_span(section.from, section.to)}]') + ..writeln(section.text.trim()) + ..writeln(); + } + if (open.isNotEmpty) { + final from = sections.openFrom; + if (from != null) buffer.writeln('[since ${_day(from)}]'); + buffer.writeln(open); + } + return buffer.toString().trimRight(); +} diff --git a/lib/features/agents/sync/agent_log_compactor.dart b/lib/features/agents/sync/agent_log_compactor.dart index ae4d1d1dc5..f79e13c8e5 100644 --- a/lib/features/agents/sync/agent_log_compactor.dart +++ b/lib/features/agents/sync/agent_log_compactor.dart @@ -10,6 +10,7 @@ import 'package:lotti/features/agents/projection/compaction_summary.dart'; import 'package:lotti/features/agents/projection/content_digest.dart'; import 'package:lotti/features/agents/projection/input_capture.dart'; import 'package:lotti/features/agents/projection/input_events.dart'; +import 'package:lotti/features/agents/projection/summary_sections.dart'; import 'package:lotti/features/agents/sync/agent_log_compactor_models.dart'; import 'package:lotti/features/agents/sync/agent_sync_service.dart'; import 'package:lotti/features/ai/service/text_chunker.dart'; @@ -192,6 +193,20 @@ class AgentLogCompactor { /// tagged with their type so both the prompt tail and the summarizer's fold /// input render them as observation-tagged lines (inline events already /// carry their type). + /// The sections [active] stores, to be extended by the next fold; none + /// when there is no checkpoint, and a checkpoint written before sections + /// existed is one open section of its whole text. + Future _sectionsOf(SummaryCheckpoint? active) async { + if (active == null) return const SummarySections(); + final payload = await _repository.getEntity(active.contentDigest); + return payload is AgentMessagePayloadEntity + ? SummarySections.fromPayload( + payload.content, + summaryText: active.summaryText, + ) + : SummarySections.legacy(active.summaryText); + } + static RenderedSource _toRenderedSource( InputEvent event, Map content, @@ -617,12 +632,20 @@ class AgentLogCompactor { ContentDigest.of(loaded.content), }; - final summaryText = await summarize( + // The summary is sections (ADR 0174): the prior checkpoint's frozen + // ones are carried over as they are, and only its open section is handed + // to the model with the folded entries. + final sections = await foldIntoSections( + prior: await _sectionsOf(view.active), sources: [ for (final loaded in folded) - _toRenderedSource(loaded.event, loaded.content), + ( + source: _toRenderedSource(loaded.event, loaded.content), + // The time recall filters a period by, not when it was written. + at: loaded.event.position.at, + ), ], - priorSummary: view.active?.summaryText, + write: summarize, ); final payloadContent = { @@ -632,7 +655,9 @@ class AgentLogCompactor { 'key': cutoff.key, }, 'coveredSources': coveredSources, - 'summaryText': summaryText, + // What a prompt shows — and all a build from before sections reads. + 'summaryText': renderSummarySections(sections), + ...sections.toPayload(), }; final payloadId = ContentDigest.of(payloadContent); final summaryId = _uuid.v4(); diff --git a/scripts/agent_log_summary_eval.sh b/scripts/agent_log_summary_eval.sh index 9d430926d6..08fcecf449 100755 --- a/scripts/agent_log_summary_eval.sh +++ b/scripts/agent_log_summary_eval.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash # Runs the live check of the agent log summary over a long-running log on one # model and prints, fold by fold, whether the summarizer took the fold, how -# long the summary is, and how many of each earlier fold's ten decisions it -# still names. +# many sections are frozen, how long the summary a wake is shown is beside +# all of it, and how many of the planted decisions it holds and shows. # # Usage: # scripts/agent_log_summary_eval.sh [provider_type] [folds] @@ -55,9 +55,11 @@ print(f"{data['model']} ({data['provider']}), completion cap " f"{data['maxSummaryTokens']}") for row in data['folds']: state = f"REFUSED ({row['refused']})" if 'refused' in row else 'ok' - kept = row['keptPerFold'] - print(f" fold {row['fold']:2d} {state:<44s} {row['words']:5d}w " - f"kept {sum(kept)}/{10 * (row['fold'] + 1)} {kept}") + total = 10 * (row['fold'] + 1) + print(f" fold {row['fold']:2d} {state:<44s} " + f"{row['frozenSections']} frozen, shown {row['shownWords']:5d}w of " + f"{row['storedWords']:5d}w; decisions held {sum(row['keptPerFold'])}" + f"/{total}, shown {sum(row['shownPerFold'])}/{total}") PY echo "Folds: $OUT_DIR/folds.json" diff --git a/test/features/agents/projection/summary_sections_test.dart b/test/features/agents/projection/summary_sections_test.dart new file mode 100644 index 0000000000..dfea14a6ed --- /dev/null +++ b/test/features/agents/projection/summary_sections_test.dart @@ -0,0 +1,323 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:lotti/features/agents/projection/input_capture.dart'; +import 'package:lotti/features/agents/projection/summary_sections.dart'; +import 'package:lotti/features/ai/service/text_chunker.dart'; + +void main() { + /// An entry that entered the log on [day] of March. It was written a + /// year earlier, which no section may be dated by. + FoldedSource entry(int day, [String text = 'an ordinary entry']) => ( + source: RenderedSource( + contentEntryId: 'e$day', + sourceCreatedAt: DateTime.utc(2025, 3, day), + content: {'text': text}, + ), + at: DateTime.utc(2026, 3, day), + ); + + String words(int count, [String word = 'fact']) => + List.filled(count, word).join(' '); + + group('foldIntoSections', () { + test('a fold under the limit extends the open section and remembers ' + 'when it began', () async { + final priors = []; + final folded = await foldIntoSections( + prior: const SummarySections(), + sources: [entry(1), entry(2)], + write: ({required sources, priorSummary}) async { + priors.add(priorSummary); + return ' The colony chose the north ridge. '; + }, + ); + + expect(priors, [null]); + expect(folded.frozen, isEmpty); + expect(folded.open, 'The colony chose the north ridge.'); + expect(folded.openFrom, DateTime.utc(2026, 3)); + + // The next fold hands the open text back and keeps its start. + final next = await foldIntoSections( + prior: folded, + sources: [entry(9)], + write: ({required sources, priorSummary}) async { + priors.add(priorSummary); + return '$priorSummary The move is set for September.'; + }, + ); + expect(priors.last, 'The colony chose the north ridge.'); + expect(next.open, endsWith('September.')); + expect(next.openFrom, DateTime.utc(2026, 3)); + }); + + test('an open section past the limit is frozen with the days it ' + 'covers, and the next fold starts a new one from nothing', () async { + final priors = []; + Future write({ + required List sources, + String? priorSummary, + }) async { + priors.add(priorSummary); + return words(priorSummary == null ? 40 : 61); + } + + final first = await foldIntoSections( + prior: const SummarySections(), + sources: [entry(1)], + write: write, + freezeWords: 60, + ); + expect(first.frozen, isEmpty); + + final second = await foldIntoSections( + prior: first, + sources: [entry(5), entry(8)], + write: write, + freezeWords: 60, + ); + expect(second.frozen.single.from, DateTime.utc(2026, 3)); + expect(second.frozen.single.to, DateTime.utc(2026, 3, 8)); + expect(second.frozen.single.text, words(61)); + expect(second.open, isEmpty); + expect(second.openFrom, isNull); + + final third = await foldIntoSections( + prior: second, + sources: [entry(12)], + write: write, + freezeWords: 60, + ); + // The frozen section is carried as it is and never handed to the + // model: the new open section is written from the entries alone. + expect(priors.last, isNull); + expect(third.frozen, second.frozen); + expect(third.openFrom, DateTime.utc(2026, 3, 12)); + }); + + test('a fold too large for one call is written a batch at a time, so ' + 'its sections freeze as they fill', () async { + final batches = []; + // Each entry is about 100 tokens; a batch of 250 takes two of them. + final sources = [ + for (var day = 1; day <= 6; day++) entry(day, words(75, 'krill')), + ]; + + final folded = await foldIntoSections( + prior: const SummarySections(), + sources: sources, + write: ({required sources, priorSummary}) async { + batches.add(sources.length); + return words(priorSummary == null ? 40 : 70); + }, + freezeWords: 60, + batchTokens: 250, + ); + + expect(batches, [2, 2, 2]); + // Batch 1 opens a section, batch 2 fills and freezes it, batch 3 + // opens the next. + expect(folded.frozen.single.from, DateTime.utc(2026, 3)); + expect(folded.frozen.single.to, DateTime.utc(2026, 3, 4)); + expect(folded.open, words(40)); + expect(folded.openFrom, DateTime.utc(2026, 3, 5)); + }); + + test('an entry larger than a batch still goes through whole', () async { + final seen = []; + await foldIntoSections( + prior: const SummarySections(), + sources: [entry(1, words(400)), entry(2)], + write: ({required sources, priorSummary}) async { + seen.add(sources.length); + return 'ok'; + }, + batchTokens: 50, + ); + + expect(seen, [1, 1]); + }); + + test('a writer that refuses ends the fold with nothing returned', () { + expect( + foldIntoSections( + prior: const SummarySections(open: 'kept'), + sources: [entry(1)], + write: ({required sources, priorSummary}) async => + throw StateError('summary was cut off at the completion cap'), + ), + throwsStateError, + ); + }); + }); + + group('renderSummarySections', () { + SummarySection section(int month, String text) => SummarySection( + from: DateTime.utc(2026, month, 2), + to: DateTime.utc(2026, month, 27), + text: text, + ); + + test('with nothing frozen the summary is its open text alone', () { + expect(renderSummarySections(const SummarySections()), isEmpty); + expect( + renderSummarySections( + SummarySections( + open: ' One running summary. ', + openFrom: DateTime.utc(2026, 3), + ), + ), + 'One running summary.', + ); + }); + + test('frozen sections read oldest first under their days, then the ' + 'open one', () { + final text = renderSummarySections( + SummarySections( + frozen: [section(3, 'March facts.'), section(4, 'April facts.')], + open: 'May so far.', + openFrom: DateTime.utc(2026, 5, 4), + ), + ); + + expect( + text, + '[2026-03-02 to 2026-03-27]\n' + 'March facts.\n' + '\n' + '[2026-04-02 to 2026-04-27]\n' + 'April facts.\n' + '\n' + '[since 2026-05-04]\n' + 'May so far.', + ); + }); + + test('past the budget the oldest sections are left out, and a line ' + 'says how many, what days they cover, and how to reach them', () { + final sections = SummarySections( + frozen: [ + for (var month = 1; month <= 6; month++) + section(month, words(300, 'm$month')), + ], + open: 'Now.', + openFrom: DateTime.utc(2026, 7), + ); + + final text = renderSummarySections(sections, shownTokens: 900); + + expect( + text, + startsWith( + '(4 earlier sections of this summary, covering 2026-01-02 to ' + '2026-04-27, are not shown. search_memory reaches everything in ' + 'them, by words or by period.)', + ), + ); + for (final hidden in ['m1', 'm2', 'm3', 'm4']) { + expect(text, isNot(contains('$hidden '))); + } + expect(text.indexOf('m5 '), lessThan(text.indexOf('m6 '))); + expect(text, endsWith('[since 2026-07-01]\nNow.')); + expect( + TextChunker.estimateTokens(text), + lessThan(900 + 100), + reason: 'the shown sections stay within their budget', + ); + }); + + test('the newest frozen section is shown whatever it costs, and one ' + 'hidden section is named in the singular', () { + final text = renderSummarySections( + SummarySections( + frozen: [section(1, 'January.'), section(2, words(900))], + ), + shownTokens: 10, + ); + + expect(text, contains('(1 earlier section of this summary')); + expect(text, contains(' is not shown.')); + expect(text, contains(words(900))); + expect(text, isNot(contains('January.'))); + }); + + test('a section within one day is labelled with that day', () { + expect( + renderSummarySections( + SummarySections( + frozen: [ + SummarySection( + from: DateTime.utc(2026, 3, 5, 8), + to: DateTime.utc(2026, 3, 5, 20), + text: 'One long day.', + ), + ], + ), + ), + '[2026-03-05]\nOne long day.', + ); + }); + }); + + group('SummarySections payload', () { + test('a payload from before sections is one open section of its text', () { + final sections = SummarySections.fromPayload( + const {'summaryText': 'The old running summary.'}, + summaryText: 'The old running summary.', + ); + + expect(sections.frozen, isEmpty); + expect(sections.open, 'The old running summary.'); + expect(sections.openFrom, isNull); + expect(renderSummarySections(sections), 'The old running summary.'); + }); + + test('sections survive the payload round trip', () { + final sections = SummarySections( + frozen: [ + SummarySection( + from: DateTime.utc(2026, 3, 2), + to: DateTime.utc(2026, 3, 27), + text: 'March facts.', + ), + ], + open: 'April so far.', + openFrom: DateTime.utc(2026, 4, 3), + ); + + expect( + SummarySections.fromPayload(sections.toPayload(), summaryText: 'x'), + sections, + ); + // An empty open section has no start to store. + expect( + SummarySections(frozen: sections.frozen).toPayload().containsKey( + SummarySections.openFromKey, + ), + isFalse, + ); + }); + + test('a stored section that is not one is skipped, not fatal', () { + final sections = SummarySections.fromPayload( + const { + SummarySections.frozenKey: [ + 'not a map', + {'from': 'never', 'to': '2026-03-27T00:00:00Z', 'text': 'x'}, + {'from': '2026-03-02T00:00:00Z', 'to': '2026-03-27T00:00:00Z'}, + { + 'from': '2026-03-02T00:00:00Z', + 'to': '2026-03-27T00:00:00Z', + 'text': 'Kept.', + }, + ], + SummarySections.openKey: 7, + }, + summaryText: 'ignored', + ); + + expect(sections.frozen.single.text, 'Kept.'); + expect(sections.open, isEmpty); + }); + }); +} diff --git a/test/features/agents/service/agent_log_summarizer_eval_live_test.dart b/test/features/agents/service/agent_log_summarizer_eval_live_test.dart index 6fdacf4112..05d2cbeb05 100644 --- a/test/features/agents/service/agent_log_summarizer_eval_live_test.dart +++ b/test/features/agents/service/agent_log_summarizer_eval_live_test.dart @@ -6,8 +6,10 @@ /// again — what a fold drops is gone from the agent's view. This drives the /// real summarizer through twelve folds of about ten thousand tokens of /// ordinary entries, with ten decisions planted in each, every one carrying a -/// word found nowhere else, and counts after every fold how many of each -/// earlier fold's decisions the summary still names. +/// word found nowhere else, folding them into sections as production does +/// (ADR 0174). After every fold it counts how many of each earlier fold's +/// decisions the summary still holds, and how many of those a wake is +/// shown. /// /// A fold the summarizer refuses — no text, a completion cut at its cap, a /// collapsed summary — is handled as production handles it: nothing is @@ -37,6 +39,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:lotti/classes/ai/ai_config.dart'; import 'package:lotti/features/agents/projection/input_capture.dart'; +import 'package:lotti/features/agents/projection/summary_sections.dart'; import 'package:lotti/features/agents/service/agent_log_llm_summarizer.dart'; import 'package:lotti/features/ai/constants/provider_config.dart'; import 'package:lotti/features/ai/repository/cloud_inference_repository.dart'; @@ -240,6 +243,9 @@ List _kept(String summary, int upTo) { ]; } +int _wordCount(String text) => + text.trim().isEmpty ? 0 : text.trim().split(RegExp(r'\s+')).length; + void main() { test( 'decisions survive the folds of a long-running log', @@ -288,7 +294,9 @@ void main() { ); final rows = >[]; - String? summary; + // The summary as production keeps it (ADR 0174): frozen sections the + // model never sees again, and one open section each fold extends. + var sections = const SummarySections(); // Entries of folds the summarizer refused: still in the tail, so the // next fold takes them too. var waiting = []; @@ -297,11 +305,18 @@ void main() { final watch = Stopwatch()..start(); String? refused; try { - summary = await summarizer.summarize( - sources: sources, - model: model, - provider: provider, - priorSummary: summary, + sections = await foldIntoSections( + prior: sections, + sources: [ + for (final source in sources) + (source: source, at: source.sourceCreatedAt), + ], + write: ({required sources, priorSummary}) => summarizer.summarize( + sources: sources, + model: model, + provider: provider, + priorSummary: priorSummary, + ), ); waiting = []; // The summarizer's own refusals are StateErrors, which production @@ -311,19 +326,33 @@ void main() { refused = error.message; waiting = sources; } - final kept = summary == null ? [] : _kept(summary, fold); + // Two questions: is the decision still in the summary at all, and is + // it in what a wake is shown. + final stored = [ + for (final section in sections.frozen) section.text, + sections.open, + ].join('\n'); + final shown = renderSummarySections(sections); + final kept = _kept(stored, fold); + final keptShown = _kept(shown, fold); rows.add({ 'fold': fold, 'seconds': watch.elapsed.inSeconds, 'refused': ?refused, - 'words': summary?.split(RegExp(r'\s+')).length ?? 0, + 'frozenSections': sections.frozen.length, + 'storedWords': _wordCount(stored), + 'shownWords': _wordCount(shown), 'keptPerFold': kept, - 'summary': summary, + 'shownPerFold': keptShown, + 'shown': shown, }); stdout.writeln( '[summary-eval] $model fold $fold ' '${refused == null ? 'ok' : 'REFUSED ($refused)'} ' - '${watch.elapsed.inSeconds}s ${rows.last['words']}w kept=$kept', + '${watch.elapsed.inSeconds}s ' + 'sections=${sections.frozen.length} ' + 'shown=${rows.last['shownWords']}w ' + 'stored=$kept shown=$keptShown', ); } diff --git a/test/features/agents/sync/agent_log_compactor_test.dart b/test/features/agents/sync/agent_log_compactor_test.dart index 473bbfaf65..577356e9d4 100644 --- a/test/features/agents/sync/agent_log_compactor_test.dart +++ b/test/features/agents/sync/agent_log_compactor_test.dart @@ -12,6 +12,7 @@ import 'package:lotti/features/agents/projection/compaction_summary.dart'; import 'package:lotti/features/agents/projection/decision_events.dart'; import 'package:lotti/features/agents/projection/input_capture.dart'; import 'package:lotti/features/agents/projection/input_events.dart'; +import 'package:lotti/features/agents/projection/summary_sections.dart'; import 'package:lotti/features/agents/sync/agent_input_capture_service.dart'; import 'package:lotti/features/agents/sync/agent_log_compactor.dart'; import 'package:lotti/features/agents/sync/agent_sync_service.dart'; @@ -1021,6 +1022,140 @@ void main() { ); }); + group('summary sections (ADR 0174)', () { + String words(int count, String word) => List.filled(count, word).join(' '); + + Future> activePayload() async { + final active = (await activeView()).checkpoint!; + return ((await repo.getEntity(active.contentDigest))! + as AgentMessagePayloadEntity) + .content; + } + + test('a section past its limit is frozen; later folds carry it ' + 'untouched, hand the model only the open section, and the prompt ' + 'reads the sections under their days', () async { + final priors = []; + var call = 0; + Future fold(int day) => compactor.maybeCompact( + agentId: _agentId, + budget: 0, + at: DateTime.utc(2024, 3, day), + summarize: ({required sources, priorSummary}) async { + priors.add(priorSummary); + call++; + // The first fold overfills a section; the second starts the next. + return call == 1 + ? words(summarySectionFreezeWords + 1, 'early') + : 'Late facts.'; + }, + ); + + await captureAll([ + src('e1', 'alpha', day: 1), + src('e2', 'beta', day: 2), + ], 10); + await fold(11); // folds e1; tail = [e2] + + final first = await activePayload(); + final frozen = (first[SummarySections.frozenKey]! as List).single as Map; + // Dated by when the entry entered the log — the 10th — not by when it + // was written, the 1st: the day a period search would find it under. + expect(frozen['from'], DateTime.utc(2024, 3, 10).toIso8601String()); + expect(frozen['to'], DateTime.utc(2024, 3, 10).toIso8601String()); + expect(first[SummarySections.openKey], isEmpty); + // A single frozen section and nothing open: its text under its day. + expect(first['summaryText'], startsWith('[2024-03-10]\nearly early')); + + await captureAll([ + src('e1', 'alpha', day: 1), + src('e2', 'beta', day: 2), + src('e3', 'gamma', day: 3), + ], 12); + await fold(13); // folds e2; tail = [e3] + + // The frozen section was never handed back to the model. + expect(priors, [null, null]); + final second = await activePayload(); + expect( + second[SummarySections.frozenKey], + first[SummarySections.frozenKey], + ); + expect(second[SummarySections.openKey], 'Late facts.'); + expect( + second[SummarySections.openFromKey], + DateTime.utc(2024, 3, 10).toIso8601String(), + ); + + // The section's day is one a recall can ask for: the entry it covers + // is found under it, and not under the day it was written. + final byCaptureDay = await compactor.searchLog( + _agentId, + query: 'alpha', + from: DateTime.utc(2024, 3, 10), + before: DateTime.utc(2024, 3, 11), + ); + expect(byCaptureDay.single.contentEntryId, 'e1'); + expect( + await compactor.searchLog( + _agentId, + query: 'alpha', + from: DateTime.utc(2024, 3), + before: DateTime.utc(2024, 3, 2), + ), + isEmpty, + ); + + final context = await compactor.assembleContext(_agentId); + expect( + context.indexOf('[2024-03-10]'), + lessThan(context.indexOf('[since 2024-03-10]\nLate facts.')), + ); + expect(context, contains('gamma')); + }); + + test('a checkpoint written before sections is taken as one open ' + 'section: its text is handed to the next fold as before', () async { + await captureAll([ + src('e1', 'alpha', day: 1), + src('e2', 'beta', day: 2), + ], 10); + await compact(budget: 0); // 'SUMMARY(1)', tail = [e2] + + // Strip the section fields, as a build before ADR 0174 stored it. + final payload = (await activePayload()).map(MapEntry.new) + ..remove(SummarySections.frozenKey) + ..remove(SummarySections.openKey) + ..remove(SummarySections.openFromKey); + final summary = summaryMessages().single; + await sync.upsertEntity( + AgentDomainEntity.agentMessagePayload( + id: 'legacy-payload', + agentId: _agentId, + createdAt: DateTime.utc(2024, 3, 10), + vectorClock: null, + content: payload, + ), + ); + await sync.upsertEntity( + summary.copyWith(contentEntryId: 'legacy-payload'), + ); + + await captureAll([ + src('e1', 'alpha', day: 1), + src('e2', 'beta', day: 2), + src('e3', 'gamma', day: 3), + ], 12); + await compact(budget: 0, day: 13); + + expect(summarizeCalls.last.prior, 'SUMMARY(1)'); + final upgraded = await activePayload(); + expect(upgraded[SummarySections.frozenKey], isEmpty); + expect(upgraded[SummarySections.openKey], 'SUMMARY(1)'); + expect(upgraded['summaryText'], 'SUMMARY(1)'); + }); + }); + group('searchLog (recall)', () { test('finds folded content the summary no longer shows verbatim', () async { await captureAll([