[PR #2644] [MERGED] fix(agents): retry result-loop break, lorebook-write approval gate, tracker-tag sanitizer, PDF-cache poison, multi-pass double-inject #5702

Closed
opened 2026-10-22 04:18:40 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/2644
Author: @Romuromylus
Created: 6/19/2026
Status: ✅ Merged
Merged: 6/19/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/agents-retry-approval-tracker-pdf-multipass


📝 Commits (1)

  • f0f09fc fix(agents): retry result-loop break, lorebook-write approval gate, tracker-tag sanitizer, PDF-cache poison, multi-pass double-inject

📊 Changes

5 files changed (+118 additions, -62 deletions)

View changed files

📝 packages/server/src/routes/generate/retry-agents-route.ts (+52 -4)
📝 packages/server/src/routes/knowledge-sources.routes.ts (+5 -1)
📝 packages/server/src/services/agents/agent-executor.ts (+2 -2)
📝 packages/server/src/services/agents/knowledge-retrieval.ts (+23 -54)
📝 packages/server/src/services/generation/tool-resolution-runtime.ts (+36 -1)

📄 Description

Linked issue

Closes #2639
Closes #2640
Closes #2641
Closes #2642
Closes #2643

Why this change

Five independent bugs in the agents subsystem, all in packages/server. They were filed separately but share a code area and are each small, so I'm batching them into one reviewable PR with a tight, per-issue diff.

  • #2639 — During an agent retry, applyRetryResultEffects runs every agent result through one for (const result of sortedResults) loop. The text_rewrite stale-edit guard ran break, which exits the entire loop the moment a rewrite is skipped, silently dropping every later result (tracker, quest, persona, cyoa, illustrator, sprite). On top of that, the guard compared the macro-resolved baseline (currentResponseForRewrite, seeded from agentContext.mainResponse) against the raw stored currentMessage.content, so any message containing literal {{...}} macros falsely tripped "edited during retry" — meaning a perfectly normal retry could drop tracker writes for no reason.
  • #2640 — The save_lorebook_entry tool writer wrote to the lorebook DB immediately, bypassing agentWriteApprovalRequired. Approval only gated the structured lorebook_update path, so an agent that wrote lore via the tool call skipped the user's approval gate entirely.
  • #2641 — sanitizeTextAgentResponse stripped only the bare <committed_tracker_state> tag, but buildCommittedTrackerStateContext now emits <committed_tracker_state message_id="...">. The attributed tag slipped through and a smaller model could leak tracker JSON into the injected directive.
  • #2642 — extractFileText cached the "[PDF text extraction failed]" sentinel unconditionally, so a single transient parse failure poisoned that knowledge source for the rest of the process lifetime — every later turn served the failure string instead of re-attempting.
  • #2643 — Multi-pass knowledge retrieval used extractions.length < chunks.length as the "consolidation missing" proxy, but a chunk is also absent from extractions when it returned "No relevant information found.". So when a middle chunk came back empty, it concatenated the raw partials with the final consolidation that had already merged them — double-injecting those facts into the prompt.

What changed

  • #2639 (routes/generate/retry-agents-route.ts): changed the stale-rewrite guard's break to continue so only the stale rewrite is skipped and every later result still persists. Added an expectedStoredMessageContent baseline seeded from the raw last-assistant content (threaded in as mainResponseRaw) and advanced to editedText after each applied rewrite, so the guard now compares raw-vs-raw and no longer misfires on macro-bearing messages.
  • #2640 (services/generation/tool-resolution-runtime.ts + routes/generate/retry-agents-route.ts): both lorebook tool writers (createLorebookEntryWriter and the retry attachRetryLorebookWriterToolContexts writer) now check the approval flag and, when approval is required, return a proposal envelope built with buildLorebookWriteApprovalProposal instead of writing inline — mirroring the existing structured lorebook_update gate.
  • #2641 (services/agents/agent-executor.ts): made both strips attribute-tolerant — /<committed_tracker_state\b[^>]*>[\s\S]*?<\/committed_tracker_state\s*>/gi and the same for the adjacent <assistant_response> strip.
  • #2642 (routes/knowledge-sources.routes.ts): track an extractionFailed flag and skip setCachedText when extraction throws, so only successful extractions are cached and a transient failure is re-attempted next turn.
  • #2643 (services/agents/knowledge-retrieval.ts): track consolidation success with an explicit consolidatedText variable. Return only the consolidated text when the final pass produced output; fall back to concatenating raw partials only when the consolidation pass itself produced nothing.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

  • #2639 (verified live): Deployed this branch to my private EasyPanel instance and drove /api/generate/retry-agents on a roleplay chat whose assistant message contains a literal {{user}} macro (the false-trigger condition), with a batch of prose-guardian (text_rewrite) + quest + world-state + character-tracker + persona-stats. The stream ran agent_start → 5 agent_results (incl. prose-guardian/text_rewrite, success) → 4 game_state_patch → done: all four tracker writes persisted in the same batch as the rewrite result, no early break, no error. On that run prose-guardian returned no-edit-needed, so the stale-edit guard branch itself wasn't entered — the break-vs-continue decision is covered by the diff + pnpm check rather than a live trip.
  • #2640: Manually verify that, with agent write-approval enabled, an agent using the save_lorebook_entry tool surfaces a proposal rather than a silent inline lorebook write (both the main generation path and the retry path).
  • #2641: Manually verify a text-injection agent shown attributed <committed_tracker_state message_id="..."> context no longer leaks the tracker block into its injected output.
  • #2642: Manually verify that after a transient PDF parse failure the source recovers on a later turn rather than permanently returning the failure sentinel.
  • #2643: Manually verify a long (multi-chunk) knowledge source with an empty middle chunk no longer double-injects the consolidated facts.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

Summary by CodeRabbit

Release Notes

  • New Features

    • Knowledge base entries created or modified by agents can now require approval before being saved.
  • Bug Fixes

    • PDF text extraction no longer caches failed extractions.
    • Agent message retries now handle stale content more gracefully without interrupting other agent effects.

🔄 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/2644 **Author:** [@Romuromylus](https://github.com/Romuromylus) **Created:** 6/19/2026 **Status:** ✅ Merged **Merged:** 6/19/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/agents-retry-approval-tracker-pdf-multipass` --- ### 📝 Commits (1) - [`f0f09fc`](https://github.com/Pasta-Devs/Marinara-Engine/commit/f0f09fccb134da5e3d4e02e9e46cc301fbc1af80) fix(agents): retry result-loop break, lorebook-write approval gate, tracker-tag sanitizer, PDF-cache poison, multi-pass double-inject ### 📊 Changes **5 files changed** (+118 additions, -62 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/routes/generate/retry-agents-route.ts` (+52 -4) 📝 `packages/server/src/routes/knowledge-sources.routes.ts` (+5 -1) 📝 `packages/server/src/services/agents/agent-executor.ts` (+2 -2) 📝 `packages/server/src/services/agents/knowledge-retrieval.ts` (+23 -54) 📝 `packages/server/src/services/generation/tool-resolution-runtime.ts` (+36 -1) </details> ### 📄 Description ## Linked issue Closes #2639 Closes #2640 Closes #2641 Closes #2642 Closes #2643 ## Why this change Five independent bugs in the agents subsystem, all in `packages/server`. They were filed separately but share a code area and are each small, so I'm batching them into one reviewable PR with a tight, per-issue diff. - **#2639** — During an agent retry, `applyRetryResultEffects` runs every agent result through one `for (const result of sortedResults)` loop. The `text_rewrite` stale-edit guard ran `break`, which exits the *entire* loop the moment a rewrite is skipped, silently dropping every later result (tracker, quest, persona, cyoa, illustrator, sprite). On top of that, the guard compared the macro-*resolved* baseline (`currentResponseForRewrite`, seeded from `agentContext.mainResponse`) against the *raw* stored `currentMessage.content`, so any message containing literal `{{...}}` macros falsely tripped "edited during retry" — meaning a perfectly normal retry could drop tracker writes for no reason. - **#2640** — The `save_lorebook_entry` tool writer wrote to the lorebook DB immediately, bypassing `agentWriteApprovalRequired`. Approval only gated the structured `lorebook_update` path, so an agent that wrote lore via the tool call skipped the user's approval gate entirely. - **#2641** — `sanitizeTextAgentResponse` stripped only the bare `<committed_tracker_state>` tag, but `buildCommittedTrackerStateContext` now emits `<committed_tracker_state message_id="...">`. The attributed tag slipped through and a smaller model could leak tracker JSON into the injected directive. - **#2642** — `extractFileText` cached the `"[PDF text extraction failed]"` sentinel unconditionally, so a single transient parse failure poisoned that knowledge source for the rest of the process lifetime — every later turn served the failure string instead of re-attempting. - **#2643** — Multi-pass knowledge retrieval used `extractions.length < chunks.length` as the "consolidation missing" proxy, but a chunk is also absent from `extractions` when it returned `"No relevant information found."`. So when a middle chunk came back empty, it concatenated the raw partials with the final consolidation that had *already* merged them — double-injecting those facts into the prompt. ## What changed - **#2639** (`routes/generate/retry-agents-route.ts`): changed the stale-rewrite guard's `break` to `continue` so only the stale rewrite is skipped and every later result still persists. Added an `expectedStoredMessageContent` baseline seeded from the raw last-assistant content (threaded in as `mainResponseRaw`) and advanced to `editedText` after each applied rewrite, so the guard now compares raw-vs-raw and no longer misfires on macro-bearing messages. - **#2640** (`services/generation/tool-resolution-runtime.ts` + `routes/generate/retry-agents-route.ts`): both lorebook tool writers (`createLorebookEntryWriter` and the retry `attachRetryLorebookWriterToolContexts` writer) now check the approval flag and, when approval is required, return a proposal envelope built with `buildLorebookWriteApprovalProposal` instead of writing inline — mirroring the existing structured `lorebook_update` gate. - **#2641** (`services/agents/agent-executor.ts`): made both strips attribute-tolerant — `/<committed_tracker_state\b[^>]*>[\s\S]*?<\/committed_tracker_state\s*>/gi` and the same for the adjacent `<assistant_response>` strip. - **#2642** (`routes/knowledge-sources.routes.ts`): track an `extractionFailed` flag and skip `setCachedText` when extraction throws, so only successful extractions are cached and a transient failure is re-attempted next turn. - **#2643** (`services/agents/knowledge-retrieval.ts`): track consolidation success with an explicit `consolidatedText` variable. Return only the consolidated text when the final pass produced output; fall back to concatenating raw partials only when the consolidation pass itself produced nothing. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes - **#2639 (verified live):** Deployed this branch to my private EasyPanel instance and drove `/api/generate/retry-agents` on a roleplay chat whose assistant message contains a literal `{{user}}` macro (the false-trigger condition), with a batch of **prose-guardian (text_rewrite) + quest + world-state + character-tracker + persona-stats**. The stream ran `agent_start → 5 agent_results (incl. prose-guardian/text_rewrite, success) → 4 game_state_patch → done`: all four tracker writes persisted in the same batch as the rewrite result, no early break, no error. On that run prose-guardian returned no-edit-needed, so the stale-edit guard branch itself wasn't entered — the break-vs-continue decision is covered by the diff + `pnpm check` rather than a live trip. - **#2640:** Manually verify that, with agent write-approval enabled, an agent using the `save_lorebook_entry` tool surfaces a proposal rather than a silent inline lorebook write (both the main generation path and the retry path). - **#2641:** Manually verify a text-injection agent shown attributed `<committed_tracker_state message_id="...">` context no longer leaks the tracker block into its injected output. - **#2642:** Manually verify that after a transient PDF parse failure the source recovers on a later turn rather than permanently returning the failure sentinel. - **#2643:** Manually verify a long (multi-chunk) knowledge source with an empty middle chunk no longer double-injects the consolidated facts. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Release Notes * **New Features** * Knowledge base entries created or modified by agents can now require approval before being saved. * **Bug Fixes** * PDF text extraction no longer caches failed extractions. * Agent message retries now handle stale content more gracefully without interrupting other agent effects. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:18:40 +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#5702
No description provided.