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(apps): per-app Layered Intelligence config UI + effective-config endpoint (#2262)
Adam Eivye5608a3be321
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0a220717d6..9b55dd8d08 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -159,3 +159,5 @@- **[issue-2264] Image Cleaner GPU FLUX diffusion round-trip + resolution-aware options + save-to-gallery.** Completes the composable Image Cleaner (predecessor #1763): the `/devtools/image-clean` page can now run the higher-reliability GPU FLUX img2img round-trip, not just the CPU light pass. The GPU render is GPU-serialized through `mediaJobQueue` (two concurrent FLUX renders OOM the box), so for `?diffusion=gpu` the route stages the already-sync-cleaned bytes to a non-gallery temp dir, enqueues a job through the SAME regen seam the lightbox `/regenerate` flow uses (`resolveRegenBackend` / `buildRegenParams` / `clampRegenDimensions` / `enqueueJob`), and returns HTTP 202 + a `jobId`; the client tracks progress via the existing media-job channel (`useMediaJobProgress`), then GETs the finished bytes from a result endpoint. A non-gallery render seam was factored out of `generateImage` (`resolveOutputPlacement` + an `outputTarget` param): the cleaner renders to `data/image-clean-tmp/` with **no sidecar** and the gallery `completed` index/federate hooks suppressed, so a clean pass never pollutes the gallery by default — the lightbox gallery-write + lineage/variant behavior is untouched. The finished result is ephemeral; an explicit "Save to gallery" action promotes it via `saveUploadedGalleryImage`. Resolution-aware diffusion options land in the page: a GPU/CPU sub-mode selector auto-picked by hardware (`getRegenAvailability()`), a strength slider bounded by the server's `strengthMin`/`strengthMax`, an optional max-render-MP override, a render-budget warning when the source exceeds the FLUX attention budget, and a resolution-squeeze note. The ignore-zone preserve-region mask (#1763) applies to the GPU sub-mode too — the original (oriented) pixels are composited back over the diffused frame after the render. A short-grace age-gated GC (`imageCleanTmpGc.js`) sweeps the temp working files. (`server/routes/imageClean.js`, `server/services/imageGen/cleanGpu.js`, `server/services/imageGen/local.js`, `server/services/imageGen/regen.js`, `server/services/imageCleanTmpGc.js`, `server/lib/fileUtils.js`, `client/src/pages/ImageClean.jsx`, `client/src/services/apiMedia.js`)- **[issue-2262] Layered Intelligence Loop — deterministic backbone (server slice).** A perpetual, per-managed-app self-improvement loop that runs as an Engine-B autonomous script job (`job-layered-intelligence`, off by default). On its schedule the handler sweeps `getActiveApps()` and, for each app whose `layeredIntelligence.enabled === true` and whose per-app interval has elapsed, runs four layers: GATHER (reads enabled sources — GOALS.md, CoS `learning.json` metrics, HEALTH_REPORT.md, PLAN.md, open tracker issues, plus app-declared `file` custom sources), REASON (`callProviderAISimple` against the active/overridden provider with a JSON-only prompt), DECIDE (deterministic scope-gate + slug/label dedup against live tracker state), and ACT (files exactly ONE issue via the app's resolved work tracker, and optionally pauses the app on a blocking issue). The reasoning model never touches code — it returns structured JSON and every side effect is deterministic handler code, so the "model must not make direct code changes" contract holds by construction. Dedup and pause are fully tracker-derived (a `<!-- lil-slug: … -->` marker + `layered-intelligence` / `layered-intelligence:blocking` labels; closed-issue suppression pinned at 30 days) — the only local state is per-app `lastRunAt` bookkeeping. Meta/self proposal scopes (`loop-meta` / `portos-self`) are double-enforced to PortOS-only so a hallucinated or hand-edited scope can't file against the loop from someone else's app. GitHub (`gh`) and GitLab (`glab`) forge filing + `plan`-tracker PLAN.md append are implemented; ships via the `DEFAULT_JOBS` catalog (merged into existing installs on boot by `applyAdditiveFields`) and the per-app config accessor's default (all sources on; PortOS gets the meta/self scopes) — so no seed file or migration is needed. Off by default; only runs as a user-enabled scheduled automation (no cold-bootstrap LLM calls). (`server/services/layeredIntelligence.js`, `server/services/autonomousJobs/layeredIntelligenceHandler.js`, `server/services/autonomousJobs/scriptHandlers.js`, `server/services/autonomousJobs/defaults.js`, `server/services/apps.js`, `server/lib/validation.js`)++- **[issue-2262] Layered Intelligence Loop — per-app config UI (client slice).** The Edit App drawer gains an "Intelligence" tab that configures the self-improvement loop per managed app: enable/disable, a run-interval preset select (hourly → weekly, with a "Custom" readout for a hand-set cadence), an optional provider/model override (defaults to the active CoS provider), the Layer-1 telemetry source toggles (goals, CoS metrics, health report, PLAN.md, open issues), an add/remove list of repo-relative custom `file` sources, a free-text guidance-rules box, and the allowed-proposal-scope checkboxes — with the `loop-meta` / `portos-self` scopes shown only on the PortOS baseline app (mirroring the server's PORTOS-only gate). The tab reads the effective config from a new read-only `GET /api/apps/:id/layered-intelligence` endpoint (stored partial merged over the shipped defaults + `isPortos` flag) and, on save, PATCHes only the fields that changed against that baseline via a `buildLayeredIntelligenceUpdate` diff — so an unchanged config stays absent and the server's merge-over-stored contract keeps the install forward-compatible with future default changes (persisting the full effective config would freeze it). No migration or seed file is needed: the job ships via the `DEFAULT_JOBS` boot-merge and the per-app config comes from the accessor default (per the design doc in `docs/plans/2026-07-07-layered-intelligence-loop.md`). (`client/src/components/apps/LayeredIntelligenceTab.jsx`, `client/src/components/apps/EditAppDrawer.jsx`, `client/src/services/apiApps.js`, `server/routes/apps.js`)diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsxindex 2ba3083589..80d6869b3f 100644--- a/client/src/components/apps/EditAppDrawer.jsx+++ b/client/src/components/apps/EditAppDrawer.jsx@@ -9,6 +9,7 @@ import Drawer from '../Drawer';import Banner from '../ui/Banner';import useDrawerTab from '../../hooks/useDrawerTab';import { copyToClipboard } from '../../lib/clipboard';+import LayeredIntelligenceTab, { buildLayeredIntelligenceUpdate } from './LayeredIntelligenceTab';const WORK_TRACKER_OPTIONS = [{ value: 'auto', label: 'Auto (detect from git origin)' },@@ -27,6 +28,7 @@ const TABS = [{ id: 'ports', label: 'Ports & TLS' },{ id: 'commands', label: 'Commands' },{ id: 'workflow', label: 'Workflow' },+ { id: 'intelligence', label: 'Intelligence' },{ id: 'jira', label: 'JIRA' },{ id: 'datadog', label: 'DataDog' }];@@ -77,6 +79,17 @@ export default function EditAppDrawer({ app, onClose, onSave }) {});const [saving, setSaving] = useState(false);const [error, setError] = useState(null);+ // Layered Intelligence (self-improvement loop) config lives in its own slice —+ // it's saved through a dedicated server merge helper (updateAppLayeredIntelligence)+ // that patches over the STORED config, not the effective one, so we diff the+ // edited config against the loaded effective baseline and PATCH only what changed+ // (see buildLayeredIntelligenceUpdate). `liBaseline` is the effective config the+ // drawer loaded; `liConfig` is the working copy the tab edits.+ const [liConfig, setLiConfig] = useState(null);+ const [liBaseline, setLiBaseline] = useState(null);+ const [liProviders, setLiProviders] = useState([]);+ const [liIsPortos, setLiIsPortos] = useState(app.id === PORTOS_APP_ID);+ const [liLoaded, setLiLoaded] = useState(false);const [tlsUpgrading, setTlsUpgrading] = useState(false);const [tlsResult, setTlsResult] = useState(null);const [tlsError, setTlsError] = useState(null);@@ -140,6 +153,28 @@ export default function EditAppDrawer({ app, onClose, onSave }) {.catch(() => setWorkTrackerInfo(null));}, [app.id]);+ // Load the app's effective Layered Intelligence config + the CLI provider list+ // (the loop runs an agentic CLI, same as other CoS work). The tab edits a+ // working copy; on save we diff it against the baseline.+ useEffect(() => {+ let cancelled = false;+ Promise.all([+ api.getAppLayeredIntelligence(app.id),+ api.getProviders({ silent: true }).catch(() => ({ providers: [] }))+ ]).then(([li, provData]) => {+ if (cancelled) return;+ const cfg = li?.config || null;+ setLiConfig(cfg);+ setLiBaseline(cfg);+ setLiIsPortos(!!li?.isPortos);+ setLiProviders((provData?.providers || []).filter(p => p.type === 'cli' && p.enabled !== false));+ setLiLoaded(true);+ }).catch(() => { if (!cancelled) setLiLoaded(true); });+ return () => { cancelled = true; };+ }, [app.id]);++ const updateLiConfig = (patch) => setLiConfig(prev => ({ ...(prev || {}), ...patch }));+useEffect(() => {if (!formData.jiraInstanceId) {setJiraProjects([]);@@ -320,6 +355,13 @@ export default function EditAppDrawer({ app, onClose, onSave }) {} : { enabled: false }};+ // Only send layeredIntelligence when the user actually changed something —+ // the server merges the PATCH over the STORED config, so an unchanged config+ // must stay absent (persisting the full effective config would freeze this+ // install against future default changes).+ const liUpdate = buildLayeredIntelligenceUpdate(liBaseline, liConfig);+ if (liUpdate) data.layeredIntelligence = liUpdate;+await api.updateApp(app.id, data).catch(err => {setError(err.message);setSaving(false);@@ -603,6 +645,16 @@ export default function EditAppDrawer({ app, onClose, onSave }) {</div>)}+ {activeTab === 'intelligence' && (+ <LayeredIntelligenceTab+ li={liConfig || {}}+ onChange={updateLiConfig}+ providers={liProviders}+ isPortos={liIsPortos}+ loaded={liLoaded && !!liConfig}+ />+ )}+{activeTab === 'jira' && (<div className="space-y-3"><label className="flex items-center gap-2 cursor-pointer">diff --git a/client/src/components/apps/EditAppDrawer.test.jsx b/client/src/components/apps/EditAppDrawer.test.jsxindex 49912602dd..a8e7b85baa 100644--- a/client/src/components/apps/EditAppDrawer.test.jsx+++ b/client/src/components/apps/EditAppDrawer.test.jsx@@ -9,6 +9,8 @@ vi.mock('../../services/api', () => ({getDatadogInstances: vi.fn(),getJiraProjects: vi.fn(),getAppWorkTracker: vi.fn(),+ getAppLayeredIntelligence: vi.fn(),+ getProviders: vi.fn(),updateApp: vi.fn(),upgradeAppTls: vi.fn(),}));@@ -50,6 +52,20 @@ beforeEach(() => {forge: 'gh',source: 'origin',});+ api.getAppLayeredIntelligence.mockResolvedValue({+ appId: 'app-1',+ isPortos: false,+ config: {+ enabled: false,+ intervalMs: 86400000,+ providerId: null,+ model: null,+ rules: '',+ sources: { goals: true, cosMetrics: true, healthReport: true, planMd: true, openIssues: true, custom: [] },+ allowedScopes: ['app-improvement', 'app-data-gap'],+ },+ });+ api.getProviders.mockResolvedValue({ providers: [] });api.updateApp.mockResolvedValue({});});diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsxnew file mode 100644index 0000000000..ee6beb4100--- /dev/null+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx@@ -0,0 +1,276 @@+import { Plus, Trash2, Brain } from 'lucide-react';+import Banner from '../ui/Banner';+import ProviderModelSelector from '../ProviderModelSelector';+import { filterSelectableModels } from '../../utils/providers';++// The self-improvement loop's per-app config surface. Field set mirrors the+// server schema (server/lib/validation.js `layeredIntelligenceConfigSchema`)+// and the effective-config accessor (server/services/layeredIntelligence.js).+// Off by default — the loop is a user-enabled scheduled automation.++// The Layer-1 telemetry toggles the loop can gather. Keep in sync with the+// server `sources` object (custom[] file sources are handled separately below).+export const LI_SOURCE_FIELDS = [+ { key: 'goals', label: 'Goals (GOALS.md)', hint: 'The app\'s inferred/authored product goals' },+ { key: 'cosMetrics', label: 'CoS metrics', hint: 'Recent autonomous-agent run stats for this app' },+ { key: 'healthReport', label: 'Health report', hint: 'Latest health / lint / test summary' },+ { key: 'planMd', label: 'PLAN.md', hint: 'The app\'s open work-plan items' },+ { key: 'openIssues', label: 'Open issues', hint: 'Currently open tracker issues' }+];++// The proposal scopes the loop may file. loop-meta / portos-self extend the loop+// itself (which lives in the PortOS repo), so they only apply to the PortOS+// baseline app — mirrors PORTOS_ONLY_SCOPES on the server.+export const LI_SCOPES = [+ { id: 'app-improvement', label: 'App improvement', portosOnly: false, hint: 'Propose feature/quality improvements to this app' },+ { id: 'app-data-gap', label: 'App data gap', portosOnly: false, hint: 'Propose new telemetry/data the loop should gather' },+ { id: 'loop-meta', label: 'Loop meta', portosOnly: true, hint: 'Improve the intelligence loop itself (PortOS only)' },+ { id: 'portos-self', label: 'PortOS self', portosOnly: true, hint: 'Improve PortOS itself (PortOS only)' }+];++const INPUT_CLASS = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden';++// Common cadences for the interval select. Values are milliseconds; the schema+// floor is 60_000 (1 minute). A stored non-preset value renders as "Custom".+export const LI_INTERVAL_PRESETS = [+ { ms: 60 * 60 * 1000, label: 'Hourly' },+ { ms: 6 * 60 * 60 * 1000, label: 'Every 6 hours' },+ { ms: 12 * 60 * 60 * 1000, label: 'Every 12 hours' },+ { ms: 24 * 60 * 60 * 1000, label: 'Daily' },+ { ms: 7 * 24 * 60 * 60 * 1000, label: 'Weekly' }+];++// 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;+ const sb = new Set(b);+ return a.every(s => sb.has(s));+}++function sameCustom(a, b) {+ const A = Array.isArray(a) ? a : [];+ const B = Array.isArray(b) ? b : [];+ if (A.length !== B.length) return false;+ return A.every((s, i) => s?.type === B[i]?.type && s?.ref === B[i]?.ref);+}++/**+ * Build the minimal Layered Intelligence PATCH: only the top-level keys whose+ * value differs from the effective baseline the drawer loaded. Sending the full+ * effective config would persist every default to disk and freeze this install+ * against future default changes — the server's merge-over-stored contract+ * (updateAppLayeredIntelligence) depends on untouched fields staying absent.+ * Returns null when nothing changed (caller then omits `layeredIntelligence`).+ * providerId/model normalize '' → null (the "use default" sentinel).+ */+export function buildLayeredIntelligenceUpdate(baseline, current) {+ if (!baseline || !current) return null;+ const update = {};+ if (!!current.enabled !== !!baseline.enabled) update.enabled = !!current.enabled;+ if (current.intervalMs !== baseline.intervalMs) update.intervalMs = current.intervalMs;+ const curProvider = current.providerId || null;+ if (curProvider !== (baseline.providerId || null)) update.providerId = curProvider;+ const curModel = current.model || null;+ if (curModel !== (baseline.model || null)) update.model = curModel;+ if ((current.rules || '') !== (baseline.rules || '')) update.rules = current.rules || '';++ const curSources = current.sources || {};+ const baseSources = baseline.sources || {};+ const toggleChanged = LI_SOURCE_FIELDS.some(f => !!curSources[f.key] !== !!baseSources[f.key]);+ const customChanged = !sameCustom(curSources.custom, baseSources.custom);+ if (toggleChanged || customChanged) {+ update.sources = {+ ...Object.fromEntries(LI_SOURCE_FIELDS.map(f => [f.key, !!curSources[f.key]])),+ custom: (Array.isArray(curSources.custom) ? curSources.custom : [])+ .map(s => ({ type: 'file', ref: String(s?.ref || '').trim() }))+ .filter(s => s.ref)+ };+ }++ if (!sameScopes(current.allowedScopes, baseline.allowedScopes)) {+ update.allowedScopes = Array.isArray(current.allowedScopes) ? current.allowedScopes : [];+ }++ return Object.keys(update).length > 0 ? update : null;+}++/**+ * Presentational Layered Intelligence config tab. All mutable state lives in the+ * parent EditAppDrawer's `formData` (the Drawer body remounts per tab), so this+ * component is fully controlled: it reads the `li` slice and calls `onChange`+ * 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 }) {+ if (!loaded) {+ return <div className="text-sm text-gray-500">Loading Layered Intelligence config…</div>;+ }++ const sources = li.sources || {};+ const custom = Array.isArray(sources.custom) ? sources.custom : [];+ const allowedScopes = Array.isArray(li.allowedScopes) ? li.allowedScopes : [];+ const isPreset = LI_INTERVAL_PRESETS.some(p => p.ms === li.intervalMs);++ const setSources = (patch) => onChange({ sources: { ...sources, ...patch } });+ const setCustom = (next) => setSources({ custom: next });++ const currentProvider = providers.find(p => p.id === li.providerId);+ const availableModels = currentProvider+ ? filterSelectableModels(currentProvider.models || [currentProvider.defaultModel])+ : [];++ const toggleScope = (id, on) => {+ const next = on ? [...new Set([...allowedScopes, id])] : allowedScopes.filter(s => s !== id);+ onChange({ allowedScopes: next });+ };++ const visibleScopes = LI_SCOPES.filter(s => !s.portosOnly || isPortos);++ 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's telemetry and files improvement proposals via CoS. Off by default — it runs on the schedule below only when enabled.+ </p>+ </div>++ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={!!li.enabled}+ onChange={e => onChange({ enabled: e.target.checked })}+ className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ <span className="text-sm text-white">Enable the self-improvement loop for this app</span>+ </label>++ <div>+ <label htmlFor="li-interval" className="block text-sm text-gray-400 mb-1">Run interval</label>+ <select+ id="li-interval"+ value={isPreset ? String(li.intervalMs) : 'custom'}+ onChange={e => {+ if (e.target.value === 'custom') return;+ onChange({ intervalMs: Number(e.target.value) });+ }}+ className={INPUT_CLASS}+ >+ {LI_INTERVAL_PRESETS.map(p => (+ <option key={p.ms} value={String(p.ms)}>{p.label}</option>+ ))}+ {!isPreset && <option value="custom">Custom ({Math.round(li.intervalMs / 60000)} min)</option>}+ </select>+ </div>++ <div>+ <span className="block text-sm text-gray-400 mb-1">AI provider</span>+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={li.providerId || ''}+ selectedModel={li.model || ''}+ availableModels={availableModels}+ onProviderChange={id => onChange({ providerId: id || null, model: '' })}+ onModelChange={model => onChange({ model: model || null })}+ label="Provider"+ emptyProviderOption="Use default provider"+ emptyModelOption="Default model"+ alwaysShowModel+ />+ <p className="text-xs text-gray-500 mt-1">Leave on "Use default provider" to run the loop with the active CoS provider.</p>+ </div>++ <div>+ <span className="block text-sm text-gray-400 mb-2">Telemetry sources</span>+ <div className="space-y-2">+ {LI_SOURCE_FIELDS.map(f => (+ <label key={f.key} className="flex items-start gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={!!sources[f.key]}+ onChange={e => setSources({ [f.key]: e.target.checked })}+ className="mt-1 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ <span className="text-sm text-white">{f.label}<span className="block text-xs text-gray-500">{f.hint}</span></span>+ </label>+ ))}+ </div>+ </div>++ <div>+ <div className="flex items-center justify-between mb-2">+ <span className="text-sm text-gray-400">Custom file sources</span>+ <button+ type="button"+ onClick={() => setCustom([...custom, { type: 'file', ref: '' }])}+ 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"+ >+ <Plus size={12} /> Add file+ </button>+ </div>+ {custom.length === 0 ? (+ <p className="text-xs text-gray-500">No custom sources. Add a repo-relative file (e.g. <code className="text-gray-400">docs/metrics.md</code>) to feed it into the loop's prompt.</p>+ ) : (+ <div className="space-y-2">+ {custom.map((src, i) => (+ <div key={i} className="flex items-center gap-2">+ <input+ type="text"+ value={src.ref || ''}+ onChange={e => setCustom(custom.map((s, j) => j === i ? { ...s, ref: e.target.value } : s))}+ className={INPUT_CLASS}+ placeholder="repo-relative path, e.g. docs/metrics.md"+ aria-label={`Custom file source ${i + 1}`}+ />+ <button+ type="button"+ onClick={() => setCustom(custom.filter((_, j) => j !== i))}+ className="p-2 text-gray-500 hover:text-port-error shrink-0"+ aria-label={`Remove custom source ${i + 1}`}+ >+ <Trash2 size={14} />+ </button>+ </div>+ ))}+ <p className="text-xs text-gray-500">Paths must be repo-relative — no leading <code>/</code> and no <code>..</code> segments.</p>+ </div>+ )}+ </div>++ <div>+ <label htmlFor="li-rules" className="block text-sm text-gray-400 mb-1">Guidance rules</label>+ <textarea+ id="li-rules"+ value={li.rules || ''}+ onChange={e => onChange({ rules: e.target.value })}+ className={`${INPUT_CLASS} font-mono text-sm`}+ rows={4}+ placeholder="Free-text guidance for the loop (e.g. 'Prioritize accessibility fixes; never propose new dependencies.')"+ maxLength={8000}+ />+ </div>++ <div>+ <span className="block text-sm text-gray-400 mb-2">Allowed proposal scopes</span>+ <div className="space-y-2">+ {visibleScopes.map(s => (+ <label key={s.id} className="flex items-start gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={allowedScopes.includes(s.id)}+ onChange={e => toggleScope(s.id, e.target.checked)}+ className="mt-1 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"+ />+ <span className="text-sm text-white">{s.label}<span className="block text-xs text-gray-500">{s.hint}</span></span>+ </label>+ ))}+ </div>+ {!isPortos && (+ <Banner tone="info" size="sm" className="mt-2">+ Loop-meta and PortOS-self scopes are only available on the PortOS baseline app.+ </Banner>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/apps/LayeredIntelligenceTab.test.jsx b/client/src/components/apps/LayeredIntelligenceTab.test.jsxnew file mode 100644index 0000000000..1e7d67c4b2--- /dev/null+++ b/client/src/components/apps/LayeredIntelligenceTab.test.jsx@@ -0,0 +1,101 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import LayeredIntelligenceTab, { buildLayeredIntelligenceUpdate } from './LayeredIntelligenceTab';++const baseline = {+ enabled: false,+ intervalMs: 86400000,+ providerId: null,+ model: null,+ rules: '',+ sources: { goals: true, cosMetrics: true, healthReport: true, planMd: true, openIssues: true, custom: [] },+ allowedScopes: ['app-improvement', 'app-data-gap']+};++describe('buildLayeredIntelligenceUpdate', () => {+ it('returns null when nothing changed (avoids persisting the effective config to disk)', () => {+ expect(buildLayeredIntelligenceUpdate(baseline, { ...baseline })).toBeNull();+ });++ it('returns null on missing baseline or current', () => {+ expect(buildLayeredIntelligenceUpdate(null, baseline)).toBeNull();+ expect(buildLayeredIntelligenceUpdate(baseline, null)).toBeNull();+ });++ it('emits only the changed enabled flag', () => {+ const update = buildLayeredIntelligenceUpdate(baseline, { ...baseline, enabled: true });+ expect(update).toEqual({ enabled: true });+ });++ it('emits intervalMs when it changes', () => {+ const update = buildLayeredIntelligenceUpdate(baseline, { ...baseline, intervalMs: 3600000 });+ expect(update).toEqual({ intervalMs: 3600000 });+ });++ it('normalizes empty provider/model to null and only emits when changed', () => {+ // '' provider equals the null baseline → no change+ expect(buildLayeredIntelligenceUpdate(baseline, { ...baseline, providerId: '', model: '' })).toBeNull();+ const update = buildLayeredIntelligenceUpdate(baseline, { ...baseline, providerId: 'claude-code', model: 'sonnet' });+ expect(update).toEqual({ providerId: 'claude-code', model: 'sonnet' });+ });++ it('emits the full source object (toggles + sanitized custom) when a toggle flips', () => {+ const update = buildLayeredIntelligenceUpdate(baseline, {+ ...baseline,+ sources: { ...baseline.sources, goals: false }+ });+ expect(update.sources.goals).toBe(false);+ expect(update.sources.cosMetrics).toBe(true);+ expect(update.sources.custom).toEqual([]);+ });++ it('sanitizes custom sources — trims refs and drops blanks', () => {+ const update = buildLayeredIntelligenceUpdate(baseline, {+ ...baseline,+ sources: { ...baseline.sources, custom: [{ type: 'file', ref: ' docs/x.md ' }, { type: 'file', ref: '' }] }+ });+ expect(update.sources.custom).toEqual([{ type: 'file', ref: 'docs/x.md' }]);+ });++ it('detects allowedScopes changes regardless of order', () => {+ // reordered = no change+ expect(buildLayeredIntelligenceUpdate(baseline, { ...baseline, allowedScopes: ['app-data-gap', 'app-improvement'] })).toBeNull();+ const update = buildLayeredIntelligenceUpdate(baseline, { ...baseline, allowedScopes: ['app-improvement'] });+ expect(update).toEqual({ allowedScopes: ['app-improvement'] });+ });++ it('emits rules changes including an intentional clear', () => {+ const withRules = { ...baseline, rules: 'be careful' };+ const update = buildLayeredIntelligenceUpdate(withRules, { ...withRules, rules: '' });+ expect(update).toEqual({ rules: '' });+ });+});++describe('LayeredIntelligenceTab (render)', () => {+ const props = { li: baseline, onChange: () => {}, providers: [], loaded: true };++ it('shows a loading state until loaded', () => {+ render(<LayeredIntelligenceTab {...props} loaded={false} />);+ expect(screen.getByText(/Loading Layered Intelligence config/i)).toBeInTheDocument();+ });++ it('hides PortOS-only scopes for a regular app', () => {+ render(<LayeredIntelligenceTab {...props} isPortos={false} />);+ expect(screen.getByText('App improvement')).toBeInTheDocument();+ expect(screen.queryByText('Loop meta')).not.toBeInTheDocument();+ expect(screen.getByText(/only available on the PortOS baseline/i)).toBeInTheDocument();+ });++ it('shows PortOS-only scopes for the PortOS baseline app', () => {+ render(<LayeredIntelligenceTab {...props} isPortos={true} />);+ expect(screen.getByText('Loop meta')).toBeInTheDocument();+ expect(screen.getByText('PortOS self')).toBeInTheDocument();+ });++ it('calls onChange when a source toggle flips', () => {+ const onChange = vi.fn();+ render(<LayeredIntelligenceTab {...props} onChange={onChange} isPortos={false} />);+ fireEvent.click(screen.getByLabelText(/Enable the self-improvement loop/i));+ expect(onChange).toHaveBeenCalledWith({ enabled: true });+ });+});diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.jsindex 874c9f2276..3a6c4f23ce 100644--- a/client/src/services/apiApps.js+++ b/client/src/services/apiApps.js@@ -9,6 +9,12 @@ export const getApp = (id) => request(`/apps/${id}`);// caller (EditAppDrawer) owns its own .catch fallback, so default to silent.export const getAppWorkTracker = (id, options) =>request(`/apps/${id}/work-tracker`, { silent: true, ...options });+// Effective Layered Intelligence config (self-improvement loop) for an app —+// stored partial merged over the shipped defaults. Read-only; saved through+// updateApp (the `layeredIntelligence` key routes to the merge helper server-+// side). Caller owns its own .catch fallback, so default to silent.+export const getAppLayeredIntelligence = (id, options) =>+ request(`/apps/${id}/layered-intelligence`, { silent: true, ...options });export const createApp = (data) => request('/apps', {method: 'POST',body: JSON.stringify(data)diff --git a/server/routes/apps.js b/server/routes/apps.jsindex 452bcece15..fad5bb6652 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -732,6 +732,18 @@ router.get('/:id/work-tracker', loadApp, asyncHandler(async (req, res) => {res.json({ appId: app.id, appName: app.name, ...info });}));+// 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, safe+// config — including the isPortos-derived scope set. Read-only; the value is+// saved through PUT /api/apps/:id (layeredIntelligence goes via the dedicated+// merge helper there). See server/services/layeredIntelligence.js.+router.get('/:id/layered-intelligence', loadApp, asyncHandler(async (req, res) => {+ const app = req.loadedApp;+ const config = await appsService.getAppLayeredIntelligenceConfig(app.id);+ res.json({ appId: app.id, appName: app.name, isPortos: app.id === PORTOS_APP_ID, config });+}));+// 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.test.js b/server/routes/apps.test.jsindex 3f582ea22f..306d982e95 100644--- a/server/routes/apps.test.js+++ b/server/routes/apps.test.js@@ -13,6 +13,7 @@ vi.mock('../services/apps.js', () => ({archiveApp: vi.fn(),updateAppTaskTypeOverride: vi.fn(),getAppTaskTypeOverrides: vi.fn(),+ getAppLayeredIntelligenceConfig: vi.fn(),updateAppLayeredIntelligence: vi.fn(),toggleAllAppTaskTypes: vi.fn(),notifyAppsChanged: vi.fn(),@@ -278,6 +279,37 @@ describe('Apps Routes', () => {expect(response.body.layeredIntelligence.enabled).toBe(true);});+ it('GET /:id/layered-intelligence returns the effective config + isPortos flag', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'App' });+ appsService.getAppLayeredIntelligenceConfig.mockResolvedValue({+ enabled: false, intervalMs: 86400000, sources: { goals: true }, allowedScopes: ['app-improvement']+ });++ const response = await request(app).get('/api/apps/app-001/layered-intelligence');++ expect(response.status).toBe(200);+ expect(response.body.appId).toBe('app-001');+ expect(response.body.isPortos).toBe(false);+ expect(response.body.config.allowedScopes).toEqual(['app-improvement']);+ expect(appsService.getAppLayeredIntelligenceConfig).toHaveBeenCalledWith('app-001');+ });++ it('GET /:id/layered-intelligence flags the PortOS baseline app', async () => {+ appsService.getAppById.mockResolvedValue({ id: 'portos-default', name: 'PortOS' });+ appsService.getAppLayeredIntelligenceConfig.mockResolvedValue({ enabled: false, allowedScopes: ['app-improvement', 'loop-meta'] });++ const response = await request(app).get('/api/apps/portos-default/layered-intelligence');++ expect(response.status).toBe(200);+ expect(response.body.isPortos).toBe(true);+ });++ it('GET /:id/layered-intelligence returns 404 for an unknown app', async () => {+ appsService.getAppById.mockResolvedValue(null);+ const response = await request(app).get('/api/apps/app-999/layered-intelligence');+ expect(response.status).toBe(404);+ });+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 };