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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: surface Layered Intelligence proposal outcomes in the app Intelligence tab (#2689)
[._.]/ Adam Eivy545fb09cf23f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c0d9174ab2..e3d5388fec 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,8 @@- [issue-2698] **Layered Intelligence now sees the work you've already committed to, and won't propose against it.** A new **Planned work** source feeds the loop your `plan`-labeled tracker issues (or your prioritized Jira backlog, or PLAN.md's unchecked items) alongside the flat open-issue list it used to get, with the instruction to cross-reference its proposal and file nothing when it overlaps something already in scope. It also gets told when its own merge rate falls below 20% and pointed at that backlog as the likely reason — LI's most common rejection was "not planned", which is what filing into work you'd already scheduled looks like from the tracker's side. A tracker that can't be read says so explicitly rather than reading as "nothing is planned", so a transient `gh` blip can't hand the loop a blank cheque. On by default for every app; toggle it off per-app under the app's Intelligence tab.+- [issue-2689] **You can now see how Layered Intelligence's proposals have fared.** The app's Intelligence tab gains a read-only Proposal outcomes panel: your merge rate (of the proposals that have resolved), a breakdown of filed / merged / rejected / abandoned / still-open, why the non-merged ones were closed — grouped by reason using the same diagnosis the loop feeds back into its own prompt — and a list of the most recent proposals with their outcome. It reads only what the loop already records, so it costs no AI calls and no extra tracker lookups; an app that has filed nothing says so plainly, a store that can't be read says "couldn't load" rather than pretending your history is empty, and proposals still awaiting triage are counted as open, never as failures.+- [issue-2700] **Layered Intelligence now checks its own work before it files.** A new **Self-evaluation** source hands the loop a deterministic read of its own record — how many of its proposals you actually merged (and the reasons you rejected the rest), which proposals it has already filed that are still suppressed, and whether its own agent runs are even succeeding — so it can judge a proposal's quality *before* filing instead of only learning from your rejections afterward. When it's reasoning with little evidence about itself it's told to hold a higher bar and file nothing rather than guess; when its own runs are failing more than half the time it's told the problem may be the loop rather than the app, and to stop marking work for unattended hand-off. Every signal is either present or explicitly reported missing: "no proposal has been triaged yet" never reads as "everything I file gets rejected", and a tracker that couldn't be read never reads as "I've filed nothing" (which would license a duplicate re-file). Costs no extra AI calls — it's computed from data the loop already has. On by default for PortOS, off for managed apps; toggle it per-app under the app's Intelligence tab.## Changeddiff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsxindex 0b6bd4b954..7f6d28d0ea 100644--- a/client/src/components/apps/EditAppDrawer.jsx+++ b/client/src/components/apps/EditAppDrawer.jsx@@ -691,6 +691,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {{activeTab === 'intelligence' && (<LayeredIntelligenceTab+ appId={app.id}li={liConfig || {}}onChange={updateLiConfig}providers={liProviders}diff --git a/client/src/components/apps/LayeredIntelligenceOutcomes.jsx b/client/src/components/apps/LayeredIntelligenceOutcomes.jsxnew file mode 100644index 0000000000..a20488c6d2--- /dev/null+++ b/client/src/components/apps/LayeredIntelligenceOutcomes.jsx@@ -0,0 +1,188 @@+import { useEffect, useState } from 'react';+import { BarChart3 } from 'lucide-react';+import Banner from '../ui/Banner';+import * as api from '../../services/api';+import { timeAgo } from '../../utils/formatters';+import { formatLiRejectionReason } from '../../utils/layeredIntelligenceReasons';++// Read-only dashboard (#2689): how this app's filed Layered Intelligence proposals+// fared. Display-only, so it fetches its own data OUTSIDE the drawer's controlled+// form state (unlike the config fields, which live in the parent's formData) and+// refetches whenever the app changes or the user retries. Renders nothing without+// an appId so the config tab's own render tests don't trigger a fetch.++const OUTCOME_META = {+ merged: { label: 'Merged', className: 'text-port-success' },+ rejected: { label: 'Rejected', className: 'text-port-error' },+ abandoned: { label: 'Abandoned', className: 'text-port-warning' },+ pending: { label: 'Open', className: 'text-gray-400' }+};++// The outcome/pending buckets, in the order the count strip renders them.+const COUNT_KEYS = ['merged', 'rejected', 'abandoned', 'pending'];++// How many recent rows the panel lists before collapsing the rest to a count —+// keeps the config tab compact (the API already caps the payload higher).+const RECENT_VISIBLE = 6;++function OutcomeBadge({ outcome }) {+ const meta = OUTCOME_META[outcome] || { label: outcome || 'Open', className: 'text-gray-400' };+ return <span className={`text-xs font-medium ${meta.className}`}>{meta.label}</span>;+}++export default function LayeredIntelligenceOutcomes({ appId }) {+ const [nonce, setNonce] = useState(0);+ const [state, setState] = useState({ status: 'loading', data: null });++ useEffect(() => {+ if (!appId) return;+ let active = true;+ setState({ status: 'loading', data: null });+ api.getAppLayeredIntelligenceOutcomes(appId)+ .then(res => { if (active) setState({ status: 'ready', data: res }); })+ .catch(() => { if (active) setState({ status: 'error', data: null }); });+ return () => { active = false; };+ }, [appId, nonce]);++ if (!appId) return null;++ const heading = (+ <div className="flex items-center gap-2">+ <BarChart3 size={14} className="text-port-accent shrink-0" />+ <span className="text-sm text-gray-400">Proposal outcomes</span>+ </div>+ );++ if (state.status === 'loading') {+ return (+ <div className="space-y-2">+ {heading}+ <p className="text-xs text-gray-500">Loading proposal outcomes…</p>+ </div>+ );+ }++ // A thrown request OR an explicit read:false (store unreadable) both mean we+ // can't show the record — distinct from a successful, empty history below.+ if (state.status === 'error' || !state.data?.read) {+ return (+ <div className="space-y-2">+ {heading}+ <Banner tone="error" size="sm">+ Couldn't load proposal outcomes for this app.+ </Banner>+ <button+ type="button"+ onClick={() => setNonce(n => n + 1)}+ className="text-xs px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded"+ >+ Retry+ </button>+ </div>+ );+ }++ const { stats, rejections, recent } = state.data;++ if (!stats || stats.total === 0) {+ return (+ <div className="space-y-2">+ {heading}+ <p className="text-xs text-gray-500">+ No proposals filed yet. Once the loop files improvement issues, their outcomes (merge rate + why any were rejected) appear here.+ </p>+ </div>+ );+ }++ const counts = { ...stats, pending: stats.pending };+ const mergeRateText = stats.mergeRate == null ? '—' : `${Math.round(stats.mergeRate)}%`;+ const rejectionEntries = Array.isArray(rejections?.entries) ? rejections.entries : [];+ const unknown = rejections?.unknown || 0;+ const unclassified = rejections?.unclassified || 0;+ const visible = Array.isArray(recent) ? recent.slice(0, RECENT_VISIBLE) : [];+ const hiddenCount = (Array.isArray(recent) ? recent.length : 0) - visible.length;++ return (+ <div className="space-y-3 bg-port-bg border border-port-border rounded-lg px-3 py-3">+ {heading}++ <div className="flex items-baseline gap-2">+ <span className="text-2xl font-semibold text-white">{mergeRateText}</span>+ <span className="text-xs text-gray-500">+ merge rate+ {stats.resolved > 0+ ? ` — ${stats.merged} of ${stats.resolved} resolved merged`+ : ' — none resolved yet'}+ </span>+ </div>++ <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs">+ <span className="text-gray-500">{stats.total} filed:</span>+ {COUNT_KEYS.map(key => {+ const meta = OUTCOME_META[key];+ return (+ <span key={key} className="flex items-center gap-1">+ <span className={meta.className}>{counts[key]}</span>+ <span className="text-gray-500">{meta.label.toLowerCase()}</span>+ </span>+ );+ })}+ </div>++ {(rejectionEntries.length > 0 || unknown > 0 || unclassified > 0) && (+ <div className="space-y-1">+ <span className="text-xs text-gray-500">Why non-merged proposals were closed</span>+ <ul className="space-y-0.5">+ {rejectionEntries.map(({ reason, count }) => (+ <li key={reason} className="text-xs text-gray-300 flex justify-between gap-2">+ <span>{formatLiRejectionReason(reason)}</span>+ <span className="text-gray-500 shrink-0">{count}</span>+ </li>+ ))}+ {unknown > 0 && (+ <li className="text-xs text-gray-500 flex justify-between gap-2">+ <span>closed with no recorded reason</span>+ <span className="shrink-0">{unknown}</span>+ </li>+ )}+ {unclassified > 0 && (+ <li className="text-xs text-gray-500 flex justify-between gap-2">+ <span>not yet classified</span>+ <span className="shrink-0">{unclassified}</span>+ </li>+ )}+ </ul>+ </div>+ )}++ {visible.length > 0 && (+ <div className="space-y-1">+ <span className="text-xs text-gray-500">Recent</span>+ <ul className="space-y-1">+ {visible.map(item => {+ const gloss = item.outcome !== 'merged' ? formatLiRejectionReason(item.rejectionReason) : '';+ const when = timeAgo(item.outcomeAt || item.filedAt);+ return (+ <li key={`${item.slug}-${item.filedAt}`} className="text-xs flex items-start justify-between gap-2">+ <span className="min-w-0">+ <span className="text-gray-300 font-mono break-all">{item.slug}</span>+ {item.scope && <span className="text-gray-500"> · {item.scope}</span>}+ {gloss && <span className="block text-gray-500">{gloss}</span>}+ </span>+ <span className="flex flex-col items-end shrink-0">+ <OutcomeBadge outcome={item.outcome || 'pending'} />+ {when && <span className="text-gray-600">{when}</span>}+ </span>+ </li>+ );+ })}+ </ul>+ {hiddenCount > 0 && (+ <p className="text-xs text-gray-600">+{hiddenCount} older</p>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/apps/LayeredIntelligenceOutcomes.test.jsx b/client/src/components/apps/LayeredIntelligenceOutcomes.test.jsxnew file mode 100644index 0000000000..3e74e6eeeb--- /dev/null+++ b/client/src/components/apps/LayeredIntelligenceOutcomes.test.jsx@@ -0,0 +1,98 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import LayeredIntelligenceOutcomes from './LayeredIntelligenceOutcomes';++vi.mock('../../services/api', () => ({+ getAppLayeredIntelligenceOutcomes: vi.fn()+}));++import { getAppLayeredIntelligenceOutcomes } from '../../services/api';++const ready = (overrides = {}) => ({+ read: true,+ stats: { total: 4, merged: 1, rejected: 1, abandoned: 1, pending: 1, resolved: 3, mergeRate: 100 / 3 },+ rejections: { entries: [{ reason: 'user-rejected', count: 1 }], unknown: 1, unclassified: 0, diagnosed: 1, total: 2 },+ recent: [+ { slug: 'add-metrics', scope: 'app-improvement', outcome: 'merged', rejectionReason: null, filedAt: '2026-07-04T00:00:00.000Z', outcomeAt: '2026-07-05T00:00:00.000Z' },+ { slug: 'drop-feature', scope: 'app-improvement', outcome: 'rejected', rejectionReason: 'user-rejected', filedAt: '2026-07-03T00:00:00.000Z', outcomeAt: '2026-07-04T00:00:00.000Z' }+ ],+ ...overrides+});++describe('LayeredIntelligenceOutcomes', () => {+ beforeEach(() => vi.clearAllMocks());++ it('renders nothing and never fetches without an appId', () => {+ const { container } = render(<LayeredIntelligenceOutcomes />);+ expect(container).toBeEmptyDOMElement();+ expect(getAppLayeredIntelligenceOutcomes).not.toHaveBeenCalled();+ });++ it('shows the rounded merge rate, counts, rejection tally, and recent rows', async () => {+ getAppLayeredIntelligenceOutcomes.mockResolvedValue(ready());+ render(<LayeredIntelligenceOutcomes appId="app-001" />);++ expect(await screen.findByText('33%')).toBeInTheDocument();+ expect(screen.getByText(/1 of 3 resolved merged/)).toBeInTheDocument();+ // Real diagnosis is glossed (in both the tally and the matching recent row);+ // the undiagnosed row shows as a distinct gap line.+ expect(screen.getAllByText(/the user declined it/).length).toBeGreaterThan(0);+ expect(screen.getByText(/closed with no recorded reason/)).toBeInTheDocument();+ expect(screen.getByText('add-metrics')).toBeInTheDocument();+ expect(screen.getByText('drop-feature')).toBeInTheDocument();+ expect(getAppLayeredIntelligenceOutcomes).toHaveBeenCalledWith('app-001');+ });++ it('shows a dash for the merge rate when nothing has resolved yet', async () => {+ getAppLayeredIntelligenceOutcomes.mockResolvedValue(ready({+ stats: { total: 1, merged: 0, rejected: 0, abandoned: 0, pending: 1, resolved: 0, mergeRate: null },+ rejections: { entries: [], unknown: 0, unclassified: 0, diagnosed: 0, total: 0 },+ recent: [{ slug: 'open-one', scope: 'app-improvement', outcome: null, rejectionReason: null, filedAt: '2026-07-01T00:00:00.000Z', outcomeAt: null }]+ }));+ render(<LayeredIntelligenceOutcomes appId="app-001" />);++ expect(await screen.findByText('—')).toBeInTheDocument();+ expect(screen.getByText(/none resolved yet/)).toBeInTheDocument();+ });++ it('shows the empty state when no proposals have been filed', async () => {+ getAppLayeredIntelligenceOutcomes.mockResolvedValue(ready({+ stats: { total: 0, merged: 0, rejected: 0, abandoned: 0, pending: 0, resolved: 0, mergeRate: null },+ rejections: { entries: [], unknown: 0, unclassified: 0, diagnosed: 0, total: 0 },+ recent: []+ }));+ render(<LayeredIntelligenceOutcomes appId="app-001" />);++ expect(await screen.findByText(/No proposals filed yet/)).toBeInTheDocument();+ });++ it('surfaces an error (and retries) when the store is unreadable', async () => {+ getAppLayeredIntelligenceOutcomes.mockResolvedValue({ read: false, stats: null, rejections: null, recent: [] });+ render(<LayeredIntelligenceOutcomes appId="app-001" />);++ expect(await screen.findByText(/Couldn.t load proposal outcomes/)).toBeInTheDocument();++ getAppLayeredIntelligenceOutcomes.mockResolvedValue(ready());+ fireEvent.click(screen.getByText('Retry'));+ expect(await screen.findByText('33%')).toBeInTheDocument();+ expect(getAppLayeredIntelligenceOutcomes).toHaveBeenCalledTimes(2);+ });++ it('surfaces an error when the request throws', async () => {+ getAppLayeredIntelligenceOutcomes.mockRejectedValue(new Error('network'));+ render(<LayeredIntelligenceOutcomes appId="app-001" />);+ expect(await screen.findByText(/Couldn.t load proposal outcomes/)).toBeInTheDocument();+ });++ it('collapses recent rows past the visible cap to a count', async () => {+ const many = Array.from({ length: 9 }, (_, i) => ({+ slug: `item-${i}`, scope: 'app-improvement', outcome: 'merged', rejectionReason: null,+ filedAt: `2026-07-0${(i % 9) + 1}T00:00:00.000Z`, outcomeAt: `2026-07-0${(i % 9) + 1}T00:00:00.000Z`+ }));+ getAppLayeredIntelligenceOutcomes.mockResolvedValue(ready({ recent: many }));+ render(<LayeredIntelligenceOutcomes appId="app-001" />);++ await waitFor(() => expect(screen.getByText('item-0')).toBeInTheDocument());+ expect(screen.getByText('+3 older')).toBeInTheDocument();+ });+});diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsxindex 17238713ed..6ad788db01 100644--- a/client/src/components/apps/LayeredIntelligenceTab.jsx+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx@@ -1,6 +1,7 @@import { Plus, Trash2, Brain } from 'lucide-react';import Banner from '../ui/Banner';import ProviderModelSelector from '../ProviderModelSelector';+import LayeredIntelligenceOutcomes from './LayeredIntelligenceOutcomes';import { filterSelectableModels } from '../../utils/providers';import { timeAgo } from '../../utils/formatters';import { formatLiReason, liReasonTone } from '../../utils/layeredIntelligenceReasons';@@ -215,7 +216,7 @@ export function buildLayeredIntelligenceScheduleUpdate(baseline, current) {* with a partial update. `sources` updates merge one level deep here so a single* toggle doesn't wipe the others.*/-export default function LayeredIntelligenceTab({ li, onChange, providers, isPortos, loaded, error = false, onRetry }) {+export default function LayeredIntelligenceTab({ appId, li, onChange, providers, isPortos, loaded, error = false, onRetry }) {if (!loaded) {return <div className="text-sm text-gray-500">Loading Layered Intelligence config…</div>;}@@ -273,6 +274,8 @@ export default function LayeredIntelligenceTab({ li, onChange, providers, isPort</div>)}+ <LayeredIntelligenceOutcomes appId={appId} />+<label className="flex items-center gap-2 cursor-pointer"><inputtype="checkbox"diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex 3a52466e6d..1dc9022ec6 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -15,6 +15,11 @@ export const getAppWorkTracker = (id, options) =>// side). Caller owns its own .catch fallback, so default to silent.export const getAppLayeredIntelligence = (id, options) =>request(`/apps/${id}/layered-intelligence`, { silent: true, ...options });+// Read-only LI proposal-outcome dashboard data (#2689): merge-rate stats, the+// rejection-reason tally, and a capped recent list. The panel owns its own error+// UI, so default to silent.+export const getAppLayeredIntelligenceOutcomes = (id, options) =>+ request(`/apps/${id}/layered-intelligence/outcomes`, { silent: true, ...options });export const createApp = (data) => request('/apps', {method: 'POST',body: JSON.stringify(data)diff --git a/client/src/utils/layeredIntelligenceReasons.js b/client/src/utils/layeredIntelligenceReasons.jsindex d04c953a53..486514b146 100644--- a/client/src/utils/layeredIntelligenceReasons.js+++ b/client/src/utils/layeredIntelligenceReasons.js@@ -58,3 +58,30 @@ export function liReasonTone(reason = null) {if (LI_NEUTRAL_REASONS.has(reason)) return 'neutral';return 'warn';}++// The proposal-REJECTION taxonomy (#2689) — WHY a filed proposal ended up not+// merged. Distinct vocabulary from the run-reason tokens above: those explain why a+// LOOP RUN produced no proposal, these explain why a FILED proposal was rejected.+// Mirrors the server gloss (REJECTION_REASON_LABELS in+// server/services/layeredIntelligenceRejections.js) so the outcomes dashboard reads+// the same as the reasoner prompt. Keep in lockstep; an unknown token degrades to+// itself. `unknown-reason` is the honest "we classified it and found no signal"+// sentinel — a real answer, not a gap.+const LI_REJECTION_REASON_LABELS = {+ 'duplicate': 'already tracked elsewhere (duplicate)',+ 'user-rejected': 'the user declined it (closed as not planned)',+ 'scope-mismatch': "outside the app's scope",+ 'missing-context': 'missing context the proposal should have supplied',+ 'quality-issue': 'the proposal itself was low quality or malformed',+ 'environment-blocker': 'blocked on the environment or a dependency',+ 'merge-conflict': 'the implementing change could not be merged',+ 'validation-failed': 'the implementing change failed lint/validation',+ 'unknown-reason': 'closed with no recorded reason'+};++// Gloss one rejection-reason token as prose. A nullish input renders as '' (not+// classified — nothing to say); an unglossed token passes through.+export function formatLiRejectionReason(reason = null) {+ if (!reason) return '';+ return LI_REJECTION_REASON_LABELS[reason] || reason;+}diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.jsindex f450f2f833..dfbc2becb2 100644--- a/server/routes/apps/taskTypes.js+++ b/server/routes/apps/taskTypes.js@@ -5,7 +5,8 @@* PUT /bulk-task-type/:taskType → { success, appsUpdated } (all active apps)* GET /:id/task-types → { taskTypeOverrides }* GET /:id/work-tracker → { tracker info }- * GET /:id/layered-intelligence → { config, isPortos }+ * GET /:id/layered-intelligence → { config, isPortos }+ * GET /:id/layered-intelligence/outcomes → { stats, rejections, recent }* PUT /:id/task-types/all → { success, taskTypeOverrides }* PUT /:id/task-types/:taskType → { success, taskTypeOverrides }*@@ -20,10 +21,18 @@ import { sanitizeTaskMetadata } from '../../lib/validation.js';import { parseCronToNextRun } from '../../services/eventScheduler.js';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';import { SELF_IMPROVEMENT_TASK_TYPES } from '../../services/taskSchedule.js';+import { summarizeOutcomeStats } from '../../services/layeredIntelligence.js';+import { listOutcomesResult } from '../../services/layeredIntelligenceOutcomes.js';+import { summarizeRejectionReasons } from '../../services/layeredIntelligenceRejections.js';import { loadApp } from './shared.js';const router = Router();+// How many recent outcome rows the dashboard payload carries. The aggregate+// stats/rejection tally are computed over the FULL retained set; this cap only+// bounds the per-record list the UI renders newest-first.+const OUTCOMES_DASHBOARD_LIMIT = 25;+// PUT /api/apps/bulk-task-type/:taskType - Enable/disable a task type for all active appsrouter.put('/bulk-task-type/:taskType', asyncHandler(async (req, res) => {const { enabled } = req.body;@@ -68,6 +77,47 @@ router.get('/:id/layered-intelligence', loadApp, asyncHandler(async (req, res) =res.json({ appId: app.id, appName: app.name, isPortos: app.id === PORTOS_APP_ID, config });}));+// GET /api/apps/:id/layered-intelligence/outcomes - Read-only dashboard of how+// this app's filed LI proposals fared (#2689). Composes the same pure aggregators+// the reasoner prompt reasons over — summarizeOutcomeStats (merge-rate math) and+// the rejection taxonomy (summarizeRejectionReasons) — plus a capped recent list,+// so the diagnostics the loop already produces are visible to the user. Only reads+// the outcome store: no tracker fetch, no LLM call.+//+// `read: false` is surfaced verbatim from listOutcomesResult so the UI can say+// "couldn't load" rather than the lie "nothing has ever been filed" — the same+// sentinel discipline the reasoner's selfEval uses (an unreadable store must not+// collapse into an empty history).+router.get('/:id/layered-intelligence/outcomes', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const { read, outcomes } = await listOutcomesResult({ appId: app.id });+ if (!read) {+ return res.json({ appId: app.id, appName: app.name, read: false, stats: null, rejections: null, recent: [] });+ }+ const { total, merged, rejected, abandoned, pending, resolved, rawMergeRate } = summarizeOutcomeStats(outcomes);+ const rejections = summarizeRejectionReasons(outcomes);+ const recent = outcomes.slice(0, OUTCOMES_DASHBOARD_LIMIT).map(o => ({+ slug: o.slug,+ scope: o.scope,+ outcome: o.outcome,+ rejectionReason: o.rejectionReason,+ issueRef: o.issueRef,+ tracker: o.tracker,+ filedAt: o.filedAt,+ outcomeAt: o.outcomeAt+ }));+ res.json({+ appId: app.id,+ appName: app.name,+ read: true,+ // `mergeRate` is the raw 0–100 percentage over RESOLVED proposals, or null when+ // none have resolved (still-pending ≠ 0% merged). The client rounds for display.+ stats: { total, merged, rejected, abandoned, pending, resolved, mergeRate: rawMergeRate },+ rejections,+ recent+ });+}));+// PUT /api/apps/:id/task-types/all - Toggle all task types for an approuter.put('/:id/task-types/all', loadApp, asyncHandler(async (req, res) => {const { enabled } = req.body;diff --git a/server/routes/apps/taskTypes.test.js b/server/routes/apps/taskTypes.test.jsindex 27d70f61cd..280aa3bc61 100644--- a/server/routes/apps/taskTypes.test.js+++ b/server/routes/apps/taskTypes.test.js@@ -17,7 +17,15 @@ vi.mock('../../services/apps.js', () => ({PORTOS_APP_ID: 'portos-default'}));+// The outcome STORE (file I/O) is mocked; the pure aggregators the route composes+// (summarizeOutcomeStats + the rejection taxonomy) run for real so the test covers+// the real merge-rate/rejection math, not a restated stub.+vi.mock('../../services/layeredIntelligenceOutcomes.js', () => ({+ listOutcomesResult: vi.fn()+}));+import * as appsService from '../../services/apps.js';+import { listOutcomesResult } from '../../services/layeredIntelligenceOutcomes.js';describe('Apps Task-Type Routes', () => {let app;@@ -62,6 +70,64 @@ describe('Apps Task-Type Routes', () => {});});+ describe('GET /api/apps/:id/layered-intelligence/outcomes', () => {+ it('composes stats + rejection tally + recent list from the store', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'App' });+ listOutcomesResult.mockResolvedValue({+ read: true,+ outcomes: [+ { slug: 'add-metrics', scope: 'app-improvement', outcome: 'merged', rejectionReason: null, issueRef: '#10', tracker: 'github', filedAt: '2026-07-04T00:00:00.000Z', outcomeAt: '2026-07-05T00:00:00.000Z' },+ { slug: 'drop-feature', scope: 'app-improvement', outcome: 'rejected', rejectionReason: 'user-rejected', issueRef: '#11', tracker: 'github', filedAt: '2026-07-03T00:00:00.000Z', outcomeAt: '2026-07-04T00:00:00.000Z' },+ { slug: 'vague-idea', scope: 'app-data-gap', outcome: 'abandoned', rejectionReason: 'unknown-reason', issueRef: '#12', tracker: 'github', filedAt: '2026-07-02T00:00:00.000Z', outcomeAt: '2026-07-03T00:00:00.000Z' },+ { slug: 'open-one', scope: 'app-improvement', outcome: null, rejectionReason: null, issueRef: '#13', tracker: 'github', filedAt: '2026-07-01T00:00:00.000Z', outcomeAt: null }+ ]+ });++ const response = await request(app).get('/api/apps/app-001/layered-intelligence/outcomes');++ expect(response.status).toBe(200);+ expect(response.body.read).toBe(true);+ expect(response.body.stats).toMatchObject({ total: 4, merged: 1, rejected: 1, abandoned: 1, pending: 1, resolved: 3 });+ expect(response.body.stats.mergeRate).toBeCloseTo(100 / 3, 5);+ // Real diagnoses only in entries; the undiagnosed abandoned row is `unknown`.+ expect(response.body.rejections.entries).toEqual([{ reason: 'user-rejected', count: 1 }]);+ expect(response.body.rejections.unknown).toBe(1);+ expect(response.body.rejections.unclassified).toBe(0);+ expect(response.body.recent).toHaveLength(4);+ expect(response.body.recent[0]).toMatchObject({ slug: 'add-metrics', outcome: 'merged' });+ expect(listOutcomesResult).toHaveBeenCalledWith({ appId: 'app-001' });+ });++ it('reports read:false when the store is unreadable (not an empty history)', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'App' });+ listOutcomesResult.mockResolvedValue({ read: false, outcomes: [] });++ const response = await request(app).get('/api/apps/app-001/layered-intelligence/outcomes');++ expect(response.status).toBe(200);+ expect(response.body.read).toBe(false);+ expect(response.body.stats).toBeNull();+ expect(response.body.recent).toEqual([]);+ });++ it('returns a zero-total, null merge rate for an app that has filed nothing', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'App' });+ listOutcomesResult.mockResolvedValue({ read: true, outcomes: [] });++ const response = await request(app).get('/api/apps/app-001/layered-intelligence/outcomes');++ expect(response.status).toBe(200);+ expect(response.body.read).toBe(true);+ expect(response.body.stats).toMatchObject({ total: 0, resolved: 0, mergeRate: null });+ });++ it('returns 404 for an unknown app', async () => {+ appsService.getAppById.mockResolvedValue(null);+ const response = await request(app).get('/api/apps/app-999/layered-intelligence/outcomes');+ expect(response.status).toBe(404);+ });+ });+describe('PUT /api/apps/:id/task-types/:taskType', () => {it('should accept valid taskMetadata with allowed boolean keys', async () => {appsService.updateAppTaskTypeOverride.mockResolvedValue({