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

recover Layered Intelligence proposals when a local model's .agent-done JSON is slightly malformed

[._.]/ Adam Eivyf1584c71be2e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9c041c9aeb..8ead59da6a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -16,3 +16,4 @@
- **AI Providers warns before enabling the Grok Build CLI/TUI.** The Grok harness uploads your entire working repo to xAI (GCP) as it works. A callout now appears both on the `grok-cli` / `grok-tui` provider cards and in the create/edit form (when the command is `grok`) — before you enable it — telling you to add `[harness]` / `disable_codebase_upload = true` to `~/.grok/config.toml` to keep your code local. The plain `grok` API provider — which doesn't run the harness — is intentionally excluded.
- **Layered Intelligence no longer wedges on a stale API-only provider.** Any install that ran the Layered Intelligence loop on an api provider (ollama/lmstudio/kimi) before it became agent-backed (#2322) had that provider carried into the per-app override by migration 184 — where it now outranks the global Schedule pin at spawn. The agent-backed loop needs a file-writing CLI/TUI harness, so those runs skipped with "the selected provider is an API-only model with no coding harness," and picking a CLI/TUI provider on the global Schedule page silently missed (it only sets the fallback pin). The loop now self-heals: an api-only per-app provider falls back to a CLI/TUI schedule pin (adopting its matched model), so the Schedule-page selection finally takes effect. It still skips with the actionable message only when no CLI/TUI provider is configured anywhere.
+- **Layered Intelligence no longer silently drops a proposal when a local model's JSON is slightly malformed.** A reasoning run pinned to a smaller/local model (e.g. Ollama qwen) would find a real gap, then write an almost-valid `.agent-done` envelope — wrapped in ```json fences, trailed by prose, or with literal newlines/tabs pasted into the long markdown body — that the strict sentinel parser rejected, recording "unparseable-response" and filing nothing. The completion chokepoint now falls back to the shared robust LLM-JSON extractor (strips fences, walks balanced blocks, escapes raw control chars) to recover the envelope's payload before giving up, so the proposal still gets filed as a tracker issue. The shared `jsonExtract` repair also gained a raw-control-char pass that benefits every LLM-JSON caller, and the reasoner's finish instructions now spell out "raw JSON only, no fences, escape newlines."
diff --git a/server/lib/README.md b/server/lib/README.md
index e358f83aad..bb69ceeab3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -24,7 +24,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| Module | Purpose |
|---|---|
| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |
-| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. |
+| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
| `appleHealthValidation.js` | Apple Health import payloads. |
| `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |
diff --git a/server/lib/agentSentinel.js b/server/lib/agentSentinel.js
index cd605c93e8..5248eda808 100644
--- a/server/lib/agentSentinel.js
+++ b/server/lib/agentSentinel.js
@@ -45,3 +45,44 @@ export function parseSentinelPayload(contents) {
return { summary: trimmed, payload: null };
}
+
+/**
+ * Lenient fallback for a STRUCTURED sentinel that the strict
+ * `parseSentinelPayload` couldn't read. A less-capable model (notably a local
+ * one) commonly emits an almost-valid `{ summary, payload }` envelope — wrapped
+ * in ```json fences, trailed by prose, or with raw newlines/tabs pasted into
+ * the long markdown `body` string — which `JSON.parse` rejects, silently
+ * dropping a real proposal as "unparseable-response". This runs the shared
+ * robust LLM-JSON extractor (`jsonExtract.extractJson`: strips fences, walks
+ * balanced blocks, repairs trailing commas / orphan braces / raw control
+ * chars) over the raw contents and, ONLY when it recovers the documented
+ * envelope shape (a `{ ..., "payload": ... }` object), surfaces its payload.
+ *
+ * Deliberately narrow: it requires the `payload` key so a legacy plain-markdown
+ * sentinel that merely happens to contain a `{...}` block is never misread as
+ * structured — that stays text (payload null). Async + a LAZY import of
+ * jsonExtract so the barrel re-export of this module doesn't statically pull
+ * jsonExtract's transitive services chain into every lib consumer / mocked
+ * suite. Callers use it as a second tier after `parseSentinelPayload` returns a
+ * null payload (see agentLifecycle's dispatchTaskOutputHook).
+ *
+ * @param {string|null|undefined} contents — raw `.agent-done` contents
+ * @returns {Promise<{ summary: string, payload: unknown }>}
+ */
+export async function salvageSentinelPayload(contents) {
+ const trimmed = typeof contents === 'string' ? contents.trim() : '';
+ if (!trimmed || !trimmed.includes('{')) return { summary: trimmed, payload: null };
+
+ // The documented sentinel envelope: a plain object carrying a `payload` key.
+ const isEnvelope = (v) => v && typeof v === 'object' && !Array.isArray(v) && 'payload' in v;
+
+ const { extractJson } = await import('./jsonExtract.js');
+ const { value } = extractJson(trimmed, { shapePredicate: isEnvelope });
+ // 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.
+ if (!isEnvelope(value)) return { summary: trimmed, payload: null };
+
+ const summary = typeof value.summary === 'string' ? value.summary : '';
+ return { summary, payload: value.payload };
+}
diff --git a/server/lib/agentSentinel.test.js b/server/lib/agentSentinel.test.js
index bd17806377..03923304ec 100644
--- a/server/lib/agentSentinel.test.js
+++ b/server/lib/agentSentinel.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { DONE_SENTINEL_NAME, parseSentinelPayload } from './agentSentinel.js';
+import { DONE_SENTINEL_NAME, parseSentinelPayload, salvageSentinelPayload } from './agentSentinel.js';
describe('agentSentinel', () => {
it('exposes the sentinel filename', () => {
@@ -49,4 +49,53 @@ describe('agentSentinel', () => {
expect(parseSentinelPayload(broken)).toEqual({ summary: broken, payload: null });
});
});
+
+ describe('salvageSentinelPayload', () => {
+ const envelope = {
+ summary: 'Proposed one improvement',
+ payload: { analysis: 'a', proposal: { slug: 'add-telemetry', title: 'Add telemetry' } }
+ };
+
+ it('returns null payload for blank / brace-free contents', async () => {
+ expect(await salvageSentinelPayload(null)).toEqual({ summary: '', payload: null });
+ expect(await salvageSentinelPayload('nothing structured here')).toEqual({ summary: 'nothing structured here', payload: null });
+ });
+
+ it('recovers an envelope wrapped in ```json fences', async () => {
+ const fenced = '```json\n' + JSON.stringify(envelope) + '\n```';
+ const { payload } = await salvageSentinelPayload(fenced);
+ expect(payload).toEqual(envelope.payload);
+ });
+
+ it('recovers an envelope with leading/trailing prose', async () => {
+ const noisy = `Here is my result:\n${JSON.stringify(envelope)}\nDone.`;
+ const { summary, payload } = await salvageSentinelPayload(noisy);
+ expect(payload).toEqual(envelope.payload);
+ expect(summary).toBe('Proposed one improvement');
+ });
+
+ it('recovers an envelope with raw newlines inside a string value', async () => {
+ // A local model pastes a multi-line markdown body verbatim (literal \n,
+ // not the escaped \\n JSON requires) — strict JSON.parse rejects it.
+ const raw = '{"summary":"s","payload":{"proposal":{"slug":"x","body":"line one\nline two\ttabbed"}}}';
+ expect(parseSentinelPayload(raw).payload).toBeNull(); // strict parse fails
+ const { payload } = await salvageSentinelPayload(raw);
+ expect(payload).toEqual({ proposal: { slug: 'x', body: 'line one\nline two\ttabbed' } });
+ });
+
+ 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 });
+ });
+
+ it('does NOT adopt an incidental non-envelope JSON object as payload', async () => {
+ const md = 'Summary of work:\n{"unrelated": "config", "count": 3}';
+ expect((await salvageSentinelPayload(md)).payload).toBeNull();
+ });
+
+ it('surfaces an explicit null payload from a fenced envelope', async () => {
+ const fenced = '```json\n{"summary":"nothing to file","payload":null}\n```';
+ expect(await salvageSentinelPayload(fenced)).toEqual({ summary: 'nothing to file', payload: null });
+ });
+ });
});
diff --git a/server/lib/jsonExtract.js b/server/lib/jsonExtract.js
index d116c53149..4f3dbeb075 100644
--- a/server/lib/jsonExtract.js
+++ b/server/lib/jsonExtract.js
@@ -121,6 +121,45 @@ function replaceOutsideStrings(input, pattern, replacement) {
)).join('');
}
+/**
+ * Escape raw ASCII control characters (U+0000–U+001F) that appear INSIDE a
+ * JSON string literal — the JSON spec forbids them there, they must be
+ * `\n`/`\t`/`\uXXXX` escapes. Less-capable models (notably local ones asked
+ * for a large multi-line markdown field) routinely paste literal newlines/tabs
+ * into a string value, which makes `JSON.parse` throw "Bad control character
+ * in string literal". String-aware: control chars OUTSIDE strings are the
+ * structural whitespace between tokens and are left untouched.
+ */
+function escapeControlCharsInStrings(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) {
+ if (escaped) { out += ch; escaped = false; continue; }
+ if (ch === '\\') { out += ch; escaped = true; continue; }
+ if (ch === '"') { out += ch; inString = false; continue; }
+ const code = input.charCodeAt(i);
+ if (code <= 0x1f) {
+ if (ch === '\n') out += '\\n';
+ else if (ch === '\r') out += '\\r';
+ else if (ch === '\t') out += '\\t';
+ else if (ch === '\b') out += '\\b';
+ else if (ch === '\f') out += '\\f';
+ else out += `\\u${code.toString(16).padStart(4, '0')}`;
+ continue;
+ }
+ out += ch;
+ continue;
+ }
+ if (ch === '"') { out += ch; inString = true; continue; }
+ out += ch;
+ }
+ return out;
+}
+
/**
* Try JSON.parse on a candidate block. If it fails, apply cheap repairs
* for observed LLM corruption patterns and try again:
@@ -130,10 +169,15 @@ function replaceOutsideStrings(input, pattern, replacement) {
* 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.
+ * - 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
+ * multi-line markdown field into a string literal verbatim.
*
- * All repairs are STRING-AWARE: the regexes only touch characters
- * outside quoted JSON string values, so a string containing `,}` or
- * `}}]` as ordinary content is preserved.
+ * The brace/comma repairs are STRING-AWARE: the regexes only touch
+ * characters outside quoted JSON string values, so a string containing
+ * `,}` or `}}]` as ordinary content is preserved. The control-char repair
+ * is likewise confined to inside-string regions.
*
* Returns `{ value }` on success (where `value` may be a valid JSON
* `null`); returns `{ error }` if all repairs fail. The wrapper lets a
@@ -162,6 +206,13 @@ export function tryParseWithRepair(jsonText) {
const orphanResult = safeParse(fixedOrphan);
if (!orphanResult.error) return orphanResult;
+ // Last resort: escape raw control chars inside string literals. Runs on top
+ // of the prior repairs (cumulative) so trailing-comma + orphan-brace + raw
+ // newline corruption in one block still recovers. safeParse already returns
+ // the discriminated { value }/{ error } shape, so pass it straight through.
+ const escaped = escapeControlCharsInStrings(fixedOrphan);
+ if (escaped !== fixedOrphan) return safeParse(escaped);
+
// Surface the last attempt's parse error so the caller can include the
// concrete reason ("Unexpected token } in JSON at position 47") in its
// error message rather than a generic "no JSON block found".
diff --git a/server/lib/jsonExtract.test.js b/server/lib/jsonExtract.test.js
index f68a4343fe..f9b4013f78 100644
--- a/server/lib/jsonExtract.test.js
+++ b/server/lib/jsonExtract.test.js
@@ -89,6 +89,24 @@ describe('jsonExtract.tryParseWithRepair', () => {
expect(tryParseWithRepair('{"vars":[...]}')).toEqual({ value: { vars: [] } });
});
+ 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 throws
+ // "Bad control character". The repair escapes only inside-string controls.
+ const bad = '{"body":"line one\nline two\ttabbed","ok":true}';
+ expect(tryParseWithRepair(bad)).toEqual({
+ value: { body: 'line one\nline two\ttabbed', ok: true },
+ });
+ });
+
+ 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('returns the concrete parse error when no repair can recover the input', () => {
const r1 = tryParseWithRepair('{ this is not valid json');
expect(r1.value).toBeUndefined();
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index c39a96ccfb..255db85d6f 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -935,10 +935,22 @@ async function dispatchTaskOutputHook({ agentId, task, success, workspacePath })
const cwd = workspacePath || task?.metadata?.repoPath || null;
let payload = null;
if (cwd) {
- const { DONE_SENTINEL_NAME, parseSentinelPayload } = await import('../lib/agentSentinel.js');
+ const { DONE_SENTINEL_NAME, parseSentinelPayload, salvageSentinelPayload } = await import('../lib/agentSentinel.js');
const { tryReadFile } = await import('../lib/fileUtils.js');
const contents = await tryReadFile(join(cwd, DONE_SENTINEL_NAME));
payload = parseSentinelPayload(contents).payload;
+ // A less-capable (often local) reasoner can emit an almost-valid
+ // `{ summary, payload }` envelope — ```json-fenced, prose-trailed, or with
+ // raw newlines in the markdown body — that strict parse rejects, dropping a
+ // real proposal as "unparseable-response" and filing nothing. Before giving
+ // up, run the robust LLM-JSON extractor over the raw sentinel.
+ if (payload == null) {
+ const salvaged = await salvageSentinelPayload(contents);
+ if (salvaged.payload != null) {
+ payload = salvaged.payload;
+ emitLog('info', `Recovered structured .agent-done payload for ${agentId} (${taskType}) via lenient JSON extraction`, { agentId });
+ }
+ }
}
await hook({
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index 93a225af0a..e3daa9a533 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -239,13 +239,16 @@ function buildCompletionContract() {
'discarded. Your ONLY output is the JSON described above.',
'',
'When you have decided, write a file named `.agent-done` in the current',
- 'directory containing a single JSON object:',
+ 'directory containing a single JSON object with this shape:',
'',
'```json',
'{ "summary": "<one-line human summary of what you proposed, or that you proposed nothing>",',
' "payload": <the exact JSON object described above> }',
'```',
'',
+ 'The file MUST contain ONLY that raw JSON object — no ``` fences, no prose',
+ 'before or after it, and every newline inside a string value escaped as \\n.',
+ '',
'Then stop. Do nothing else.'
].join('\n')
}