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

fix: bound the output-hook dispatch and tell malformed reasoner output from an empty answer (#2727)

[._.]/ Adam Eivy40b621615373
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e415a3252a..04026dd594 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -28,7 +28,7 @@
- [issue-2700] **Layered Intelligence runs were being recorded as failures even when they succeeded.** An LI run is a *reasoning* run: it's explicitly told not to commit or open a PR, and hands its result back through a sentinel file instead. But the shared success check only knows how to look for a code commit, and its verdict overrides the run's actual exit code — so every correct LI run was filed as a failure, dragging the loop's success rate toward 0% and skewing anything built on it (task routing, the CoS Learning card, duration estimates). Task types that hand back results programmatically rather than as a commit are now exempt from the commit check, the same way pipeline and media jobs already were. Ordinary code tasks are still held to it. Because the mis-recorded history can't be reconstructed after the fact, installs that already ran the loop get that one bucket cleared on upgrade, so it starts from an honest "no runs recorded yet" rather than a fabricated 0% — no other task type's stats are touched.
-- [issue-2727] **A Layered Intelligence run that finished cleanly but produced nothing is no longer recorded as a success.** Exempting these reasoning runs from the code-commit check (above) left them judged purely on whether the process exited cleanly — so a run that exited fine but wrote back a missing or malformed result, or whose follow-up step (filing the issue) blew up, still counted as a win and quietly inflated the loop's success rate. These runs are now judged on what they actually deliver: the result was readable and the follow-up step accepted it. A run that hands back nothing usable is recorded as the failure it is, a run that delivers is recorded as a success with no commit required, and the "nothing filed this time" outcomes (no proposal, duplicate, out of scope) still count as successes — the run did its job. Ordinary code tasks are still held to the commit check, and pipeline and media jobs are unchanged.
+- [issue-2727] **A Layered Intelligence run that finished cleanly but produced nothing is no longer recorded as a success.** Exempting these reasoning runs from the code-commit check (above) left them judged purely on whether the process exited cleanly — so a run that exited fine but wrote back a missing or unreadable result, or whose follow-up step crashed, still counted as a win and quietly inflated the loop's success rate. These runs are now judged on what they actually hand back: the result was readable and the follow-up step could act on it. A run that returns nothing usable is recorded as the failure it is, a run that delivers is recorded as a success with no commit required, and the "nothing filed this time" outcomes (no proposal, duplicate, out of scope) still count as successes — the run did its job. Output that isn't a real answer at all (a stray sentence where a structured result belongs) is now told apart from a genuine "I looked and there's nothing to propose", instead of both counting as a win. A run whose reasoning was sound but whose issue tracker was simply unreachable still counts as a success — an outage at GitHub isn't the run's fault, and shouldn't drag the loop's score down or pause it. Ordinary code tasks are still held to the commit check, and pipeline and media jobs are unchanged.
- **The Scene evaluation model dropdown no longer comes up empty when you have vision models installed.** Picking Ollama for a Creative Director project's Scene evaluation showed an empty model list (and a bare text box) even with vision-capable models pulled, because the browser decided what counts as a vision model from a hard-coded list of model-name patterns that knew `gemma-3` but not `gemma4` — so `gemma4:e4b` and `qwen3.6:35b` were filtered out as if they were text-only. Vision pickers now ask the server, which reads each model's real capabilities from the backend itself (Ollama's `/api/show`, LM Studio's `vlm` tag), and union that with the old name matching — so a newer model family shows up without waiting for the pattern list to catch up, and nothing that used to be offered disappears. The AI Assignments table's vision rows get the same fix. Also, the Scene evaluation stage now explains that it needs an API provider (Ollama / LM Studio) and can't use an agent CLI/TUI provider such as Claude Ollama TUI — pinning one there was silently ignored at run time — and a provider with no vision model installed now says so, with a link to install one, instead of showing an empty dropdown.
- The Chief of Staff status panel's Learning card no longer spills its skipped-task count outside the card on mobile. The "(3 skipped)" note used to sit beside the success rate on one line, where it was too wide to fit a narrow card and rendered past the border; it now sits on its own line under the percentage and truncates if it can't fit.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 81c3ec8a17..6d63179073 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -21,7 +21,7 @@ import { createToolExecution, startExecution, completeExecution, errorExecution
import { determineLane, acquire, release } from './executionLanes.js';
import { analyzeAgentFailure, resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';
import { createAgentRun, completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';
-import { isProgrammaticIoTaskType } from './taskTypeHooks.js';
+import { isProgrammaticIoTaskType, resolveTaskHookType } from './taskTypeHooks.js';
import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';
import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';
@@ -839,7 +839,7 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac
// Judging them purely by exit code instead is also wrong: an exit-0 run whose
// `.agent-done` sentinel was missing/malformed, or whose hook threw, produced
// nothing usable and must be recorded as the failure it is (#2727).
- if (isProgrammaticIoTaskType(task?.metadata?.analysisType)) {
+ if (isProgrammaticIoTaskType(resolveTaskHookType(task))) {
return resolveProgrammaticIoVerdict({ success, hookResult });
}
// Interactive/user tasks declare no machine-checkable criterion; neither does
@@ -856,27 +856,75 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac
}
/**
- * The programmatic-I/O success criterion (#2727): "the sentinel parsed and the
- * output hook accepted it". Pure.
+ * The programmatic-I/O success criterion (#2727): "the agent's structured output
+ * parsed and the output hook accepted it". Pure.
+ *
+ * The question this answers is about the AGENT'S OUTPUT, not about whether the
+ * hook's downstream side effect ultimately landed. So a hook that accepted the
+ * payload and then couldn't reach the tracker (`file-failed`, `tracker-read-failed`)
+ * is NOT a failure of the run: the reasoning was sound and delivered, and a forge
+ * outage is environmental. Blaming the run would tank the type's measured success
+ * rate — and, through the shared classification below, auto-park the whole task
+ * type — every time `gh` has a bad afternoon. Deliberate, not inherited: raised in
+ * review on #2727 and kept.
*
* Delegates the accept/reject classification to `resolveTypeFailureSignal`, the
* same pure decision the #2616 type-level failure ledger uses — so the learning
- * verdict and the ledger can never drift apart on what counts as a bad run
- * (thrown hook, `unparseable-response`), and a new benign reason only has to be
- * taught to one function.
+ * verdict and the ledger can never drift apart on what counts as a bad run, and a
+ * new benign reason only has to be taught to one function.
*
- * Sentinel discipline: a hook that never ran (type registers no
- * `processTaskOutput`, or no task type resolved) yields NO verdict — null, not
- * `true`. "Nothing evaluated the output" must not collapse into "the output was
- * accepted"; null lets task-learning fall back to the exit code as before.
+ * Sentinel discipline throughout — three distinct answers, never collapsed:
+ * - `false` — the hook ran and REJECTED the output (threw, or `unparseable-response`).
+ * - `null` — NOTHING evaluated the output (no hook ran, it timed out, or it
+ * returned no structured outcome), so no criterion was declared and
+ * task-learning falls back to the exit code exactly as before. "Not evaluated"
+ * must never become "accepted".
+ * - `true` — the hook ran and accepted the output.
*
* @returns {boolean|null} true = accepted, false = rejected, null = undeclared
*/
export function resolveProgrammaticIoVerdict({ success, hookResult }) {
+ // An absent/non-boolean exit-code verdict can't be weighed against anything.
+ if (typeof success !== 'boolean') return null;
if (!hookResult?.ran) return null;
- const signal = resolveTypeFailureSignal({ success, hookResult });
- if (signal.record === 'skip') return null;
- return signal.record === 'success';
+ // A thrown hook rejected the output — it carries no outcome, so classify it
+ // before the outcome-shape guard below.
+ if (hookResult.threw) return false;
+ // Ran, but handed back no structured outcome to read: nothing evaluated the
+ // output, so declare no verdict rather than defaulting to "accepted".
+ if (!hookResult.outcome || typeof hookResult.outcome !== 'object') return null;
+ return resolveTypeFailureSignal({ success, hookResult }).record === 'success';
+}
+
+/**
+ * Hard bound on output-hook dispatch (#2727). The hook is only awaited BEFORE
+ * `completeAgent` so its verdict can be recorded — but `status: 'running'` is what
+ * the CoS concurrency gate counts (`cos.js`, default 3 slots), and that flips in
+ * completeAgent. So an un-bounded hook (it shells out to `gh`/`glab` and can walk
+ * up to 50 embeddings for semantic dedup) would hold a slot for its whole
+ * duration, and a HUNG one would hold it until restart — with the task stuck
+ * `in_progress` and the orphan reaper protecting the zombie rather than reaping
+ * it, because it too filters on `status === 'running'`.
+ *
+ * A timeout resolves to the "no verdict" sentinel, NOT a rejection: a hook we
+ * stopped waiting for told us nothing about the agent's output, so finalize
+ * proceeds and task-learning falls back to the exit code (the pre-#2727
+ * behavior). Generous by design — this is a hang backstop, not a latency budget;
+ * a slow-but-honest hook should still get to return its real verdict.
+ */
+const OUTPUT_HOOK_TIMEOUT_MS = 5 * 60_000;
+
+function withOutputHookTimeout(promise, { agentId, timeoutMs = OUTPUT_HOOK_TIMEOUT_MS }) {
+ let timer;
+ const timeout = new Promise(resolve => {
+ timer = setTimeout(() => {
+ emitLog('error', `⏱️ processTaskOutput hook timed out after ${timeoutMs}ms for ${agentId} — finalizing with no verdict`, { agentId });
+ resolve({ ran: false, timedOut: true });
+ }, timeoutMs);
+ // Never let the backstop itself hold the event loop open.
+ timer.unref?.();
+ });
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
/**
@@ -940,11 +988,17 @@ export async function finalizeAgent({
// (isProgrammaticIoTaskType), so nothing else is reordered. The lane is already
// released by this point (releaseAgentLane fires earlier, in the spawn paths),
// and `agent:completed` — which schedules the next dequeue — still fires from
- // completeAgent below, i.e. AFTER any handoff task the hook enqueues.
- const hookResult = await dispatchTaskOutputHook({ agentId, task, success, workspacePath }).catch(err => {
- emitLog('error', `processTaskOutput hook threw for ${agentId} (${task?.taskType}): ${err.message}`, { agentId, error: err.message });
+ // completeAgent below, i.e. AFTER any handoff task the hook enqueues. The cost
+ // of awaiting here is that the agent still counts against the CoS concurrency
+ // gate for the hook's duration, so the dispatch is hard-bounded — see
+ // withOutputHookTimeout.
+ const hookResult = await withOutputHookTimeout(
+ dispatchTaskOutputHook({ agentId, task, success, workspacePath }),
+ { agentId }
+ ).catch(err => {
+ emitLog('error', `❌ processTaskOutput hook threw for ${agentId} (${task?.taskType}): ${err.message}`, { agentId, error: err.message });
// A thrown hook is a non-success signal for the type ledger (#2616) and a
- // failed success criterion for task-learning (#2727).
+ // rejected success criterion for task-learning (#2727).
return { ran: true, threw: true };
});
@@ -1040,10 +1094,9 @@ export async function finalizeAgent({
* loads its own app/config — finalizeAgent stays domain-agnostic.
*/
async function dispatchTaskOutputHook({ agentId, task, success, workspacePath }) {
- // The scheduled task type lives in metadata.analysisType (the top-level
- // task.taskType is the CoS queue category, e.g. 'internal'). A programmatic-I/O
- // hook is keyed on the scheduled type.
- const taskType = task?.metadata?.analysisType || task?.taskType;
+ // Shared resolver with evaluateSuccessCriteria's gate — "runs a hook" and "gets
+ // the programmatic-I/O criterion" must stay the same question (#2727).
+ const taskType = resolveTaskHookType(task);
if (!taskType) return { ran: false };
const { getTaskOutputHook } = await import('./taskTypeHooks.js');
const hook = await getTaskOutputHook(taskType);
diff --git a/server/services/agentLifecycle.successCriteria.test.js b/server/services/agentLifecycle.successCriteria.test.js
index 18d35f0077..0451586492 100644
--- a/server/services/agentLifecycle.successCriteria.test.js
+++ b/server/services/agentLifecycle.successCriteria.test.js
@@ -15,7 +15,7 @@ vi.mock('./agentRunTracking.js', () => ({
completeAgentRun: vi.fn(),
}));
-import { evaluateSuccessCriteria } from './agentLifecycle.js';
+import { evaluateSuccessCriteria, resolveProgrammaticIoVerdict } from './agentLifecycle.js';
import { checkForTaskCommit } from './agentRunTracking.js';
describe('evaluateSuccessCriteria (#2344)', () => {
@@ -124,6 +124,70 @@ describe('evaluateSuccessCriteria — programmatic-I/O criterion (#2727)', () =>
})).toBe(false);
});
+ it('applies the criterion to a task typed on taskType alone, not just metadata.analysisType', async () => {
+ // The criterion gate and the hook-dispatch gate share one resolver
+ // (resolveTaskHookType), so a task shaped with the scheduled type at the top
+ // level can't run a hook AND still get commit-checked (the #2700 bug, one shape
+ // over).
+ const task = { id: 't9', taskType: 'layered-intelligence' };
+ expect(await evaluateSuccessCriteria({
+ task, workspacePath: '/w', success: true, hookResult: { ran: true, threw: true }
+ })).toBe(false);
+ expect(checkForTaskCommit).not.toHaveBeenCalled();
+ });
+});
+
+/**
+ * `resolveProgrammaticIoVerdict` is the pure criterion behind the branch above.
+ * Tested directly so the three-way sentinel (accepted / rejected / undeclared) is
+ * pinned without routing every case through evaluateSuccessCriteria.
+ */
+describe('resolveProgrammaticIoVerdict (#2727)', () => {
+ it('rejects a run whose hook threw, and one whose output was unparseable', () => {
+ expect(resolveProgrammaticIoVerdict({ success: true, hookResult: { ran: true, threw: true } })).toBe(false);
+ expect(resolveProgrammaticIoVerdict({
+ success: true, hookResult: { ran: true, outcome: { reason: 'unparseable-response' } }
+ })).toBe(false);
+ });
+
+ it('accepts a run whose hook processed the output', () => {
+ expect(resolveProgrammaticIoVerdict({
+ success: true, hookResult: { ran: true, outcome: { action: 'filed', reason: null } }
+ })).toBe(true);
+ });
+
+ it('declares no verdict when nothing evaluated the output', () => {
+ // No hook ran / no hook result at all / the dispatch timed out — none of these
+ // are a rejection, so task-learning falls back to the exit code.
+ expect(resolveProgrammaticIoVerdict({ success: true, hookResult: { ran: false } })).toBeNull();
+ expect(resolveProgrammaticIoVerdict({ success: true, hookResult: null })).toBeNull();
+ expect(resolveProgrammaticIoVerdict({ success: true, hookResult: { ran: false, timedOut: true } })).toBeNull();
+ });
+
+ it('declares no verdict when the hook ran but handed back no structured outcome', () => {
+ // `ran: true` with a missing/non-object outcome must NOT optional-chain its way
+ // into the success default — nothing evaluated the output.
+ expect(resolveProgrammaticIoVerdict({ success: true, hookResult: { ran: true } })).toBeNull();
+ expect(resolveProgrammaticIoVerdict({ success: true, hookResult: { ran: true, outcome: undefined } })).toBeNull();
+ expect(resolveProgrammaticIoVerdict({ success: true, hookResult: { ran: true, outcome: 'nope' } })).toBeNull();
+ });
+
+ it('declares no verdict when the exit-code result is absent/non-boolean', () => {
+ // "Not supplied" must not silently mean "the run failed".
+ expect(resolveProgrammaticIoVerdict({ hookResult: { ran: true, outcome: { reason: null } } })).toBeNull();
+ expect(resolveProgrammaticIoVerdict({ success: undefined, hookResult: { ran: true, outcome: { reason: null } } })).toBeNull();
+ });
+
+ it('treats a downstream tracker failure as a SUCCESS — the output was accepted', () => {
+ // `file-failed` / `tracker-read-failed` mean the reasoning landed but the forge
+ // was unreachable. That is environmental: blaming the run would tank the type's
+ // success rate (and auto-park it) every time `gh` has a bad afternoon. Raised in
+ // review on #2727 and deliberately kept.
+ for (const reason of ['file-failed', 'tracker-read-failed']) {
+ expect(resolveProgrammaticIoVerdict({ success: true, hookResult: { ran: true, outcome: { reason } } })).toBe(true);
+ }
+ });
+
it('still applies the commit criterion to a NON-programmatic self-improvement task', async () => {
// The exemption is keyed on the taskTypeHooks registry, not on selfImprovement —
// an ordinary self-improve task still commits and must still be checked.
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index 60f25742e5..ae72cbe210 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -460,9 +460,16 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {
// The payload IS the reasoner's JSON object (parsed from the sentinel). A null/
// malformed payload is the "returned nothing usable" case.
- const { proposal, pause } = validateReasonerResponse(
- payload && typeof payload === 'object' ? payload : null
- )
+ //
+ // Sentinel discipline (#2727): resolve the usable ENVELOPE once and key both the
+ // validation and the `reason` below off it. A payload that parsed as JSON but
+ // isn't a reasoner envelope at all (a bare string, a number, an array) used to
+ // reach `reason = 'no-proposal'` — the same reason a well-formed response that
+ // legitimately proposes nothing gets — so "the agent emitted garbage" was
+ // indistinguishable from "the agent correctly had nothing to propose", and the
+ // former was recorded as a successful run.
+ const envelope = payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : null
+ const { proposal, pause } = validateReasonerResponse(envelope)
// Re-read issues NOW (not at gather time) so dedup sees the freshest tracker
// state — the agent may have run for minutes.
@@ -471,7 +478,7 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {
let filedNumber = null
let filedKey = null
let filedAction = 'no-op'
- let reason = payload == null ? 'unparseable-response' : 'no-proposal'
+ let reason = envelope == null ? 'unparseable-response' : 'no-proposal'
let handedOff = false
if (proposal) {
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
index bb5e7fa820..7126235080 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
@@ -392,6 +392,26 @@ describe('processTaskOutput', () => {
expect(out).toMatchObject({ action: 'no-op', reason: 'unparseable-response' });
});
+ it('records unparseable-response when the payload parsed but is not a reasoner envelope (#2727)', async () => {
+ // A bare string/number/array is JSON that parsed but says nothing. It used to
+ // land on `no-proposal` — the SAME reason a well-formed "nothing to propose"
+ // response gets — so garbage was indistinguishable from a correct empty answer
+ // and got recorded as a successful run.
+ li.validateReasonerResponse.mockReturnValue({ proposal: null, pause: null });
+ for (const payload of ['just some prose', 42, ['a', 'b'], true]) {
+ const out = await processTaskOutput({ appId: 'app-1', success: true, payload });
+ expect(out).toMatchObject({ action: 'no-op', reason: 'unparseable-response' });
+ }
+ });
+
+ it('still records no-proposal for a well-formed envelope that proposes nothing (#2727)', async () => {
+ // The other side of the sentinel: the reasoner answered correctly and simply
+ // had nothing to file. That is a successful run, not malformed output.
+ li.validateReasonerResponse.mockReturnValue({ proposal: null, pause: null });
+ const out = await processTaskOutput({ appId: 'app-1', success: true, payload: { analysis: 'nothing worth proposing', proposal: null } });
+ expect(out).toMatchObject({ action: 'no-op', reason: 'no-proposal' });
+ });
+
it('files a fresh, in-scope proposal and records the ref', async () => {
li.validateReasonerResponse.mockReturnValue({
proposal: { scope: 'app-improvement', slug: 'add-telemetry', title: 'Add telemetry', body: 'do it' },
diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.js
index 5aa854d128..261a118d8d 100644
--- a/server/services/taskTypeHooks.js
+++ b/server/services/taskTypeHooks.js
@@ -57,6 +57,21 @@ export function isProgrammaticIoTaskType(taskType) {
return typeof taskType === 'string' && Object.hasOwn(HOOK_MODULES, taskType);
}
+/**
+ * The task type a hook is keyed on, for a task record. The SCHEDULED type lives in
+ * `metadata.analysisType` (the top-level `task.taskType` is the CoS queue category,
+ * e.g. 'internal'), falling back to `taskType` for a task shaped the other way.
+ *
+ * Single resolver on purpose (#2727): "does this task get the programmatic-I/O
+ * success criterion?" and "does this task run an output hook?" must be the same
+ * question. When they diverged, a task carrying only `taskType:
+ * 'layered-intelligence'` ran the hook but was still commit-checked — the exact
+ * #2700 bug, one shape over.
+ */
+export function resolveTaskHookType(task) {
+ return task?.metadata?.analysisType || task?.taskType || null;
+}
+
/**
* Resolve the pre-agent input hook for a task type, or null if it has none.
* `buildTaskInput({ app, taskType })` → `{ prompt?, providerId?, model?, skip? }`.