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([issue-2944]): add LI post-approval telemetry
[._.]/ Adam Eivycb2fb40b7ee3
diff --git a/client/src/components/apps/LayeredIntelligenceOutcomes.jsx b/client/src/components/apps/LayeredIntelligenceOutcomes.jsxindex cb3d65b31d..2db6e13f63 100644--- a/client/src/components/apps/LayeredIntelligenceOutcomes.jsx+++ b/client/src/components/apps/LayeredIntelligenceOutcomes.jsx@@ -2,7 +2,7 @@ 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 { formatDurationMs, timeAgo } from '../../utils/formatters';import { formatLiRejectionReason } from '../../utils/layeredIntelligenceReasons';// Read-only dashboard (#2689): how this app's filed Layered Intelligence proposals@@ -82,7 +82,7 @@ export default function LayeredIntelligenceOutcomes({ appId }) {);}- const { stats, rejections, recent, tracked = true } = state.data;+ const { stats, execution, rejections, recent, tracked = true } = state.data;if (!stats || stats.total === 0) {return (@@ -117,6 +117,7 @@ export default function LayeredIntelligenceOutcomes({ appId }) {// the API caps `recent` at a limit above what we render, so `recent.length` would// undercount the real remainder for an app with a long proposal history.const hiddenCount = Math.max(0, stats.total - visible.length);+ const executionScopes = Object.entries(execution?.byScope || {});return (<div className="space-y-3 bg-port-bg border border-port-border rounded-lg px-3 py-3">@@ -153,6 +154,37 @@ export default function LayeredIntelligenceOutcomes({ appId }) {})}</div>+ {execution?.approved > 0 && (+ <div className="space-y-1 border-t border-port-border pt-3">+ <div className="flex items-baseline gap-2">+ <span className="text-sm font-semibold text-white">+ {execution.completionRate == null ? '—' : `${Math.round(execution.completionRate)}%`}+ </span>+ <span className="text-xs text-gray-500">post-approval hand-off completion</span>+ </div>+ <p className="text-xs text-gray-500">+ {execution.completed} completed · {execution.abandoned} abandoned · {execution.awaitingExecution} awaiting execution+ </p>+ {execution.duration?.count > 0 && (+ <p className="text-xs text-gray-500">+ Filed → completed: median {formatDurationMs(execution.duration.medianMs)} · p90 {formatDurationMs(execution.duration.p90Ms)}+ </p>+ )}+ {executionScopes.length > 0 && (+ <ul className="space-y-0.5">+ {executionScopes.map(([scope, summary]) => (+ <li key={scope} className="text-xs text-gray-500 flex justify-between gap-2">+ <span className="min-w-0 break-all">{scope}</span>+ <span className="shrink-0">+ {summary.completionRate == null ? 'awaiting' : `${Math.round(summary.completionRate)}%`} · {summary.completed}/{summary.attempted || 0}+ </span>+ </li>+ ))}+ </ul>+ )}+ </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>diff --git a/client/src/components/apps/LayeredIntelligenceOutcomes.test.jsx b/client/src/components/apps/LayeredIntelligenceOutcomes.test.jsxindex f3f29d5f0f..0de39f9100 100644--- a/client/src/components/apps/LayeredIntelligenceOutcomes.test.jsx+++ b/client/src/components/apps/LayeredIntelligenceOutcomes.test.jsx@@ -12,6 +12,16 @@ const ready = (overrides = {}) => ({read: true,tracked: true,stats: { total: 4, merged: 1, rejected: 1, abandoned: 1, pending: 1, resolved: 3, mergeRate: 100 / 3 },+ execution: {+ approved: 1, completed: 1, abandoned: 0, awaitingExecution: 0, attempted: 1, completionRate: 100,+ duration: { count: 1, averageMs: 3_600_000, medianMs: 3_600_000, p90Ms: 3_600_000, minMs: 3_600_000, maxMs: 3_600_000 },+ byScope: {+ 'app-improvement': {+ approved: 1, completed: 1, abandoned: 0, awaitingExecution: 0, attempted: 1, completionRate: 100,+ duration: { count: 1, averageMs: 3_600_000, medianMs: 3_600_000, p90Ms: 3_600_000, minMs: 3_600_000, maxMs: 3_600_000 }+ }+ }+ },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' },@@ -41,6 +51,9 @@ describe('LayeredIntelligenceOutcomes', () => {expect(screen.getByText(/closed with no recorded reason/)).toBeInTheDocument();expect(screen.getByText('add-metrics')).toBeInTheDocument();expect(screen.getByText('drop-feature')).toBeInTheDocument();+ expect(screen.getByText('post-approval hand-off completion')).toBeInTheDocument();+ expect(screen.getByText(/Filed → completed: median 1h 0m/)).toBeInTheDocument();+ expect(screen.getByText('app-improvement')).toBeInTheDocument();expect(getAppLayeredIntelligenceOutcomes).toHaveBeenCalledWith('app-001');});diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.jsindex f89bce1771..5dae9f08d9 100644--- a/server/routes/apps/taskTypes.js+++ b/server/routes/apps/taskTypes.js@@ -6,7 +6,7 @@* GET /:id/task-types → { taskTypeOverrides }* GET /:id/work-tracker → { tracker info }* GET /:id/layered-intelligence → { config, isPortos }- * GET /:id/layered-intelligence/outcomes → { stats, rejections, recent }+ * GET /:id/layered-intelligence/outcomes → { stats, execution, rejections, recent }* PUT /:id/task-types/all → { success, taskTypeOverrides }* PUT /:id/task-types/:taskType → { success, taskTypeOverrides }*@@ -21,7 +21,7 @@ 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 { summarizeOutcomeStats, computePostApprovalCompletion } from '../../services/layeredIntelligence.js';import { listOutcomesResult } from '../../services/layeredIntelligenceOutcomes.js';import { summarizeRejectionReasons } from '../../services/layeredIntelligenceRejections.js';import { loadApp } from './shared.js';@@ -79,10 +79,10 @@ router.get('/:id/layered-intelligence', loadApp, asyncHandler(async (req, res) =// 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.+// the reasoner prompt reasons over — merge-rate, post-approval execution, and+// rejection taxonomy — 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@@ -108,7 +108,7 @@ router.get('/:id/layered-intelligence/outcomes', loadApp, asyncHandler(async (reconst tracked = !!config?.sources?.outcomes;const { read, outcomes } = await listOutcomesResult({ appId: app.id });if (!read) {- return res.json({ appId: app.id, appName: app.name, read: false, tracked, stats: null, rejections: null, recent: [] });+ return res.json({ appId: app.id, appName: app.name, read: false, tracked, stats: null, execution: null, rejections: null, recent: [] });}const { total, merged, rejected, abandoned, pending, resolved, rawMergeRate } = summarizeOutcomeStats(outcomes);const rejections = summarizeRejectionReasons(outcomes);@@ -130,6 +130,7 @@ router.get('/:id/layered-intelligence/outcomes', loadApp, asyncHandler(async (re// `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 },+ execution: computePostApprovalCompletion(outcomes),rejections,recent});diff --git a/server/routes/apps/taskTypes.test.js b/server/routes/apps/taskTypes.test.jsindex b3a8e68523..bae292e7f9 100644--- a/server/routes/apps/taskTypes.test.js+++ b/server/routes/apps/taskTypes.test.js@@ -77,7 +77,7 @@ describe('Apps Task-Type Routes', () => {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: 'add-metrics', scope: 'app-improvement', outcome: 'merged', executionOutcome: 'success', executionAt: '2026-07-04T01:00:00.000Z', 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 }@@ -90,6 +90,11 @@ describe('Apps Task-Type Routes', () => {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);+ expect(response.body.execution).toMatchObject({+ approved: 1, completed: 1, abandoned: 0, awaitingExecution: 0, attempted: 1, completionRate: 100,+ duration: { count: 1, medianMs: 3_600_000 }+ });+ expect(response.body.execution.byScope['app-improvement']).toMatchObject({ completed: 1, completionRate: 100 });// 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);@@ -121,6 +126,7 @@ describe('Apps Task-Type Routes', () => {expect(response.status).toBe(200);expect(response.body.read).toBe(false);expect(response.body.stats).toBeNull();+ expect(response.body.execution).toBeNull();expect(response.body.recent).toEqual([]);});diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex ae8b9acb73..111e21d362 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -45,6 +45,7 @@ import {LI_DEGRADED_MIN_SAMPLE,computeScopeAwareness,computeExecutionByDomain,+ computePostApprovalCompletion,computeProposalExecutionAwareness,computeCrossReferenceAnalysis,computeHandoffRouting,@@ -506,6 +507,75 @@ describe('computeExecutionByDomain (#2765)', () => {});});+describe('computePostApprovalCompletion (#2944)', () => {+ it('separates approved hand-off completion states and summarizes duration by scope', () => {+ const out = computePostApprovalCompletion([+ {+ scope: 'app-improvement', outcome: 'merged', executionOutcome: 'success',+ filedAt: '2026-07-01T00:00:00.000Z', executionAt: '2026-07-01T01:00:00.000Z'+ },+ {+ scope: 'app-improvement', outcome: 'merged', executionOutcome: 'failure',+ filedAt: '2026-07-01T00:00:00.000Z', executionAt: '2026-07-01T02:00:00.000Z'+ },+ {+ scope: 'app-data-gap', outcome: 'merged', executionOutcome: null,+ filedAt: '2026-07-01T00:00:00.000Z'+ },+ // Rejected proposals never enter the post-approval denominator.+ {+ scope: 'app-improvement', outcome: 'rejected', executionOutcome: 'success',+ filedAt: '2026-07-01T00:00:00.000Z', executionAt: '2026-07-01T03:00:00.000Z'+ },+ // Invalid chronology must not poison duration telemetry.+ {+ scope: 'loop-meta', outcome: 'merged', executionOutcome: 'success',+ filedAt: '2026-07-02T00:00:00.000Z', executionAt: '2026-07-01T00:00:00.000Z'+ }+ ]);++ expect(out).toMatchObject({+ approved: 4,+ completed: 2,+ abandoned: 1,+ awaitingExecution: 1,+ attempted: 3+ });+ expect(out.completionRate).toBeCloseTo(200 / 3, 10);+ expect(out.duration).toEqual({+ count: 1,+ averageMs: 3_600_000,+ medianMs: 3_600_000,+ p90Ms: 3_600_000,+ minMs: 3_600_000,+ maxMs: 3_600_000+ });+ expect(out.byScope['app-improvement']).toMatchObject({+ approved: 2, completed: 1, abandoned: 1, awaitingExecution: 0, attempted: 2, completionRate: 50+ });+ expect(out.byScope['app-data-gap']).toMatchObject({+ approved: 1, completed: 0, abandoned: 0, awaitingExecution: 1, attempted: 0, completionRate: null+ });+ });++ it('calculates median and p90 from the completed duration distribution', () => {+ const filedAt = '2026-07-01T00:00:00.000Z';+ const out = computePostApprovalCompletion([1, 2, 3, 4].map(hours => ({+ scope: 'app-data-gap', outcome: 'merged', executionOutcome: 'success', filedAt,+ executionAt: `2026-07-01T${String(hours).padStart(2, '0')}:00:00.000Z`+ })));++ expect(out.duration).toEqual({+ count: 4,+ averageMs: 9_000_000,+ medianMs: 9_000_000,+ p90Ms: 14_400_000,+ minMs: 3_600_000,+ maxMs: 14_400_000+ });+ });+});+describe('computeProposalExecutionAwareness (#2765)', () => {const execRecords = (scope, successes, failures) => [...Array.from({ length: successes }, () => ({ scope, executionOutcome: 'success' })),@@ -1216,6 +1286,28 @@ describe('computeOutcomesReport', () => {expect(report).toContain('Why non-merged proposals were closed: already tracked elsewhere (duplicate) (1)');});+ it('adds post-approval completion rates and filed-to-completed duration distribution (#2944)', () => {+ const report = computeOutcomesReport({+ outcomes: [+ {+ scope: 'app-improvement', outcome: 'merged', executionOutcome: 'success',+ filedAt: '2026-07-01T00:00:00.000Z', executionAt: '2026-07-01T01:00:00.000Z'+ },+ {+ scope: 'app-improvement', outcome: 'merged', executionOutcome: 'failure',+ filedAt: '2026-07-01T00:00:00.000Z', executionAt: '2026-07-01T02:00:00.000Z'+ },+ { scope: 'app-data-gap', outcome: 'merged', executionOutcome: null }+ ]+ });++ expect(report).toContain('Post-approval LI hand-off follow-through:');+ expect(report).toContain('Approved proposals: 3; 1 completed, 1 abandoned, 1 awaiting execution.');+ expect(report).toContain('Completion rate: 50% (1/2 attempted).');+ expect(report).toContain('average 1h 0m, median 1h 0m, p90 1h 0m (1 completed)');+ expect(report).toContain('app-improvement: 1 completed, 1 abandoned, 0 awaiting execution; 50% completed');+ });+it('surfaces the execution-failure taxonomy line only when a hand-off has failed (#2764 §1)', () => {// A clean execution record shows no failure line…const clean = computeOutcomesReport({diff --git a/server/services/layeredIntelligence/awareness.js b/server/services/layeredIntelligence/awareness.jsindex a619332915..e376588952 100644--- a/server/services/layeredIntelligence/awareness.js+++ b/server/services/layeredIntelligence/awareness.js@@ -181,6 +181,72 @@ export function computeExecutionByDomain(outcomes = []) {return byDomain;}+/**+ * Summarize what happens after a proposal has been approved/merged. The existing+ * outcome store already persists both sides of this lifecycle: `outcome: 'merged'`+ * marks approval, while `executionOutcome` records the terminal LI hand-off result.+ * Keep this derivation pure so the prompt and dashboard cannot disagree about the+ * post-approval completion signal.+ *+ * Duration is measured from filing to a successful hand-off completion. That is the+ * only timestamp pair available for every tracker and remains meaningful when the+ * coding hand-off finishes before the tracker issue is reconciled as merged.+ */+export function computePostApprovalCompletion(outcomes = []) {+ const approved = (Array.isArray(outcomes) ? outcomes : []).filter(record =>+ record && typeof record === 'object' && record.outcome === 'merged'+ );++ const summarize = (records) => {+ const completedRecords = records.filter(record => record.executionOutcome === 'success');+ const abandoned = records.filter(record => record.executionOutcome === 'failure').length;+ const completed = completedRecords.length;+ const attempted = completed + abandoned;+ const durations = completedRecords+ .map(record => Date.parse(record.executionAt) - Date.parse(record.filedAt))+ .filter(duration => Number.isFinite(duration) && duration >= 0)+ .sort((a, b) => a - b);+ const percentile = (fraction) => {+ if (durations.length === 0) return null;+ return durations[Math.max(0, Math.ceil(durations.length * fraction) - 1)];+ };+ const median = durations.length % 2 === 1+ ? durations[Math.floor(durations.length / 2)]+ : Math.round((durations[(durations.length / 2) - 1] + durations[durations.length / 2]) / 2);+ const duration = durations.length === 0+ ? { count: 0, averageMs: null, medianMs: null, p90Ms: null, minMs: null, maxMs: null }+ : {+ count: durations.length,+ averageMs: Math.round(durations.reduce((sum, value) => sum + value, 0) / durations.length),+ medianMs: median,+ p90Ms: percentile(0.9),+ minMs: durations[0],+ maxMs: durations.at(-1)+ };+ return {+ approved: records.length,+ completed,+ abandoned,+ awaitingExecution: records.length - attempted,+ attempted,+ completionRate: attempted > 0 ? (completed / attempted) * 100 : null,+ duration+ };+ };++ const recordsByScope = new Map();+ for (const record of approved) {+ const scope = typeof record.scope === 'string' && record.scope.trim() ? record.scope.trim() : 'unknown';+ const records = recordsByScope.get(scope) || [];+ records.push(record);+ recordsByScope.set(scope, records);+ }+ const byScope = Object.create(null);+ for (const [scope, records] of recordsByScope) byScope[scope] = summarize(records);++ return { ...summarize(approved), byScope };+}+/*** Render the dominant execution-failure causes from a domain's `failureSummary`* (#2764 §3) as a compact clause for the per-domain avoid line. Reuses the shareddiff --git a/server/services/layeredIntelligence/outcomes.js b/server/services/layeredIntelligence/outcomes.jsindex f44394a491..89ae8c6a23 100644--- a/server/services/layeredIntelligence/outcomes.js+++ b/server/services/layeredIntelligence/outcomes.js@@ -7,7 +7,7 @@* self-eval summary (suppressed issues, rejection reasons, LI execution health).*/-import { DAY } from '../../lib/fileUtils.js';+import { DAY, formatDuration } from '../../lib/fileUtils.js';import { computeEffectiveSuccessRate } from '../taskLearning/store.js';import { formatRejectionReasons, formatRejectionReason, REJECTION_REASONS } from '../layeredIntelligenceRejections.js';import { formatExecutionFailures } from '../layeredIntelligenceExecutionFailures.js';@@ -16,6 +16,7 @@ import {LI_DEGRADED_SUCCESS_THRESHOLD, LI_HARD_GATE_EXECUTION_THRESHOLD, CLOSED_SUPPRESSION_MS,} from './constants.js';import { normalizeSlug, extractSlugFromBody, isIssueWithinDedupWindow } from './dedup.js';+import { computePostApprovalCompletion } from './awareness.js';/*** Derive a resolved outcome for a filed proposal from its live tracker issue.@@ -111,6 +112,25 @@ export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false }// no hand-off has failed, so the line below is omitted rather than contradicting a// clean execution record.const executionFailures = formatExecutionFailures(filed, 5);+ const postApproval = computePostApprovalCompletion(filed);+ const postApprovalScopeLines = Object.entries(postApproval.byScope)+ .sort((a, b) => b[1].approved - a[1].approved)+ .map(([scope, summary]) => {+ const rate = summary.completionRate == null ? 'no completed hand-offs yet' : `${Math.round(summary.completionRate)}% completed`;+ const duration = summary.duration.medianMs == null+ ? 'no completion-time sample yet'+ : `median filed-to-completed ${formatDuration(summary.duration.medianMs)} (p90 ${formatDuration(summary.duration.p90Ms)})`;+ return `- ${scope}: ${summary.completed} completed, ${summary.abandoned} abandoned, ${summary.awaitingExecution} awaiting execution; ${rate}; ${duration}`;+ });+ const postApprovalLines = postApproval.approved === 0 ? [] : [+ '',+ 'Post-approval LI hand-off follow-through:',+ `- Approved proposals: ${postApproval.approved}; ${postApproval.completed} completed, ${postApproval.abandoned} abandoned, ${postApproval.awaitingExecution} awaiting execution.`,+ `- Completion rate: ${postApproval.completionRate == null ? 'no terminal hand-offs yet' : `${Math.round(postApproval.completionRate)}% (${postApproval.completed}/${postApproval.attempted} attempted)`}.`,+ `- Filed-to-completed duration: ${postApproval.duration.medianMs == null ? 'no valid completion-time sample yet' : `average ${formatDuration(postApproval.duration.averageMs)}, median ${formatDuration(postApproval.duration.medianMs)}, p90 ${formatDuration(postApproval.duration.p90Ms)} (${postApproval.duration.count} completed)`}.`,+ '- By approved proposal scope:',+ ...(postApprovalScopeLines.length ? postApprovalScopeLines : ['- (none)'])+ ];// Low-merge-rate alarm (#2698). `rawMergeRate` is measured over RESOLVED// proposals only and is null when none have resolved — see summarizeOutcomeStats@@ -150,6 +170,7 @@ export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false }// an app whose proposals were never handed off (or all succeeded) shows nothing// here rather than a misleading "no failures" line....(executionFailures ? [`Why LI's own hand-offs failed when implemented: ${executionFailures}`] : []),+ ...postApprovalLines,...lowMergeWarning].join('\n');}