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: close the remaining paths where an unevaluated LI run banked a free success (#2727)

[._.]/ Adam Eivy84aa183d34ac
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 20b5c4e653..a869d1d343 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -884,18 +884,28 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac
* @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;
- // A thrown hook rejected the output — it carries no outcome, so classify it
- // before the outcome-shape guard below.
+ // A thrown hook rejected the output. Classified FIRST: it carries no outcome (so
+ // it must precede the outcome-shape guard), and a rejection shouldn't hinge on
+ // the exit-code guard below.
if (hookResult.threw) return false;
+ // An absent/non-boolean exit-code verdict can't be weighed against anything.
+ if (typeof success !== 'boolean') return null;
// 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;
+ // Ran, but bailed out BEFORE it ever looked at the output (its app was deleted
+ // mid-run, or the task carries no app). Nothing evaluated the agent's work — and
+ // these paths don't even record a run — so this is "undeclared", not a free
+ // success for the type.
+ if (HOOK_ABORTED_BEFORE_EVALUATION.has(hookResult.outcome.reason)) return null;
return resolveTypeFailureSignal({ success, hookResult }).record === 'success';
}
+// Output-hook outcomes that mean "the hook returned before validating the agent's
+// output at all" — distinct from both a rejection and an acceptance.
+const HOOK_ABORTED_BEFORE_EVALUATION = new Set(['no-app', 'app-not-found']);
+
/**
* 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
@@ -920,12 +930,21 @@ export function resolveProgrammaticIoVerdict({ success, hookResult }) {
*/
const OUTPUT_HOOK_TIMEOUT_MS = 5 * 60_000;
-function withOutputHookTimeout(promise, { agentId, timeoutMs = OUTPUT_HOOK_TIMEOUT_MS }) {
+export 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 BEFORE logging, and never let the log throw out of the callback:
+ // this runs outside the request lifecycle, so an uncaught throw here would
+ // crash the process — and a throw before `resolve` would leave the race
+ // permanently unsettled, wedging the exact finalize this timer exists to
+ // rescue.
resolve({ ran: false, timedOut: true });
+ try {
+ emitLog('error', `⏱️ processTaskOutput hook timed out after ${timeoutMs}ms for ${agentId} — finalizing with no verdict`, { agentId });
+ } catch (err) {
+ console.error(`❌ Failed to log output-hook timeout for ${agentId}: ${err.message}`);
+ }
}, timeoutMs);
// Never let the backstop itself hold the event loop open.
timer.unref?.();
@@ -1067,7 +1086,12 @@ export async function finalizeAgent({
// Type-level consecutive-failure ledger (#2616): feed the per-type
// backoff/auto-park in taskSchedule. Only SCHEDULED task types carry
- // `metadata.analysisType`; user/ad-hoc tasks don't participate. The pure
+ // `metadata.analysisType`; user/ad-hoc tasks don't participate — so this gate
+ // deliberately does NOT use resolveTaskHookType (#2727). That resolver falls back
+ // to `task.taskType`, which for an ad-hoc task is the CoS queue category
+ // ('internal', 'user'); ledgering those would invent a failure ledger for a
+ // "task type" that no schedule owns. "Which tasks run a hook" and "which task
+ // types back off" are genuinely different questions. The pure
// resolveTypeFailureSignal decides success vs failure vs skip — including the
// exit-0-but-unparseable-output case that must count as a failure.
const scheduledType = task?.metadata?.analysisType || null;
@@ -1320,9 +1344,11 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
// Catch + log instead of letting finalizeAgent's throw skip the rest of
// the cleanup (JIRA push, plan-question notification, pipeline
// progression, worktree cleanup). The error is still visible via
- // emitLog + the agent's persisted state (completeAgent runs first
- // inside finalizeAgent and is the most likely throw point — the
- // partial-state cases are best-effort by design).
+ // emitLog + the agent's persisted state (completeAgent is the first
+ // STATE WRITE inside finalizeAgent and the most likely throw point —
+ // the output-hook dispatch and success-criteria evaluation now precede
+ // it (#2727) but both carry their own .catch, so neither throws out —
+ // the partial-state cases are best-effort by design).
let finalizeError = null;
try {
await finalizeAgent({
diff --git a/server/services/agentLifecycle.successCriteria.test.js b/server/services/agentLifecycle.successCriteria.test.js
index 0451586492..0f5673d0b7 100644
--- a/server/services/agentLifecycle.successCriteria.test.js
+++ b/server/services/agentLifecycle.successCriteria.test.js
@@ -6,7 +6,7 @@
* declared vs declared-and-checked).
*/
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
vi.mock('./agentRunTracking.js', () => ({
checkForTaskCommit: vi.fn(),
@@ -15,7 +15,7 @@ vi.mock('./agentRunTracking.js', () => ({
completeAgentRun: vi.fn(),
}));
-import { evaluateSuccessCriteria, resolveProgrammaticIoVerdict } from './agentLifecycle.js';
+import { evaluateSuccessCriteria, resolveProgrammaticIoVerdict, withOutputHookTimeout } from './agentLifecycle.js';
import { checkForTaskCommit } from './agentRunTracking.js';
describe('evaluateSuccessCriteria (#2344)', () => {
@@ -188,6 +188,56 @@ describe('resolveProgrammaticIoVerdict (#2727)', () => {
}
});
+ it('declares no verdict when the hook aborted before it could look at the output', () => {
+ // `no-app` / `app-not-found` return before the payload is validated (and before
+ // the hook records anything). Nothing evaluated the agent's output, so this is
+ // the undeclared sentinel — NOT a success, which would bank a free win for the
+ // type every time an app is deleted mid-run.
+ for (const reason of ['no-app', 'app-not-found']) {
+ expect(resolveProgrammaticIoVerdict({
+ success: true, hookResult: { ran: true, outcome: { action: 'no-op', reason } }
+ })).toBeNull();
+ }
+ });
+});
+
+/**
+ * The hard bound that keeps a hung output hook from pinning a CoS concurrency slot
+ * until restart — the mitigation matters enough to pin directly (#2727).
+ */
+describe('withOutputHookTimeout (#2727)', () => {
+ beforeEach(() => vi.useRealTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('resolves a hung dispatch to the undeclared sentinel rather than hanging finalize', async () => {
+ vi.useFakeTimers();
+ // A hook that never settles — the wedge case.
+ const settled = withOutputHookTimeout(new Promise(() => {}), { agentId: 'a1', timeoutMs: 1000 });
+ await vi.advanceTimersByTimeAsync(1000);
+ // `ran: false` → resolveProgrammaticIoVerdict returns null → task-learning falls
+ // back to the exit code. A timeout is "we never got a verdict", not a rejection.
+ expect(await settled).toEqual({ ran: false, timedOut: true });
+ expect(resolveProgrammaticIoVerdict({ success: true, hookResult: await settled })).toBeNull();
+ });
+
+ it('passes a hook that settles in time straight through, and clears its timer', async () => {
+ vi.useFakeTimers();
+ const outcome = { ran: true, outcome: { action: 'filed', reason: null } };
+ const settled = withOutputHookTimeout(Promise.resolve(outcome), { agentId: 'a1', timeoutMs: 1000 });
+ expect(await settled).toBe(outcome);
+ // Timer cleared on the resolve path — nothing left pending to fire.
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('propagates a hook rejection (finalizeAgent maps it to the thrown-hook verdict)', async () => {
+ await expect(withOutputHookTimeout(Promise.reject(new Error('boom')), { agentId: 'a1', timeoutMs: 1000 }))
+ .rejects.toThrow('boom');
+ });
+});
+
+describe('evaluateSuccessCriteria — commit criterion (#2344)', () => {
+ beforeEach(() => vi.clearAllMocks());
+
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 ae72cbe210..fd4027f8e8 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -429,6 +429,10 @@ async function recordRun(app, outcome = {}) {
}
/** Default hand-off enqueue: an approval-gated internal CoS task for a coding agent. */
+// The documented reasoner response shape. An object carrying none of these keys
+// isn't an answer at all — see the envelope resolution in processTaskOutput.
+const REASONER_ENVELOPE_KEYS = ['analysis', 'proposal', 'pause']
+
async function defaultEnqueueHandoff(taskData) {
const { addTask } = await import('../cos.js')
return addTask(taskData, 'internal')
@@ -463,18 +467,20 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {
//
// 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
+ // isn't a reasoner envelope — a bare string/number/array, or an object carrying
+ // none of the documented keys ({}, {"foo":1}) — 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
+ // former was recorded as a successful run. Reachable both ways: the sentinel
+ // envelope only requires `payload` to be an object, and salvageSentinelPayload's
+ // lenient extractor can surface a non-envelope object out of prose.
+ // `Object.hasOwn` — an inherited key must not qualify a junk object as an answer.
+ const isEnvelope = !!payload && typeof payload === 'object' && !Array.isArray(payload)
+ && REASONER_ENVELOPE_KEYS.some(k => Object.hasOwn(payload, k))
+ const envelope = isEnvelope ? 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.
- const { existingIssues, trackerReadFailed } = await readIssues({ filer, forgeCli, cwd, jira, config })
-
let filedNumber = null
let filedKey = null
let filedAction = 'no-op'
@@ -482,6 +488,13 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {
let handedOff = false
if (proposal) {
+ // Re-read issues NOW (not at gather time) so dedup sees the freshest tracker
+ // state — the agent may have run for minutes. Scoped to the has-a-proposal path:
+ // it's an unbounded forge call and only this branch consumes it, so the common
+ // no-proposal/unparseable runs no longer shell out to `gh issue list` (which,
+ // since the #2727 hoist, would hold a CoS concurrency slot and could burn the
+ // finalize timeout on a run whose verdict is already known).
+ const { existingIssues, trackerReadFailed } = await readIssues({ filer, forgeCli, cwd, jira, config })
const scopeOk = isScopeAllowed({ scope: proposal.scope, allowedScopes: config.allowedScopes, isPortos })
if (!scopeOk) {
console.log(`🚫 Layered Intelligence: ${app.name} proposal scope "${proposal.scope}" not allowed — suppressed`)
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
index 7126235080..891cc38f2b 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
@@ -393,12 +393,14 @@ describe('processTaskOutput', () => {
});
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.
+ // Garbage that still parses as JSON: a bare scalar/array, or an object carrying
+ // none of the documented keys. All of 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. `{}` is reachable: the sentinel envelope only requires
+ // `payload` to be an object.
li.validateReasonerResponse.mockReturnValue({ proposal: null, pause: null });
- for (const payload of ['just some prose', 42, ['a', 'b'], true]) {
+ for (const payload of ['just some prose', 42, ['a', 'b'], true, {}, { foo: 1 }]) {
const out = await processTaskOutput({ appId: 'app-1', success: true, payload });
expect(out).toMatchObject({ action: 'no-op', reason: 'unparseable-response' });
}
@@ -406,10 +408,37 @@ describe('processTaskOutput', () => {
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.
+ // had nothing to file. That is a successful run, not malformed output. Any ONE
+ // documented key makes it a real answer.
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' });
+ for (const payload of [{ analysis: 'nothing worth proposing', proposal: null }, { proposal: null }, { analysis: '' }]) {
+ const out = await processTaskOutput({ appId: 'app-1', success: true, payload });
+ expect(out).toMatchObject({ action: 'no-op', reason: 'no-proposal' });
+ }
+ });
+
+ it('does not touch the tracker when there is no proposal to dedup (#2727)', async () => {
+ // readIssues is an unbounded forge call and only the has-a-proposal branch
+ // consumes it. Since the #2727 hoist the hook runs while the agent still holds
+ // a CoS concurrency slot, so the common no-op path must not shell out to `gh`.
+ li.validateReasonerResponse.mockReturnValue({ proposal: null, pause: null });
+ li.listForgeIssues.mockClear();
+ await processTaskOutput({ appId: 'app-1', success: true, payload: { analysis: 'nothing to do', proposal: null } });
+ expect(li.listForgeIssues).not.toHaveBeenCalled();
+ expect(li.fileProposalToForge).not.toHaveBeenCalled();
+ });
+
+ it('still reads the tracker to dedup when there IS a proposal (#2727)', async () => {
+ // The other side of the scoping: the dedup read must still happen on the path
+ // that consumes it, against FRESH tracker state.
+ li.validateReasonerResponse.mockReturnValue({
+ proposal: { scope: 'app-improvement', slug: 'fresh-idea', title: 'Fresh idea', body: 'x' },
+ pause: null
+ });
+ li.listForgeIssues.mockClear();
+ li.fileProposalToForge.mockResolvedValue({ success: true, number: 12 });
+ await processTaskOutput({ appId: 'app-1', success: true, payload: { proposal: { slug: 'fresh-idea' } } });
+ expect(li.listForgeIssues).toHaveBeenCalled();
});
it('files a fresh, in-scope proposal and records the ref', async () => {