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

address review (claude): skip inner-fence heuristic when salvaging a sentinel with a code-fence body

[._.]/ Adam Eivy653c6ded030c
diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.js
index 5248eda808..a42d40c59b 100644
--- a/server/lib/agentSentinel.js
+++ b/server/lib/agentSentinel.js
@@ -76,8 +76,13 @@ export async function salvageSentinelPayload(contents) {
// The documented sentinel envelope: a plain object carrying a `payload` key.
const isEnvelope = (v) => v && typeof v === 'object' && !Array.isArray(v) && 'payload' in v;
+ // skipInnerFence: the reasoner's `payload.proposal.body` is markdown that
+ // routinely contains its own ```code``` fence; without this, extractJson's
+ // inner-fence heuristic would lock onto that body fence and discard the whole
+ // envelope. Balanced-block walking is string-aware, so a fence inside the
+ // JSON string value can't derail it.
const { extractJson } = await import('./jsonExtract.js');
- const { value } = extractJson(trimmed, { shapePredicate: isEnvelope });
+ const { value } = extractJson(trimmed, { shapePredicate: isEnvelope, skipInnerFence: true });
// Re-verify the shape: extractJson falls back to the first block that merely
// PARSED (ignoring the predicate) when none matched, so an incidental
// non-envelope object must not be adopted as a payload.
diff --git a/server/lib/agentSentinel.test.js b/server/lib/agentSentinel.test.js
index 03923304ec..37db3ceb0b 100644
--- a/server/lib/agentSentinel.test.js
+++ b/server/lib/agentSentinel.test.js
@@ -83,6 +83,20 @@ describe('agentSentinel', () => {
expect(payload).toEqual({ proposal: { slug: 'x', body: 'line one\nline two\ttabbed' } });
});
+ it('recovers an envelope whose proposal body contains a markdown code fence', async () => {
+ // A reasoner proposing code writes a ```-fenced snippet into the body
+ // string. The inner-fence heuristic would otherwise lock onto that body
+ // fence and discard the envelope — salvage must skip it.
+ const withCodeBody = {
+ summary: 's',
+ payload: { proposal: { slug: 'x', body: 'Change this:\n```js\nconst a = 1;\n```\ndone' } }
+ };
+ // Both a fenced-wrapper form and a raw (unwrapped) form must recover.
+ const fenced = '```json\n' + JSON.stringify(withCodeBody) + '\n```';
+ expect((await salvageSentinelPayload(fenced)).payload).toEqual(withCodeBody.payload);
+ expect((await salvageSentinelPayload(JSON.stringify(withCodeBody))).payload).toEqual(withCodeBody.payload);
+ });
+
it('does NOT misread a legacy markdown summary as structured', async () => {
const md = '## Done\n\nRefactored `foo()` to return `{ ok: true }` on success.';
expect(await salvageSentinelPayload(md)).toEqual({ summary: md, payload: null });
diff --git a/server/lib/jsonExtract.js b/server/lib/jsonExtract.js
index 4f3dbeb075..5b7c362b3c 100644
--- a/server/lib/jsonExtract.js
+++ b/server/lib/jsonExtract.js
@@ -245,12 +245,19 @@ function safeParse(text) {
* skip in-prompt schema examples that parse cleanly but aren't the answer.
* @param {'object'|'array'} [options.blockType='object'] — top-level shape
* to walk for (`{...}` vs `[...]`).
+ * @param {boolean} [options.skipInnerFence=false] — skip the "first inner
+ * ```…``` block" heuristic (see below). Set this when the JSON's own string
+ * VALUES may contain fenced markdown (e.g. a proposal `body` with a code
+ * snippet): the heuristic would otherwise lock onto that inner fence and
+ * discard the surrounding object. Only the outer-wrapper strip
+ * (`stripCodeFences`) runs, then balanced-block walking — which is
+ * string-aware, so backticks inside a JSON string can't derail it.
* @returns {{ value:unknown, lastError?:Error, lastPreview?:string }}
* — `value` is the parsed block, or `undefined` when no block matches.
* On no-match, `lastError` + `lastPreview` (200-char excerpt of the last
* candidate text) are populated for use in caller error messages.
*/
-export function extractJson(text, { shapePredicate, blockType = 'object' } = {}) {
+export function extractJson(text, { shapePredicate, blockType = 'object', skipInnerFence = false } = {}) {
if (typeof text !== 'string' || !text.trim()) {
return { value: undefined, lastError: new Error('Empty LLM response'), lastPreview: '' };
}
@@ -263,9 +270,13 @@ export function extractJson(text, { shapePredicate, blockType = 'object' } = {})
// prompt-echo content BEFORE the real response should skip this
// helper and walk the full text directly (see stageRunner.extractJson)
// — the first-fence heuristic locks onto the echoed schema and never
- // reaches the actual model output.
- const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);
- if (fence) s = fence[1].trim();
+ // reaches the actual model output. skipInnerFence disables it for callers
+ // whose JSON string values legitimately contain fenced markdown (the fence
+ // is content, not a wrapper) — see the option doc above.
+ if (!skipInnerFence) {
+ const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/);
+ if (fence) s = fence[1].trim();
+ }
const { startChar, endChar } = blockType === 'array'
? { startChar: '[', endChar: ']' }
diff --git a/server/lib/jsonExtract.test.js b/server/lib/jsonExtract.test.js
index f9b4013f78..8534c702f6 100644
--- a/server/lib/jsonExtract.test.js
+++ b/server/lib/jsonExtract.test.js
@@ -99,12 +99,15 @@ describe('jsonExtract.tryParseWithRepair', () => {
});
});
- it('leaves structural whitespace (control chars OUTSIDE strings) untouched', () => {
- // Newlines between tokens are legal structural whitespace — the
- // control-char repair must not misfire on them or on already-escaped
- // sequences inside strings.
- const pretty = '{\n "a": 1,\n "b": "has \\n escaped"\n}';
- expect(tryParseWithRepair(pretty)).toEqual({ value: { a: 1, b: 'has \n escaped' } });
+ it('leaves structural whitespace + already-escaped sequences untouched while escaping a raw control char', () => {
+ // Force the repair to actually run: one string has a RAW newline (invalid),
+ // while the object also has structural inter-token newlines and another
+ // string with an already-escaped `\n`. The repair must escape only the raw
+ // one and leave the structural whitespace and pre-escaped sequence intact.
+ const bad = '{\n "a": "raw\nnewline",\n "b": "already \\n escaped"\n}';
+ expect(tryParseWithRepair(bad)).toEqual({
+ value: { a: 'raw\nnewline', b: 'already \n escaped' },
+ });
});
it('returns the concrete parse error when no repair can recover the input', () => {