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

Explain why a Layered Intelligence "Run now" produced nothing

[._.]/ Adam Eivy1ced9256ef6f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9df9c89882..bf7189ac66 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -15,3 +15,4 @@
- **[issue-2328] Auto-fixer now has a circuit breaker so a persistently-failing resource can't flood the task queue.** The auto-fixer only deduped identical errors within a 60-second window, so a provider/model (or critical error) that failed every ~minute would queue a fresh investigation/fix task indefinitely — a runaway loop that exhausts the plan queue and never gets healed by yet another identical task. It now trips a per-resource circuit after more than 3 task-worthy failures within a rolling 1-hour window, suppressing further task creation (logged as `🔌 Auto-fix circuit OPEN …`) until the failure rate ages out and the circuit auto-closes. (Partial delivery of #2328's guardrails; the tiered fallback chain, structured failure-reason telemetry, and dashboard metrics remain.)
- **[issue-2328] Auto-fixer now classifies every failure into a fallback tier and records structured per-attempt diagnostics.** A deterministic classifier maps each error category (config/env, schema/type, transient, or unknown) to one of four fallback tiers — 1 config/env, 2 schema/type, 3 constrained-agent-retry, 4 escalate — with unrecognized categories always escalating so nothing is silently swallowed. Each auto-fix attempt now builds a structured `{ triggerEvent, target, errorType, category, tier, fixStrategy, failureReason }` diagnostics object that rides on the investigation/fix task record (and its agent-facing context) and is surfaced inline in the existing single-line log (`… tier=1 (config/env) …`), so failures can be broken out by tier / category / reason. (Further #2328 slices remain: dashboard telemetry surfacing, time-to-recovery metric, full 4-tier execution wiring.)
- **Layered Intelligence loop now supports every provider type.** The per-app AI-provider picker previously listed only `cli` providers, while the reasoning call went through the api-only `callProviderAISimple` — so a selected CLI provider failed at runtime with "requires an API-based provider," and API/TUI providers (Ollama, LM Studio, Claude/Codex/OpenCode TUI, etc.) never appeared at all. The reasoning call now routes through the unified `runPromptThroughProvider`, which dispatches on `provider.type`, and the picker lists all enabled `cli`/`api`/`tui` providers. CLI/TUI spawns run in the app's repo (`cwd`).
+- **A "Run now" of Layered Intelligence now tells you what actually happened.** Because the loop is handler-backed — it files one tracker issue rather than spawning a visible agent — a run that filed nothing gave no usable signal: the on-demand toast collapsed every non-filed outcome (reasoning model returned unparseable JSON, a duplicate/near-duplicate was suppressed, it parked on a blocking issue, no AI provider was configured, Jira wasn't set up, the tracker read failed) into a blanket "nothing to do right now," and on mobile that transient toast was easy to miss entirely. The handler now threads the real terminal reason through the on-demand feedback (so the toast reads e.g. "the reasoning model returned no usable JSON — try a non-reasoning model" or "paused on a blocking issue"), and every run persists its outcome (`lastRunAt` / action / reason / filed ref) so Edit App → Intelligence shows a durable **Last run** status line you can check any time. This is what made a reasoning-style local model (which often emits thinking text with no parseable JSON) look like a queued-but-not-running task with no explanation.
diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsx
index 715d3a5cbe..de58d29451 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx
@@ -2,6 +2,8 @@ import { Plus, Trash2, Brain } from 'lucide-react';
import Banner from '../ui/Banner';
import ProviderModelSelector from '../ProviderModelSelector';
import { filterSelectableModels } from '../../utils/providers';
+import { timeAgo } from '../../utils/formatters';
+import { formatLiReason, liReasonTone } from '../../utils/layeredIntelligenceReasons';
// The self-improvement loop's per-app config surface. Field set mirrors the
// server schema (server/lib/validation.js `layeredIntelligenceConfigSchema`)
@@ -40,6 +42,33 @@ export const LI_INTERVAL_PRESETS = [
{ ms: 7 * 24 * 60 * 60 * 1000, label: 'Weekly' }
];
+// Compact prose for a stored last-run outcome, keyed by the handler's action +
+// reason (persisted on the effective config as lastRunAction / lastRunReason).
+// The loop files a tracker issue and spawns no visible agent, so this durable
+// line — not the transient toast — is how a user (esp. on mobile) learns WHY a
+// run produced nothing. The reason→prose gloss + tone come from the shared
+// layeredIntelligenceReasons module so a filed run reads as success (with its
+// ref) while every non-filed reason renders identically here and in the toast.
+// Returns { tone, text, when } or null when it's never run.
+export function describeLastRun(li) {
+ if (!li?.lastRunAt) return null;
+ const when = timeAgo(li.lastRunAt);
+ const action = li.lastRunAction || null;
+ const reason = li.lastRunReason || null;
+
+ if (action === 'filed') {
+ return { tone: 'success', text: `filed an improvement issue${li.lastRunRef ? ` (${li.lastRunRef})` : ''}`, when };
+ }
+ return { tone: liReasonTone(reason), text: formatLiReason({ action, reason }), when };
+}
+
+const LAST_RUN_TONE_CLASS = {
+ success: 'text-port-success',
+ error: 'text-port-error',
+ warn: 'text-port-warning',
+ neutral: 'text-gray-400'
+};
+
// Deep-equal two allowedScopes arrays regardless of order.
function sameScopes(a, b) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
@@ -215,16 +244,24 @@ export default function LayeredIntelligenceTab({ li, onChange, providers, isPort
};
const visibleScopes = LI_SCOPES.filter(s => !s.portosOnly || isPortos);
+ const lastRun = describeLastRun(li);
return (
<div className="space-y-4">
<div className="flex items-start gap-2">
<Brain size={16} className="text-port-accent mt-0.5 shrink-0" />
<p className="text-xs text-gray-500">
- The Layered Intelligence Loop perpetually reviews this app&apos;s telemetry and files improvement proposals via CoS. Off by default — it runs on the schedule below only when enabled.
+ The Layered Intelligence Loop perpetually reviews this app&apos;s telemetry and files improvement proposals via CoS. Off by default — it runs on the schedule below only when enabled. It files a tracker issue rather than spawning a visible agent, so a run that produces nothing reports why here.
</p>
</div>
+ {lastRun && (
+ <div className="text-xs bg-port-bg border border-port-border rounded-lg px-3 py-2">
+ <span className="text-gray-500">Last run {lastRun.when}: </span>
+ <span className={LAST_RUN_TONE_CLASS[lastRun.tone] || 'text-gray-400'}>{lastRun.text}.</span>
+ </div>
+ )}
+
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
diff --git a/client/src/components/apps/LayeredIntelligenceTab.test.jsx b/client/src/components/apps/LayeredIntelligenceTab.test.jsx
index b59a8cc566..68deb163ee 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.test.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.test.jsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
-import LayeredIntelligenceTab, { buildLayeredIntelligenceUpdate, buildLayeredIntelligenceScheduleUpdate, intervalFieldsFromMs } from './LayeredIntelligenceTab';
+import LayeredIntelligenceTab, { buildLayeredIntelligenceUpdate, buildLayeredIntelligenceScheduleUpdate, intervalFieldsFromMs, describeLastRun } from './LayeredIntelligenceTab';
const baseline = {
enabled: false,
@@ -12,6 +12,60 @@ const baseline = {
allowedScopes: ['app-improvement', 'app-data-gap']
};
+describe('describeLastRun', () => {
+ const at = '2026-07-09T20:29:05.000Z';
+
+ it('returns null when the loop has never run', () => {
+ expect(describeLastRun({})).toBeNull();
+ expect(describeLastRun({ lastRunAction: 'no-op' })).toBeNull(); // no lastRunAt ⇒ never ran
+ });
+
+ it('reports a filed run with its ref as success', () => {
+ const r = describeLastRun({ lastRunAt: at, lastRunAction: 'filed', lastRunReason: null, lastRunRef: '#123' });
+ expect(r.tone).toBe('success');
+ expect(r.text).toContain('#123');
+ });
+
+ it('surfaces an unparseable reasoning response as a warning with actionable prose', () => {
+ const r = describeLastRun({ lastRunAt: at, lastRunAction: 'no-op', lastRunReason: 'unparseable-response' });
+ expect(r.tone).toBe('warn');
+ expect(r.text).toMatch(/no usable JSON/i);
+ });
+
+ it('treats a genuine no-proposal run as neutral (not an error)', () => {
+ const r = describeLastRun({ lastRunAt: at, lastRunAction: 'no-op', lastRunReason: 'no-proposal' });
+ expect(r.tone).toBe('neutral');
+ });
+
+ it('renders an llm-error reason as an error with the provider message', () => {
+ const r = describeLastRun({ lastRunAt: at, lastRunAction: 'no-op', lastRunReason: 'llm-error: provider timeout' });
+ expect(r.tone).toBe('error');
+ expect(r.text).toContain('provider timeout');
+ });
+
+ it('shows a duplicate suppression as neutral', () => {
+ const r = describeLastRun({ lastRunAt: at, lastRunAction: 'duplicate', lastRunReason: 'duplicate' });
+ expect(r.tone).toBe('neutral');
+ expect(r.text).toMatch(/existing/i);
+ });
+});
+
+describe('LayeredIntelligenceTab last-run status', () => {
+ const li = (extra) => ({ ...baseline, ...extra });
+ const noop = () => {};
+
+ it('renders the durable last-run line when the config carries a run outcome', () => {
+ render(<LayeredIntelligenceTab li={li({ lastRunAt: '2026-07-09T20:29:05.000Z', lastRunAction: 'no-op', lastRunReason: 'unparseable-response' })} onChange={noop} providers={[]} isPortos loaded />);
+ expect(screen.getByText(/Last run/i)).toBeInTheDocument();
+ expect(screen.getByText(/no usable JSON/i)).toBeInTheDocument();
+ });
+
+ it('omits the last-run line before the loop has ever run', () => {
+ render(<LayeredIntelligenceTab li={li()} onChange={noop} providers={[]} isPortos loaded />);
+ expect(screen.queryByText(/Last run/i)).not.toBeInTheDocument();
+ });
+});
+
describe('buildLayeredIntelligenceUpdate', () => {
it('returns null when nothing changed (avoids persisting the effective config to disk)', () => {
expect(buildLayeredIntelligenceUpdate(baseline, { ...baseline })).toBeNull();
diff --git a/client/src/hooks/useOnDemandTaskToast.js b/client/src/hooks/useOnDemandTaskToast.js
index 2d6d6225fa..3d1578df45 100644
--- a/client/src/hooks/useOnDemandTaskToast.js
+++ b/client/src/hooks/useOnDemandTaskToast.js
@@ -2,6 +2,7 @@ import { useEffect } from 'react';
import toast from '../components/ui/Toast';
import socket from '../services/socket';
import { timeUntil } from '../utils/formatters';
+import { formatLiReason } from '../utils/layeredIntelligenceReasons';
// Humanize a perpetual work-detector park reason for a user-facing toast. The
// raw reason strings are the same ones surfaced in the CoS → Schedule tab; here
@@ -17,6 +18,15 @@ const PARK_REASON_LABELS = {
'no-detector': 'no work detector for this task'
};
+// Icon per handler action so the toast reads right at a glance. (The reason→prose
+// gloss itself is the shared `formatLiReason`, so a new server reason lands in
+// both the toast and the durable "Last run" line without re-transcribing it.)
+const HANDLER_ICONS = {
+ parked: '⏸️',
+ duplicate: '♻️',
+ 'semantic-duplicate': '♻️'
+};
+
/**
* Global subscriber that toasts when a user-initiated on-demand task run
* produced no work. The server emits `cos:schedule:on-demand-empty` ONLY for
@@ -43,6 +53,19 @@ export function useOnDemandTaskToast() {
return;
}
+ // A handler-backed task (Layered Intelligence) that ran but filed nothing
+ // for an explicit reason — surface WHY, since it spawns no visible agent
+ // and the toast is the only feedback. (A genuinely-idle "no-proposal" run
+ // arrives as outcome 'idle' below, not here.)
+ if (data?.outcome === 'handler-issue') {
+ const message = formatLiReason({ action: data?.handlerAction, reason: data?.handlerReason, blocking: data?.blocking });
+ toast(`${task}${scope}: ran now — ${message}.`, {
+ duration: 8000,
+ icon: HANDLER_ICONS[data?.handlerAction] || '⚠️'
+ });
+ return;
+ }
+
// A non-perpetual task produced no task ⇒ genuinely nothing to do right
// now (not a failure, not a park). Keep it calm and neutral.
if (data?.outcome === 'idle') {
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index fa74a55a61..574958b691 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -37,6 +37,7 @@ grep -i "what you want to do" client/src/utils/README.md
| `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. |
| `navWorkingSet` | Recent/pinned nav persistence in localStorage (`recordVisit`, `togglePin`, `isPinned`). |
| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `filterSelectableModels`, `getProviderTimeout`, configured-default sentinels). |
+| `layeredIntelligenceReasons` | Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens, shared by the on-demand toast and the durable "Last run" line (`formatLiReason`, `liReasonTone`, `LI_NEUTRAL_REASONS`). |
## Module loading / resilience
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index 39db3e5dfd..2951c80154 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -22,6 +22,7 @@ export * from './urlNormalize.js';
export * from './platform.js';
export * from './navWorkingSet.js';
export * from './providers.js';
+export * from './layeredIntelligenceReasons.js';
// === Module loading / resilience ===
export * from './lazyWithReload.js';
diff --git a/client/src/utils/layeredIntelligenceReasons.js b/client/src/utils/layeredIntelligenceReasons.js
new file mode 100644
index 0000000000..c1c985f568
--- /dev/null
+++ b/client/src/utils/layeredIntelligenceReasons.js
@@ -0,0 +1,58 @@
+// Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens.
+//
+// The reason vocabulary is authored server-side (server/services/autonomousJobs/
+// layeredIntelligenceHandler.js — `no-provider`, `unparseable-response`,
+// `no-proposal`, `scope-suppressed`, `file-failed`, `duplicate`,
+// `semantic-duplicate`, `tracker-read-failed`, `blocking-read-failed`,
+// `jira-not-configured`, `blocking-open`, plus the synthesized `llm-error:<msg>`
+// prefix) and consumed by BOTH the on-demand toast (useOnDemandTaskToast) and the
+// durable "Last run" status line (LayeredIntelligenceTab). Keeping the token→prose
+// map here — not forked per component — means a new server reason has exactly ONE
+// place to add its gloss, and a missing one degrades to the raw token in one spot
+// rather than silently rendering three different ways.
+
+// Reasons that are a normal, non-alarming outcome (a run that simply had nothing
+// new to file) — rendered in a neutral tone rather than a warning.
+export const LI_NEUTRAL_REASONS = new Set([
+ 'no-proposal', 'duplicate', 'semantic-duplicate', 'blocking-open'
+]);
+
+const LI_REASON_LABELS = {
+ 'no-provider': 'no AI provider is configured for it',
+ 'unparseable-response': 'the reasoning model returned no usable JSON — try a non-reasoning model or an API provider',
+ 'no-proposal': 'the loop had nothing to propose',
+ 'scope-suppressed': "the proposal's scope isn't allowed for this app",
+ 'file-failed': 'filing the tracker issue failed',
+ 'duplicate': 'the proposal matched an existing open issue',
+ 'semantic-duplicate': 'the proposal closely matched an existing issue',
+ 'tracker-read-failed': "couldn't read the issue tracker — it'll retry next run",
+ 'blocking-read-failed': "couldn't read blocking issues — it'll retry next run",
+ 'jira-not-configured': "Jira isn't fully configured for this app"
+};
+
+const LLM_ERROR_PREFIX = 'llm-error:';
+
+// Turn a handler outcome (action + reason [+ open blocking count]) into one
+// sentence. Handles the two synthesized shapes — the `llm-error:<msg>` prefix (the
+// provider threw) and `blocking-open`/parked (an open blocking issue, with an
+// optional count only the toast carries) — then falls back to the reason gloss.
+export function formatLiReason({ action = null, reason = null, blocking = null } = {}) {
+ if (typeof reason === 'string' && reason.startsWith(LLM_ERROR_PREFIX)) {
+ return `the AI provider errored —${reason.slice(LLM_ERROR_PREFIX.length)}`.trimEnd();
+ }
+ if (reason === 'blocking-open' || action === 'parked') {
+ const n = typeof blocking === 'number' && blocking > 0 ? ` (${blocking} open)` : '';
+ return `paused on a blocking issue${n} — resolve or unblock it to resume`;
+ }
+ if (action === 'in-flight') return 'a previous run is still in progress — try again shortly';
+ return LI_REASON_LABELS[reason] || reason || 'it produced no proposal';
+}
+
+// Status-line tone for a NON-filed outcome: error for a provider/runtime throw,
+// neutral for a "nothing new" run, warning for the rest (a filed run is success —
+// the caller owns that, since it also renders the filed ref).
+export function liReasonTone(reason = null) {
+ if (typeof reason === 'string' && reason.startsWith(LLM_ERROR_PREFIX)) return 'error';
+ if (LI_NEUTRAL_REASONS.has(reason)) return 'neutral';
+ return 'warn';
+}
diff --git a/client/src/utils/layeredIntelligenceReasons.test.js b/client/src/utils/layeredIntelligenceReasons.test.js
new file mode 100644
index 0000000000..df440d347a
--- /dev/null
+++ b/client/src/utils/layeredIntelligenceReasons.test.js
@@ -0,0 +1,43 @@
+import { describe, it, expect } from 'vitest';
+import { formatLiReason, liReasonTone, LI_NEUTRAL_REASONS } from './layeredIntelligenceReasons';
+
+describe('formatLiReason', () => {
+ it('glosses a plain reason token', () => {
+ expect(formatLiReason({ action: 'no-op', reason: 'unparseable-response' })).toMatch(/no usable JSON/i);
+ expect(formatLiReason({ action: 'no-op', reason: 'no-provider' })).toMatch(/no AI provider/i);
+ });
+
+ it('strips the llm-error prefix into a provider-error sentence', () => {
+ expect(formatLiReason({ action: 'no-op', reason: 'llm-error: provider timeout' }))
+ .toBe('the AI provider errored — provider timeout');
+ });
+
+ it('renders a park from either the reason token or the parked action, with an optional count', () => {
+ expect(formatLiReason({ action: 'parked', reason: 'blocking-open', blocking: 3 })).toMatch(/paused on a blocking issue \(3 open\)/);
+ // The durable status line has no persisted count → no parenthetical.
+ expect(formatLiReason({ reason: 'blocking-open' })).toBe('paused on a blocking issue — resolve or unblock it to resume');
+ });
+
+ it('explains an in-flight run', () => {
+ expect(formatLiReason({ action: 'in-flight' })).toMatch(/still in progress/i);
+ });
+
+ it('falls back to the raw token then a generic phrase', () => {
+ expect(formatLiReason({ reason: 'some-future-reason' })).toBe('some-future-reason');
+ expect(formatLiReason({})).toBe('it produced no proposal');
+ });
+});
+
+describe('liReasonTone', () => {
+ it('is error for a provider throw', () => {
+ expect(liReasonTone('llm-error: boom')).toBe('error');
+ });
+ it('is neutral for a nothing-new run', () => {
+ for (const r of LI_NEUTRAL_REASONS) expect(liReasonTone(r)).toBe('neutral');
+ });
+ it('is warn for a config/read failure', () => {
+ expect(liReasonTone('unparseable-response')).toBe('warn');
+ expect(liReasonTone('jira-not-configured')).toBe('warn');
+ expect(liReasonTone(null)).toBe('warn');
+ });
+});
diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.js b/server/services/autonomousJobs/layeredIntelligenceHandler.js
index 96617a9310..f5d450b212 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHandler.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.js
@@ -99,6 +99,14 @@ export async function runLayeredIntelligenceForApp(app, deps = {}) {
if (override.providerId != null) config.providerId = override.providerId
if (override.model != null) config.model = override.model
+ // Every terminal path records the run's OUTCOME (not just lastRunAt) and returns
+ // the same object, so the durable last-run status the UI reads always matches
+ // what was returned to the on-demand feedback layer. One seam ⇒ no drift.
+ const settle = async (outcome) => {
+ await recordRun(app, config, now, outcome)
+ return { app: app.id, ...outcome }
+ }
+
// Resolve where this app files work — branch up front so a `plan` app never
// hits the forge-only label/issue paths.
const tracker = await resolveAppWorkTracker(app).catch(() => ({ resolved: 'plan', forge: null }))
@@ -114,8 +122,7 @@ export async function runLayeredIntelligenceForApp(app, deps = {}) {
? { instanceId: app.jira.instanceId, projectKey: app.jira.projectKey, issueType: app.jira.issueType || 'Task' }
: null
if (filer === 'jira' && !jira) {
- await recordRun(app, config, now)
- return { app: app.id, action: 'skipped', reason: 'jira-not-configured' }
+ return settle({ action: 'skipped', reason: 'jira-not-configured' })
}
// ---- Park check (forge + jira; plan has no issue to block on) ----
@@ -127,13 +134,11 @@ export async function runLayeredIntelligenceForApp(app, deps = {}) {
// than risk resuming work the user parked, and try again next run.
if (blocking && !blocking.ok) {
console.warn(`⚠️ Layered Intelligence: ${app.name} blocking-issue read failed — skipping this run`)
- await recordRun(app, config, now)
- return { app: app.id, action: 'skipped', reason: 'blocking-read-failed' }
+ return settle({ action: 'skipped', reason: 'blocking-read-failed' })
}
if (blocking && isAppParked(blocking.issues)) {
console.log(`⏸️ Layered Intelligence: ${app.name} parked on ${blocking.issues.length} blocking issue(s) — skipping`)
- await recordRun(app, config, now)
- return { app: app.id, action: 'parked', blocking: blocking.issues.length }
+ return settle({ action: 'parked', reason: 'blocking-open', blocking: blocking.issues.length })
}
}
@@ -168,13 +173,11 @@ export async function runLayeredIntelligenceForApp(app, deps = {}) {
const prompt = buildPrompt({ app, config, sources, openIssues, isPortos })
const llm = await resolveLLM(config, callLLM, cwd)
if (!llm.ok) {
- await recordRun(app, config, now)
- return { app: app.id, action: 'no-op', reason: llm.reason }
+ return settle({ action: 'no-op', reason: llm.reason })
}
const llmResult = await llm.call(prompt)
if (llmResult?.error) {
- await recordRun(app, config, now)
- return { app: app.id, action: 'no-op', reason: `llm-error: ${llmResult.error}` }
+ return settle({ action: 'no-op', reason: `llm-error: ${llmResult.error}` })
}
const parsed = safeParse(llmResult?.text)
@@ -184,21 +187,31 @@ export async function runLayeredIntelligenceForApp(app, deps = {}) {
let filedNumber = null // forge: integer issue number
let filedKey = null // jira: string ticket key (PROJ-123)
let filedAction = 'no-op'
+ // Machine-readable reason for a non-filed terminal outcome, so the durable
+ // last-run status + the on-demand toast can tell the user WHY nothing was filed
+ // (the common silent case being a reasoning model that returns no usable JSON).
+ // `no-proposal` = the reasoner ran fine and proposed nothing; `unparseable-
+ // response` = it returned text we couldn't parse into a proposal at all.
+ let reason = parsed == null ? 'unparseable-response' : 'no-proposal'
let handedOff = false
if (proposal) {
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`)
+ reason = 'scope-suppressed'
} else if (trackerReadFailed) {
// Dedup would be blind against a failed tracker read — never file, or a
// transient forge blip files a duplicate. Retry next run (CLAUDE.md sentinel).
console.warn(`⚠️ Layered Intelligence: ${app.name} tracker read failed — suppressing proposal to avoid a blind duplicate`)
filedAction = 'tracker-read-failed'
+ reason = 'tracker-read-failed'
} else if (isProposalDuplicate({ slug: proposal.slug, existingIssues, now })) {
console.log(`♻️ Layered Intelligence: ${app.name} proposal "${proposal.slug}" is a duplicate — suppressed`)
filedAction = 'duplicate'
+ reason = 'duplicate'
} else if (await isSemanticDuplicate(app, proposal, existingIssues, now)) {
filedAction = 'semantic-duplicate'
+ reason = 'semantic-duplicate'
} else {
// ---- Layer 4: ACT (file exactly one) ----
const filed = await fileProposal({ filer, forgeCli, cwd, app, proposal, jira })
@@ -206,7 +219,8 @@ export async function runLayeredIntelligenceForApp(app, deps = {}) {
filedNumber = filed.number ?? null
filedKey = filed.key ?? null
filedAction = 'filed'
- const ref = filedKey || (filedNumber ? `#${filedNumber}` : '')
+ reason = null // filed ⇒ nothing to explain
+ const ref = filedRef(filedKey, filedNumber) ?? ''
console.log(`📌 Layered Intelligence: ${app.name} filed "${proposal.title}" [${proposal.slug}]${ref ? ` (${ref})` : ''}`)
// ---- Optional Engine-A hand-off: enqueue a coding agent for a
// trivial+safe fix (approval-gated) rather than only filing it. Only
@@ -225,6 +239,7 @@ export async function runLayeredIntelligenceForApp(app, deps = {}) {
}
} else {
console.error(`❌ Layered Intelligence: ${app.name} failed to file proposal: ${filed.error || 'unknown'}`)
+ reason = 'file-failed'
}
}
}
@@ -247,8 +262,7 @@ export async function runLayeredIntelligenceForApp(app, deps = {}) {
}
}
- await recordRun(app, config, now)
- return { app: app.id, action: filedAction, filedNumber, filedKey, paused, handedOff }
+ return settle({ action: filedAction, reason, filedNumber, filedKey, paused, handedOff })
}
/**
@@ -348,14 +362,35 @@ function safeParse(text) {
}
/**
- * Persist per-app run bookkeeping (lastRunAt) — run cadence, not issue memory.
- * Routes through updateAppLayeredIntelligence so the write RE-READS the current
- * stored config and merges ONLY `lastRunAt` over it, rather than writing back the
+ * The user-facing ref for a filed proposal: the Jira key when present, else
+ * `#<number>` on a forge, else null (a plain PLAN item files no number/key).
+ */
+function filedRef(key, number) {
+ return key || (number != null ? `#${number}` : null)
+}
+
+/**
+ * Persist per-app run bookkeeping — run cadence AND the last run's OUTCOME, so a
+ * user (especially on mobile, where the transient "Run" toast is easy to miss)
+ * can look up WHY the loop produced nothing after the fact. Routes through
+ * updateAppLayeredIntelligence so the write RE-READS the current stored config
+ * and merges ONLY these bookkeeping fields over it, rather than writing back the
* (possibly seconds-stale) snapshot captured at sweep start — so a user config
* edit made mid-sweep isn't clobbered by the run-bookkeeping write.
+ *
+ * `lastRunAction` is the terminal action (filed / no-op / duplicate / parked /
+ * skipped / …); `lastRunReason` is the machine-readable reason for a non-filed
+ * outcome (or null when it filed / had nothing to explain); `lastRunRef` is the
+ * filed issue ref (`#123` / `PROJ-1`) when it filed, else null.
*/
-async function recordRun(app, config, now) {
- await updateAppLayeredIntelligence(app.id, { lastRunAt: new Date(now).toISOString() }).catch((err) => {
+async function recordRun(app, config, now, outcome = {}) {
+ const patch = {
+ lastRunAt: new Date(now).toISOString(),
+ lastRunAction: outcome.action ?? null,
+ lastRunReason: outcome.reason ?? null,
+ lastRunRef: filedRef(outcome.filedKey, outcome.filedNumber)
+ }
+ await updateAppLayeredIntelligence(app.id, patch).catch((err) => {
console.error(`❌ Layered Intelligence: failed to record run for ${app.id}: ${err.message}`)
})
}
diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
index 2b515191e5..dd53443617 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
@@ -465,6 +465,63 @@ describe('processApp — jira tracker', () => {
});
});
+describe('run outcome reason + persisted bookkeeping', () => {
+ const enabledApp = (extra = {}) => ({
+ id: 'app-1', name: 'App One', repoPath: '/repo',
+ layeredIntelligence: { enabled: true, intervalMs: DAY, allowedScopes: ['app-improvement', 'app-data-gap'] },
+ ...extra
+ });
+
+ // The last recordRun patch (updateAppLayeredIntelligence is recordRun's sink).
+ const lastRunPatch = () => updateAppMock.mock.calls.at(-1)?.[1];
+
+ it('reports unparseable-response when the model returns no usable JSON', async () => {
+ const callLLM = vi.fn().mockResolvedValue({ text: 'I am thinking… no JSON here.' });
+ const out = await processApp(enabledApp(), { callLLM });
+ expect(out.action).toBe('no-op');
+ expect(out.reason).toBe('unparseable-response');
+ expect(lastRunPatch()).toMatchObject({ lastRunAction: 'no-op', lastRunReason: 'unparseable-response', lastRunRef: null });
+ });
+
+ it('reports no-proposal when the reasoner ran but proposed nothing', async () => {
+ const callLLM = reasoner({ analysis: 'nothing worth doing' });
+ const out = await processApp(enabledApp(), { callLLM });
+ expect(out.action).toBe('no-op');
+ expect(out.reason).toBe('no-proposal');
+ });
+
+ it('reports scope-suppressed with a reason (was a silent no-op)', async () => {
+ const callLLM = reasoner({ proposal: { scope: 'loop-meta', slug: 'meta', title: 'Meta' } });
+ const out = await processApp(enabledApp(), { callLLM });
+ expect(out.action).toBe('no-op');
+ expect(out.reason).toBe('scope-suppressed');
+ });
+
+ it('persists the filed ref + null reason on a successful file', async () => {
+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' } });
+ const out = await processApp(enabledApp(), { callLLM });
+ expect(out.action).toBe('filed');
+ expect(out.reason).toBeNull();
+ expect(lastRunPatch()).toMatchObject({ lastRunAction: 'filed', lastRunReason: null, lastRunRef: '#100' });
+ });
+
+ it('carries the llm-error reason through to the persisted outcome', async () => {
+ const callLLM = vi.fn().mockResolvedValue({ error: 'provider timeout' });
+ const out = await processApp(enabledApp(), { callLLM });
+ expect(out.action).toBe('no-op');
+ expect(out.reason).toBe('llm-error: provider timeout');
+ expect(lastRunPatch()?.lastRunReason).toBe('llm-error: provider timeout');
+ });
+
+ it('records the park reason + blocking count in the outcome', async () => {
+ forgeState.blocking = [{ number: 5, state: 'open' }];
+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 's', title: 'T' } });
+ const out = await processApp(enabledApp(), { callLLM });
+ expect(out).toMatchObject({ action: 'parked', reason: 'blocking-open', blocking: 1 });
+ expect(lastRunPatch()).toMatchObject({ lastRunAction: 'parked', lastRunReason: 'blocking-open' });
+ });
+});
+
describe('runLayeredIntelligenceForApp (removed global sweep)', () => {
it('no longer exports a cross-app sweep — the scheduler drives one app at a time', async () => {
const mod = await import('./layeredIntelligenceHandler.js');
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 27b1927d35..942b28151a 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1623,13 +1623,24 @@ export async function emitHandlerBackedOnDemand({ outcome, request, targetApp })
});
return;
}
+ // Non-filed: forward the handler's ACTUAL action + reason so the client can
+ // explain WHY nothing was filed (llm-error, unparseable-response, duplicate,
+ // parked, jira-not-configured, …) instead of a blanket "nothing to do". A
+ // plain `no-op`/`no-proposal` is genuinely idle; everything else is a
+ // handler-issue the user should see. `error` is the thrown-run shape the
+ // caller synthesizes when the handler itself rejects.
+ const action = outcome?.action || 'no-op';
+ const reason = outcome?.reason ?? outcome?.error ?? null;
+ const isIdle = action === 'no-op' && (reason == null || reason === 'no-proposal');
cosEvents.emit('schedule:on-demand-empty', {
requestId: request.id,
taskType: request.taskType,
appId,
appName,
- outcome: 'idle',
- handlerAction: outcome?.action || 'no-op'
+ outcome: isIdle ? 'idle' : 'handler-issue',
+ handlerAction: action,
+ handlerReason: reason,
+ blocking: outcome?.blocking ?? null
});
}
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index c2b4d3edf2..b99e58a5bc 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -15,7 +15,8 @@ import { describe, it, expect } from 'vitest';
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
-import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask } from './cosTaskGenerator.js';
+import { selectDryRunAutoApproved, exceedsMaxSpawns, resolveIssueAuthorFilterBlock, resolveSwarmBlock, isCooldownExemptTask, emitHandlerBackedOnDemand } from './cosTaskGenerator.js';
+import { cosEvents } from './cosEvents.js';
import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -467,3 +468,55 @@ describe('selectDryRunAutoApproved', () => {
expect(out.map(t => t.id)).toEqual(['2']);
});
});
+
+// emitHandlerBackedOnDemand is the on-demand feedback bridge for a handler-backed
+// task (Layered Intelligence): it files a tracker issue rather than spawning a
+// visible agent, so the emitted event is the user's only clue. Before the fix it
+// collapsed every non-filed outcome to a bland `outcome:'idle'` and dropped the
+// reason; these pin that the real action + reason now reach the client.
+describe('emitHandlerBackedOnDemand', () => {
+ const capture = (event) => {
+ const seen = [];
+ const handler = (d) => seen.push(d);
+ cosEvents.on(event, handler);
+ return { seen, done: () => cosEvents.off(event, handler) };
+ };
+ const request = { id: 'req-1', taskType: 'layered-intelligence' };
+ const targetApp = { id: 'app-1', name: 'App One' };
+
+ it('emits on-demand-ran with the filed ref on a filed outcome', async () => {
+ const cap = capture('schedule:on-demand-ran');
+ await emitHandlerBackedOnDemand({ outcome: { action: 'filed', filedNumber: 42 }, request, targetApp });
+ cap.done();
+ expect(cap.seen).toHaveLength(1);
+ expect(cap.seen[0]).toMatchObject({ action: 'filed', filedNumber: 42, appName: 'App One' });
+ });
+
+ it('classifies a genuine no-proposal run as idle', async () => {
+ const cap = capture('schedule:on-demand-empty');
+ await emitHandlerBackedOnDemand({ outcome: { action: 'no-op', reason: 'no-proposal' }, request, targetApp });
+ cap.done();
+ expect(cap.seen[0]).toMatchObject({ outcome: 'idle', handlerAction: 'no-op', handlerReason: 'no-proposal' });
+ });
+
+ it('forwards the reason for an unparseable-response run as a handler-issue', async () => {
+ const cap = capture('schedule:on-demand-empty');
+ await emitHandlerBackedOnDemand({ outcome: { action: 'no-op', reason: 'unparseable-response' }, request, targetApp });
+ cap.done();
+ expect(cap.seen[0]).toMatchObject({ outcome: 'handler-issue', handlerAction: 'no-op', handlerReason: 'unparseable-response' });
+ });
+
+ it('surfaces a park with its blocking count', async () => {
+ const cap = capture('schedule:on-demand-empty');
+ await emitHandlerBackedOnDemand({ outcome: { action: 'parked', reason: 'blocking-open', blocking: 3 }, request, targetApp });
+ cap.done();
+ expect(cap.seen[0]).toMatchObject({ outcome: 'handler-issue', handlerAction: 'parked', blocking: 3 });
+ });
+
+ it('maps a thrown-run { error } into a handler-issue reason', async () => {
+ const cap = capture('schedule:on-demand-empty');
+ await emitHandlerBackedOnDemand({ outcome: { action: 'error', error: 'store down' }, request, targetApp });
+ cap.done();
+ expect(cap.seen[0]).toMatchObject({ outcome: 'handler-issue', handlerAction: 'error', handlerReason: 'store down' });
+ });
+});