[GH-ISSUE #4925] [Feature]: Upgrade summary parser JSON repair to use shared json-repair.ts module #2729

Closed
opened 2026-10-21 05:54:01 +07:00 by bsakaguchi · 0 comments
Owner

Originally created by @xDanteMD on GitHub (Aug 11, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/4925

Originally assigned to: @SpicyMarinara on GitHub.

What problem does this solve?

PR #4761 (fixing #4753) created a shared JSON repair utility (packages/server/src/lib/json-repair.ts) and wired it into both the workspace agent and download agents. However, the summary parsers were excluded from that scope and still use bare JSON.parse() with minimal pre-processing.

MoE models (Deepseek, Kimi, GLM, MiMo) have a known failure mode of producing JSON that is structurally malformed sometimes — single quotes instead of double quotes, unquoted keys, missing closing brackets when truncated. The shared repairJsonText() function handles all of these via a 4-candidate waterfall (raw → jsonrepair → bracket-closing → combined). The summary parsers do not.

The two repair systems

Shared module (robust) — introduced in PR #4761

Location: packages/server/src/lib/json-repair.ts:39-58

export function repairJsonText(raw: string): string | null {
  let repaired: string | null = null;
  try { repaired = jsonrepair(raw); } catch {}
  const candidates = [raw, repaired, closeOpenJsonContainers(raw),
                      repaired && closeOpenJsonContainers(repaired)];
  for (const candidate of candidates) {
    if (!candidate) continue;
    try {
      JSON.parse(candidate);
      return candidate;
    } catch {}
  }
  return null;
}

4-candidate waterfall: raw → jsonrepair → bracket-closing → combined. Handles single quotes, unquoted keys, missing brackets, comments, trailing commas, unescaped control characters.

Summary parsers (minimal) — unchanged

Roleplay rolling summary (roleplay-summary-runtime.ts:135-160):

export function parseChatSummaryResult(rawContent: string): ParsedChatSummaryResult {
  const cleaned = rawContent
    .trim()
    .replace(/```(?:json)?\s*/giu, "")   // strip code fences
    .replace(/```/gu, "");
  try {
    const first = cleaned.indexOf("{");
    const last = cleaned.lastIndexOf("}");
    if (first >= 0 && last > first) {
      const parsed = JSON.parse(cleaned.slice(first, last + 1)); // bare parse
      if (typeof parsed.summary === "string") {
        return { summary: parsed.summary.trim(), title: ... };
      }
    }
  } catch {
    // Fall through to raw text.
  }
  return { summary: cleaned.trim(), title: "" };
}

Conversation auto-summary (auto-summary.service.ts:233-256):

function cleanJsonishResponse(raw: string): string {
  // Strip fences, find first { last }
}

function parseSummaryResponse(raw: string): DaySummaryEntry {
  try {
    const parsed = JSON.parse(cleanJsonishResponse(trimmed)); // bare parse
  } catch {
    return { summary: trimmed, keyDetails: [] }; // fallback: raw text
  }
}

Both fall through to raw text on parse failure. No jsonrepair, no bracket closing, no structural repair.

What the summary parsers fix vs miss

Malformed JSON pattern Shared module (repairJsonText) Summary parsers
Trailing commas: {"a": 1,} ✅ ❌
// and /* */ comments ✅ ❌
... ellipsis placeholders ✅ ❌
Single quotes: {'key': 'val'} ✅ ❌
Unquoted keys: {key: "val"} ✅ ❌
Missing closing brackets: { ✅ (closeOpenJsonContainers) ❌
Unescaped control characters ✅ ❌
Mixed structural issues ✅ (4-candidate waterfall) ❌

Impact

The roleplay rolling summary fires every N messages (default: 5) and requests JSON output:

{
  "name": "short one-line title for this summary, or empty string",
  "summary": "new summary text to append, or empty string"
}

If the model produces malformed JSON (common with MoEs), the current fallback silently returns the raw text as the summary. This means:

  • The summary may contain markdown fences, code block artifacts, or explanation text
  • The name field is lost (empty string fallback)
  • No retry or repair is attempted

The conversation auto-summary has the same gap — it requests { "summary": "...", "keyDetails": [...] } and falls through to raw text on parse failure.

Proposed solution

Replace bare JSON.parse with the shared repair utility:

roleplay-summary-runtime.ts:

import { repairJsonText } from "../../lib/json-repair.js";

export function parseChatSummaryResult(rawContent: string): ParsedChatSummaryResult {
  const cleaned = rawContent.trim();
  const repaired = repairJsonText(cleaned);
  const jsonStr = repaired ?? (() => {
    // Fallback: extract { } from raw text (existing behavior)
    const first = cleaned.indexOf("{");
    const last = cleaned.lastIndexOf("}");
    return (first >= 0 && last > first) ? cleaned.slice(first, last + 1) : null;
  })();
  if (!jsonStr) return { summary: cleaned.replace(/```(?:json)?\s*/gi, "").replace(/```/g, "").trim(), title: "" };
  try {
    const parsed = JSON.parse(jsonStr);
    if (typeof parsed.summary === "string") {
      return { summary: parsed.summary.trim(), title: normalizeChatSummaryTitle(parsed.name ?? parsed.title) };
    }
  } catch {}
  return { summary: cleaned.replace(/```(?:json)?\s*/gi, "").replace(/```/g, "").trim(), title: "" };
}

auto-summary.service.ts:

import { repairJsonText } from "../../lib/json-repair.js";

function parseSummaryResponse(raw: string): DaySummaryEntry {
  const trimmed = raw.trim();
  const repaired = repairJsonText(trimmed);
  const jsonStr = repaired ?? cleanJsonishResponse(trimmed);
  try {
    const parsed = JSON.parse(jsonStr) as Record<string, unknown>;
    return {
      summary: (typeof parsed.summary === "string" ? parsed.summary : trimmed).trim(),
      keyDetails: Array.isArray(parsed.keyDetails)
        ? parsed.keyDetails.filter((d): d is string => typeof d === "string" && d.trim().length > 0)
        : [],
    };
  } catch {
    return { summary: trimmed, keyDetails: [] };
  }
}

Option B: Add retry with user-visible toast on parse failure

If repairJsonText returns null (unrepairable JSON), retry the LLM call once with a JSON-specific reminder prompt, and show a toast if the retry also fails. This mirrors the agent retry pattern from #4753.

Recommended: Option A + B combined. Upgrade the repair AND add a single retry with toast notification.

Retry consideration

The roleplay summary currently has zero retry logic — if parseChatSummaryResult returns raw text, it's silently accepted. Adding one retry (with a focused "return valid JSON" reminder) would catch cases where the model's first attempt was malformed but the second succeeds. This mirrors the agent retry pattern already established in #4753.

  • #4753 (Agents use weaker JSON repair): This issue identified the two-tier repair problem and proposed the shared json-repair.ts module. PR #4761 implemented it for agents and the workspace agent. The summary parsers were out of scope. This FR extends the fix to cover the remaining code paths.
  • #4741 (Model catalog gaps): Addresses incorrect maxOutput limits for MoE models. Correct token budgets reduce truncation-induced parse failures, but don't fix structurally malformed JSON from MoEs.
  • MoE prompt variant: Improves prompt quality for MoEs to reduce malformed output at the source. Complementary — better prompts mean less repair needed, but robust repair remains necessary as a safety net.

*Research undertaken: Analysis of parseChatSummaryResult (roleplay-summary-runtime.ts:135-160), cleanJsonishResponse/parseSummaryResponse (auto-summary.service.ts:233-256), repairJsonText/tryParseJsonRecord (json-repair.ts:39-65). Confirmed both summary parsers use bare JSON.parse() with fallback to raw text. Verified json-repair.ts is already a dependency and imported by agent-executor.ts (line 38) and workspace-agent.service.ts (line 45). Confirmed no prior art for summary parser repair upgrade in existing issues or PRs — #4753 explicitly scoped to agents and workspace agent only.

Originally created by @xDanteMD on GitHub (Aug 11, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/4925 Originally assigned to: @SpicyMarinara on GitHub. ## What problem does this solve? PR #4761 (fixing #4753) created a shared JSON repair utility (`packages/server/src/lib/json-repair.ts`) and wired it into both the workspace agent and download agents. However, the **summary parsers** were excluded from that scope and still use bare `JSON.parse()` with minimal pre-processing. MoE models (Deepseek, Kimi, GLM, MiMo) have a known failure mode of producing JSON that is structurally malformed sometimes — single quotes instead of double quotes, unquoted keys, missing closing brackets when truncated. The shared `repairJsonText()` function handles all of these via a 4-candidate waterfall (raw → jsonrepair → bracket-closing → combined). The summary parsers do not. ## The two repair systems ### Shared module (robust) — introduced in PR #4761 Location: `packages/server/src/lib/json-repair.ts:39-58` ```typescript export function repairJsonText(raw: string): string | null { let repaired: string | null = null; try { repaired = jsonrepair(raw); } catch {} const candidates = [raw, repaired, closeOpenJsonContainers(raw), repaired && closeOpenJsonContainers(repaired)]; for (const candidate of candidates) { if (!candidate) continue; try { JSON.parse(candidate); return candidate; } catch {} } return null; } ``` **4-candidate waterfall:** raw → jsonrepair → bracket-closing → combined. Handles single quotes, unquoted keys, missing brackets, comments, trailing commas, unescaped control characters. ### Summary parsers (minimal) — unchanged **Roleplay rolling summary** (`roleplay-summary-runtime.ts:135-160`): ```typescript export function parseChatSummaryResult(rawContent: string): ParsedChatSummaryResult { const cleaned = rawContent .trim() .replace(/```(?:json)?\s*/giu, "") // strip code fences .replace(/```/gu, ""); try { const first = cleaned.indexOf("{"); const last = cleaned.lastIndexOf("}"); if (first >= 0 && last > first) { const parsed = JSON.parse(cleaned.slice(first, last + 1)); // bare parse if (typeof parsed.summary === "string") { return { summary: parsed.summary.trim(), title: ... }; } } } catch { // Fall through to raw text. } return { summary: cleaned.trim(), title: "" }; } ``` **Conversation auto-summary** (`auto-summary.service.ts:233-256`): ```typescript function cleanJsonishResponse(raw: string): string { // Strip fences, find first { last } } function parseSummaryResponse(raw: string): DaySummaryEntry { try { const parsed = JSON.parse(cleanJsonishResponse(trimmed)); // bare parse } catch { return { summary: trimmed, keyDetails: [] }; // fallback: raw text } } ``` Both fall through to raw text on parse failure. No `jsonrepair`, no bracket closing, no structural repair. ## What the summary parsers fix vs miss | Malformed JSON pattern | Shared module (`repairJsonText`) | Summary parsers | | --- | --- | --- | | Trailing commas: `{"a": 1,}` | ✅ | ❌ | | `//` and `/* */` comments | ✅ | ❌ | | `...` ellipsis placeholders | ✅ | ❌ | | Single quotes: `{'key': 'val'}` | ✅ | ❌ | | Unquoted keys: `{key: "val"}` | ✅ | ❌ | | Missing closing brackets: `{` | ✅ (`closeOpenJsonContainers`) | ❌ | | Unescaped control characters | ✅ | ❌ | | Mixed structural issues | ✅ (4-candidate waterfall) | ❌ | ## Impact The roleplay rolling summary fires every N messages (default: 5) and requests JSON output: ```json { "name": "short one-line title for this summary, or empty string", "summary": "new summary text to append, or empty string" } ``` If the model produces malformed JSON (common with MoEs), the current fallback silently returns the raw text as the summary. This means: - The summary may contain markdown fences, code block artifacts, or explanation text - The `name` field is lost (empty string fallback) - No retry or repair is attempted The conversation auto-summary has the same gap — it requests `{ "summary": "...", "keyDetails": [...] }` and falls through to raw text on parse failure. ## Proposed solution ### Option A: Import `repairJsonText` into both parsers (recommended) Replace bare `JSON.parse` with the shared repair utility: **`roleplay-summary-runtime.ts`:** ```typescript import { repairJsonText } from "../../lib/json-repair.js"; export function parseChatSummaryResult(rawContent: string): ParsedChatSummaryResult { const cleaned = rawContent.trim(); const repaired = repairJsonText(cleaned); const jsonStr = repaired ?? (() => { // Fallback: extract { } from raw text (existing behavior) const first = cleaned.indexOf("{"); const last = cleaned.lastIndexOf("}"); return (first >= 0 && last > first) ? cleaned.slice(first, last + 1) : null; })(); if (!jsonStr) return { summary: cleaned.replace(/```(?:json)?\s*/gi, "").replace(/```/g, "").trim(), title: "" }; try { const parsed = JSON.parse(jsonStr); if (typeof parsed.summary === "string") { return { summary: parsed.summary.trim(), title: normalizeChatSummaryTitle(parsed.name ?? parsed.title) }; } } catch {} return { summary: cleaned.replace(/```(?:json)?\s*/gi, "").replace(/```/g, "").trim(), title: "" }; } ``` **`auto-summary.service.ts`:** ```typescript import { repairJsonText } from "../../lib/json-repair.js"; function parseSummaryResponse(raw: string): DaySummaryEntry { const trimmed = raw.trim(); const repaired = repairJsonText(trimmed); const jsonStr = repaired ?? cleanJsonishResponse(trimmed); try { const parsed = JSON.parse(jsonStr) as Record<string, unknown>; return { summary: (typeof parsed.summary === "string" ? parsed.summary : trimmed).trim(), keyDetails: Array.isArray(parsed.keyDetails) ? parsed.keyDetails.filter((d): d is string => typeof d === "string" && d.trim().length > 0) : [], }; } catch { return { summary: trimmed, keyDetails: [] }; } } ``` ### Option B: Add retry with user-visible toast on parse failure If `repairJsonText` returns null (unrepairable JSON), retry the LLM call once with a JSON-specific reminder prompt, and show a toast if the retry also fails. This mirrors the agent retry pattern from #4753. **Recommended: Option A + B combined.** Upgrade the repair AND add a single retry with toast notification. ## Retry consideration The roleplay summary currently has **zero retry logic** — if `parseChatSummaryResult` returns raw text, it's silently accepted. Adding one retry (with a focused "return valid JSON" reminder) would catch cases where the model's first attempt was malformed but the second succeeds. This mirrors the agent retry pattern already established in #4753. ## Related issues - **#4753 (Agents use weaker JSON repair):** This issue identified the two-tier repair problem and proposed the shared `json-repair.ts` module. PR #4761 implemented it for agents and the workspace agent. The summary parsers were out of scope. This FR extends the fix to cover the remaining code paths. - **#4741 (Model catalog gaps):** Addresses incorrect `maxOutput` limits for MoE models. Correct token budgets reduce truncation-induced parse failures, but don't fix structurally malformed JSON from MoEs. - **[MoE prompt variant](feature-moe-prompt-variant.md):** Improves prompt quality for MoEs to reduce malformed output at the source. Complementary — better prompts mean less repair needed, but robust repair remains necessary as a safety net. --- *Research undertaken: Analysis of `parseChatSummaryResult` (roleplay-summary-runtime.ts:135-160), `cleanJsonishResponse`/`parseSummaryResponse` (auto-summary.service.ts:233-256), `repairJsonText`/`tryParseJsonRecord` (json-repair.ts:39-65). Confirmed both summary parsers use bare `JSON.parse()` with fallback to raw text. Verified `json-repair.ts` is already a dependency and imported by `agent-executor.ts` (line 38) and `workspace-agent.service.ts` (line 45). Confirmed no prior art for summary parser repair upgrade in existing issues or PRs — #4753 explicitly scoped to agents and workspace agent only.
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#2729
No description provided.