[GH-ISSUE #8589] [Feature]: Let Advanced Memory return a structured memory block for Long-Term Memory and expose its records to packages #8415

Closed
opened 2026-11-07 16:42:49 +07:00 by bsakaguchi · 3 comments
Owner

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

Originally assigned to: @Promansis on GitHub.

What problem does this solve?

Advanced Memory already pays a model call for every scene recap. The Long-Term Memory package cannot use that work:

  • Its records are not reachable from a package. persistence.listChatSummaries (1.387) returns day, week, rolling and game-session summaries from chat metadata; advanced_memory_records is not part of it.
  • Even if they were, the recap is prose written for the narrator. Turning it into memory would mean a second model pass over text a model just produced. The package only skips the model for one input today: Game Mode session summaries, because their ## timeline_event / Summary: ... blocks are machine-readable.

Since #8359 Long-Term Memory replaces built-in recall in chats that list it. A roleplay chat with both Advanced Memory and Long-Term Memory on therefore runs two summary systems, and the second one has to extract from the chat again.

Proposed solution

Host-only. When Long-Term Memory is registered and active for the chat, the one Advanced Memory scene summary call also returns a structured block, the record stores it, and packages can read it. Scenes only: a continuity record is the compacted recap of messages the scene records already cover and is rewritten as the window moves, so it carries nothing new and would be re-imported on every rewrite. Nothing else about Advanced Memory changes, and the request is byte-identical when Long-Term Memory is not registered.

References are to Engine 307d91bed. S = packages/server/src, SH = packages/shared/src.

  1. Ask for one more JSON key. In S/services/advanced-memory.ts (prompt assembly, about lines 1893-1915), when longTermMemoryRuntimeAvailable() and the chat lists Long-Term Memory (the longTermMemoryActive predicate resolveMemoryRecallPolicy already uses), append the package's instruction to the Advanced Memory tail and change the output line to {"summary":"historical recap","memory":"..."}. The instruction text comes from the package: LongTermMemoryRuntimeService (S/services/generation/long-term-memory-runtime.ts:17) gains an optional summaryMemoryInstruction?(): string | null. No method or null means no block and no change to the request. Only scene summaries ask for it; continuity, temporary, excerpt, recollectOnly and audienceOnly paths do not. It follows the existing pattern for audience and recollections: one reply, one more key.
  2. Store it, never parse it. New nullable text column structured_memory on advanced_memory_records (S/db/schema/advanced-memory.ts, next to summary_work). In the single-output parse (about line 2140) read tryParseJsonRecord(outputs[0])?.memory when it is a string and save it with the record; content keeps parseChatSummaryResult(...).summary exactly as today. For multi-batch runs, ask for the block in first-pass batches only and store the batch blocks joined with a blank line; combine passes do not ask for it. The shorten check (about line 2192) measures summary only, so a block never triggers a shortening pass. The column is internal like summaryWork: not on the public AdvancedMemoryRecord, and left out of transferRecordSchema in S/services/advanced-memory-transfer.ts on export and import.
  3. Fix clears it. When a record's text is edited by hand (manualOverride), set structured_memory to null. The package then extracts from the edited prose with its model path instead of importing units the user may have corrected away.
  4. Expose it to packages. Extend CapabilityChatSummaries (SH/types/capability-runtime.ts:389) with advancedMemory: CapabilityAdvancedMemorySummary[] and fill it in listChatSummaries (S/services/capability-packages/capability-persistence.service.ts:561) under the same chat-read permission: enabled, completed scene records of the chat, each as { id, kind, title, content, timeline, startMessageId, endMessageId, audienceCharacterIds, sourceFingerprint, updatedAt, memory } where memory is the stored block or null. Not included: summaryWork, embeddings, dependencies, continuity, temporary, excerpt, recollection.
  5. Capability API 1.391, a comment line in SH/schemas/capability-package.schema.ts (block at 1496-1500), and a section after "Capability API 1.387: read a chat's summaries" in docs/development/optional-agent-packages.md (line 1832) showing the new field and the runtime method.
  6. Regressions. advanced-memory-summary.regression.ts: the tail carries the instruction only when a runtime with summaryMemoryInstruction is registered and the chat lists the package; a reply with memory stores it and leaves content unchanged; a reply without it stores null; shortening ignores the block; Fix nulls it. capability-persistence-permissions.regression.ts: advancedMemory present under chat-read, denied without it, and memory round-trips as stored. Transfer export has no structured_memory.

Minimal fix

 S/services/generation/long-term-memory-runtime.ts
   export interface LongTermMemoryRuntimeService {
+    /** Optional. One paragraph the Engine appends to Advanced Memory's summary request; the reply's "memory" string is stored untouched. */
+    summaryMemoryInstruction?(): string | null;
     refresh?(...)
+  export function longTermMemorySummaryInstruction(): string | null  // null when no runtime, no method, or null

 S/services/advanced-memory.ts (~1893-1915, ~2100-2192)
+  const memoryInstruction = longTermMemoryActive(ctx) ? longTermMemorySummaryInstruction() : null;
   ...tail: `Return only valid JSON: {"summary":"historical recap"${memoryInstruction ? ',"memory":"..."' : ""}}`
+  // first-pass batches only: `${memoryInstruction}` appended after the audience text
+  const memory = typeof result.memory === "string" ? result.memory : null;  // single-output parse
+  // multi-batch: join first-pass `memory` strings; combine passes do not request it
+  // shorten check: tokenSize(summary) not tokenSize(whole reply)
+  // put(): structuredMemory: memory ; Fix/manualOverride: structuredMemory: null

 S/db/schema/advanced-memory.ts
+  structuredMemory: text("structured_memory"),

 S/services/advanced-memory-transfer.ts
   transferRecordSchema: unchanged keys (structured_memory never exported; import ignores it)

 SH/types/capability-runtime.ts (~389)
+  export interface CapabilityAdvancedMemorySummary { id; kind: "scene"; title; content; timeline: string | null; startMessageId; endMessageId; audienceCharacterIds: string[]; sourceFingerprint; updatedAt; memory: string | null }
   export interface CapabilityChatSummaries {
     ...
+    /** Capability API 1.391: enabled, completed scene records. */
+    advancedMemory: CapabilityAdvancedMemorySummary[];
   }

 S/services/capability-packages/capability-persistence.service.ts (239, 561)
+  advancedMemory: await listAdvancedMemorySummaries(db, chatId)   // chat-read, same guard as the rest of listChatSummaries

 SH/schemas/capability-package.schema.ts (1500-1502)
+  // 1.391: `persistence.listChatSummaries(chatId).advancedMemory` ...; `long-term-memory:runtime.summaryMemoryInstruction()`.
-  export const supportedCapabilityApi = Object.freeze({ major: 1, minor: 390 } as const);
+  export const supportedCapabilityApi = Object.freeze({ major: 1, minor: 391 } as const);

 docs/development/optional-agent-packages.md (after 1832)
+  ### Capability API 1.391: Advanced Memory records and the summary memory block

 scripts/regressions/advanced-memory-summary.regression.ts, capability-persistence-permissions.regression.ts: cases above

Alternatives considered

  • Recommend the Long-Term Memory Chat Summary template to Advanced Memory users. Advanced Memory follows the global Chat Summary template, and that template is already gated to chats with the package active. But it is prose with headings the package's extractor still has to run a model over, its "Still open" section contradicts the Advanced Memory tail ("Omit ... unresolved-thread lists"), a package cannot set the Engine's global template, and a global change affects every roleplay chat. It does not remove the second model pass.
  • Hard-code the block format in the Engine. Works, but every format change becomes an Engine release. Letting the package hand over the instruction keeps the format where the parser lives.
  • Replace the prose recap with the structured block. That would change what the narrator reads and what the archive shows. The dual field leaves Advanced Memory's behaviour alone.
  • Let the package read advanced_memory_records directly. Packages have no table access, by design.

Additional context

  • The Long-Term Memory side (filed separately) adds an advanced_memory source, imports records whose memory block is present without a model call, falls back to its existing summary extraction when it is null, and raises engine.min to the Engine release that ships this.
  • Cost: extra output tokens per scene summary, only in chats that list the package. The block is not combined or shortened, so a long multi-batch scene stores the first-pass blocks as they came.
  • Proof for the PR: one scene summary in a chat with the package active shows the "memory" key in the request and the stored block in listChatSummaries(...).advancedMemory[0].memory; the same scene without the package registered sends today's request unchanged and stores null.

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-Engine/issues/8589 Originally assigned to: @Promansis on GitHub. ## What problem does this solve? Advanced Memory already pays a model call for every scene recap. The Long-Term Memory package cannot use that work: - Its records are not reachable from a package. `persistence.listChatSummaries` (1.387) returns day, week, rolling and game-session summaries from chat metadata; `advanced_memory_records` is not part of it. - Even if they were, the recap is prose written for the narrator. Turning it into memory would mean a second model pass over text a model just produced. The package only skips the model for one input today: Game Mode session summaries, because their `## timeline_event` / `Summary: ...` blocks are machine-readable. Since #8359 Long-Term Memory replaces built-in recall in chats that list it. A roleplay chat with both Advanced Memory and Long-Term Memory on therefore runs two summary systems, and the second one has to extract from the chat again. ## Proposed solution Host-only. When Long-Term Memory is registered and active for the chat, the one Advanced Memory scene summary call also returns a structured block, the record stores it, and packages can read it. Scenes only: a continuity record is the compacted recap of messages the scene records already cover and is rewritten as the window moves, so it carries nothing new and would be re-imported on every rewrite. Nothing else about Advanced Memory changes, and the request is byte-identical when Long-Term Memory is not registered. References are to Engine 307d91bed. S = `packages/server/src`, SH = `packages/shared/src`. 1. **Ask for one more JSON key.** In `S/services/advanced-memory.ts` (prompt assembly, about lines 1893-1915), when `longTermMemoryRuntimeAvailable()` and the chat lists Long-Term Memory (the `longTermMemoryActive` predicate `resolveMemoryRecallPolicy` already uses), append the package's instruction to the Advanced Memory tail and change the output line to `{"summary":"historical recap","memory":"..."}`. The instruction text comes from the package: `LongTermMemoryRuntimeService` (`S/services/generation/long-term-memory-runtime.ts:17`) gains an optional `summaryMemoryInstruction?(): string | null`. No method or `null` means no block and no change to the request. Only `scene` summaries ask for it; `continuity`, `temporary`, `excerpt`, `recollectOnly` and `audienceOnly` paths do not. It follows the existing pattern for `audience` and `recollections`: one reply, one more key. 2. **Store it, never parse it.** New nullable text column `structured_memory` on `advanced_memory_records` (`S/db/schema/advanced-memory.ts`, next to `summary_work`). In the single-output parse (about line 2140) read `tryParseJsonRecord(outputs[0])?.memory` when it is a string and save it with the record; `content` keeps `parseChatSummaryResult(...).summary` exactly as today. For multi-batch runs, ask for the block in first-pass batches only and store the batch blocks joined with a blank line; combine passes do not ask for it. The shorten check (about line 2192) measures `summary` only, so a block never triggers a shortening pass. The column is internal like `summaryWork`: not on the public `AdvancedMemoryRecord`, and left out of `transferRecordSchema` in `S/services/advanced-memory-transfer.ts` on export and import. 3. **Fix clears it.** When a record's text is edited by hand (`manualOverride`), set `structured_memory` to null. The package then extracts from the edited prose with its model path instead of importing units the user may have corrected away. 4. **Expose it to packages.** Extend `CapabilityChatSummaries` (`SH/types/capability-runtime.ts:389`) with `advancedMemory: CapabilityAdvancedMemorySummary[]` and fill it in `listChatSummaries` (`S/services/capability-packages/capability-persistence.service.ts:561`) under the same `chat-read` permission: enabled, completed `scene` records of the chat, each as `{ id, kind, title, content, timeline, startMessageId, endMessageId, audienceCharacterIds, sourceFingerprint, updatedAt, memory }` where `memory` is the stored block or `null`. Not included: `summaryWork`, embeddings, dependencies, `continuity`, `temporary`, `excerpt`, `recollection`. 5. **Capability API 1.391**, a comment line in `SH/schemas/capability-package.schema.ts` (block at 1496-1500), and a section after "Capability API 1.387: read a chat's summaries" in `docs/development/optional-agent-packages.md` (line 1832) showing the new field and the runtime method. 6. **Regressions.** `advanced-memory-summary.regression.ts`: the tail carries the instruction only when a runtime with `summaryMemoryInstruction` is registered and the chat lists the package; a reply with `memory` stores it and leaves `content` unchanged; a reply without it stores null; shortening ignores the block; Fix nulls it. `capability-persistence-permissions.regression.ts`: `advancedMemory` present under `chat-read`, denied without it, and `memory` round-trips as stored. Transfer export has no `structured_memory`. ### Minimal fix ```diff S/services/generation/long-term-memory-runtime.ts export interface LongTermMemoryRuntimeService { + /** Optional. One paragraph the Engine appends to Advanced Memory's summary request; the reply's "memory" string is stored untouched. */ + summaryMemoryInstruction?(): string | null; refresh?(...) + export function longTermMemorySummaryInstruction(): string | null // null when no runtime, no method, or null S/services/advanced-memory.ts (~1893-1915, ~2100-2192) + const memoryInstruction = longTermMemoryActive(ctx) ? longTermMemorySummaryInstruction() : null; ...tail: `Return only valid JSON: {"summary":"historical recap"${memoryInstruction ? ',"memory":"..."' : ""}}` + // first-pass batches only: `${memoryInstruction}` appended after the audience text + const memory = typeof result.memory === "string" ? result.memory : null; // single-output parse + // multi-batch: join first-pass `memory` strings; combine passes do not request it + // shorten check: tokenSize(summary) not tokenSize(whole reply) + // put(): structuredMemory: memory ; Fix/manualOverride: structuredMemory: null S/db/schema/advanced-memory.ts + structuredMemory: text("structured_memory"), S/services/advanced-memory-transfer.ts transferRecordSchema: unchanged keys (structured_memory never exported; import ignores it) SH/types/capability-runtime.ts (~389) + export interface CapabilityAdvancedMemorySummary { id; kind: "scene"; title; content; timeline: string | null; startMessageId; endMessageId; audienceCharacterIds: string[]; sourceFingerprint; updatedAt; memory: string | null } export interface CapabilityChatSummaries { ... + /** Capability API 1.391: enabled, completed scene records. */ + advancedMemory: CapabilityAdvancedMemorySummary[]; } S/services/capability-packages/capability-persistence.service.ts (239, 561) + advancedMemory: await listAdvancedMemorySummaries(db, chatId) // chat-read, same guard as the rest of listChatSummaries SH/schemas/capability-package.schema.ts (1500-1502) + // 1.391: `persistence.listChatSummaries(chatId).advancedMemory` ...; `long-term-memory:runtime.summaryMemoryInstruction()`. - export const supportedCapabilityApi = Object.freeze({ major: 1, minor: 390 } as const); + export const supportedCapabilityApi = Object.freeze({ major: 1, minor: 391 } as const); docs/development/optional-agent-packages.md (after 1832) + ### Capability API 1.391: Advanced Memory records and the summary memory block scripts/regressions/advanced-memory-summary.regression.ts, capability-persistence-permissions.regression.ts: cases above ``` ## Alternatives considered - **Recommend the Long-Term Memory Chat Summary template to Advanced Memory users.** Advanced Memory follows the global Chat Summary template, and that template is already gated to chats with the package active. But it is prose with headings the package's extractor still has to run a model over, its "Still open" section contradicts the Advanced Memory tail ("Omit ... unresolved-thread lists"), a package cannot set the Engine's global template, and a global change affects every roleplay chat. It does not remove the second model pass. - **Hard-code the block format in the Engine.** Works, but every format change becomes an Engine release. Letting the package hand over the instruction keeps the format where the parser lives. - **Replace the prose recap with the structured block.** That would change what the narrator reads and what the archive shows. The dual field leaves Advanced Memory's behaviour alone. - **Let the package read `advanced_memory_records` directly.** Packages have no table access, by design. ## Additional context - The Long-Term Memory side (filed separately) adds an `advanced_memory` source, imports records whose `memory` block is present without a model call, falls back to its existing summary extraction when it is `null`, and raises `engine.min` to the Engine release that ships this. - Cost: extra output tokens per scene summary, only in chats that list the package. The block is not combined or shortened, so a long multi-batch scene stores the first-pass blocks as they came. - Proof for the PR: one scene summary in a chat with the package active shows the `"memory"` key in the request and the stored block in `listChatSummaries(...).advancedMemory[0].memory`; the same scene without the package registered sends today's request unchanged and stores `null`. ## 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
Author
Owner

@Promansis commented on GitHub (Oct 31, 2026):

Package side: Pasta-Devs/Marinara-Agents#1964.

<!-- gh-comment-id:6539102466 --> @Promansis commented on GitHub (Oct 31, 2026): Package side: Pasta-Devs/Marinara-Agents#1964.
Author
Owner

@Promansis commented on GitHub (Oct 31, 2026):

Decisions from the maintainer: the package owns the block format (summaryMemoryInstruction), Fix clears the stored block, and continuity records are included only if the implementer confirms they are stable once written (not rewritten each turn); otherwise scenes only.

<!-- gh-comment-id:6540247791 --> @Promansis commented on GitHub (Oct 31, 2026): Decisions from the maintainer: the package owns the block format (`summaryMemoryInstruction`), Fix clears the stored block, and continuity records are included only if the implementer confirms they are stable once written (not rewritten each turn); otherwise scenes only.
Author
Owner

@Promansis commented on GitHub (Oct 31, 2026):

Correction to the decision above: scenes only. Continuity is the compacted recap of messages the scene records already cover and is rewritten as the window moves, so it carries nothing new for the package. The body is updated.

<!-- gh-comment-id:6540258683 --> @Promansis commented on GitHub (Oct 31, 2026): Correction to the decision above: scenes only. Continuity is the compacted recap of messages the scene records already cover and is rewritten as the window moves, so it carries nothing new for the package. The body is updated.
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#8415
No description provided.