[PR #8837] [MERGED] fix(memory): compact continuity summaries to half their size with just the combine prompt #8834

Closed
opened 2026-11-07 17:40:03 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/8837
Author: @SpicyMarinara
Created: 11/4/2026
Status: ✅ Merged
Merged: 11/5/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/memory-compaction-halves


📝 Commits (4)

  • 63bc65f fix(memory): compact continuity summaries to half their size with just the combine prompt
  • 95f35c8 docs(memory): say when a skipped continuity update is sent again
  • dbfdf55 fix(memory): save compacted sections a common phrase matched, and send each reader set once
  • 4fbffec Merge remote-tracking branch 'origin/staging' into fix/memory-compaction-halves

📊 Changes

6 files changed (+795 additions, -391 deletions)

View changed files

📝 docs/agents/memory.md (+4 -2)
📝 packages/server/src/services/advanced-memory.ts (+305 -159)
➕ scripts/regressions/advanced-memory-compaction.regression.ts (+326 -0)
📝 scripts/regressions/advanced-memory-fix.regression.ts (+4 -4)
📝 scripts/regressions/advanced-memory-post-generation.regression.ts (+155 -225)
📝 scripts/regressions/advanced-memory-summary-order.regression.ts (+1 -1)

📄 Description

Important

Contributions target staging. Only SpicyMarinara may promote this repository's staging branch or a same-repository hotfix/* branch to main.

Linked issue

Closes #8820

Why this change

Issue #8820: Updating continuity sent constant summaries through the scene-summary path. That request stacked the knowledge instruction, the scene prompt, the historical-recap rules and a soft budget-proportional target, with an output allowance of at least 8,196 tokens and up to 12 rewrite passes. The target changed whenever other summaries grew, so the cache id changed and the same group was asked again on almost every reply. Conditional summaries had to copy {{#if char}} sections. Each dropped section was rejected and re-queued by reader set, then in halves down to single summaries. Users saw 10–15 minute updates, 25–28k-token outputs and 236 privacy rejections in one chat. The maintainer's spec has three rules: compact only when a character's constant view is over the share; cut the text in half; send only the compaction prompt and the summary. 63bc65f362 implements all three. The audit found it meets requirements A–H. The only defect was in the docs: they said a skipped update repeats only when a summary changes. In fact the saved attempt is keyed on the helper connection and model, the temperature and the Combine prompt too. The docs also left out the macro-keeping sentence and that a reply which adds a macro counts as a failed attempt. 95f35c80f4 fixes those sentences, and issue #8834 now carries the same English text.

What changed

  • Updating continuity has its own request (compactTexts in packages/server/src/services/advanced-memory.ts). It sends two messages: system = the user's Combine prompt plus "Shorten it to about N tokens, about half its current length. Return only the shortened summary.", and user = the text. When the text has macros, one more sentence asks to keep {{…}} macros as written. Nothing comes from the scene path: no knowledge instruction, scene prompt, historical-recap rules, eligible-source line or soft target.
  • The target is half the text being compacted, counted without conditions. It follows from the summaries alone, so the cache id (which includes the target) is stable while they are unchanged. A view still over the share after one halving is halved again on a later update.
  • The output cap is min(outputBudget, 2 × target + 1,024), where outputBudget = max(8,196, Chat Summary Maximum output size). That is the text's size plus 1,024 tokens for a stray thinking block. A ponytail: comment on COMPACTION_REASONING_ROOM names the ceiling.
  • A failed attempt keeps the originals, logs one logger.warn with the chat id and sizes, saves the reply in summaryWork and does not throw. A cut-off is saved as "". Failure means a reply cut at the cap, empty, not shorter, adding a macro or condition, or a rebuilt result that fails the privacy check. The job still ends ready, and unchanged summaries are not sent again on later replies or after a restart.
  • Summaries with character conditions are split by reader set through scopeConstantSummary/scopeCharacterSummary's mark callback. Each set's text is halved in its own request without conditions, then rebuilt inside the condition scopeCharacterSummary writes for those readers. Shared text keeps the all-readers condition. Parts under 64 tokens, and parts with macros other than {{user}}, stay verbatim with no request. The existing sections()/leaks() check still runs on the rebuilt result as a safety net.
  • The cascading re-queue (by reader set, then halves, down to single summaries) is removed: one attempt per group per input revision. Legacy unranged groups key their cache record on the first message, not the whole transcript, so a new reply no longer invalidates their saved attempt.
  • summarize() loses only the budget and keepConditions parameters compaction used. Scene summaries, recollections, audience checks and Long-Term Memory send byte-identical requests: all remaining callers passed budget = null. Shared helpers savedWork, summaryLimits, tokenSlices and tokenBatches are factored out without behaviour change.
  • docs/agents/memory.md "Updating continuity" bullets cover: half the size; one request per text with only the Combine prompt and a size line (plus the macro sentence when needed); private parts compacted per reader group and put back in the same condition; a failed attempt keeps the originals and is not repeated until a summary, the helper model or the Combine prompt changes. The 95f35c80f4 corrections are included.
  • New regression scripts/regressions/advanced-memory-compaction.regression.ts covers (1) the two-message request shape, (2) the half target and the cap, (3) per-reader-set compaction with byte-exact conditions, privacy-check pass and save, (4) unchanged, empty or cut-off replies make exactly one call and none on the next update, and (5) a privacy-rejected result triggers no smaller-group calls. advanced-memory-post-generation, -fix and -summary-order regressions are updated to the new request and behaviour.
  • Docs translation follow-up: issue #8834, "[docs-i18n] docs/agents/memory.md", open, created by the implementer. Its body is now updated to the final English text.
  • A compacted summary is no longer thrown away when its shortened shared part happens to use a common phrase (such as 'at the end of') that also appears in a private part. The Helper never sees a private part while shortening shared text, so such a match is a coincidence.
  • Text the same group of characters reads goes out in one shortening request and comes back in one condition, even when summaries name those characters in a different order.

Validation

  • pnpm check passes locally
  • Ran the app, clicked through the changes manually

Manual verification notes

  • Manually verify in a Roleplay chat with Advanced Memory on and a small summary budget: after a reply pushes the constant summaries over 70% of the budget, Agent activity shows Updating continuity once and the new Chat Summary is about half the size of the summaries it replaced.
  • Manually verify with DEBUG_AGENTS=true (or debug mode) that the logged "[advanced-memory] Compaction prompt" contains only the Combine prompt, the "Shorten it to about N tokens, about half its current length" line and the summary text.
  • Manually verify in a one-by-one group chat whose summaries have {{#if char == "Name"}} sections: after compaction, Peek Prompt for each character shows only that character's private parts plus the shared text, and the saved summary keeps one condition per reader group.
  • Manually verify with a helper that returns an unshortened reply: the summaries stay, the server log shows one "asked to shorten a … token summary text" warning, memory status ends ready, and the next reply makes no new compaction request.
  • Manually verify that editing the Combine prompt in Summaries settings makes the next update send the skipped summaries again.
  • Manually verify that scene summaries in a fresh Roleplay chat still return the 2–3 paragraph JSON recap with audience, as before.

Agent-run checks (for reference):

  • pnpm check on dbfdf55417: exit 0
  • node ./scripts/run-regressions.mjs --filter advanced-memory: 24/24 passed

Independent review of 63bc65f362 and 95f35c80f4: 2 findings (a run-of-words privacy check that rejected valid per-reader results whenever two sections shared a common phrase, and a reader-set key that depended on name order), both fixed in dbfdf55417. Dottore Review: Viable, With Notes, no defects.

Known limits and risks:

  • A reader set whose runs interleave with other sets is rebuilt grouped by set, in the order each set first appears. Each reader still reads exactly the same parts, but a later shared event can come before an earlier private one. This is marked ponytail: in the code, with the upgrade path of one request per run.
  • Authored character-only conditions such as {{else}} or a different || order are saved in the normalized form scopeCharacterSummary writes (e.g. {{#if char == "Pantalone" || "Narr"}}). The reader sets are identical. A probe with 3 readers plus a narrator, else, ||, nested and {{user}} parts showed every reader's facts unchanged. This matches the pre-fix saving, which also stored the scoped form.
  • When one reader set fails, the group stops and the other sets are not asked. Nothing is saved until a summary, the helper model or the Combine prompt changes.
  • There is no in-app notice when an update is skipped. Memory status has no non-blocking 'skipped' field, so the job ends ready and the single logger.warn is the only signal.
  • Finish reasons other than "length" (error, abort, tool_calls, content_filter) still throw "did not complete" and stop the update with an error that Resume processing retries. This is unchanged and documented.
  • A Helper that reasons for more than 1,024 tokens beyond the text size is cut off, and that counts as a failed attempt (ponytail: COMPACTION_REASONING_ROOM).
  • Pre-existing ponytail: the safety net cannot catch a reworded private fact placed in a wider section. Per-set compaction means the Helper never sees another set's private text, so that can now happen only by chance.
  • The PR's first commit message (63bc65f362) and its description say a reply failing 'the existing privacy check' is a failed attempt. That check is no longer applied to compaction: the result is private by construction, and only the size and section-structure checks remain. The PR description should be updated to match.

🤖 Generated with Claude Code


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/8837 **Author:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Created:** 11/4/2026 **Status:** ✅ Merged **Merged:** 11/5/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/memory-compaction-halves` --- ### 📝 Commits (4) - [`63bc65f`](https://github.com/Pasta-Devs/Marinara-Engine/commit/63bc65f362ddae1f8e6e1232a2d6ead718a3d81e) fix(memory): compact continuity summaries to half their size with just the combine prompt - [`95f35c8`](https://github.com/Pasta-Devs/Marinara-Engine/commit/95f35c80f417afbe53aef5d80686569b8d1cc145) docs(memory): say when a skipped continuity update is sent again - [`dbfdf55`](https://github.com/Pasta-Devs/Marinara-Engine/commit/dbfdf5541706729d5f66360dbc02df10d636b02d) fix(memory): save compacted sections a common phrase matched, and send each reader set once - [`4fbffec`](https://github.com/Pasta-Devs/Marinara-Engine/commit/4fbffec5a4596375204da64843aef3a98f241b84) Merge remote-tracking branch 'origin/staging' into fix/memory-compaction-halves ### 📊 Changes **6 files changed** (+795 additions, -391 deletions) <details> <summary>View changed files</summary> 📝 `docs/agents/memory.md` (+4 -2) 📝 `packages/server/src/services/advanced-memory.ts` (+305 -159) ➕ `scripts/regressions/advanced-memory-compaction.regression.ts` (+326 -0) 📝 `scripts/regressions/advanced-memory-fix.regression.ts` (+4 -4) 📝 `scripts/regressions/advanced-memory-post-generation.regression.ts` (+155 -225) 📝 `scripts/regressions/advanced-memory-summary-order.regression.ts` (+1 -1) </details> ### 📄 Description > [!IMPORTANT] > Contributions target `staging`. Only `SpicyMarinara` may promote this repository's `staging` branch or a same-repository `hotfix/*` branch to `main`. ## Linked issue Closes #8820 ## Why this change Issue #8820: Updating continuity sent constant summaries through the scene-summary path. That request stacked the knowledge instruction, the scene prompt, the historical-recap rules and a soft budget-proportional target, with an output allowance of at least 8,196 tokens and up to 12 rewrite passes. The target changed whenever other summaries grew, so the cache id changed and the same group was asked again on almost every reply. Conditional summaries had to copy {{#if char}} sections. Each dropped section was rejected and re-queued by reader set, then in halves down to single summaries. Users saw 10–15 minute updates, 25–28k-token outputs and 236 privacy rejections in one chat. The maintainer's spec has three rules: compact only when a character's constant view is over the share; cut the text in half; send only the compaction prompt and the summary. 63bc65f362 implements all three. The audit found it meets requirements A–H. The only defect was in the docs: they said a skipped update repeats only when a summary changes. In fact the saved attempt is keyed on the helper connection and model, the temperature and the Combine prompt too. The docs also left out the macro-keeping sentence and that a reply which adds a macro counts as a failed attempt. 95f35c80f4 fixes those sentences, and issue #8834 now carries the same English text. ## What changed - Updating continuity has its own request (compactTexts in packages/server/src/services/advanced-memory.ts). It sends two messages: system = the user's Combine prompt plus "Shorten it to about N tokens, about half its current length. Return only the shortened summary.", and user = the text. When the text has macros, one more sentence asks to keep {{…}} macros as written. Nothing comes from the scene path: no knowledge instruction, scene prompt, historical-recap rules, eligible-source line or soft target. - The target is half the text being compacted, counted without conditions. It follows from the summaries alone, so the cache id (which includes the target) is stable while they are unchanged. A view still over the share after one halving is halved again on a later update. - The output cap is min(outputBudget, 2 × target + 1,024), where outputBudget = max(8,196, Chat Summary Maximum output size). That is the text's size plus 1,024 tokens for a stray thinking block. A ponytail: comment on COMPACTION_REASONING_ROOM names the ceiling. - A failed attempt keeps the originals, logs one logger.warn with the chat id and sizes, saves the reply in summaryWork and does not throw. A cut-off is saved as "". Failure means a reply cut at the cap, empty, not shorter, adding a macro or condition, or a rebuilt result that fails the privacy check. The job still ends ready, and unchanged summaries are not sent again on later replies or after a restart. - Summaries with character conditions are split by reader set through scopeConstantSummary/scopeCharacterSummary's mark callback. Each set's text is halved in its own request without conditions, then rebuilt inside the condition scopeCharacterSummary writes for those readers. Shared text keeps the all-readers condition. Parts under 64 tokens, and parts with macros other than {{user}}, stay verbatim with no request. The existing sections()/leaks() check still runs on the rebuilt result as a safety net. - The cascading re-queue (by reader set, then halves, down to single summaries) is removed: one attempt per group per input revision. Legacy unranged groups key their cache record on the first message, not the whole transcript, so a new reply no longer invalidates their saved attempt. - summarize() loses only the budget and keepConditions parameters compaction used. Scene summaries, recollections, audience checks and Long-Term Memory send byte-identical requests: all remaining callers passed budget = null. Shared helpers savedWork, summaryLimits, tokenSlices and tokenBatches are factored out without behaviour change. - docs/agents/memory.md "Updating continuity" bullets cover: half the size; one request per text with only the Combine prompt and a size line (plus the macro sentence when needed); private parts compacted per reader group and put back in the same condition; a failed attempt keeps the originals and is not repeated until a summary, the helper model or the Combine prompt changes. The 95f35c80f4 corrections are included. - New regression scripts/regressions/advanced-memory-compaction.regression.ts covers (1) the two-message request shape, (2) the half target and the cap, (3) per-reader-set compaction with byte-exact conditions, privacy-check pass and save, (4) unchanged, empty or cut-off replies make exactly one call and none on the next update, and (5) a privacy-rejected result triggers no smaller-group calls. advanced-memory-post-generation, -fix and -summary-order regressions are updated to the new request and behaviour. - Docs translation follow-up: issue #8834, "[docs-i18n] docs/agents/memory.md", open, created by the implementer. Its body is now updated to the final English text. - A compacted summary is no longer thrown away when its shortened shared part happens to use a common phrase (such as 'at the end of') that also appears in a private part. The Helper never sees a private part while shortening shared text, so such a match is a coincidence. - Text the same group of characters reads goes out in one shortening request and comes back in one condition, even when summaries name those characters in a different order. ## Validation <!-- These are human tasks. Never tick a box for a check that was not actually performed. --> - [ ] `pnpm check` passes locally - [ ] Ran the app, clicked through the changes manually ### Manual verification notes - Manually verify in a Roleplay chat with Advanced Memory on and a small summary budget: after a reply pushes the constant summaries over 70% of the budget, Agent activity shows Updating continuity once and the new Chat Summary is about half the size of the summaries it replaced. - Manually verify with DEBUG_AGENTS=true (or debug mode) that the logged "[advanced-memory] Compaction prompt" contains only the Combine prompt, the "Shorten it to about N tokens, about half its current length" line and the summary text. - Manually verify in a one-by-one group chat whose summaries have {{#if char == "Name"}} sections: after compaction, Peek Prompt for each character shows only that character's private parts plus the shared text, and the saved summary keeps one condition per reader group. - Manually verify with a helper that returns an unshortened reply: the summaries stay, the server log shows one "asked to shorten a … token summary text" warning, memory status ends ready, and the next reply makes no new compaction request. - Manually verify that editing the Combine prompt in Summaries settings makes the next update send the skipped summaries again. - Manually verify that scene summaries in a fresh Roleplay chat still return the 2–3 paragraph JSON recap with audience, as before. Agent-run checks (for reference): - `pnpm check` on dbfdf55417: exit 0 - `node ./scripts/run-regressions.mjs --filter advanced-memory`: 24/24 passed Independent review of 63bc65f362 and 95f35c80f4: 2 findings (a run-of-words privacy check that rejected valid per-reader results whenever two sections shared a common phrase, and a reader-set key that depended on name order), both fixed in dbfdf55417. Dottore Review: Viable, With Notes, no defects. Known limits and risks: - A reader set whose runs interleave with other sets is rebuilt grouped by set, in the order each set first appears. Each reader still reads exactly the same parts, but a later shared event can come before an earlier private one. This is marked ponytail: in the code, with the upgrade path of one request per run. - Authored character-only conditions such as {{else}} or a different || order are saved in the normalized form scopeCharacterSummary writes (e.g. {{#if char == "Pantalone" || "Narr"}}). The reader sets are identical. A probe with 3 readers plus a narrator, else, ||, nested and {{user}} parts showed every reader's facts unchanged. This matches the pre-fix saving, which also stored the scoped form. - When one reader set fails, the group stops and the other sets are not asked. Nothing is saved until a summary, the helper model or the Combine prompt changes. - There is no in-app notice when an update is skipped. Memory status has no non-blocking 'skipped' field, so the job ends ready and the single logger.warn is the only signal. - Finish reasons other than "length" (error, abort, tool_calls, content_filter) still throw "did not complete" and stop the update with an error that Resume processing retries. This is unchanged and documented. - A Helper that reasons for more than 1,024 tokens beyond the text size is cut off, and that counts as a failed attempt (ponytail: COMPACTION_REASONING_ROOM). - Pre-existing ponytail: the safety net cannot catch a reworded private fact placed in a wider section. Per-set compaction means the Helper never sees another set's private text, so that can now happen only by chance. - The PR's first commit message (63bc65f362) and its description say a reply failing 'the existing privacy check' is a failed attempt. That check is no longer applied to compaction: the result is private by construction, and only the size and section-structure checks remain. The PR description should be updated to match. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-11-07 17:40:03 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#8834
No description provided.