Skip to content

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

refactor: share schema-echo handling for prompt refinement (#6794)

[._.]/ Adam Eivyf17fba168b70
diff --git a/server/lib/README.md b/server/lib/README.md
index c9bd159833..68e12d4594 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -414,7 +414,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
|---|---|
| `clientApiPaths.js` | Static scan of the paths `client/src/services/api*.js` requests, for the client↔server route-parity guard (`apiRouteParity.test.js`). `scanClientApiPaths({ repoRoot | sources })` constant-folds the first argument of every `request(…)` — and of every `fetch(`${API_BASE}…`)` the streaming/blob wrappers use instead — from string and template literals, module-local path helpers, ternaries and `...helper(path, …)` spreads into normalized `/api/...` paths (dynamic segments → `:p`), and REPORTS what it cannot fold instead of dropping it. `findUnmountedClientPaths(clientPaths, serverPaths)` diffs those against the `apiRouteGraph.js` inventory, honoring Express 5 `*wildcard` segments. Pure. |
| `htmlToText.js` | Shared HTML → plain-text converter. `htmlToText(html, { extraEntities?, paragraphBreak?, collapseSpaces? })` — strips script/style/head/noscript blocks, converts `<br>`/block closes to newlines, strips remaining tags, decodes entities via `decodeXmlEntities`, collapses 3+ newlines, trims. Options preserve caller-specific output (Gmail: `paragraphBreak: '\n\n'` + `collapseSpaces`; SongBook import: defaults — space runs preserved for tab alignment). |
-| `jsonExtract.js` | Pull JSON blocks out of LLM responses. `findBalancedBlocks` walks top-level blocks and stops at the first unbalanced one; `findAllBalancedBlocks` is the stack-based variant that scans past stray braces and returns nested blocks in closing order (reverse it for outermost-newest-first). |
+| `jsonExtract.js` | Pull JSON blocks out of LLM responses. `extractNonPlaceholderJson(raw, { field })` skips echoed schema placeholders and distinguishes placeholder-only from parse failures. `findBalancedBlocks` walks top-level blocks and stops at the first unbalanced one; `findAllBalancedBlocks` is the stack-based variant that scans past stray braces and returns nested blocks in closing order (reverse it for outermost-newest-first). |
| `taskParser.js` | Parse `TASKS.md` format. |
| `taskGenerationOverrides.js` | `applyTaskGenerationOverrides(provider, metadata)` — the per-RUN `temperature` / `thinking` / `effort` a task form or schedule entry pins, layered onto a COPY of the provider record (the saved record is shared by every other run; the child-env composer turns the copy into OpenCode’s dynamic `agent.build` config downstream). Every value arrives untrusted — a COS-TASKS.md round-trip hands back strings — so each override applies only when it validates, and an empty temperature field is absent rather than `0`, which would otherwise pin greedy decoding on a task whose author just cleared the box. |
| `cosTaskPrompt.js` | The CoS task prompt/note split (#4153) — `metadata.prompt` is the full agent-facing payload, `metadata.context` the one-line human note. `isPromptPayload(value)` is the single discriminator (a newline means it's a prompt, not a note), shared by the store's write path and the on-disk migration so they can't classify the same task differently. `getTaskPrompt(task)` prefers `metadata.prompt` and falls back to a legacy `metadata.context`; `getTaskContextNote(task)` returns the note only on an already-split task; `taskContextBlock(task)` renders both as one block so prompt templates (including customized ones) never see the split; `splitTaskPromptFields(metadata)` routes a multi-line `context` to `prompt` at CREATE time only. Pure, dependency-free. |
diff --git a/server/lib/jsonExtract.js b/server/lib/jsonExtract.js
index e34ef4707b..d6bf782b69 100644
--- a/server/lib/jsonExtract.js
+++ b/server/lib/jsonExtract.js
@@ -8,14 +8,8 @@
* emit trailing commas, `[...]` placeholder elisions, and the Codex
* `}}]` orphan-brace corruption pattern.
*
- * This module collapses three near-identical extractors that all solved
- * the same problem:
- * - universeBuilderExpand.js — string-aware brace walker + repair passes
- * - mediaPromptRefiner.js#extractRefinementJson — brace walker without repairs
- * - stageRunner.js#extractJson — greedy regex
- *
- * The richest implementation (universeBuilderExpand) is promoted here and
- * the three callers import from this file with optional shape predicates.
+ * Callers share the brace walkers and repair passes; refinement callers
+ * additionally reject echoed schema placeholders with extractNonPlaceholderJson.
*/
import { stripCodeFences } from './llmText.js';
@@ -514,3 +508,43 @@ export function extractJson(text, { shapePredicate, blockType = 'object', skipIn
lastPreview,
};
}
+
+/**
+ * Extract a refinement with a string field, skipping echoed <...> schema
+ * placeholders. Keeps placeholder-only failures distinct from parse failures;
+ * unlike extractJson, never falls back to an object with the wrong shape.
+ * Preserves the refiners' first-inner-fence heuristic.
+ */
+export function extractNonPlaceholderJson(raw, { field }) {
+ if (typeof raw !== 'string' || !raw.trim()) throw new Error('Empty AI response');
+ let s = raw.trim();
+ const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);
+ if (fence) s = fence[1].trim();
+
+ const candidates = findBalancedBlocks(s);
+ if (!candidates.length) candidates.push(s);
+
+ // Walk every balanced block ourselves rather than calling the shared
+ // extractJson — we need a tri-state outcome (real refinement, placeholder
+ // echo, or parse error) to surface the "schema placeholder" error message
+ // that helps users pick a stronger model. extractJson's shape predicate
+ // collapses placeholder-vs-real into a single fallback path.
+ let placeholderSeen = false;
+ let lastErr;
+ for (const block of candidates) {
+ const result = tryParseWithRepair(block);
+ if (result.error) {
+ lastErr = result.error;
+ continue;
+ }
+ const { value } = result;
+ if (value && typeof value === 'object' && typeof value[field] === 'string') {
+ if (/^\s*<.+>\s*$/.test(value[field])) { placeholderSeen = true; }
+ else return value;
+ }
+ }
+ if (placeholderSeen) {
+ throw new Error('AI returned the schema placeholder instead of a real refinement — try a stronger model or rerun');
+ }
+ throw new Error(`Invalid JSON in AI response${lastErr ? `: ${lastErr.message}` : ''}`);
+}
diff --git a/server/lib/jsonExtract.test.js b/server/lib/jsonExtract.test.js
index f6e7a3dd83..ba74901e0a 100644
--- a/server/lib/jsonExtract.test.js
+++ b/server/lib/jsonExtract.test.js
@@ -1,3 +1,4 @@
+import { extractNonPlaceholderJson } from "./jsonExtract.js";
import { describe, it, expect } from 'vitest';
import { findAllBalancedBlocks, findBalancedBlocks, tryParseWithRepair, extractJson } from './jsonExtract.js';
import { BRAIN_DIGEST_ECHO_FIXTURE } from '../test/fixtures/brainDigestEcho.js';
@@ -349,3 +350,66 @@ describe('findAllBalancedBlocks', () => {
expect(findAllBalancedBlocks('')).toEqual([]);
});
});
+
+describe("extractNonPlaceholderJson", () => {
+ const extractRefinementJson = (raw) => extractNonPlaceholderJson(raw, { field: "starterPrompt" });
+ it("parses a raw refinement object", () => {
+ const obj = {
+ starterPrompt: "a darker scavenger universe",
+ stylePrompt: "gritty palette, deep shadows",
+ negativePrompt: "cute, neon",
+ rationale: "pushed mood toward grim",
+ };
+ expect(extractRefinementJson(JSON.stringify(obj))).toEqual(obj);
+ });
+
+ it("strips ```json fences", () => {
+ const fenced =
+ '```json\n{"starterPrompt":"x","stylePrompt":"y","negativePrompt":""}\n```';
+ expect(extractRefinementJson(fenced)).toMatchObject({
+ starterPrompt: "x",
+ stylePrompt: "y",
+ });
+ });
+
+ it("skips preamble before the JSON", () => {
+ const raw =
+ 'Here is the refinement:\n{"starterPrompt":"x","stylePrompt":"y"}\nend';
+ expect(extractRefinementJson(raw)).toMatchObject({ starterPrompt: "x" });
+ });
+
+ it("skips a schema-example block that has a <…> placeholder starterPrompt and parses the real block (Codex CLI prompt echo)", () => {
+ const raw = [
+ "codex banner",
+ // The prompt template body — its first balanced { ... } block contains
+ // <…> placeholders that walked past extractRefinementJson by mistake
+ // would surface as "AI returned schema placeholder" instead of finding
+ // the real response below it.
+ '{"starterPrompt":"<full rewritten…>","stylePrompt":"<…>","negativePrompt":"<…>"}',
+ "codex response:",
+ '{"starterPrompt":"a darker universe","stylePrompt":"gritty","negativePrompt":""}',
+ ].join("\n");
+ const out = extractRefinementJson(raw);
+ expect(out.starterPrompt).toBe("a darker universe");
+ expect(out.stylePrompt).toBe("gritty");
+ });
+
+ it("throws when ONLY schema-placeholder blocks are present", () => {
+ const raw = '{"starterPrompt":"<placeholder>","stylePrompt":"<x>"}';
+ expect(() => extractRefinementJson(raw)).toThrow(/schema placeholder/);
+ });
+
+ it("throws on empty / non-string input", () => {
+ expect(() => extractRefinementJson("")).toThrow(/Empty AI response/);
+ expect(() => extractRefinementJson(null)).toThrow(/Empty AI response/);
+ });
+
+ it("throws when no balanced JSON object with starterPrompt is present", () => {
+ expect(() => extractRefinementJson("just prose, no json")).toThrow(
+ /Invalid JSON/,
+ );
+ expect(() => extractRefinementJson('{"prompt":"unrelated shape"}')).toThrow(
+ /Invalid JSON/,
+ );
+ });
+});
diff --git a/server/services/mediaPromptRefiner.js b/server/services/mediaPromptRefiner.js
index 1131748550..1db89f9c73 100644
--- a/server/services/mediaPromptRefiner.js
+++ b/server/services/mediaPromptRefiner.js
@@ -1,5 +1,5 @@
import { ServerError } from '../lib/errorHandler.js';
-import { findBalancedBlocks, tryParseWithRepair } from '../lib/jsonExtract.js';
+import { extractNonPlaceholderJson } from '../lib/jsonExtract.js';
import { clampToCharLimit } from '../lib/textUtils.js';
import { resolveEffectiveModel, runPromptThroughProvider } from './promptRunner.js';
import { getProviderById } from './providers.js';
@@ -17,52 +17,6 @@ const cleanChanges = (changes) => (
: []
);
-// The prompt template uses `<...>` markers for every field placeholder. If a
-// JSON block's `prompt` is still wrapped in angle brackets, the model parroted
-// the schema example back instead of producing a real refinement — skip it so
-// Codex's habit of replaying its stdin to stdout doesn't poison the result.
-const isPlaceholderPrompt = (s) => typeof s === 'string' && /^\s*<.+>\s*$/.test(s);
-
-// Codex CLI prepends a banner like `OpenAI Codex CLI...` and `[workdir, /…]`
-// metadata before the model's JSON output, AND echoes the input prompt to
-// stdout (which contains the schema example {…}). Walk braces with string-
-// awareness via the shared lib, skip any block whose `prompt` is a
-// placeholder, and return the first remaining block that parses as an
-// object with a `prompt` field.
-function extractRefinementJson(raw) {
- if (typeof raw !== 'string' || !raw.trim()) throw new Error('Empty AI response');
- let s = raw.trim();
- const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (fence) s = fence[1].trim();
-
- const candidates = findBalancedBlocks(s);
- if (!candidates.length) candidates.push(s);
-
- // Walk every balanced block ourselves rather than calling the shared
- // extractJson — we need a tri-state outcome (real refinement, placeholder
- // echo, or parse error) to surface the "schema placeholder" error message
- // that helps users pick a stronger model. extractJson's shape predicate
- // collapses placeholder-vs-real into a single fallback path.
- let placeholderSeen = false;
- let lastErr;
- for (const block of candidates) {
- const result = tryParseWithRepair(block);
- if (result.error) {
- lastErr = result.error;
- continue;
- }
- const { value } = result;
- if (value && typeof value === 'object' && typeof value.prompt === 'string') {
- if (isPlaceholderPrompt(value.prompt)) { placeholderSeen = true; }
- else return value;
- }
- }
- if (placeholderSeen) {
- throw new Error('AI returned the schema placeholder instead of a real refinement — try a stronger model or rerun');
- }
- throw new Error(`Invalid JSON in AI response${lastErr ? `: ${lastErr.message}` : ''}`);
-}
-
export function buildMediaPromptRefinePrompt({ kind, prompt, negativePrompt, feedback, renderConfig = {}, maxPromptLength }) {
const kindLabel = kind === 'video' ? 'video' : 'image';
// Some render backends cap the prompt and REJECT anything longer instead of
@@ -209,7 +163,7 @@ export async function refineMediaPrompt({
let parsed;
try {
- parsed = extractRefinementJson(text || '');
+ parsed = extractNonPlaceholderJson(text || '', { field: 'prompt' });
} catch (e) {
// Log only the response size + error reason, not the raw body. The body
// can contain user prompts or other sensitive content; the persisted
diff --git a/server/services/universeBuilderRefine.js b/server/services/universeBuilderRefine.js
index f68dfd89b1..f3772f3ac9 100644
--- a/server/services/universeBuilderRefine.js
+++ b/server/services/universeBuilderRefine.js
@@ -12,7 +12,7 @@
*/
import { ServerError } from "../lib/errorHandler.js";
-import { findBalancedBlocks, tryParseWithRepair } from "../lib/jsonExtract.js";
+import { extractNonPlaceholderJson } from "../lib/jsonExtract.js";
import { assertProvider, resolveProviderAndModel, resolveEffectiveModel, runPromptThroughProvider, assertVisionRunUsedImages } from "./promptRunner.js";
import { resolveAPIProvider } from './aiProvider.js';
import {
@@ -55,58 +55,6 @@ const cleanChanges = (changes) =>
.slice(0, MAX_CHANGES)
: [];
-// Same extractor shape as mediaPromptRefiner: Codex CLI echoes the prompt to
-// stdout before the model response, and the prompt itself contains a JSON
-// schema example whose braces balance but whose contents are placeholder
-// text. Walk every brace-balanced block in order (lib/jsonExtract.js) and
-// return the first that looks like a refinement payload (object with a
-// `starterPrompt` string).
-const isPlaceholder = (s) => typeof s === "string" && /^\s*<.+>\s*$/.test(s);
-
-function extractRefinementJson(raw) {
- if (typeof raw !== "string" || !raw.trim())
- throw new Error("Empty AI response");
- let s = raw.trim();
- const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (fence) s = fence[1].trim();
-
- const candidates = findBalancedBlocks(s);
- if (!candidates.length) candidates.push(s);
-
- // Walk every balanced block ourselves rather than calling the shared
- // extractJson — we need a tri-state outcome (real refinement, placeholder
- // echo, or parse error) to surface the "schema placeholder" error message
- // that helps users pick a stronger model. extractJson's shape predicate
- // collapses placeholder-vs-real into a single fallback path.
- let placeholderSeen = false;
- let lastErr;
- for (const block of candidates) {
- const result = tryParseWithRepair(block);
- if (result.error) {
- lastErr = result.error;
- continue;
- }
- const { value } = result;
- if (
- value &&
- typeof value === "object" &&
- typeof value.starterPrompt === "string"
- ) {
- if (isPlaceholder(value.starterPrompt)) {
- placeholderSeen = true;
- } else return value;
- }
- }
- if (placeholderSeen) {
- throw new Error(
- "AI returned the schema placeholder instead of a real refinement — try a stronger model or rerun",
- );
- }
- throw new Error(
- `Invalid JSON in AI response${lastErr ? `: ${lastErr.message}` : ""}`,
- );
-}
-
const lockedList = (locked) =>
LOCKABLE_FIELDS.filter((k) => locked && locked[k] === true).map(
(k) => `- ${LOCKABLE_FIELD_LABELS[k]} ("${k}")`,
@@ -471,7 +419,7 @@ export async function refineWorldPrompts({
let parsed;
try {
- parsed = extractRefinementJson(text || "");
+ parsed = extractNonPlaceholderJson(text || "", { field: "starterPrompt" });
} catch (e) {
console.warn(
`⚠️ universe-refine [${provider.id}/${selectedModel || "default"} runId=${runId}] parse failed: ${e.message} (response size: ${(text || "").length} chars)`,
@@ -561,7 +509,6 @@ export async function refineWorldPrompts({
}
export const __testing = {
- extractRefinementJson,
buildWorldRefinePrompt,
collapseStyleDirectionDupes,
mergeCategoriesWithLocks,
diff --git a/server/services/universeBuilderRefine.test.js b/server/services/universeBuilderRefine.test.js
index 1d84858688..4127b58516 100644
--- a/server/services/universeBuilderRefine.test.js
+++ b/server/services/universeBuilderRefine.test.js
@@ -3,75 +3,12 @@ import { __testing } from "./universeBuilderRefine.js";
import { mergeInfluencesWithLocksAdditive } from "./universeBuilder.js";
const {
- extractRefinementJson,
buildWorldRefinePrompt,
collapseStyleDirectionDupes,
mergeCategoriesWithLocks,
mergeCompositesWithLocks,
} = __testing;
-describe("universeBuilderRefine.extractRefinementJson", () => {
- it("parses a raw refinement object", () => {
- const obj = {
- starterPrompt: "a darker scavenger universe",
- stylePrompt: "gritty palette, deep shadows",
- negativePrompt: "cute, neon",
- rationale: "pushed mood toward grim",
- };
- expect(extractRefinementJson(JSON.stringify(obj))).toEqual(obj);
- });
-
- it("strips ```json fences", () => {
- const fenced =
- '```json\n{"starterPrompt":"x","stylePrompt":"y","negativePrompt":""}\n```';
- expect(extractRefinementJson(fenced)).toMatchObject({
- starterPrompt: "x",
- stylePrompt: "y",
- });
- });
-
- it("skips preamble before the JSON", () => {
- const raw =
- 'Here is the refinement:\n{"starterPrompt":"x","stylePrompt":"y"}\nend';
- expect(extractRefinementJson(raw)).toMatchObject({ starterPrompt: "x" });
- });
-
- it("skips a schema-example block that has a <…> placeholder starterPrompt and parses the real block (Codex CLI prompt echo)", () => {
- const raw = [
- "codex banner",
- // The prompt template body — its first balanced { ... } block contains
- // <…> placeholders that walked past extractRefinementJson by mistake
- // would surface as "AI returned schema placeholder" instead of finding
- // the real response below it.
- '{"starterPrompt":"<full rewritten…>","stylePrompt":"<…>","negativePrompt":"<…>"}',
- "codex response:",
- '{"starterPrompt":"a darker universe","stylePrompt":"gritty","negativePrompt":""}',
- ].join("\n");
- const out = extractRefinementJson(raw);
- expect(out.starterPrompt).toBe("a darker universe");
- expect(out.stylePrompt).toBe("gritty");
- });
-
- it("throws when ONLY schema-placeholder blocks are present", () => {
- const raw = '{"starterPrompt":"<placeholder>","stylePrompt":"<x>"}';
- expect(() => extractRefinementJson(raw)).toThrow(/schema placeholder/);
- });
-
- it("throws on empty / non-string input", () => {
- expect(() => extractRefinementJson("")).toThrow(/Empty AI response/);
- expect(() => extractRefinementJson(null)).toThrow(/Empty AI response/);
- });
-
- it("throws when no balanced JSON object with starterPrompt is present", () => {
- expect(() => extractRefinementJson("just prose, no json")).toThrow(
- /Invalid JSON/,
- );
- expect(() => extractRefinementJson('{"prompt":"unrelated shape"}')).toThrow(
- /Invalid JSON/,
- );
- });
-});
-
describe("universeBuilderRefine.buildWorldRefinePrompt", () => {
it("includes originals + influences + feedback verbatim", () => {
const out = buildWorldRefinePrompt({