Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: recover serialized LLM JSON tails
[._.]/ Adam Eivy8bce773a0ec8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c36319b103..672387c64f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -56,6 +56,8 @@## Fixed+- **Complete LLM answers no longer fail on recoverable JSON serialization mistakes.** A long character-foundation repair could begin as normal JSON, then emit its complete remaining objects as escaped `\\n` / `\\"` text and leave quotation marks inside prose unescaped. The shared parser now decodes an escaped tail only from the JSON parser's exact failure position, escapes only quotes that cannot legally close their string, and accepts repairs only when the entire reconstructed response parses—preserving expensive completed work without making partial or arbitrary text look valid.+- **The foundation judge no longer mistakes visual prompt families for binding story canon.** Universe Builder categories are additive image-prompt design systems, but the foundation judge rendered their labels beside the narrative bible and named canon, then penalized duplicate-looking creatures, vehicles, and artifacts even though its world-repair editor can only revise narrative world rules. That produced a structurally unwinnable loop: the critic demanded canon-tier metadata or inventory pruning from a repair path that could not—and must not—delete the user's visual assets. Foundation scoring now reads the universe logline, premise, style, influences, and named canon only; visual prompt families remain intact and available for rendering, but edits to them no longer invalidate or distort a narrative verdict.- **A TUI provider that exhausts its own request retries no longer returns an error screen as successful story output.** Claude Code may retry a backend timeout ten times, render a final `Request timed out` banner, and still exit with code 0. One long foundation repair consequently spent nearly an hour, produced no response file, and then sent terminal chrome into the universe JSON parser as if it were a 13K-character bible. The one-shot TUI runner now distinguishes recoverable `Retrying … attempt N/10` banners from the terminal gutter-owned timeout, records the latter as a real timeout, and enters the existing fallback cascade. Genuine long-running model work keeps its configured ceiling; only the provider's explicit exhausted-retry state ends the call.diff --git a/server/lib/jsonExtract.js b/server/lib/jsonExtract.jsindex ae550dffb5..96b1faed18 100644--- a/server/lib/jsonExtract.js+++ b/server/lib/jsonExtract.js@@ -221,6 +221,52 @@ function escapeControlCharsInStrings(input) {return out;}+/**+ * Escape a quote that appears inside a JSON string without its required+ * backslash. A quote can close a JSON string only when the next non-whitespace+ * character is a structural delimiter (`:`, `,`, `}`, or `]`) or the document+ * ends. Anything else means prose continues after the quote, so retaining it as+ * a delimiter cannot produce valid JSON. This deliberately repairs only that+ * unambiguous case; the caller still accepts the result only after a full parse.+ */+function escapeBareQuotesInStrings(input) {+ if (typeof input !== 'string' || !input) return input;+ let out = '';+ let inString = false;+ let escaped = false;+ for (let i = 0; i < input.length; i += 1) {+ const ch = input[i];+ if (!inString) {+ out += ch;+ if (ch === '"') inString = true;+ continue;+ }+ if (escaped) {+ out += ch;+ escaped = false;+ continue;+ }+ if (ch === '\\') {+ out += ch;+ escaped = true;+ continue;+ }+ if (ch !== '"') {+ out += ch;+ continue;+ }+ let next = i + 1;+ while (next < input.length && /\s/.test(input[next])) next += 1;+ if (next >= input.length || /[:,}\]]/.test(input[next])) {+ out += ch;+ inString = false;+ } else {+ out += '\\"';+ }+ }+ return out;+}+/*** Try JSON.parse on a candidate block. If it fails, apply cheap repairs* for observed LLM corruption patterns and try again:@@ -230,6 +276,12 @@ function escapeControlCharsInStrings(input) {* between a variation's close-brace and the array's `]`. Swapping* `}}]` → `}]}` (not dropping the brace) keeps the brace count* correct so the outer container still closes.+ * - A serialized JSON tail — the model begins with ordinary JSON, then+ * accidentally emits the remainder as JSON-string escapes (`\\n`, `\\"`).+ * Decode only from JSON.parse's exact failure position and only keep the+ * result when the reconstructed whole document parses.+ * - Unescaped quotation marks inside prose string values — escape only a+ * quote that cannot legally close the string because prose follows it.* - Raw control chars (literal newlines/tabs) inside a string value —* escaped to their `\n`/`\t`/`\uXXXX` forms (see* escapeControlCharsInStrings). Common when a model writes a long@@ -257,8 +309,20 @@ export function tryParseWithRepair(jsonText) {const initialResult = safeParse(initial);if (!initialResult.error) return initialResult;- const noTrailing = replaceOutsideStrings(initial, /,(\s*[}\]])/g, '$1');- if (noTrailing !== initial) {+ const unescapedTail = unescapeSerializedJsonTail(initial, initialResult.error);+ if (unescapedTail !== initial) {+ const tailResult = safeParse(unescapedTail);+ if (!tailResult.error) return tailResult;+ }++ const escapedQuotes = escapeBareQuotesInStrings(unescapedTail);+ if (escapedQuotes !== unescapedTail) {+ const quotesResult = safeParse(escapedQuotes);+ if (!quotesResult.error) return quotesResult;+ }++ const noTrailing = replaceOutsideStrings(escapedQuotes, /,(\s*[}\]])/g, '$1');+ if (noTrailing !== escapedQuotes) {const trailingResult = safeParse(noTrailing);if (!trailingResult.error) return trailingResult;}@@ -280,6 +344,29 @@ export function tryParseWithRepair(jsonText) {return { error: orphanResult.error };}+/**+ * Recover an observed one-shot LLM corruption where a valid JSON prefix is+ * followed by the rest of the document encoded as a JSON string fragment.+ * V8 reports the first outside-string backslash as the parse position, giving+ * us an exact and conservative decode boundary. Wrapping the tail in quotes+ * decodes its `\\n` / `\\"` sequences without guessing at individual escapes;+ * callers still require the entire reconstructed document to parse before+ * accepting it.+ */+function unescapeSerializedJsonTail(input, error) {+ const match = error?.message?.match(/position (\d+)/);+ const position = Number(match?.[1]);+ if (!Number.isInteger(position) || position < 0 || input[position] !== '\\') return input;++ const tail = input.slice(position);+ if (!/^\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4})/.test(tail)) return input;+ const trailingWhitespace = tail.match(/\s*$/)?.[0] || '';+ const encodedTail = trailingWhitespace ? tail.slice(0, -trailingWhitespace.length) : tail;+ const decoded = safeParse(`"${encodedTail}"`);+ if (decoded.error || typeof decoded.value !== 'string') return input;+ return `${input.slice(0, position)}${decoded.value}${trailingWhitespace}`;+}+// Returns `{ value }` on success or `{ error }` on failure. The discriminated// shape lets a JSON `null` literal flow through as a valid parsed value// (some LLMs legitimately return `null`); a single-value-with-sentineldiff --git a/server/lib/jsonExtract.test.js b/server/lib/jsonExtract.test.jsindex 6e04084c3f..fabf6a2d4b 100644--- a/server/lib/jsonExtract.test.js+++ b/server/lib/jsonExtract.test.js@@ -89,6 +89,41 @@ describe('jsonExtract.tryParseWithRepair', () => {expect(tryParseWithRepair('{"vars":[...]}')).toEqual({ value: { vars: [] } });});+ it('repairs a complete JSON document whose remaining tail was serialized as escaped text', () => {+ const bad = [+ '{',+ ' "items": [',+ ' { "name": "Alpha", "notes": ["kept"]\\n },\\n {\\n \\"name\\": \\"Beta\\",\\n \\"notes\\": [\\"also kept\\"]\\n }\\n ]\\n}',+ ].join('\n');+ expect(tryParseWithRepair(bad)).toEqual({+ value: {+ items: [+ { name: 'Alpha', notes: ['kept'] },+ { name: 'Beta', notes: ['also kept'] },+ ],+ },+ });+ });++ it('escapes unescaped quotation marks inside a prose string value', () => {+ const bad = '{"voice":"She calls it "the old rule" before rejecting it.","ok":true}';+ expect(tryParseWithRepair(bad)).toEqual({+ value: { voice: 'She calls it "the old rule" before rejecting it.', ok: true },+ });+ });++ it('combines serialized-tail and bare-quote repairs in one completed response', () => {+ const bad = '{"items":[{"voice":"plain"}\\n, {\\n \\"voice\\": \\"Calls it \\"witness\\" before answering.\\"\\n}\\n]}';+ expect(tryParseWithRepair(bad)).toEqual({+ value: { items: [{ voice: 'plain' }, { voice: 'Calls it "witness" before answering.' }] },+ });+ });++ it('does not guess at an invalid backslash tail that is not a serialized JSON fragment', () => {+ const bad = '{"items":[]}\\not-json';+ expect(tryParseWithRepair(bad).error).toBeInstanceOf(Error);+ });+it('escapes raw control chars (literal newlines/tabs) inside a string value', () => {// A model writes a multi-line markdown field with literal newlines/tabs// instead of the `\n`/`\t` escapes JSON requires — JSON.parse throwsdiff --git a/server/lib/stageRunner.test.js b/server/lib/stageRunner.test.jsindex de123124b5..085a0e4b46 100644--- a/server/lib/stageRunner.test.js+++ b/server/lib/stageRunner.test.js@@ -185,6 +185,10 @@ describe('stageRunner — extractJson', () => {it('parses JSON inside markdown code fences', () => {expect(extractJson('```json\n{"a":1}\n```')).toEqual({ a: 1 });});+ it('recovers a response that serializes its remaining JSON tail as escaped text', () => {+ const raw = '{"items":[{"id":"one"}\\n, {\\n \\"id\\": \\"two\\"\\n}\\n]}';+ expect(extractJson(raw)).toEqual({ items: [{ id: 'one' }, { id: 'two' }] });+ });it('extracts the first balanced object even when prose is prepended', () => {expect(extractJson('Sure! Here is the data: {"a":1,"b":2} cheers.')).toEqual({ a: 1, b: 2 });});