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(layered-intelligence): evaluate managed apps against their own metrics
Adam Eivyaa22d2e82955
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 72b5a7fa59..89ceedd96f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,8 @@## Features+- **Layered Intelligence now evaluates a managed app against its OWN goals and performance — not PortOS's agent telemetry.** Running the loop on a managed app previously fed it the PortOS install's global autonomous-agent run stats (`data/cos/learning.json`) as the "CoS metrics" source — which is on by default for every app — so a managed-app run reasoned over PortOS's tooling performance instead of the app's own product performance. Two changes fix this: (1) a new **App metrics (METRICS.md)** telemetry source, on by default for every app, reads a repo-root `METRICS.md` from the app (same as `GOALS.md`/`PLAN.md`) — the place an app documents how it measures success (user-success KPIs, production telemetry, where its data lives, and read-only queries an agent can run); and (2) the **CoS metrics** source now defaults **on only for the PortOS install** (where the agent stats genuinely are its own-performance metric) and **off for managed apps** (where they're a tooling/interaction signal, still opt-in). The reasoning prompt is reframed around "how is THIS app performing against its own goals and purpose," and when a managed app exposes no own-performance metrics the loop is nudged to propose adding a `METRICS.md` as an `app-data-gap`. New standard documented in [`docs/METRICS.md`](../docs/METRICS.md); apps can also wire a custom `cmd`/`http` source to feed live numbers into each run. Back-compat: these are default changes only — any explicitly-stored source toggle is preserved, so no migration is needed.+- **Code Review Defaults can now gate merges on arbitrary GitHub reviewer usernames (e.g. `@CodeReviewbot`).** The Review Loop was limited to a fixed set of reviewer kinds (Copilot, the Claude/Antigravity/Codex CLIs, and the local LM Studio/Ollama backends); there was no way to require a specific GitHub bot or teammate as a PR reviewer. The reviewer picker (AI Providers → Code Review Defaults, plus per-task in the task form and per-task-type in the Schedule config) grows a **"GitHub reviewers (gate merge)"** row where you type any GitHub username or `org/team` slug. Those usernames are appended to slashdo's `--review-with` as `@user` tokens after the keyed reviewers, and the review-loop follow-up agent is instructed to request each as a PR reviewer (`gh pr edit … --add-reviewer`), wait for their review, and treat their approval as a merge gate — end to end through the original-agent completion prompt, the follow-up loop, and the `/do:next` claim flow. Usernames are stored without the `@`, validated against a shell-safe GitHub-username charset (1–39 chars, alphanumeric/hyphen, optional `/team`), case-insensitively deduped, and capped at 20, so a hand-edited `settings.json` can't smuggle in an unsafe or oversized token. They're a distinct class from the behavior reviewers — external PR reviewers that gate the merge, not CLIs that apply fixes — so `--reviewer-applies` never turns on for a username-only addition, and a username reviewer is forge-agnostic (kept even when Copilot is stripped on a non-GitHub forge, and able to drive the loop on its own). New config key: `settings.codeReview.usernames` (+ per-task `metadata.usernames`); no migration needed (absent = none).- **Image Gen now supports arbitrary (larger) output dimensions, not just the fixed preset list.** The resolution dropdown gained a **Custom…** entry that reveals Width and Height number inputs, so sizes the presets never covered — e.g. 704×1280 (9:16 portrait) for Z-Image — no longer require adding a new preset. Any edge in 64–3840px is accepted as long as the total stays ≤ 8,294,400px (the same `imageEdgeSchema` + pixel cap the server already enforced); a below-minimum edge snaps up to 64 (on blur, and again at submit so an Enter-key submit can't slip a sub-64 value through), and an over-cap total shows an inline warning before you submit. Custom mode also auto-engages whenever the current size matches no preset (a remix, an uploaded init image, or a stale off-backend size), so the exact dimensions stay visible and editable instead of collapsing to a read-only "(custom)" label. The inputs live in the shared `ImageGenControls`, so the Image Gen page, Universe Builder batch render, and the pipeline image-gen drawers all get custom dimensions at once.diff --git a/client/src/components/apps/EditAppDrawer.test.jsx b/client/src/components/apps/EditAppDrawer.test.jsxindex e44b8fd315..1559378020 100644--- a/client/src/components/apps/EditAppDrawer.test.jsx+++ b/client/src/components/apps/EditAppDrawer.test.jsx@@ -63,7 +63,7 @@ beforeEach(() => {providerId: null,model: null,rules: '',- sources: { goals: true, cosMetrics: true, healthReport: true, planMd: true, openIssues: true, custom: [] },+ sources: { goals: true, appMetrics: true, cosMetrics: true, healthReport: true, planMd: true, openIssues: true, custom: [] },allowedScopes: ['app-improvement', 'app-data-gap'],},});diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsxindex e80314213e..9a018733dc 100644--- a/client/src/components/apps/LayeredIntelligenceTab.jsx+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx@@ -14,7 +14,8 @@ import { formatLiReason, liReasonTone } from '../../utils/layeredIntelligenceRea// 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: 'appMetrics', label: 'App metrics (METRICS.md)', hint: 'The app\'s own success metrics — user-success / KPIs / production telemetry it tracks about itself' },+ { key: 'cosMetrics', label: 'CoS metrics', hint: 'This install\'s autonomous coding-agent run stats (how PortOS\'s agents perform) — not the app\'s own product performance' },{ 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' },diff --git a/client/src/components/apps/LayeredIntelligenceTab.test.jsx b/client/src/components/apps/LayeredIntelligenceTab.test.jsxindex 1a907d47fb..a7993d46e6 100644--- a/client/src/components/apps/LayeredIntelligenceTab.test.jsx+++ b/client/src/components/apps/LayeredIntelligenceTab.test.jsx@@ -8,7 +8,7 @@ const baseline = {providerId: null,model: null,rules: '',- sources: { goals: true, cosMetrics: true, healthReport: true, planMd: true, openIssues: true, custom: [] },+ sources: { goals: true, appMetrics: true, cosMetrics: true, healthReport: true, planMd: true, openIssues: true, custom: [] },allowedScopes: ['app-improvement', 'app-data-gap']};diff --git a/docs/METRICS.md b/docs/METRICS.mdnew file mode 100644index 0000000000..d3acee8de4--- /dev/null+++ b/docs/METRICS.md@@ -0,0 +1,112 @@+# The `METRICS.md` convention++`METRICS.md` is a repo-root file a **managed app** adds to document its own+success metrics — how the app measures whether it is doing its job — so that+agents can evaluate the app against its own goals and purpose instead of guessing.++It is the app-performance counterpart to `GOALS.md`: `GOALS.md` says *what the app+is trying to achieve*; `METRICS.md` says *how you know whether it's achieving it,+and where those numbers live*.++## Why it exists++PortOS's [Layered Intelligence loop](./plans/2026-07-07-layered-intelligence-loop.md)+perpetually reviews each managed app and files one high-value improvement proposal+per run. To reason well it needs to evaluate the app against **its own**+performance — user success, product KPIs, production telemetry — not against how+reliably PortOS's coding agents happen to change it.++Most of that data lives outside the repo: a production database, an external+telemetry/analytics service, a metrics dashboard, an events pipeline. An agent has+no way to discover those unless the repo tells it where they are and how to read+them. `METRICS.md` is that map.++## Who reads it++- **Layered Intelligence** gathers repo-root `METRICS.md` as the `appMetrics`+ source (on by default for every app) and folds it into the reasoning prompt.+ When an app has no `METRICS.md`, the loop is nudged to propose adding one as an+ `app-data-gap` — so the app becomes measurable over time.+- **Coding agents** picking up a filed proposal can follow the same doc to fetch+ current numbers before/after a change and judge whether it moved the metric.+- **Humans** get a single, honest description of what "healthy" means for the app.++## What to put in it++Keep it concise and specific. A good `METRICS.md` answers:++1. **What does success mean for this app?** The 3–7 metrics that actually matter,+ each tied back to a goal in `GOALS.md`.+2. **Where does each metric live?** Production database, telemetry service,+ dashboard, or log/event source — named by role, with a non-secret locator.+3. **How does an agent read the current value?** A query, an endpoint, or a CLI+ command it can run — parameterized by environment variables, never with+ embedded credentials.+4. **What's a good/bad value?** A target, threshold, or recent baseline so a+ reader can tell whether the number is healthy.++### Suggested shape++```markdown+# Metrics — example-app++How we measure whether example-app is succeeding. See GOALS.md for the goals+these metrics serve.++## Key metrics++| Metric | Why it matters (goal) | Source | Target |+|--------|-----------------------|--------|--------|+| Weekly active users | Reach — "help more people do X" | production DB | ↑ week over week |+| Task completion rate | Core value — users finish the flow | events pipeline | ≥ 80% |+| p95 request latency | Quality of service | telemetry service | < 400 ms |+| 7-day retention | Stickiness | production DB | ≥ 45% |++## Where the data lives++- **Production database** — read-only analytics replica. Connection string in the+ `ANALYTICS_DB_URL` environment variable (never commit it). Read-only user only.+- **Telemetry / analytics service** — dashboard at the URL in `TELEMETRY_URL`;+ API token in `TELEMETRY_TOKEN`.++## How to read current values (for agents)++Run these from the repo with the environment loaded. They print current numbers;+they do not modify anything.++- Weekly active users:+ `psql "$ANALYTICS_DB_URL" -c "select count(distinct user_id) from events where ts > now() - interval '7 days';"`+- Task completion rate: `GET $TELEMETRY_URL/api/metrics/completion-rate` with+ `Authorization: Bearer $TELEMETRY_TOKEN`.++## Notes++- All queries above hit a **read-only** replica/endpoint. Do not point them at a+ primary or run anything that writes.+```++## Rules++- **Repo-root only.** Layered Intelligence reads `METRICS.md` at the repository+ root of the app (same place it reads `GOALS.md` / `PLAN.md` / `HEALTH_REPORT.md`).+- **No secrets.** Reference credentials by environment variable or secret-manager+ key. Never paste a real connection string, password, token, or private hostname+ into the file — it is committed and shared like any other source.+- **Read-only access.** Every query or endpoint you document for agents must be a+ read-only path. An agent should be able to *observe* the metric, never mutate+ production data to measure it.+- **Keep it current.** Stale targets are worse than none — update the file when the+ metrics or their sources change.++## Feeding live numbers into the loop++`METRICS.md` documents *where* the metrics are and *how* to read them. If you also+want current values injected into each Layered Intelligence run automatically, add+a **custom source** in the app's Layered Intelligence config (Edit App →+Intelligence):++- a **command** source that runs one of the read-only queries above, or+- an **http** source that fetches a metrics endpoint.++That keeps `METRICS.md` as the human-readable map while the loop reasons over fresh+numbers each run.diff --git a/docs/README.md b/docs/README.mdindex 5d84d05161..7db9d31621 100644--- a/docs/README.md+++ b/docs/README.md@@ -18,6 +18,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo| [DEPS.md](./DEPS.md) | Dependency audit — every third-party package and its verdict || [TROUBLESHOOTING.md](./TROUBLESHOOTING.md) | Common runtime issues, known issues || [GOALS_OPERATIONAL.md](./GOALS_OPERATIONAL.md) | Runtime operating principles the CoS agent reads (parsed by `goalProgress.js`) |+| [METRICS.md](./METRICS.md) | The `METRICS.md` convention — how a managed app exposes its own success metrics so agents (incl. Layered Intelligence) can evaluate it against its goals || [SECURITY_AUDIT.md](./SECURITY_AUDIT.md) | Historical hardening audit (2026-02, all items resolved) |## Feature deep dives (`features/`)diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 3e949a2fcf..bab2bfd557 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -122,6 +122,9 @@ export const layeredIntelligenceConfigSchema = z.object({model: z.string().nullable().optional(),sources: z.object({goals: z.boolean().optional(),+ // The app's own success/performance metrics doc (METRICS.md in the app repo).+ // Default on: the primary signal for judging a managed app against its goals.+ appMetrics: z.boolean().optional(),cosMetrics: z.boolean().optional(),healthReport: z.boolean().optional(),planMd: z.boolean().optional(),diff --git a/server/services/apps.layeredIntelligence.test.js b/server/services/apps.layeredIntelligence.test.jsindex 72e95ffc72..fefc043e33 100644--- a/server/services/apps.layeredIntelligence.test.js+++ b/server/services/apps.layeredIntelligence.test.js@@ -56,7 +56,7 @@ describe('updateAppLayeredIntelligence', () => {const c = await getAppLayeredIntelligenceConfig('app-1');expect(c.enabled).toBe(true);expect(c.sources.goals).toBe(false);- expect(c.sources.cosMetrics).toBe(true); // untouched default preserved+ expect(c.sources.appMetrics).toBe(true); // untouched default preserved});it('preserves lastRunAt bookkeeping across a config PATCH', async () => {diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex 9c803c20ac..882b79a2df 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -98,7 +98,19 @@ export function defaultLayeredIntelligenceConfig(isPortos = false) {model: null,sources: {goals: true,- cosMetrics: true,+ // The app's OWN performance metrics (a METRICS.md doc in the app repo): the+ // user-success / KPI / production-telemetry signals the app tracks about+ // itself. This is the PRIMARY signal for evaluating a managed app against+ // its own goals and purpose, so it's on by default for every app. See the+ // METRICS.md convention in docs/METRICS.md.+ appMetrics: true,+ // The autonomous coding-agent run stats this install records (learning.json).+ // For the PortOS install these ARE its own-performance metrics; for a MANAGED+ // app they describe how reliably PortOS's agents change the app (a tooling /+ // interaction signal), NOT the app's own product performance — so default it+ // on only for PortOS. A managed app measures itself through appMetrics/custom+ // sources instead; the user can still opt this on per-app.+ cosMetrics: isPortos,healthReport: true,planMd: true,openIssues: true,@@ -493,6 +505,14 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort? openIssues.map(i => `- #${i.number ?? '?'} [${i.slug || extractSlugFromBody(i.body) || 'no-slug'}] ${i.title || ''}`).join('\n'): '(none)';+ // Nudge a managed app with no own-performance signal (no METRICS.md gathered)+ // toward adding one, so future runs can judge real performance. PortOS is exempt+ // — it measures itself through cosMetrics.+ const hasAppMetrics = Boolean(typeof sources.appMetrics === 'string' && sources.appMetrics.trim());+ const metricsGuidance = (!isPortos && !hasAppMetrics)+ ? '\nThis app exposes no own-performance metrics yet (no METRICS.md). If you lack the data to judge how it is doing against its goals, a high-value app-data-gap proposal is to add a METRICS.md documenting how the app measures success — its user-success/KPI signals and where its production telemetry or data lives — so future runs can reason about real performance.\n'+ : '';+const handoffNote = config.handoff?.enabled? '\nHand-off: a proposal you mark BOTH "complexity":"trivial" AND "safe":true may be handed directly to a coding agent to implement now (not just filed). Only mark a proposal trivial+safe when it is small, self-contained, and carries no regression or data-loss risk — when in doubt, use a higher complexity or "safe":false so a human triages it first.\n': '';@@ -503,8 +523,8 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort? `\n### liOutcomes\n${outcomesReport.trim()}\n\nUse this data to calibrate your proposal: prefer scopes with higher merge rates, avoid patterns that were repeatedly rejected, and consider that lower-merge scopes may need more justification.\n`: '';- return `You are the Layered Intelligence reasoner for the app "${app.name}". Analyze the app's goals and telemetry and decide the SINGLE highest-value improvement to propose this run — signal, not noise. You never write code; you return structured JSON that a deterministic system files as ONE tracker issue.-${handoffNote}+ return `You are the Layered Intelligence reasoner for the app "${app.name}". Your job is to evaluate how THIS app is performing against its OWN goals and purpose${isPortos ? '' : ', not how well PortOS\'s tooling manages it'}. Decide the SINGLE highest-value improvement to propose this run (signal, not noise), grounded in the app's own goals and its own performance metrics (user success, KPIs, production telemetry). You never write code; you return structured JSON that a deterministic system files as ONE tracker issue.+${handoffNote}${metricsGuidance}Rules & guidance from the operator:${config.rules?.trim() || '(none)'}@@ -567,6 +587,13 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos } = {}) {const goals = await tryReadFile(join(repo, 'GOALS.md'));if (goals) out.goals = goals.slice(0, 8000);}+ if (src.appMetrics && repo) {+ // The app's own success/performance metrics doc (the METRICS.md convention,+ // see docs/METRICS.md) — where a managed app records what "performing well"+ // means. Absent → omitted (the reasoner may then propose adding one).+ const metrics = await tryReadFile(join(repo, 'METRICS.md'));+ if (metrics) out.appMetrics = metrics.slice(0, 8000);+ }if (src.planMd && repo) {const plan = await tryReadFile(join(repo, 'PLAN.md'));if (plan) out.planMd = plan.slice(0, 8000);@@ -576,6 +603,9 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos } = {}) {if (health) out.healthReport = health.slice(0, 8000);}if (src.cosMetrics) {+ // This install's own autonomous-agent run stats (per task type), NOT scoped to+ // the app being analyzed — see the default-config note for the PortOS-vs-managed+ // rationale (default-off for managed apps).const learning = await readJSONFile(join(cosPath, 'learning.json'), null);if (learning?.byTaskType) {out.cosMetrics = JSON.stringify(learning.byTaskType).slice(0, 4000);diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex 34a4f5fd57..119d1c4765 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -57,11 +57,11 @@ import {} from './layeredIntelligence.js';describe('defaultLayeredIntelligenceConfig', () => {- it('is off by default with all sources on', () => {+ it('is off by default with the app-owned sources on', () => {const c = defaultLayeredIntelligenceConfig(false);expect(c.enabled).toBe(false);expect(c.sources.goals).toBe(true);- expect(c.sources.cosMetrics).toBe(true);+ expect(c.sources.appMetrics).toBe(true); // the app's own performance metricsexpect(c.sources.custom).toEqual([]);});@@ -87,6 +87,16 @@ describe('defaultLayeredIntelligenceConfig', () => {expect(defaultLayeredIntelligenceConfig(false).sources.outcomes).toBe(false);expect(defaultLayeredIntelligenceConfig(true).sources.outcomes).toBe(true);});++ it('defaults cosMetrics on for PortOS, off for managed apps (it is a PortOS-side agent-perf metric)', () => {+ expect(defaultLayeredIntelligenceConfig(false).sources.cosMetrics).toBe(false);+ expect(defaultLayeredIntelligenceConfig(true).sources.cosMetrics).toBe(true);+ });++ it('defaults the appMetrics (own-performance) source on for every app', () => {+ expect(defaultLayeredIntelligenceConfig(false).sources.appMetrics).toBe(true);+ expect(defaultLayeredIntelligenceConfig(true).sources.appMetrics).toBe(true);+ });});describe('getEffectiveConfig', () => {@@ -97,7 +107,7 @@ describe('getEffectiveConfig', () => {it('merges sources one level deep (partial toggle does not wipe others)', () => {const c = getEffectiveConfig({ layeredIntelligence: { sources: { goals: false } } });expect(c.sources.goals).toBe(false);- expect(c.sources.cosMetrics).toBe(true); // untouched default preserved+ expect(c.sources.appMetrics).toBe(true); // untouched default preservedexpect(c.sources.planMd).toBe(true);});@@ -450,6 +460,28 @@ describe('buildPrompt', () => {expect(withReport).toContain('Total filed: 3');expect(withReport).toContain('calibrate your proposal');});++ it('frames the mission around the app\'s own goals and performance', () => {+ const out = buildPrompt({ app, isPortos: false, config: { allowedScopes: ['app-improvement'], rules: '' } });+ expect(out).toContain('its OWN goals and purpose');+ });++ it('nudges a managed app with no own-performance metrics toward a METRICS.md data gap', () => {+ // No appMetrics source gathered → guidance to add a METRICS.md.+ const missing = buildPrompt({ app, isPortos: false, config: { allowedScopes: ['app-data-gap'], rules: '' } });+ expect(missing).toContain('METRICS.md');+ // Present appMetrics → no add-a-METRICS.md nudge.+ const present = buildPrompt({+ app, isPortos: false, config: { allowedScopes: ['app-data-gap'], rules: '' },+ sources: { appMetrics: 'Weekly active users: up' }+ });+ expect(present).not.toContain('no METRICS.md');+ });++ it('does not nudge PortOS toward a METRICS.md (it measures itself via cosMetrics)', () => {+ const out = buildPrompt({ app, isPortos: true, config: { allowedScopes: ['portos-self'], rules: '' } });+ expect(out).not.toContain('no METRICS.md');+ });});describe('deriveOutcome', () => {@@ -625,6 +657,29 @@ describe('gatherSources custom file confinement', () => {});});+describe('gatherSources appMetrics (METRICS.md)', () => {+ let dir;+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'lil-metrics-')); });+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });++ it('reads the app repo METRICS.md as the appMetrics source', async () => {+ await writeFile(join(dir, 'METRICS.md'), '# Metrics\nWeekly active users: up');+ const out = await gatherSources({ repoPath: dir }, { sources: { appMetrics: true } });+ expect(out.appMetrics).toContain('Weekly active users');+ });++ it('omits appMetrics when no METRICS.md exists (reasoner may then propose adding one)', async () => {+ const out = await gatherSources({ repoPath: dir }, { sources: { appMetrics: true } });+ expect(out.appMetrics).toBeUndefined();+ });++ it('does not read METRICS.md when the source is off', async () => {+ await writeFile(join(dir, 'METRICS.md'), 'present');+ const out = await gatherSources({ repoPath: dir }, { sources: { appMetrics: false } });+ expect(out.appMetrics).toBeUndefined();+ });+});+describe('customSourceKey', () => {it('namespaces by type so file/http/cmd never collide', () => {expect(customSourceKey({ type: 'file', ref: 'x' })).toBe('custom:x');