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: dedicated Layered Intelligence loop status page + ⌘K entry (#2262)
Adam Eivycaf0a4d3d9d7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d0da96bd36..8c87aeae90 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -25,6 +25,10 @@- **Partially-completed issues no longer become un-claimable "zombies," and a new scheduled task heals any that already exist.** When a claim run shipped only PART of an issue's scope and merged the PR, the issue was left OPEN with its `in-progress` label (and assignee) still on — and since the claim queue treats `in-progress` as "claimed and being worked," the remaining scope was never re-picked and never finished (real cases: #2220, #2179, #2175). The completion flow was binary (fully-done → close + unlabel) with no "partial ship" path, and the branch reconciler is branch-centric so it never touched the linked issue. Two fixes: **(1)** the `claim-issue` / `-gitlab` / `-jira` prompts now choose the PR trailer deliberately (`Closes` for a full ship, `Refs` + a `## Remaining` section for a partial one) and Phase 7 reconciles the issue with an agent-judged hybrid — close + file a scoped follow-up when the remainder is a clean separable chunk, else post a `Done ✓ / Remaining ▢` comment and release the `in-progress` claim so the queue re-picks it (JIRA records remaining scope + files a follow-up ticket). **(2)** a new opt-in per-app `issue-reconcile` CoS task (sibling to `branch-reconcile`, disabled by default) runs a deterministic `gh`/`git` scan for zombie issues — open + `in-progress` yet with their PR merged and no live claim anywhere (no open PR, no local/remote/CoS claim branch, no active agent) — and dispatches a coordinator agent that applies the same hybrid per issue, with an `autoClose` toggle (OFF ⇒ comment + release only) and follow-up dedup so two federated peers can't file duplicates. Perpetual drain with a convergence signature, exactly like branch-reconcile. (`server/services/issueReconcile.js`, `server/services/cosTaskGenerator.js`, `server/services/taskSchedule.js`, `server/lib/cosValidation.js`, `server/services/taskPromptDefaults/`)+## Layered Intelligence++- **[issue-2262] A dedicated Layered Intelligence page now surfaces the self-improvement loop's status across every app.** The perpetual per-app loop was previously visible only inside each app's Edit-App → Intelligence drawer tab, so there was no single place to see which apps had it enabled, when each last ran / is next due, or whether the global sweep job is even on. The new `/layered-intelligence` route (Chief of Staff → Layered Intelligence, `⌘K`/voice-navigable) reads a deterministic cross-app overview — each active app's effective config plus scheduler bookkeeping (`lastRunAt`/`nextDueAt`/due) and the global job's on/off state — with no LLM or forge I/O. It warns when the global job is disabled (per-app configs are inert until it's on), lists enabled apps with their interval, telemetry sources, allowed scopes, and provider, and deep-links each app's "Configure" action straight into its Intelligence tab (`/apps/:id?edit=1&appTab=intelligence`, via a new auto-open trigger on the app-detail drawer). (`server/routes/apps.js`, `server/services/layeredIntelligence.js` `summarizeLoopStatus`, `client/src/pages/LayeredIntelligence.jsx`, `client/src/components/apps/AppDetailView.jsx`, `server/lib/navManifest.js`)+## Creative Writing Quality Engine- **[issue-2181] Prose series can now be exported as a compiled manuscript, an ePub, or a print-interior PDF.** A prose-format series had no shipping step — once the quality-engine phases produced publishable prose the pipeline dead-ended at "text in stages" (comic series already had `comicPdf`/`volumePdf`, prose had nothing). A new **Export** tab on the series page (deep-linkable `/pipeline/series/:id/export`, registered in the nav manifest) offers three downloads, each assembled on demand and streamed straight to disk: (1) a **compiled manuscript** (Markdown with YAML front matter, volume breaks, and chapter headings) that reuses the same arc-ordered, drafted-prose-only `collectManuscriptSections` stitching the editorial passes use, so the exported prose matches what the editor and LLM see; (2) an **ePub** — an OCF container (mimetype + container.xml + OPF manifest + nav doc + per-volume XHTML chapters + CSS + the cover image from the existing cover stage) packaged in-repo with the existing `zipWriter.createZip` (no epub dependency added, per the dependency policy — `mimetype` stays entry #0, stored, per spec); (3) a **print-interior PDF** — a trade-format interior (trim size, margins, running heads, title page, chapter openers) built on the same `pdf-lib` plumbing as `volumePdf.js`. Per-series export settings (trim size, interior font, title-page/subtitle/author/copyright/dedication) persist on the series record under a new `exportSettings` field (`sanitizeProseExportSettings`, wire-gated at `pipelineSeries` v12 + `ADDITIVE_SERIES_FIELDS` so an older peer can't strip-then-LWW it). Issues group into volume breaks by `seasonId`. (`server/services/pipeline/proseExport.js`, `server/lib/proseExportSettings.js`, `server/routes/pipeline/proseExport.js`, `client/src/pages/PipelineExport.jsx`)diff --git a/client/src/App.jsx b/client/src/App.jsxindex 4f033550dc..6ba68e5a25 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -38,6 +38,7 @@ const Submodules = lazyWithReload(() => import('./pages/Submodules'));const ImageClean = lazyWithReload(() => import('./pages/ImageClean'));const VideoDownloaderPage = lazyWithReload(() => import('./pages/VideoDownloaderPage'));const ChiefOfStaff = lazyWithReload(() => import('./pages/ChiefOfStaff'));+const LayeredIntelligence = lazyWithReload(() => import('./pages/LayeredIntelligence'));const Ask = lazyWithReload(() => import('./pages/Ask'));const MediaGen = lazyWithReload(() => import('./pages/MediaGen'));const ImageGen = lazyWithReload(() => import('./pages/ImageGen'));@@ -203,6 +204,7 @@ export default function App() {<Route path="/" element={<Layout />}><Route index element={<Dashboard />} /><Route path="apps" element={<Apps />} />+ <Route path="layered-intelligence" element={<LayeredIntelligence />} /><Route path="devtools" element={<Navigate to="/devtools/runs" replace />} /><Route path="devtools/datadog" element={<DataDog />} /><Route path="devtools/flows" element={<FlowsDoc />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex d206cd9209..cb1b2f891c 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -186,6 +186,7 @@ const navItems = [{ to: '/feature-agents', label: 'Feature Agents', icon: Wand2 },{ to: '/cos/gsd', label: 'GSD', icon: Compass },{ to: '/cos/health', label: 'Health', icon: Activity },+ { to: '/layered-intelligence', label: 'Layered Intelligence', icon: Layers },{ to: '/cos/learning', label: 'Learning', icon: GraduationCap },{ to: '/cos/memory', label: 'Memory', icon: Brain },{ to: '/cos/schedule', label: 'Schedule', icon: Clock },diff --git a/client/src/components/apps/AppDetailView.jsx b/client/src/components/apps/AppDetailView.jsxindex 75252f4dcc..8a2fa5b896 100644--- a/client/src/components/apps/AppDetailView.jsx+++ b/client/src/components/apps/AppDetailView.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useCallback, useMemo } from 'react';-import { Link, useParams, useNavigate } from 'react-router-dom';+import { Link, useParams, useNavigate, useSearchParams } from 'react-router-dom';import { ArrowLeft, Play, Square, RotateCcw, ExternalLink, Hammer, RefreshCw, Pencil, AlertTriangle, Sparkles } from 'lucide-react';import DeployPanel from './DeployPanel';import EditAppDrawer from './EditAppDrawer';@@ -24,6 +24,7 @@ import UpdateTab from './tabs/UpdateTab';export default function AppDetailView() {const { appId, tab } = useParams();const navigate = useNavigate();+ const [searchParams, setSearchParams] = useSearchParams();const activeTab = tab || 'overview';const [app, setApp] = useState(null);@@ -61,6 +62,19 @@ export default function AppDetailView() {setEditing(false);}, [appId]);+ // Deep-link into the Edit App drawer (e.g. the Layered Intelligence overview+ // links here with `?edit=1&appTab=intelligence` to open the Intelligence tab).+ // The `edit` trigger is consumed immediately so closing the drawer doesn't+ // re-open it; `appTab` is preserved for the drawer's own useDrawerTab to read.+ // Declared AFTER the appId-close effect so it wins on the same-commit mount.+ useEffect(() => {+ if (searchParams.get('edit') == null) return;+ setEditing(true);+ const next = new URLSearchParams(searchParams);+ next.delete('edit');+ setSearchParams(next, { replace: true });+ }, [searchParams, setSearchParams]);+// Real-time updatesuseEffect(() => {const handleAppsChanged = () => fetchApp();diff --git a/client/src/pages/LayeredIntelligence.jsx b/client/src/pages/LayeredIntelligence.jsxnew file mode 100644index 0000000000..0d27a2b36e--- /dev/null+++ b/client/src/pages/LayeredIntelligence.jsx@@ -0,0 +1,208 @@+import { useState, useEffect, useCallback } from 'react';+import { Link } from 'react-router-dom';+import { Brain, Settings, Clock, CheckCircle2, PauseCircle, Sparkles } from 'lucide-react';+import BrailleSpinner from '../components/BrailleSpinner';+import Banner from '../components/ui/Banner';+import * as api from '../services/api';+import { timeAgo, timeUntil } from '../utils/formatters';+import {+ LI_SCOPES,+ LI_SOURCE_FIELDS,+ LI_INTERVAL_PRESETS+} from '../components/apps/LayeredIntelligenceTab';++// Label lookups reused from the per-app config tab so the page and the drawer+// never drift on scope/source/interval naming.+const SCOPE_LABEL = Object.fromEntries(LI_SCOPES.map(s => [s.id, s.label]));+const SOURCE_LABEL = Object.fromEntries(LI_SOURCE_FIELDS.map(s => [s.key, s.label]));+const INTERVAL_LABEL = Object.fromEntries(LI_INTERVAL_PRESETS.map(p => [p.ms, p.label]));++// Human interval: a known preset renders as its label ("Daily"), else "every N min".+function intervalLabel(ms) {+ if (INTERVAL_LABEL[ms]) return INTERVAL_LABEL[ms];+ if (!ms) return '-';+ return `every ${Math.round(ms / 60000)} min`;+}++// The enabled telemetry sources for an app as short chip labels (+ custom count).+function sourceChips(sources = {}) {+ const chips = LI_SOURCE_FIELDS.filter(f => sources[f.key]).map(f => SOURCE_LABEL[f.key]);+ if (sources.customCount > 0) chips.push(`${sources.customCount} custom`);+ return chips;+}++function Chip({ children, tone = 'default' }) {+ const tones = {+ default: 'bg-port-bg text-gray-300 border-port-border',+ accent: 'bg-port-accent/15 text-port-accent border-port-accent/30',+ success: 'bg-port-success/15 text-port-success border-port-success/30',+ warning: 'bg-port-warning/15 text-port-warning border-port-warning/30'+ };+ return (+ <span className={`inline-block px-2 py-0.5 rounded border text-xs ${tones[tone] || tones.default}`}>+ {children}+ </span>+ );+}++function AppLoopCard({ app }) {+ const scopes = (app.allowedScopes || []).map(id => SCOPE_LABEL[id] || id);+ const chips = sourceChips(app.sources);+ return (+ <div className="bg-port-card border border-port-border rounded-lg p-4 flex flex-col gap-3">+ <div className="flex items-start justify-between gap-2">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <Link to={`/apps/${app.id}`} className="font-medium text-white hover:underline truncate">+ {app.name}+ </Link>+ {app.isPortos && <Chip tone="accent">PortOS</Chip>}+ </div>+ <div className="mt-1 flex items-center gap-2 text-xs">+ {app.enabled+ ? <span className="flex items-center gap-1 text-port-success"><CheckCircle2 size={13} /> Enabled</span>+ : <span className="flex items-center gap-1 text-gray-500"><PauseCircle size={13} /> Disabled</span>}+ {app.enabled && app.due && <Chip tone="warning">Due now</Chip>}+ </div>+ </div>+ <Link+ to={`/apps/${app.id}?edit=1&appTab=intelligence`}+ className="flex items-center gap-1 text-xs px-2 py-1 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded shrink-0"+ >+ <Settings size={12} /> Configure+ </Link>+ </div>++ {app.enabled && (+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs">+ <div>+ <div className="text-gray-500">Interval</div>+ <div className="text-gray-300 flex items-center gap-1"><Clock size={11} /> {intervalLabel(app.intervalMs)}</div>+ </div>+ <div>+ <div className="text-gray-500">Last run</div>+ <div className="text-gray-300">{timeAgo(app.lastRunAt)}</div>+ </div>+ <div>+ <div className="text-gray-500">Next due</div>+ <div className="text-gray-300">{app.due ? 'now' : (app.nextDueAt ? timeUntil(app.nextDueAt, 'soon') : 'first run')}</div>+ </div>+ <div>+ <div className="text-gray-500">Provider</div>+ <div className="text-gray-300 truncate">{app.providerId || 'default'}</div>+ </div>+ </div>+ )}++ {app.enabled && (+ <div className="flex flex-col gap-2">+ {chips.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {chips.map(c => <Chip key={c}>{c}</Chip>)}+ </div>+ )}+ {scopes.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {scopes.map(s => <Chip key={s} tone="accent">{s}</Chip>)}+ </div>+ )}+ {app.hasRules && <div className="text-xs text-gray-500 flex items-center gap-1"><Sparkles size={11} /> Custom guidance rules set</div>}+ </div>+ )}+ </div>+ );+}++export default function LayeredIntelligence() {+ const [data, setData] = useState(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState(false);++ const load = useCallback(async () => {+ setError(false);+ const res = await api.getLayeredIntelligenceOverview({ silent: true }).catch(() => null);+ if (!res) setError(true);+ else setData(res);+ setLoading(false);+ }, []);++ useEffect(() => { load(); }, [load]);++ const apps = data?.apps || [];+ const enabledApps = apps.filter(a => a.enabled);+ const availableApps = apps.filter(a => !a.enabled);++ return (+ <div className="max-w-5xl mx-auto space-y-4">+ <div className="flex items-start gap-3">+ <Brain size={24} className="text-port-accent mt-0.5 shrink-0" />+ <div>+ <h1 className="text-xl font-semibold text-white">Layered Intelligence</h1>+ <p className="text-sm text-gray-400">+ A perpetual, per-app self-improvement loop. On its schedule it reads each enabled app's goals and+ telemetry, asks a reasoning model for the single highest-value improvement, and files one deduplicated+ tracker issue for a coding agent — the model never touches code. Configure it per app on each app's+ Intelligence tab.+ </p>+ </div>+ </div>++ {loading ? (+ <div className="flex items-center justify-center py-16"><BrailleSpinner text="Loading" /></div>+ ) : error ? (+ <div className="space-y-3">+ <Banner tone="error" size="md">Couldn't load the Layered Intelligence overview.</Banner>+ <button+ type="button"+ onClick={() => { setLoading(true); load(); }}+ className="text-xs px-3 py-1.5 bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded"+ >+ Retry+ </button>+ </div>+ ) : (+ <>+ {!data.jobEnabled && (+ <Banner tone="warning" size="md">+ The global <strong>Layered Intelligence Loop</strong> job is off, so no app's loop will run even when+ enabled below. Turn it on under{' '}+ <Link to="/cos/jobs" className="underline hover:text-white">Chief of Staff → System Tasks</Link>.+ </Banner>+ )}++ <div className="text-sm text-gray-400">+ {enabledApps.length} of {apps.length} app{apps.length === 1 ? '' : 's'} have the loop enabled.+ </div>++ {enabledApps.length > 0 ? (+ <div className="grid gap-3 md:grid-cols-2">+ {enabledApps.map(app => <AppLoopCard key={app.id} app={app} />)}+ </div>+ ) : (+ <Banner tone="info" size="md">+ No app has the loop enabled yet. Enable it per app on its Intelligence tab — it's off by default.+ </Banner>+ )}++ {availableApps.length > 0 && (+ <div className="space-y-2 pt-2">+ <h2 className="text-sm font-medium text-gray-400">Available apps ({availableApps.length})</h2>+ <div className="grid gap-2 sm:grid-cols-2 md:grid-cols-3">+ {availableApps.map(app => (+ <Link+ key={app.id}+ to={`/apps/${app.id}?edit=1&appTab=intelligence`}+ className="flex items-center justify-between gap-2 bg-port-card border border-port-border rounded-lg px-3 py-2 hover:border-port-accent/50"+ >+ <span className="text-sm text-gray-300 truncate">{app.name}</span>+ <Settings size={13} className="text-gray-500 shrink-0" />+ </Link>+ ))}+ </div>+ </div>+ )}+ </>+ )}+ </div>+ );+}diff --git a/client/src/pages/LayeredIntelligence.test.jsx b/client/src/pages/LayeredIntelligence.test.jsxnew file mode 100644index 0000000000..d2a232f942--- /dev/null+++ b/client/src/pages/LayeredIntelligence.test.jsx@@ -0,0 +1,72 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router-dom';+import LayeredIntelligence from './LayeredIntelligence';+import * as api from '../services/api';++vi.mock('../services/api', () => ({+ getLayeredIntelligenceOverview: vi.fn()+}));++const renderPage = () => render(+ <MemoryRouter>+ <LayeredIntelligence />+ </MemoryRouter>+);++const overview = (extra = {}) => ({+ jobId: 'job-layered-intelligence',+ jobEnabled: true,+ jobExists: true,+ enabledCount: 1,+ apps: [+ {+ id: 'app-on', name: 'Alpha', isPortos: false, enabled: true, intervalMs: 86400000,+ providerId: null, model: null, hasRules: false,+ lastRunAt: null, nextDueAt: null, due: true,+ allowedScopes: ['app-improvement'],+ sources: { goals: true, cosMetrics: false, healthReport: false, planMd: false, openIssues: true, customCount: 0 }+ },+ {+ id: 'app-off', name: 'Zeta', isPortos: false, enabled: false, intervalMs: 86400000,+ providerId: null, model: null, hasRules: false,+ lastRunAt: null, nextDueAt: null, due: false,+ allowedScopes: ['app-improvement'],+ sources: { goals: true, cosMetrics: false, healthReport: false, planMd: false, openIssues: true, customCount: 0 }+ }+ ],+ ...extra+});++describe('LayeredIntelligence page', () => {+ beforeEach(() => vi.clearAllMocks());++ it('renders enabled apps with their status and available apps separately', async () => {+ api.getLayeredIntelligenceOverview.mockResolvedValue(overview());+ renderPage();++ await waitFor(() => expect(screen.getByText('Alpha')).toBeInTheDocument());+ expect(screen.getByText('Enabled')).toBeInTheDocument();+ expect(screen.getByText('Due now')).toBeInTheDocument();+ // The disabled app appears under "Available apps".+ expect(screen.getByText(/Available apps/)).toBeInTheDocument();+ expect(screen.getByText('Zeta')).toBeInTheDocument();+ expect(screen.getByText('1 of 2 apps have the loop enabled.')).toBeInTheDocument();+ });++ it('warns when the global job is disabled', async () => {+ api.getLayeredIntelligenceOverview.mockResolvedValue(overview({ jobEnabled: false }));+ renderPage();++ await waitFor(() => expect(screen.getByText(/global/i)).toBeInTheDocument());+ expect(screen.getByText(/System Tasks/)).toBeInTheDocument();+ });++ it('shows an error banner + retry when the overview fails to load', async () => {+ api.getLayeredIntelligenceOverview.mockRejectedValue(new Error('boom'));+ renderPage();++ await waitFor(() => expect(screen.getByText(/Couldn't load/)).toBeInTheDocument());+ expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();+ });+});diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex 3a6c4f23ce..dd8d8467db 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 });+// Cross-app Layered Intelligence Loop overview for the dedicated status page:+// { jobEnabled, jobExists, enabledCount, apps: [{ id, name, enabled, intervalMs,+// lastRunAt, nextDueAt, due, allowedScopes, sources, ... }] }. Read-only.+export const getLayeredIntelligenceOverview = (options) =>+ request('/apps/layered-intelligence/overview', options);export const createApp = (data) => request('/apps', {method: 'POST',body: JSON.stringify(data)diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 7d9b381503..a23c3a6e64 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -85,6 +85,7 @@ export const NAV_COMMANDS = [{ id: 'nav.feature-agents', path: '/feature-agents', label: 'Feature Agents', section: 'Chief of Staff', aliases: ['feature-agents'] },{ id: 'nav.cos.gsd', path: '/cos/gsd', label: 'GSD', section: 'Chief of Staff', aliases: ['gsd', 'cos-gsd'] },{ id: 'nav.cos.health', path: '/cos/health', label: 'Health', section: 'Chief of Staff', aliases: ['cos-health', 'health'] },+ { id: 'nav.cos.layered-intelligence', path: '/layered-intelligence', label: 'Layered Intelligence', section: 'Chief of Staff', aliases: ['layered-intelligence', 'intelligence-loop', 'self-improvement', 'lil'], keywords: ['layered intelligence', 'self improvement loop', 'per-app improvement', 'proposals', 'autonomous improvement', 'loop status'] },{ id: 'nav.cos.learning', path: '/cos/learning', label: 'Learning', section: 'Chief of Staff', aliases: ['cos-learning'] },{ id: 'nav.cos.memory', path: '/cos/memory', label: 'Memory', section: 'Chief of Staff', aliases: ['cos-memory'] },{ id: 'nav.cos.schedule', path: '/cos/schedule', label: 'Schedule', section: 'Chief of Staff', aliases: ['schedule', 'cos-schedule'] },diff --git a/server/routes/apps.js b/server/routes/apps.jsindex fad5bb6652..d2de61fd06 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -21,6 +21,8 @@ import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIimport { hasDeployScript } from '../services/appDeployer.js';import { checkScripts, installScripts, XCODE_SCRIPT_NAMES } from '../services/xcodeScripts.js';import { SELF_IMPROVEMENT_TASK_TYPES } from '../services/taskSchedule.js';+import { summarizeLoopStatus, LI_JOB_ID } from '../services/layeredIntelligence.js';+import * as autonomousJobs from '../services/autonomousJobs.js';import { certPaths } from '../../lib/certPaths.js';const router = Router();@@ -732,6 +734,37 @@ router.get('/:id/work-tracker', loadApp, asyncHandler(async (req, res) => {res.json({ appId: app.id, appName: app.name, ...info });}));+// GET /api/apps/layered-intelligence/overview - Cross-app Layered Intelligence+// Loop status for the dedicated page. Deterministic read only: each active app's+// effective config + scheduler bookkeeping (lastRunAt/nextDueAt/due) plus the+// global autonomous-job on/off state (a per-app config is inert while the job is+// disabled). NO LLM and NO forge I/O — filed-proposal counts stay off this+// surface deliberately (they'd require per-app `gh`/`glab` shell-outs). This+// two-segment static path can't collide with `/:id` (one segment) or+// `/:id/layered-intelligence` (literal second segment), so ordering is safe.+router.get('/layered-intelligence/overview', asyncHandler(async (req, res) => {+ const [apps, job] = await Promise.all([+ appsService.getActiveApps(),+ autonomousJobs.getJob(LI_JOB_ID).catch(() => null)+ ]);+ const now = Date.now();+ const summaries = apps+ .map(app => summarizeLoopStatus({ app, isPortos: app.id === PORTOS_APP_ID, now }))+ .sort((a, b) => {+ // Enabled apps first, then the PortOS baseline, then alphabetical by name.+ if (a.enabled !== b.enabled) return a.enabled ? -1 : 1;+ if (a.isPortos !== b.isPortos) return a.isPortos ? -1 : 1;+ return a.name.localeCompare(b.name);+ });+ res.json({+ jobId: LI_JOB_ID,+ jobEnabled: !!job?.enabled,+ jobExists: !!job,+ enabledCount: summaries.filter(s => s.enabled).length,+ apps: summaries+ });+}));+// GET /api/apps/:id/layered-intelligence - Effective Layered Intelligence config// for this app (the self-improvement loop). Merges the app's stored partial// config over the shipped defaults so the UI always renders a complete, safediff --git a/server/routes/apps.test.js b/server/routes/apps.test.jsindex 306d982e95..1c8004b9bb 100644--- a/server/routes/apps.test.js+++ b/server/routes/apps.test.js@@ -6,6 +6,7 @@ import appsRoutes from './apps.js';// Mock the servicesvi.mock('../services/apps.js', () => ({getAllApps: vi.fn(),+ getActiveApps: vi.fn(),getAppById: vi.fn(),createApp: vi.fn(),updateApp: vi.fn(),@@ -35,6 +36,12 @@ vi.mock('../services/history.js', () => ({logAction: vi.fn()}));+// Mock the autonomous-jobs barrel so the layered-intelligence overview route can+// read the global job's enabled state without pulling in the whole CoS graph.+vi.mock('../services/autonomousJobs.js', () => ({+ getJob: vi.fn()+}));+vi.mock('../services/streamingDetect.js', () => ({parseEcosystemFromPath: vi.fn(),writeEcosystemPortEdits: vi.fn().mockResolvedValue({ file: 'ecosystem.config.cjs', changed: true, remapApplied: true, applied: [], unapplied: [] }),@@ -85,6 +92,7 @@ import * as pm2Service from '../services/pm2.js';import * as history from '../services/history.js';import * as streamingDetect from '../services/streamingDetect.js';import * as cos from '../services/cos.js';+import * as autonomousJobs from '../services/autonomousJobs.js';import { detectAppIcon, getIconContentType, isUsableSvg } from '../services/appIconDetect.js';import { installScripts } from '../services/xcodeScripts.js';import { writeFileSync, readFileSync, mkdirSync, rmSync } from 'fs';@@ -310,6 +318,42 @@ describe('Apps Routes', () => {expect(response.status).toBe(404);});+ it('GET /layered-intelligence/overview summarizes every active app + global job state', async () => {+ appsService.getActiveApps.mockResolvedValue([+ { id: 'off-app', name: 'Zeta Off', layeredIntelligence: { enabled: false } },+ { id: 'on-app', name: 'Alpha On', layeredIntelligence: { enabled: true, intervalMs: 86400000 } },+ { id: 'portos-default', name: 'PortOS', layeredIntelligence: { enabled: true } }+ ]);+ autonomousJobs.getJob.mockResolvedValue({ id: 'job-layered-intelligence', enabled: true });++ const response = await request(app).get('/api/apps/layered-intelligence/overview');++ expect(response.status).toBe(200);+ expect(response.body.jobEnabled).toBe(true);+ expect(response.body.jobExists).toBe(true);+ expect(response.body.enabledCount).toBe(2);+ // Enabled first, PortOS ahead of other enabled, disabled last.+ expect(response.body.apps.map(a => a.id)).toEqual(['portos-default', 'on-app', 'off-app']);+ const portos = response.body.apps.find(a => a.id === 'portos-default');+ expect(portos.isPortos).toBe(true);+ expect(portos.allowedScopes).toContain('portos-self');+ // Free-text rules never leak into the list payload.+ expect(JSON.stringify(response.body)).not.toContain('"rules"');+ expect(appsService.getActiveApps).toHaveBeenCalled();+ });++ it('GET /layered-intelligence/overview reports jobEnabled:false when the job is missing', async () => {+ appsService.getActiveApps.mockResolvedValue([]);+ autonomousJobs.getJob.mockResolvedValue(null);++ const response = await request(app).get('/api/apps/layered-intelligence/overview');++ expect(response.status).toBe(200);+ expect(response.body.jobEnabled).toBe(false);+ expect(response.body.jobExists).toBe(false);+ expect(response.body.enabledCount).toBe(0);+ });+it('writes changed ports back to the ecosystem config (source of truth)', async () => {// repoPath must exist on disk so the pathExists guard passes.const mockApp = { id: 'app-001', name: 'App', type: 'node', repoPath: process.cwd(), apiPort: 5173, uiPort: 5174 };diff --git a/server/services/autonomousJobs/defaults.js b/server/services/autonomousJobs/defaults.jsindex 0850a0c9d4..bd8e179266 100644--- a/server/services/autonomousJobs/defaults.js+++ b/server/services/autonomousJobs/defaults.js@@ -10,6 +10,7 @@*/import { DAY, WEEK, JOB_STRUCTURAL_FIELDS, JOB_ADDITIVE_FIELDS } from './constants.js'+import { LI_JOB_ID } from '../layeredIntelligence.js'/*** Default job definitions@@ -256,7 +257,7 @@ Phase 4 — Report:updatedAt: null},{- id: 'job-layered-intelligence',+ id: LI_JOB_ID,name: 'Layered Intelligence Loop',description: 'Per-managed-app self-improvement loop. Reads each enabled app\'s goals + telemetry, asks a reasoning model (default: local LLM) for the single most-valuable improvement, and files ONE deduplicated tracker issue (GitHub/GitLab/Jira/PLAN.md) for a coding agent. The model never writes code — every side effect is deterministic. Off by default; enable per app under its config.',category: 'layered-intelligence',diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex 584303765a..8d59ca96fa 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -42,6 +42,12 @@ export const LI_JIRA_BLOCKING_LABEL = 'layered-intelligence-blocking';// so the loop doesn't immediately re-file something the user just resolved.export const CLOSED_SUPPRESSION_MS = 30 * DAY;+// The autonomous-job id that drives the whole loop (the global sweep). Single+// source of truth — the DEFAULT_JOBS catalog entry and the cross-app overview+// route both key on this so per-app enablement and the global on/off stay in+// sync in the UI (a per-app config does nothing while this job is disabled).+export const LI_JOB_ID = 'job-layered-intelligence';+// Every proposal scope the reasoner may return. The handler enforces WHERE each// lands (see PROPOSAL_SCOPE_TARGETS) and gates meta/self scopes to PortOS only.export const PROPOSAL_SCOPES = ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self'];@@ -99,6 +105,48 @@ export function getEffectiveConfig(app) {return merged;}+/**+ * Summarize one app's loop status for the cross-app overview page. Pure and+ * side-effect-free (no LLM, no forge I/O): derives the display shape from the+ * app's stored config + scheduler bookkeeping only. `lastRunAt` rides along on+ * the effective config (a passthrough stored key, absent on a never-run app);+ * `nextDueAt` is `lastRunAt + intervalMs` (null when never run), and `due` is a+ * display flag (only meaningful when enabled) mirroring the sweep's cadence+ * check. `rules` is reduced to a boolean so the free-text guidance never leaks+ * into a list payload.+ */+export function summarizeLoopStatus({ app, isPortos = false, now = Date.now() } = {}) {+ const config = getEffectiveConfig({ ...app, isPortos });+ const sources = config.sources || {};+ const lastRunAt = typeof config.lastRunAt === 'string' ? config.lastRunAt : null;+ const last = lastRunAt ? Date.parse(lastRunAt) : NaN;+ const interval = config.intervalMs || 0;+ const nextDueAt = Number.isFinite(last) ? new Date(last + interval).toISOString() : null;+ const due = !Number.isFinite(last) || (now - last) >= interval;+ return {+ id: app.id,+ name: app.name || app.id,+ isPortos,+ enabled: !!config.enabled,+ intervalMs: config.intervalMs,+ providerId: config.providerId || null,+ model: config.model || null,+ hasRules: !!(typeof config.rules === 'string' && config.rules.trim()),+ lastRunAt,+ nextDueAt,+ due: !!config.enabled && due,+ allowedScopes: Array.isArray(config.allowedScopes) ? config.allowedScopes : [],+ sources: {+ goals: !!sources.goals,+ cosMetrics: !!sources.cosMetrics,+ healthReport: !!sources.healthReport,+ planMd: !!sources.planMd,+ openIssues: !!sources.openIssues,+ customCount: Array.isArray(sources.custom) ? sources.custom.length : 0+ }+ };+}+/*** Whether a proposal scope is allowed for this app. A hallucinated or* hand-edited scope cannot escape this gate: it must be a recognized scope, bediff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex 7c56f17b86..b4bcaa68d1 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -39,7 +39,9 @@ import {CLOSED_SUPPRESSION_MS,LI_LABEL,LI_BLOCKING_LABEL,- LI_JIRA_BLOCKING_LABEL+ LI_JIRA_BLOCKING_LABEL,+ LI_JOB_ID,+ summarizeLoopStatus} from './layeredIntelligence.js';describe('defaultLayeredIntelligenceConfig', () => {@@ -94,6 +96,72 @@ describe('getEffectiveConfig', () => {});});+describe('summarizeLoopStatus (overview page shape)', () => {+ const DAY = 24 * 60 * 60 * 1000;+ const NOW = Date.parse('2026-07-07T12:00:00Z');++ it('summarizes a never-run enabled app as due with no lastRun/nextDue', () => {+ const s = summarizeLoopStatus({+ app: { id: 'a1', name: 'App One', layeredIntelligence: { enabled: true, intervalMs: DAY } },+ now: NOW+ });+ expect(s).toMatchObject({ id: 'a1', name: 'App One', enabled: true, due: true, lastRunAt: null, nextDueAt: null });+ expect(s.sources).toMatchObject({ goals: true, customCount: 0 });+ expect(s.hasRules).toBe(false);+ });++ it('computes nextDueAt = lastRunAt + intervalMs and due=false before the interval elapses', () => {+ const lastRunAt = new Date(NOW - DAY / 2).toISOString();+ const s = summarizeLoopStatus({+ app: { id: 'a2', name: 'App Two', layeredIntelligence: { enabled: true, intervalMs: DAY, lastRunAt } },+ now: NOW+ });+ expect(s.lastRunAt).toBe(lastRunAt);+ expect(s.nextDueAt).toBe(new Date(Date.parse(lastRunAt) + DAY).toISOString());+ expect(s.due).toBe(false);+ });++ it('due is always false when the app is disabled, even past the interval', () => {+ const lastRunAt = new Date(NOW - 2 * DAY).toISOString();+ const s = summarizeLoopStatus({+ app: { id: 'a3', name: 'Off', layeredIntelligence: { enabled: false, intervalMs: DAY, lastRunAt } },+ now: NOW+ });+ expect(s.enabled).toBe(false);+ expect(s.due).toBe(false);+ });++ it('reduces rules to a boolean and never leaks the free text', () => {+ const s = summarizeLoopStatus({+ app: { id: 'a4', name: 'Ruled', layeredIntelligence: { enabled: true, rules: 'never add deps' } },+ now: NOW+ });+ expect(s.hasRules).toBe(true);+ expect(JSON.stringify(s)).not.toContain('never add deps');+ });++ it('surfaces PortOS scopes + custom source count', () => {+ const s = summarizeLoopStatus({+ app: { id: 'portos-default', name: 'PortOS', layeredIntelligence: { enabled: true, sources: { custom: [{ type: 'file', ref: 'x.md' }] } } },+ isPortos: true,+ now: NOW+ });+ expect(s.isPortos).toBe(true);+ expect(s.allowedScopes).toContain('portos-self');+ expect(s.sources.customCount).toBe(1);+ });++ it('falls back to the app id when name is missing', () => {+ expect(summarizeLoopStatus({ app: { id: 'no-name' }, now: NOW }).name).toBe('no-name');+ });+});++describe('LI_JOB_ID', () => {+ it('is the autonomous-job id the loop sweep runs under', () => {+ expect(LI_JOB_ID).toBe('job-layered-intelligence');+ });+});+describe('isScopeAllowed (scope-gating)', () => {const allowedPortos = ['app-improvement', 'app-data-gap', 'loop-meta', 'portos-self'];const allowedApp = ['app-improvement', 'app-data-gap'];