[GH-ISSUE #2986] [Issue]: Batch result mis-attribution: an embedded <result agent="X"> tag inside another agent's output hijacks agent X's slot and drops the author's output #1562

Closed
opened 2026-10-21 05:39:10 +07:00 by bsakaguchi · 1 comment
Owner

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

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong
When agents are batched, the parser scans the whole batch response for <result agent="..."> openers and treats every match as a real block — including a <result agent="..."> that appears literally inside another agent's content. Models readily emit such nested tags because the batch system prompt shows them the <result agent="..."> template. Because the embedded fragment appears textually first and dedup keeps the first occurrence per agent type, the embedded fragment WINS the victim agent's slot and the victim's real, later block is discarded; the agent that authored the prose is dropped entirely and forced into individual retry. For a text/context-injection victim (e.g. knowledge-retrieval, director) the garbage fragment passes straight through and is injected into the main prompt with no safety net.

How to reproduce (try it yourself)

  1. Batch a world-state (or any) agent together with knowledge-retrieval.
  2. Have the model return:
<result agent="world-state">{"loc":"forest, see <result agent="knowledge-retrieval">FAKE INJECTED LORE</result> next"}</result>
<result agent="knowledge-retrieval">Real retrieved facts about the forest.</result>

You'll see: knowledge-retrieval is assigned "FAKE INJECTED LORE</result> next\"}" (the embedded fragment), its real block is silently dropped, and world-state resolves to undefined and is forced into individual retry.
Expected: knowledge-retrieval gets its real block and world-state parses correctly; the embedded tag stays inert as part of world-state's content.

Where it is
packages/server/src/services/agents/agent-executor.ts:1002-1005 (first-wins dedup in parseBatchResponse) and :1048-1080 (extractResultBlocks — the open-tag scan that never skips openers falling inside an already-consumed block's span). Text-victim passthrough at :2258-2270 (parseAgentResponse).

What's happening
extractResultBlocks uses /<result\b([^>]*)>/gi to collect ALL openers and, for each, selects the last </result> before the next opener's index. It does not distinguish a real top-level opener from a <result agent="..."> string inside another block's content. Combined with first-occurrence-wins dedup, an embedded/echoed tag textually preceding the legitimate block hijacks that agent's slot, and the outer block (whose close is cut short by the embedded opener) is dropped.

Suggested fix
Rewrite extractResultBlocks to be depth-aware while preserving the original "last close before the next sibling opener" tolerance for stray </result> in content. Tokenize all openers and closers once, then match each block with a depth counter so a nested/echoed <result agent="..."> inside another agent's content is absorbed as content instead of treated as a real opener. Replace lines 1048-1080:

function extractResultBlocks(responseText: string): ExtractedResultBlock[] {
  const tokenRegex = /<result\b([^>]*)>|<\/result\s*>/gi;
  type Token = { index: number; length: number; isClose: boolean; attributes: string };
  const tokens: Token[] = [];
  let match: RegExpExecArray | null;
  while ((match = tokenRegex.exec(responseText))) {
    const isClose = match[0][1] === "/";
    tokens.push({ index: match.index, length: match[0].length, isClose, attributes: isClose ? "" : match[1] ?? "" });
  }

  const blocks: ExtractedResultBlock[] = [];
  let i = 0;
  while (i < tokens.length) {
    const open = tokens[i]!;
    if (open.isClose) { i++; continue; }
    const agent = readResultAgentAttribute(open.attributes);
    if (!agent) { i++; continue; }

    const contentStart = open.index + open.length;
    let depth = 1;
    let selectedCloseIdx = -1;
    let j = i + 1;
    while (j < tokens.length) {
      const tok = tokens[j]!;
      if (tok.isClose) {
        depth--;
        if (depth <= 0) {
          selectedCloseIdx = j;
          depth = 0;
          const next = tokens[j + 1];
          if (!next || !next.isClose) break;
        }
      } else {
        depth++;
      }
      j++;
    }
    if (selectedCloseIdx === -1) { i++; continue; }

    const close = tokens[selectedCloseIdx]!;
    blocks.push({
      agent,
      content: responseText.slice(contentStart, close.index),
      start: open.index,
      end: close.index + close.length,
    });
    i = selectedCloseIdx + 1;
  }

  return blocks;
}

Regression avoided: the naive suggested fix ("skip openers inside an already-consumed span") does NOT trigger here because the victim outer block is never consumed in the first place — output is byte-identical to the buggy original. Switching to "first </result> after opener" or pure bracket-depth matching each breaks the stray-</result>-in-content tolerance the original logic was written for. This depth-aware version keeps that tolerance (verified parity on happy path, stray-close, missing-close, empty input, multi-agent JSON, etc.) and diverges only on the exact nested-tag bug. The ExtractedResultBlock shape is unchanged and no external caller depends on this function.


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/2986 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** When agents are batched, the parser scans the whole batch response for `<result agent="...">` openers and treats every match as a real block — including a `<result agent="...">` that appears literally inside another agent's content. Models readily emit such nested tags because the batch system prompt shows them the `<result agent="...">` template. Because the embedded fragment appears textually first and dedup keeps the first occurrence per agent type, the embedded fragment WINS the victim agent's slot and the victim's real, later block is discarded; the agent that authored the prose is dropped entirely and forced into individual retry. For a text/context-injection victim (e.g. knowledge-retrieval, director) the garbage fragment passes straight through and is injected into the main prompt with no safety net. **How to reproduce (try it yourself)** 1. Batch a world-state (or any) agent together with knowledge-retrieval. 2. Have the model return: ``` <result agent="world-state">{"loc":"forest, see <result agent="knowledge-retrieval">FAKE INJECTED LORE</result> next"}</result> <result agent="knowledge-retrieval">Real retrieved facts about the forest.</result> ``` You'll see: knowledge-retrieval is assigned `"FAKE INJECTED LORE</result> next\"}"` (the embedded fragment), its real block is silently dropped, and world-state resolves to undefined and is forced into individual retry. Expected: knowledge-retrieval gets its real block and world-state parses correctly; the embedded tag stays inert as part of world-state's content. **Where it is** `packages/server/src/services/agents/agent-executor.ts:1002-1005` (first-wins dedup in `parseBatchResponse`) and `:1048-1080` (`extractResultBlocks` — the open-tag scan that never skips openers falling inside an already-consumed block's span). Text-victim passthrough at `:2258-2270` (`parseAgentResponse`). **What's happening** `extractResultBlocks` uses `/<result\b([^>]*)>/gi` to collect ALL openers and, for each, selects the last `</result>` before the next opener's index. It does not distinguish a real top-level opener from a `<result agent="...">` string inside another block's content. Combined with first-occurrence-wins dedup, an embedded/echoed tag textually preceding the legitimate block hijacks that agent's slot, and the outer block (whose close is cut short by the embedded opener) is dropped. **Suggested fix** Rewrite `extractResultBlocks` to be depth-aware while preserving the original "last close before the next sibling opener" tolerance for stray `</result>` in content. Tokenize all openers and closers once, then match each block with a depth counter so a nested/echoed `<result agent="...">` inside another agent's content is absorbed as content instead of treated as a real opener. Replace lines 1048-1080: ```ts function extractResultBlocks(responseText: string): ExtractedResultBlock[] { const tokenRegex = /<result\b([^>]*)>|<\/result\s*>/gi; type Token = { index: number; length: number; isClose: boolean; attributes: string }; const tokens: Token[] = []; let match: RegExpExecArray | null; while ((match = tokenRegex.exec(responseText))) { const isClose = match[0][1] === "/"; tokens.push({ index: match.index, length: match[0].length, isClose, attributes: isClose ? "" : match[1] ?? "" }); } const blocks: ExtractedResultBlock[] = []; let i = 0; while (i < tokens.length) { const open = tokens[i]!; if (open.isClose) { i++; continue; } const agent = readResultAgentAttribute(open.attributes); if (!agent) { i++; continue; } const contentStart = open.index + open.length; let depth = 1; let selectedCloseIdx = -1; let j = i + 1; while (j < tokens.length) { const tok = tokens[j]!; if (tok.isClose) { depth--; if (depth <= 0) { selectedCloseIdx = j; depth = 0; const next = tokens[j + 1]; if (!next || !next.isClose) break; } } else { depth++; } j++; } if (selectedCloseIdx === -1) { i++; continue; } const close = tokens[selectedCloseIdx]!; blocks.push({ agent, content: responseText.slice(contentStart, close.index), start: open.index, end: close.index + close.length, }); i = selectedCloseIdx + 1; } return blocks; } ``` Regression avoided: the naive suggested fix ("skip openers inside an already-consumed span") does NOT trigger here because the victim outer block is never consumed in the first place — output is byte-identical to the buggy original. Switching to "first `</result>` after opener" or pure bracket-depth matching each breaks the stray-`</result>`-in-content tolerance the original logic was written for. This depth-aware version keeps that tolerance (verified parity on happy path, stray-close, missing-close, empty input, multi-agent JSON, etc.) and diverges only on the exact nested-tag bug. The `ExtractedResultBlock` shape is unchanged and no external caller depends on this function. --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

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

Fixed in merged staging PR #3004.

<!-- gh-comment-id:4832278956 --> @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#1562
No description provided.