[GH-ISSUE #1964] [Feature]: Long-Term Memory ingests Advanced Memory records without a second model pass #1845

Closed
opened 2026-11-07 16:37:04 +07:00 by bsakaguchi · 0 comments
Owner

Originally created by @Promansis on GitHub (Oct 31, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Agents/issues/1964

Originally assigned to: @Promansis on GitHub.

What problem does this solve?

In a roleplay chat with Advanced Memory on, the Engine already summarises every scene with a model call. Long-Term Memory cannot use those recaps: they are not reachable from a package, and even when they become reachable they are prose, so the package would have to run its own extractor over them. Today only Game Mode session summaries skip the model, because their ## timeline_event / Summary: ... blocks are machine-readable (directGameUnits).

Engine issue Pasta-Devs/Marinara-Engine#8589 (host-only) makes the Advanced Memory summary call return a structured memory block when Long-Term Memory is active, stores it on the record, and exposes the chat's scene records through persistence.listChatSummaries(chatId).advancedMemory (Capability API 1.391). This issue is the package side: read those records, import the block without a model call, and fall back to the existing summary extraction when a record has none.

Proposed package or change

Long-Term Memory stops summarising chats the host already summarises. For a chat with Advanced Memory on, its scene records are the chat's summary (continuity is the Engine's compaction of the same scenes and is not imported): Long-Term Memory imports those and runs no chat-summary or transcript import for that chat. Conversation chats keep day and week summaries, game chats keep session summaries, and the transcript-piece importer remains only for chats with no host summary at all. Each enabled scene record becomes one source note; a record with a memory block is turned into memory deterministically, like a Game Mode session summary; a record without one goes through the normal chat_summary model extraction. Import happens on the recall refresh hook when the new Memory Settings switch "Use Advanced Memory recaps" is on, and on demand from the Import panel. Inside that chat, recall leaves the notes made from its own records to Advanced Memory, which already recalls them there.

  1. Format, owned by the package. The runtime service (L/server-entry.ts, long-term-memory:runtime) gains summaryMemoryInstruction() returning the paragraph the Engine appends to the summary request. It asks for the same headed ## bucket / Field: value form the game parser reads, with names rather than ids:
    • ## timeline_event with Summary: and optional When:;
    • ## character_fact with Character: and Fact:;
    • ## relationship_state with Between: and State:;
    • ## world_fact with Fact:.
      No thread bucket: Advanced Memory's tail forbids open-thread lists, and threads keep coming from chat extraction.
  2. Provenance. SH/primitives.ts:177 adds "advanced_memory"; sourceId is the chat id, entryId the record id. Source note id comes from sourceNoteIdForProvenance like the other kinds.
  3. Candidates. L/sources/interop.ts builds them next to the chat-summary candidates (lines 638-700) from listChatSummaries(chat.id).advancedMemory ?? []: sourceId ${chat.id}:am-${record.id}, title ${chat}, ${record.title}, sourceText the prose content, deterministicSourceText the block when present, sourceTag imported_advanced_memory, modes and extraction mode from the chat. Scope follows the record's audience: with audienceCharacterIds set, the note's scope.characterIds is that audience (intersected with the chat's characters), so a character who was not in the scene does not recall it elsewhere; an empty audience (narrator-only or user-only scene) keeps the chat scope from resolveChatLtmScope(chat). Re-import is idempotent through the existing source-hash fingerprint: an unchanged record changes nothing, a regenerated or fixed record re-extracts.
  4. Deterministic for any source with a block. L/extraction/source-processing.ts: the gate at 204 becomes "the item carries deterministicSourceText" instead of directGameMode && extractionMode === "game"; useExtractionAgent in importPackageInterop (1327-1332) tests row.deterministicSourceText instead of the :game-session- string; directGameUnits learns the two extra headings (character_fact, relationship_state) and resolves Character:/Between: names to the chat's characters the way the normalizer's section adders do. Game Mode keeps today's behaviour and its useExtractionAgentOnGameMode switch.
  5. Trigger. On refresh for a chat with the switch on, list the chat's records, drop ones whose source note already matches the fingerprint, and import the rest that carry a block with extract: true. No connection and no model call are involved in the turn path. Records without a block (made before the Engine change, or cleared by Fix) are left for the backfill below. The Import panel lists "Advanced Memory" as a source for the manual path.
    5b. Backfill button. "Backfill Advanced Memory" on the Advanced Memory source in the Import panel runs the summary extractor over the chat's scene records that have no block, in batches (default 10 records, a size field next to the button), with progress and Cancel through the existing import operation. For a chat that existed before the Engine change that is its whole scene archive. Pressing it again continues: records already extracted match their fingerprint and are skipped. A scene record whose message range is already covered by a chat_summary or chat_transcript note from an earlier import of that chat is skipped, so an event enters memory once and no dialog is needed.
  6. Precedence. In the candidate builder, a chat whose advancedMemory list is non-empty contributes only those records: its rolling and legacy summary entries and its transcript pieces are skipped for the chats and messages sources. Day, week and game-session entries are untouched because Advanced Memory never runs in those modes. A chat that turns Advanced Memory off later has no records and falls back to today's sources on the next import.
  7. Echo filter. In a chat with Advanced Memory on, recall excludes notes and units whose provenance is { kind: "advanced_memory", sourceId: <this chat id> }. Advanced Memory already puts those recaps into the prompt; Long-Term Memory contributes what it alone has: the same records' notes in other chats, characters, lorebooks, and other chats' memories within scope. Same shape as the SN-5 package-record echo filter.
  8. Settings. SH/settings.ts adds useAdvancedMemory: boolean (default off), with a switch under the existing chat-import settings in C/settings/MemorySettings.tsx. Off means today's behaviour in every chat: no records imported, no sources skipped, no recall filter.
  9. Release. Patch with a CHANGELOG entry; engine-boundary capabilityApi and engine.min move to the Engine release that ships 1.391. The host field is read with optional chaining, so a host without it changes nothing.

Minimal fix

L = packages/long-term-memory/src/engine/packages/server/src/services/long-term-memory, SH = packages/long-term-memory/src/engine/packages/shared/src/features/agents/long-term-memory/schema, C = the package client.

 SH/primitives.ts (177)
-    kind: z.enum(["character", "lorebook", "chat_summary", "chat_transcript"]),
+    kind: z.enum(["character", "lorebook", "chat_summary", "chat_transcript", "advanced_memory"]),

 SH/settings.ts (307, 355) + L/extraction/extraction-config.ts
+    useAdvancedMemory: z.boolean().optional(),   // default false; off = today's behaviour everywhere

 L/server-entry.ts (41-60)
+    summaryMemoryInstruction: () => ADVANCED_MEMORY_BLOCK_INSTRUCTION,

 L/sources/interop.ts (638-700 chat-summary loop and the `messages` loop; 1327-1332)
+  const records = settings.useAdvancedMemory ? ((await getPackagePersistence().listChatSummaries?.(chat.id))?.advancedMemory ?? []) : [];
+  // precedence: with records, skip this chat's rolling/legacy entries (`summaries()` origin rolling|legacy) and its transcript pieces
+  for (const record of records)
+    result.push({ sourceId: `${chat.id}:am-${record.id}`, provenance: { kind: "advanced_memory", sourceId: chat.id, entryId: record.id },
+      sourceText: record.content, ...(record.memory ? { deterministicSourceText: record.memory } : {}), sourceTag: "imported_advanced_memory",
+      scope: record.audienceCharacterIds.length ? { ...chatScope, characterIds: audience ∩ chat.characterIds } : chatScope, ... });
-      row.extractionMode !== "game" || !row.sourceId.includes(":game-session-") || extractionConfig.useExtractionAgentOnGameMode,
+      !row.deterministicSourceText || (row.extractionMode === "game" && extractionConfig.useExtractionAgentOnGameMode),

 L/extraction/source-processing.ts (~160, 204, ~649)
-  const directBlock = /^##\s+(timeline_event|thread|world_fact)\n([^:]+):\s*(.+)$/s
+  const directBlock = /^##\s+(timeline_event|thread|world_fact|character_fact|relationship_state)\n([^:]+):\s*(.+)$/s
+  // character_fact -> character unit for the named chat character; relationship_state -> relationship unit (reuse the normalizer's name matching)
-  if (options.directGameMode && extractionMode === "game") {
+  if (options.deterministicSourceText) {   // set by the dispatcher for any item carrying a block

 L/recall (refresh hook; recall query)
+  if (settings.useAdvancedMemory) await importPackageInterop({ source: "advanced-memory", chatId, extract: true, deterministicOnly: true, ... })  // skips fingerprint-matched and blockless records
+  // backfill (Import panel): same call without deterministicOnly, sourceIds = the next batch of blockless records whose
+  // message range no existing chat_summary/chat_transcript note of the chat covers, importConcurrency from the batch size
+  // echo filter: when the chat has Advanced Memory on, drop candidates whose provenance is { kind: "advanced_memory", sourceId: chatId } (SN-5 shape)

 C/settings/MemorySettings.tsx (near 1204), C import panel source list
+  "Use Advanced Memory recaps" switch; "Advanced Memory" source with a "Backfill Advanced Memory" button and batch size

 packages/long-term-memory/CHANGELOG.md, manifest engine.min, engine-boundary capabilityApi 1.391
 regressions: block parse (four buckets, names resolved, unknown name dropped); refresh skips a record without a block, backfill extracts it;
   audience [A] gives scope.characterIds [A], empty audience gives the chat scope; backfill skips a record whose message range an earlier chat_summary/chat_transcript note covers;
   re-import of an unchanged record is a no-op; a host without `advancedMemory` imports nothing; switch off imports nothing on refresh;
   precedence: a chat with records yields no rolling/transcript candidates, a chat without them yields today's; echo: recall in that
   chat returns none of its own advanced_memory notes but does return the same notes in another chat

Why should this be optional?

Only chats that run Advanced Memory produce records, and only users who also run Long-Term Memory want them merged. The switch defaults off, so nothing changes for anyone who does not turn it on. With it on, a roleplay chat's memory is only as fresh as Advanced Memory's scene cut, and a user who wants Long-Term Memory from a roleplay chat must run Advanced Memory, with its own model cost. That trade is the user's to make.

Alternatives considered

  • Extract from the prose records with the model. Works once the records are exposed, and is the fallback here, but it keeps the second model pass this issue removes.
  • Recommend the Long-Term Memory Chat Summary template to Advanced Memory users. The package cannot set the Engine's template, the template's headings are not what the deterministic parser reads, and a global template change affects every roleplay chat.
  • Import the records next to Long-Term Memory's own chat sources. Two summaries of the same scene, one prose recap and one transcript extraction, would be deduplicated by content heuristics at best. Precedence is one rule and no heuristics.
  • Let Long-Term Memory recall the recaps in the same chat and turn Advanced Memory recall off. Advanced Memory's recall is scene-aware (dependencies, audience, recollections) and the package cannot reproduce it. Leaving each system its own chat and filtering the echo is cheaper.
  • Give every record the chat scope, ignoring audience. Simpler, but a character who was not in the scene would recall it in another chat. Advanced Memory already keeps that boundary per character, so the note keeps it too.
  • Extract blockless records automatically on refresh. Puts model calls in the turn path and could run through a long archive unasked. A button with batches keeps the cost visible and resumable.

Additional context

  • Depends on Engine Pasta-Devs/Marinara-Engine#8589 (listChatSummaries(...).advancedMemory, summaryMemoryInstruction, Capability API 1.391).
  • The block format and its instruction live in the package (summaryMemoryInstruction), so a format change is a Long-Term Memory release and never an Engine change.
  • Deterministic units get the game parser's fixed scores (importance by bucket, confidence 0.9, salience 0.75, no keywords) and never wait in Review, exactly like Game Mode session imports.
  • Proof for the PR: in a chat with Advanced Memory and the switch on, one new scene record with a block appears in Memory Vault as timeline, character and relationship units with no extraction call, and the Import panel offers that chat no rolling-summary or transcript candidates; the same record with memory: null runs the summary extractor. A turn in that chat shows the recap once, in Advanced Memory's block; a turn in a second chat with the same character shows the note in Long-Term Memory's block.

Template check

Please uncheck (untick) the box below before submitting so we know you read the template. It is intentionally pre-checked:

  • I DID NOT read this template
Originally created by @Promansis on GitHub (Oct 31, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Agents/issues/1964 Originally assigned to: @Promansis on GitHub. ## What problem does this solve? In a roleplay chat with Advanced Memory on, the Engine already summarises every scene with a model call. Long-Term Memory cannot use those recaps: they are not reachable from a package, and even when they become reachable they are prose, so the package would have to run its own extractor over them. Today only Game Mode session summaries skip the model, because their `## timeline_event` / `Summary: ...` blocks are machine-readable (`directGameUnits`). Engine issue Pasta-Devs/Marinara-Engine#8589 (host-only) makes the Advanced Memory summary call return a structured `memory` block when Long-Term Memory is active, stores it on the record, and exposes the chat's scene records through `persistence.listChatSummaries(chatId).advancedMemory` (Capability API 1.391). This issue is the package side: read those records, import the block without a model call, and fall back to the existing summary extraction when a record has none. ## Proposed package or change Long-Term Memory stops summarising chats the host already summarises. For a chat with Advanced Memory on, its scene records *are* the chat's summary (continuity is the Engine's compaction of the same scenes and is not imported): Long-Term Memory imports those and runs no chat-summary or transcript import for that chat. Conversation chats keep day and week summaries, game chats keep session summaries, and the transcript-piece importer remains only for chats with no host summary at all. Each enabled scene record becomes one source note; a record with a `memory` block is turned into memory deterministically, like a Game Mode session summary; a record without one goes through the normal `chat_summary` model extraction. Import happens on the recall `refresh` hook when the new Memory Settings switch "Use Advanced Memory recaps" is on, and on demand from the Import panel. Inside that chat, recall leaves the notes made from its own records to Advanced Memory, which already recalls them there. 1. **Format, owned by the package.** The runtime service (`L/server-entry.ts`, `long-term-memory:runtime`) gains `summaryMemoryInstruction()` returning the paragraph the Engine appends to the summary request. It asks for the same headed `## bucket` / `Field: value` form the game parser reads, with names rather than ids: - `## timeline_event` with `Summary:` and optional `When:`; - `## character_fact` with `Character:` and `Fact:`; - `## relationship_state` with `Between:` and `State:`; - `## world_fact` with `Fact:`. No `thread` bucket: Advanced Memory's tail forbids open-thread lists, and threads keep coming from chat extraction. 2. **Provenance.** `SH/primitives.ts:177` adds `"advanced_memory"`; `sourceId` is the chat id, `entryId` the record id. Source note id comes from `sourceNoteIdForProvenance` like the other kinds. 3. **Candidates.** `L/sources/interop.ts` builds them next to the chat-summary candidates (lines 638-700) from `listChatSummaries(chat.id).advancedMemory ?? []`: `sourceId` `${chat.id}:am-${record.id}`, title `${chat}, ${record.title}`, `sourceText` the prose `content`, `deterministicSourceText` the block when present, `sourceTag` `imported_advanced_memory`, modes and extraction mode from the chat. Scope follows the record's audience: with `audienceCharacterIds` set, the note's `scope.characterIds` is that audience (intersected with the chat's characters), so a character who was not in the scene does not recall it elsewhere; an empty audience (narrator-only or user-only scene) keeps the chat scope from `resolveChatLtmScope(chat)`. Re-import is idempotent through the existing source-hash fingerprint: an unchanged record changes nothing, a regenerated or fixed record re-extracts. 4. **Deterministic for any source with a block.** `L/extraction/source-processing.ts`: the gate at 204 becomes "the item carries `deterministicSourceText`" instead of `directGameMode && extractionMode === "game"`; `useExtractionAgent` in `importPackageInterop` (1327-1332) tests `row.deterministicSourceText` instead of the `:game-session-` string; `directGameUnits` learns the two extra headings (`character_fact`, `relationship_state`) and resolves `Character:`/`Between:` names to the chat's characters the way the normalizer's section adders do. Game Mode keeps today's behaviour and its `useExtractionAgentOnGameMode` switch. 5. **Trigger.** On `refresh` for a chat with the switch on, list the chat's records, drop ones whose source note already matches the fingerprint, and import the rest that carry a block with `extract: true`. No connection and no model call are involved in the turn path. Records without a block (made before the Engine change, or cleared by Fix) are left for the backfill below. The Import panel lists "Advanced Memory" as a source for the manual path. 5b. **Backfill button.** "Backfill Advanced Memory" on the Advanced Memory source in the Import panel runs the summary extractor over the chat's scene records that have no block, in batches (default 10 records, a size field next to the button), with progress and Cancel through the existing import operation. For a chat that existed before the Engine change that is its whole scene archive. Pressing it again continues: records already extracted match their fingerprint and are skipped. A scene record whose message range is already covered by a `chat_summary` or `chat_transcript` note from an earlier import of that chat is skipped, so an event enters memory once and no dialog is needed. 6. **Precedence.** In the candidate builder, a chat whose `advancedMemory` list is non-empty contributes only those records: its rolling and legacy summary entries and its transcript pieces are skipped for the `chats` and `messages` sources. Day, week and game-session entries are untouched because Advanced Memory never runs in those modes. A chat that turns Advanced Memory off later has no records and falls back to today's sources on the next import. 7. **Echo filter.** In a chat with Advanced Memory on, recall excludes notes and units whose provenance is `{ kind: "advanced_memory", sourceId: <this chat id> }`. Advanced Memory already puts those recaps into the prompt; Long-Term Memory contributes what it alone has: the same records' notes in other chats, characters, lorebooks, and other chats' memories within scope. Same shape as the SN-5 package-record echo filter. 8. **Settings.** `SH/settings.ts` adds `useAdvancedMemory: boolean` (default off), with a switch under the existing chat-import settings in `C/settings/MemorySettings.tsx`. Off means today's behaviour in every chat: no records imported, no sources skipped, no recall filter. 9. **Release.** Patch with a CHANGELOG entry; `engine-boundary` capabilityApi and `engine.min` move to the Engine release that ships 1.391. The host field is read with optional chaining, so a host without it changes nothing. ### Minimal fix L = `packages/long-term-memory/src/engine/packages/server/src/services/long-term-memory`, SH = `packages/long-term-memory/src/engine/packages/shared/src/features/agents/long-term-memory/schema`, C = the package client. ```diff SH/primitives.ts (177) - kind: z.enum(["character", "lorebook", "chat_summary", "chat_transcript"]), + kind: z.enum(["character", "lorebook", "chat_summary", "chat_transcript", "advanced_memory"]), SH/settings.ts (307, 355) + L/extraction/extraction-config.ts + useAdvancedMemory: z.boolean().optional(), // default false; off = today's behaviour everywhere L/server-entry.ts (41-60) + summaryMemoryInstruction: () => ADVANCED_MEMORY_BLOCK_INSTRUCTION, L/sources/interop.ts (638-700 chat-summary loop and the `messages` loop; 1327-1332) + const records = settings.useAdvancedMemory ? ((await getPackagePersistence().listChatSummaries?.(chat.id))?.advancedMemory ?? []) : []; + // precedence: with records, skip this chat's rolling/legacy entries (`summaries()` origin rolling|legacy) and its transcript pieces + for (const record of records) + result.push({ sourceId: `${chat.id}:am-${record.id}`, provenance: { kind: "advanced_memory", sourceId: chat.id, entryId: record.id }, + sourceText: record.content, ...(record.memory ? { deterministicSourceText: record.memory } : {}), sourceTag: "imported_advanced_memory", + scope: record.audienceCharacterIds.length ? { ...chatScope, characterIds: audience ∩ chat.characterIds } : chatScope, ... }); - row.extractionMode !== "game" || !row.sourceId.includes(":game-session-") || extractionConfig.useExtractionAgentOnGameMode, + !row.deterministicSourceText || (row.extractionMode === "game" && extractionConfig.useExtractionAgentOnGameMode), L/extraction/source-processing.ts (~160, 204, ~649) - const directBlock = /^##\s+(timeline_event|thread|world_fact)\n([^:]+):\s*(.+)$/s + const directBlock = /^##\s+(timeline_event|thread|world_fact|character_fact|relationship_state)\n([^:]+):\s*(.+)$/s + // character_fact -> character unit for the named chat character; relationship_state -> relationship unit (reuse the normalizer's name matching) - if (options.directGameMode && extractionMode === "game") { + if (options.deterministicSourceText) { // set by the dispatcher for any item carrying a block L/recall (refresh hook; recall query) + if (settings.useAdvancedMemory) await importPackageInterop({ source: "advanced-memory", chatId, extract: true, deterministicOnly: true, ... }) // skips fingerprint-matched and blockless records + // backfill (Import panel): same call without deterministicOnly, sourceIds = the next batch of blockless records whose + // message range no existing chat_summary/chat_transcript note of the chat covers, importConcurrency from the batch size + // echo filter: when the chat has Advanced Memory on, drop candidates whose provenance is { kind: "advanced_memory", sourceId: chatId } (SN-5 shape) C/settings/MemorySettings.tsx (near 1204), C import panel source list + "Use Advanced Memory recaps" switch; "Advanced Memory" source with a "Backfill Advanced Memory" button and batch size packages/long-term-memory/CHANGELOG.md, manifest engine.min, engine-boundary capabilityApi 1.391 regressions: block parse (four buckets, names resolved, unknown name dropped); refresh skips a record without a block, backfill extracts it; audience [A] gives scope.characterIds [A], empty audience gives the chat scope; backfill skips a record whose message range an earlier chat_summary/chat_transcript note covers; re-import of an unchanged record is a no-op; a host without `advancedMemory` imports nothing; switch off imports nothing on refresh; precedence: a chat with records yields no rolling/transcript candidates, a chat without them yields today's; echo: recall in that chat returns none of its own advanced_memory notes but does return the same notes in another chat ``` ## Why should this be optional? Only chats that run Advanced Memory produce records, and only users who also run Long-Term Memory want them merged. The switch defaults off, so nothing changes for anyone who does not turn it on. With it on, a roleplay chat's memory is only as fresh as Advanced Memory's scene cut, and a user who wants Long-Term Memory from a roleplay chat must run Advanced Memory, with its own model cost. That trade is the user's to make. ## Alternatives considered - **Extract from the prose records with the model.** Works once the records are exposed, and is the fallback here, but it keeps the second model pass this issue removes. - **Recommend the Long-Term Memory Chat Summary template to Advanced Memory users.** The package cannot set the Engine's template, the template's headings are not what the deterministic parser reads, and a global template change affects every roleplay chat. - **Import the records next to Long-Term Memory's own chat sources.** Two summaries of the same scene, one prose recap and one transcript extraction, would be deduplicated by content heuristics at best. Precedence is one rule and no heuristics. - **Let Long-Term Memory recall the recaps in the same chat and turn Advanced Memory recall off.** Advanced Memory's recall is scene-aware (dependencies, audience, recollections) and the package cannot reproduce it. Leaving each system its own chat and filtering the echo is cheaper. - **Give every record the chat scope, ignoring audience.** Simpler, but a character who was not in the scene would recall it in another chat. Advanced Memory already keeps that boundary per character, so the note keeps it too. - **Extract blockless records automatically on refresh.** Puts model calls in the turn path and could run through a long archive unasked. A button with batches keeps the cost visible and resumable. ## Additional context - Depends on Engine Pasta-Devs/Marinara-Engine#8589 (`listChatSummaries(...).advancedMemory`, `summaryMemoryInstruction`, Capability API 1.391). - The block format and its instruction live in the package (`summaryMemoryInstruction`), so a format change is a Long-Term Memory release and never an Engine change. - Deterministic units get the game parser's fixed scores (importance by bucket, confidence 0.9, salience 0.75, no keywords) and never wait in Review, exactly like Game Mode session imports. - Proof for the PR: in a chat with Advanced Memory and the switch on, one new scene record with a block appears in Memory Vault as timeline, character and relationship units with no extraction call, and the Import panel offers that chat no rolling-summary or transcript candidates; the same record with `memory: null` runs the summary extractor. A turn in that chat shows the recap once, in Advanced Memory's block; a turn in a second chat with the same character shows the note in Long-Term Memory's block. ## Template check Please **uncheck (untick)** the box below before submitting so we know you read the template. It is intentionally pre-checked: - [ ] I DID NOT read this template
bsakaguchi 2026-11-07 16:37:04 +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-Agents#1845
No description provided.