[GH-ISSUE #2985] [Issue]: Retry lorebook_update skips the capability gate and mis-attributes custom-agent writes to the lorebook-keeper's target lorebook #1559

Closed
opened 2026-10-21 05:39:03 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @kolacheee on GitHub (Jun 29, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2985

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong
On the retry path, the lorebook_update effect handler (1) never checks the emitting agent's capability and (2) always writes to the lorebook-keeper's target/writable set instead of the emitting agent's own. The canonical generate route does both correctly. Consequences on retry: a custom agent WITHOUT edit_lorebooks/create_lorebooks still gets its lorebook writes persisted (capability bypass), and those writes land in the keeper's target lorebook (mis-attribution) when a keeper is present, or in a freshly auto-created lorebook when no keeper ran — never the custom agent's own writable lorebook. This corrupts which lorebook receives entries.

How to reproduce (try it yourself)

  1. Create a custom agent with resultType lorebook_update that emits {updates:[...]}, and do NOT grant it edit_lorebooks/create_lorebooks (and/or point it at lorebook A via its settings).
  2. Configure a lorebook-keeper on the same chat targeting lorebook B.
  3. Generate normally — the custom agent's writes are blocked (no capability), or with capability granted go to its own lorebook A.
  4. Trigger an agent retry including both the custom agent and the keeper (POST /retry-agents). Note: agentWriteApprovalRequired defaults to false, so the approval envelope path does not gate this.

You'll see: the custom agent's updates are persisted regardless of capability, and they land in the keeper's lorebook B (or a new auto-created lorebook) instead of A.
Expected: same behavior as fresh generation — blocked without capability, and otherwise written to the agent's own lorebook A.

Where it is
packages/server/src/routes/generate/retry-agents-route.ts:2499-2520 (the lorebook_update block inside applyRetryResultEffects, defined at line 2177; reached unfiltered via line 3314). Canonical correct behavior: packages/server/src/routes/generate.routes.ts:8734-8772. Persistence helper that auto-creates a lorebook when no target is given: packages/server/src/routes/generate/lorebook-keeper-utils.ts:354-457 (auto-create at :362-376).

What's happening
The retry effect handler copies neither the capability gate nor the per-result-agent writable-scope resolution from the canonical route. It hard-wires preferredTargetLorebookId = agentContext.memory._lorebookKeeperTargetLorebookId and writableLorebookIds = agentContext.writableLorebookIds, which are keeper-scoped and only populated when the keeper is among the retried agents. A custom agent's lorebook_update result reaches applyRetryResultEffects unfiltered, so it persists to whatever the keeper's scope is (or, with both null, persistLorebookKeeperUpdates auto-creates a new lorebook and writes there).

Suggested fix
Mirror the canonical route's gate and per-agent scope resolution using the retry route's OWN local helpers, and add a local writable-id resolver so it compiles. Replace the block at retry-agents-route.ts:2499-2520 with capability checks (customAgentHasCapability(resultAgent.settings, "edit_lorebooks"/"create_lorebooks"), skipping unless built-in or capable), per-agent writable-id resolution for non-built-in agents, and the canonical refuse-to-write guard when there is no create capability and no valid target. Add a module-level resolveRetryCustomWritableLorebookIds(settings) next to findRetryResultAgent (identical to generate.routes.ts:672-685). Regression notes: the canonical resolveCustomWritableLorebookIds is private to generate.routes.ts and not importable — hence the local copy; the retry route uses BUILT_IN_AGENT_TYPE_SET and findRetryResultAgent (not builtInAgentTypes/findResultAgent), so a literal copy of the canonical block would not compile. The built-in-keeper branch must keep falling back to agentContext.writableLorebookIds / _lorebookKeeperTargetLorebookId so built-in keeper retries stay byte-for-byte unchanged. Full code:

    if (result.success && result.type === "lorebook_update" && result.data && typeof result.data === "object") {
      try {
        if (isAgentWriteApprovalEnvelope(result.data)) continue;
        const resultAgent = findRetryResultAgent(result, resolvedAgents);
        const isBuiltInLorebookAgent = BUILT_IN_AGENT_TYPE_SET.has(result.agentType);
        const customCanEditLorebooks =
          isBuiltInLorebookAgent ||
          (resultAgent ? customAgentHasCapability(resultAgent.settings, "edit_lorebooks") : false);
        const customCanCreateLorebooks =
          isBuiltInLorebookAgent ||
          (resultAgent ? customAgentHasCapability(resultAgent.settings, "create_lorebooks") : false);
        if (!customCanEditLorebooks && !customCanCreateLorebooks) continue;

        const lkData = result.data as Record<string, unknown>;
        const retryUpdates = (lkData.updates as any[]) ?? [];
        if (retryUpdates.length > 0) {
          const customWritableLorebookIds =
            !isBuiltInLorebookAgent && resultAgent
              ? resolveRetryCustomWritableLorebookIds(resultAgent.settings)
              : agentContext.writableLorebookIds;
          const writableLorebookIds = customCanEditLorebooks ? customWritableLorebookIds : null;
          const preferredTargetLorebookId =
            !isBuiltInLorebookAgent && resultAgent
              ? (writableLorebookIds?.[0] ?? null)
              : typeof agentContext.memory._lorebookKeeperTargetLorebookId === "string"
                ? (agentContext.memory._lorebookKeeperTargetLorebookId as string)
                : null;
          if (!customCanCreateLorebooks && !preferredTargetLorebookId && !writableLorebookIds?.length) {
            continue;
          }
          await persistLorebookKeeperUpdates({
            lorebooksStore,
            chatId,
            chatName: (chat as any).name,
            preferredTargetLorebookId,
            writableLorebookIds,
            updates: retryUpdates,
          });
        }
      } catch (err) {
        logger.error(err, "[retry-agents] Failed to apply lorebook update");
      }
    }

AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.

Originally created by @kolacheee on GitHub (Jun 29, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2985 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** On the retry path, the lorebook_update effect handler (1) never checks the emitting agent's capability and (2) always writes to the lorebook-keeper's target/writable set instead of the emitting agent's own. The canonical generate route does both correctly. Consequences on retry: a custom agent WITHOUT edit_lorebooks/create_lorebooks still gets its lorebook writes persisted (capability bypass), and those writes land in the keeper's target lorebook (mis-attribution) when a keeper is present, or in a freshly auto-created lorebook when no keeper ran — never the custom agent's own writable lorebook. This corrupts which lorebook receives entries. **How to reproduce (try it yourself)** 1. Create a custom agent with resultType `lorebook_update` that emits `{updates:[...]}`, and do NOT grant it edit_lorebooks/create_lorebooks (and/or point it at lorebook A via its settings). 2. Configure a lorebook-keeper on the same chat targeting lorebook B. 3. Generate normally — the custom agent's writes are blocked (no capability), or with capability granted go to its own lorebook A. 4. Trigger an agent retry including both the custom agent and the keeper (POST /retry-agents). Note: agentWriteApprovalRequired defaults to false, so the approval envelope path does not gate this. You'll see: the custom agent's updates are persisted regardless of capability, and they land in the keeper's lorebook B (or a new auto-created lorebook) instead of A. Expected: same behavior as fresh generation — blocked without capability, and otherwise written to the agent's own lorebook A. **Where it is** `packages/server/src/routes/generate/retry-agents-route.ts:2499-2520` (the lorebook_update block inside `applyRetryResultEffects`, defined at line 2177; reached unfiltered via line 3314). Canonical correct behavior: `packages/server/src/routes/generate.routes.ts:8734-8772`. Persistence helper that auto-creates a lorebook when no target is given: `packages/server/src/routes/generate/lorebook-keeper-utils.ts:354-457` (auto-create at :362-376). **What's happening** The retry effect handler copies neither the capability gate nor the per-result-agent writable-scope resolution from the canonical route. It hard-wires `preferredTargetLorebookId = agentContext.memory._lorebookKeeperTargetLorebookId` and `writableLorebookIds = agentContext.writableLorebookIds`, which are keeper-scoped and only populated when the keeper is among the retried agents. A custom agent's lorebook_update result reaches `applyRetryResultEffects` unfiltered, so it persists to whatever the keeper's scope is (or, with both null, `persistLorebookKeeperUpdates` auto-creates a new lorebook and writes there). **Suggested fix** Mirror the canonical route's gate and per-agent scope resolution using the retry route's OWN local helpers, and add a local writable-id resolver so it compiles. Replace the block at retry-agents-route.ts:2499-2520 with capability checks (`customAgentHasCapability(resultAgent.settings, "edit_lorebooks"/"create_lorebooks")`, skipping unless built-in or capable), per-agent writable-id resolution for non-built-in agents, and the canonical refuse-to-write guard when there is no create capability and no valid target. Add a module-level `resolveRetryCustomWritableLorebookIds(settings)` next to `findRetryResultAgent` (identical to generate.routes.ts:672-685). Regression notes: the canonical `resolveCustomWritableLorebookIds` is private to generate.routes.ts and not importable — hence the local copy; the retry route uses `BUILT_IN_AGENT_TYPE_SET` and `findRetryResultAgent` (not `builtInAgentTypes`/`findResultAgent`), so a literal copy of the canonical block would not compile. The built-in-keeper branch must keep falling back to `agentContext.writableLorebookIds` / `_lorebookKeeperTargetLorebookId` so built-in keeper retries stay byte-for-byte unchanged. Full code: ```ts if (result.success && result.type === "lorebook_update" && result.data && typeof result.data === "object") { try { if (isAgentWriteApprovalEnvelope(result.data)) continue; const resultAgent = findRetryResultAgent(result, resolvedAgents); const isBuiltInLorebookAgent = BUILT_IN_AGENT_TYPE_SET.has(result.agentType); const customCanEditLorebooks = isBuiltInLorebookAgent || (resultAgent ? customAgentHasCapability(resultAgent.settings, "edit_lorebooks") : false); const customCanCreateLorebooks = isBuiltInLorebookAgent || (resultAgent ? customAgentHasCapability(resultAgent.settings, "create_lorebooks") : false); if (!customCanEditLorebooks && !customCanCreateLorebooks) continue; const lkData = result.data as Record<string, unknown>; const retryUpdates = (lkData.updates as any[]) ?? []; if (retryUpdates.length > 0) { const customWritableLorebookIds = !isBuiltInLorebookAgent && resultAgent ? resolveRetryCustomWritableLorebookIds(resultAgent.settings) : agentContext.writableLorebookIds; const writableLorebookIds = customCanEditLorebooks ? customWritableLorebookIds : null; const preferredTargetLorebookId = !isBuiltInLorebookAgent && resultAgent ? (writableLorebookIds?.[0] ?? null) : typeof agentContext.memory._lorebookKeeperTargetLorebookId === "string" ? (agentContext.memory._lorebookKeeperTargetLorebookId as string) : null; if (!customCanCreateLorebooks && !preferredTargetLorebookId && !writableLorebookIds?.length) { continue; } await persistLorebookKeeperUpdates({ lorebooksStore, chatId, chatName: (chat as any).name, preferredTargetLorebookId, writableLorebookIds, updates: retryUpdates, }); } } catch (err) { logger.error(err, "[retry-agents] Failed to apply lorebook update"); } } ``` --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

@kolacheee commented on GitHub (Jun 29, 2026):

Cross-checking this against the now-merged Lorebook Keeper fixes (#2970, #2980 in the v2.0.7 branch): this is a separate, still-present bug — not obsoleted by either.

  • Different layer. #2970/#2980 fixed the content merge/replace semantics (parseLorebookWriteApprovalText now emits action: "append", and getExplicitUpdateReplacementContent now reads nested entry.content). This issue is about the retry effect handler's capability gate and write-scope — untouched by those changes.
  • Still present in v2.0.7. The block is byte-identical in origin/staging, just shifted down: it's now at retry-agents-route.ts:2557-2578 (the body above cites 2499-2520, which was correct for v2.0.6/main). Still no customAgentHasCapability gate, and still hardwired to agentContext.memory._lorebookKeeperTargetLorebookId / agentContext.writableLorebookIds — contrast the very next quest_update block, which gates on customAgentCanApplyRetryResult(..., "edit_trackers").
  • The suggested fix still composes. It continues on isAgentWriteApprovalEnvelope (deferring to the #2970 approval-commit path), and because it routes through the same persistLorebookKeeperUpdates, it inherits #2980's nested-entry.content handling for free.

Net: re-verified against v2.0.7 — only the line numbers are stale (2499-2520 → 2557-2578); the bug and the suggested fix are unchanged.

<!-- gh-comment-id:4831693685 --> @kolacheee commented on GitHub (Jun 29, 2026): Cross-checking this against the now-merged Lorebook Keeper fixes (#2970, #2980 in the v2.0.7 branch): this is a separate, still-present bug — not obsoleted by either. - **Different layer.** #2970/#2980 fixed the content *merge/replace semantics* (`parseLorebookWriteApprovalText` now emits `action: "append"`, and `getExplicitUpdateReplacementContent` now reads nested `entry.content`). This issue is about the retry *effect handler*'s capability gate and write-scope — untouched by those changes. - **Still present in v2.0.7.** The block is byte-identical in `origin/staging`, just shifted down: it's now at `retry-agents-route.ts:2557-2578` (the body above cites 2499-2520, which was correct for v2.0.6/`main`). Still no `customAgentHasCapability` gate, and still hardwired to `agentContext.memory._lorebookKeeperTargetLorebookId` / `agentContext.writableLorebookIds` — contrast the very next `quest_update` block, which gates on `customAgentCanApplyRetryResult(..., "edit_trackers")`. - **The suggested fix still composes.** It `continue`s on `isAgentWriteApprovalEnvelope` (deferring to the #2970 approval-commit path), and because it routes through the same `persistLorebookKeeperUpdates`, it inherits #2980's nested-`entry.content` handling for free. Net: re-verified against v2.0.7 — only the line numbers are stale (2499-2520 → 2557-2578); the bug and the suggested fix are unchanged.
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Fixed in merged staging PR #3004.

<!-- gh-comment-id:4832278580 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Fixed in merged staging PR #3004.
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#1559
No description provided.