Skip to content

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

feat: surface the LI proposal approval funnel in liSelfEval so the loop can see its human-review bottleneck (#3120)

[._.]/ Adam Eivyc5ac60e4c0e0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index bd62ea85f6..cf9faa0d9c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -80,6 +80,7 @@
## Layered Intelligence
+- **[issue-3120] The self-improvement loop can now see where its proposals are stuck in *your* review queue.** Its self-evaluation block reported how resolved proposals fared and whether approved ones got delivered, but nothing about the approval funnel itself — so a loop with a dozen proposals sitting unread for weeks had no way to know that its bottleneck was review capacity rather than idea quality, and kept filing into a queue nobody was reading. Every run now also reports the approval rate over the last 14 days (measured on decisions you actually made in that window, so it tracks your current triage rather than restating the lifetime rate), the median time from filing to a decision, and a proposal-phase throughput figure kept explicitly separate from the agent-task run rates in `cosMetrics`. When something is genuinely waiting there's a "pending human review" line with the count, how many have sat past 1/3/7 days, and how long the oldest has waited — and once anything crosses a week the loop is told plainly to raise its bar or file nothing. Nothing pending means no line at all, rather than a reassuring "0 awaiting review" on every run. An idle approver reads as an unknown rate, never 0%, and an unreadable history says so instead of rendering an empty queue. The same numbers are on `GET /api/apps/:id/layered-intelligence/outcomes` for querying.
- **[issue-3085] The self-improvement loop can now see whether its approved proposals actually get delivered, not just whether its agent runs finish.** The `cosMetrics` block it reasons over reported per-task-type run success — "did the agent's task complete?" — and nothing about delivery, so a 90% run rate sat there looking healthy beside a pipeline that had landed none of ten approved proposals. That same block now carries a `delivery` figure (approved, delivered, and the current delivery rate) plus a per-scope breakdown, so the two numbers are read side by side. The rate is reported as unknown rather than 0% until something has actually been approved — a loop with no track record shouldn't read as a loop that fails everything.
## Antigravity model and effort selection
diff --git a/server/routes/apps/taskTypes.js b/server/routes/apps/taskTypes.js
index 4828572fe3..7e2c8db515 100644
--- a/server/routes/apps/taskTypes.js
+++ b/server/routes/apps/taskTypes.js
@@ -7,7 +7,7 @@
* GET /:id/work-tracker → { tracker info }
* GET /:id/work-items → { tracker, items, reason }
* GET /:id/layered-intelligence → { config, isPortos }
- * GET /:id/layered-intelligence/outcomes → { stats, execution, rejections, recent }
+ * GET /:id/layered-intelligence/outcomes → { stats, execution, metrics, approvalFunnel, rejections, recent }
* PUT /:id/task-types/all → { success, taskTypeOverrides }
* PUT /:id/task-types/:taskType → { success, taskTypeOverrides }
*
@@ -24,7 +24,7 @@ import { resolveClaimWorkMetadata, resolveClaimAuthorFilter } from '../../servic
import { parseCronToNextRun } from '../../services/eventScheduler.js';
import { asyncHandler, ServerError } from '../../lib/errorHandler.js';
import { SELF_IMPROVEMENT_TASK_TYPES } from '../../services/taskSchedule.js';
-import { summarizeOutcomeStats, computePostApprovalCompletion, computeProposalOutcomeMetrics } from '../../services/layeredIntelligence.js';
+import { summarizeOutcomeStats, computePostApprovalCompletion, computeProposalOutcomeMetrics, computeApprovalFunnel } from '../../services/layeredIntelligence.js';
import { listOutcomesResult } from '../../services/layeredIntelligenceOutcomes.js';
import { summarizeRejectionReasons } from '../../services/layeredIntelligenceRejections.js';
import { loadApp } from './shared.js';
@@ -130,7 +130,7 @@ router.get('/:id/layered-intelligence/outcomes', loadApp, asyncHandler(async (re
const 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, execution: null, metrics: null, rejections: null, recent: [] });
+ return res.json({ appId: app.id, appName: app.name, read: false, tracked, stats: null, execution: null, metrics: null, approvalFunnel: null, rejections: null, recent: [] });
}
// Computed once and threaded into the roll-up below — `computeProposalOutcomeMetrics`
// is built on these same two aggregators, so handing it the results keeps the whole
@@ -166,6 +166,13 @@ router.get('/:id/layered-intelligence/outcomes', loadApp, asyncHandler(async (re
// what distinguishes "rejected" from "approved then lost". Built from the same two
// aggregate objects returned above, so the three blocks cannot drift.
metrics: computeProposalOutcomeMetrics(outcomes, { stats, execution }),
+ // The approval FUNNEL (#3120) — the human-review side none of the three blocks
+ // above can express: the windowed approval rate, the pending-review backlog with
+ // its 1d/3d/7d age buckets, filing-to-decision latency, and proposal-phase
+ // throughput (kept distinct from cosMetrics' agent-task lifecycle). Derived from the
+ // same records, so this endpoint is the queryable view of exactly what the
+ // reasoner's liSelfEval block reports — no second on-disk aggregate to drift.
+ approvalFunnel: computeApprovalFunnel(outcomes),
rejections,
recent
});
diff --git a/server/routes/apps/taskTypes.test.js b/server/routes/apps/taskTypes.test.js
index b72a1eefe4..bc460b7a23 100644
--- a/server/routes/apps/taskTypes.test.js
+++ b/server/routes/apps/taskTypes.test.js
@@ -175,6 +175,14 @@ describe('Apps Task-Type Routes', () => {
expect(response.body.metrics.byScope['app-data-gap']).toMatchObject({
approved: 0, abandonedAtFiling: 1, approvalToCompletionRate: null
});
+ // The approval funnel (#3120): the human-review side of the same records. The
+ // fixture holds 3 decided + 1 pending, so the pending indicator is populated and
+ // the proposal-phase throughput is distinct from any agent-task rate.
+ expect(response.body.approvalFunnel.proposalPhase).toMatchObject({
+ totalFiled: 4, totalDecided: 3, totalPending: 1
+ });
+ expect(response.body.approvalFunnel.pending.count).toBe(1);
+ expect(response.body.approvalFunnel.windowDays).toBe(14);
// 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);
@@ -210,6 +218,9 @@ describe('Apps Task-Type Routes', () => {
// Null, not a zeroed roll-up: an unreadable store must not read as "LI has
// approved nothing and delivered nothing" — the same sentinel rule as `stats`.
expect(response.body.metrics).toBeNull();
+ // Same sentinel rule for the funnel: an unreadable store must not report "0
+ // proposals awaiting review" — that is indistinguishable from a clean queue.
+ expect(response.body.approvalFunnel).toBeNull();
expect(response.body.recent).toEqual([]);
});
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index 9873ac8db2..adb3688704 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -31,6 +31,7 @@ export * from './layeredIntelligence/dedup.js';
export * from './layeredIntelligence/proposal.js';
export * from './layeredIntelligence/outcomes.js';
export * from './layeredIntelligence/awareness.js';
+export * from './layeredIntelligence/approvalFunnel.js';
export * from './layeredIntelligence/gates.js';
export * from './layeredIntelligence/prompt.js';
export * from './layeredIntelligence/runCli.js';
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index 49cfb96298..c4b5e8af1e 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -1979,6 +1979,55 @@ describe('computeSelfEvalSummary (#2700)', () => {
expect(report).not.toContain('DEGRADED');
});
+ const DAY_AGO_MS = 24 * 60 * 60 * 1000;
+
+ it('folds the approval funnel into the block on every run (#3120)', () => {
+ const now = Date.parse('2026-07-20T12:00:00.000Z');
+ const ago = (ms) => new Date(now - ms).toISOString();
+ const report = computeSelfEvalSummary({
+ liTaskStats: liMetrics(),
+ existingIssues: [],
+ outcomes: [
+ { slug: 'approved-one', outcome: 'merged', filedAt: ago(5 * DAY_AGO_MS), outcomeAt: ago(3 * DAY_AGO_MS) },
+ { slug: 'rejected-one', outcome: 'rejected', filedAt: ago(6 * DAY_AGO_MS), outcomeAt: ago(2 * DAY_AGO_MS) },
+ { slug: 'stalled-one', outcome: null, filedAt: ago(9 * DAY_AGO_MS), outcomeAt: null }
+ ],
+ now
+ });
+ expect(report).toContain('LI approval rate (last 14d): 50%');
+ expect(report).toContain('LI time-to-decision: median');
+ expect(report).toContain('PENDING HUMAN REVIEW: 1 filed proposal(s)');
+ expect(report).toContain('LI proposal-phase throughput');
+ });
+
+ it('omits the pending-review indicator when the count is zero (#3120)', () => {
+ const report = computeSelfEvalSummary({
+ liTaskStats: liMetrics(),
+ outcomes: [{ slug: 'done', outcome: 'merged', filedAt: '2026-07-18T00:00:00.000Z', outcomeAt: '2026-07-19T00:00:00.000Z' }],
+ now: Date.parse('2026-07-20T12:00:00.000Z')
+ });
+ expect(report).not.toContain('PENDING HUMAN REVIEW');
+ });
+
+ it('reports the funnel as UNAVAILABLE when outcomes were not gathered (#3120)', () => {
+ const report = computeSelfEvalSummary({ outcomes: null, liTaskStats: liMetrics() });
+ expect(report).toContain('LI approval funnel: UNAVAILABLE');
+ expect(report).not.toContain('PENDING HUMAN REVIEW');
+ });
+
+ it('does not let the approval funnel inflate the confidence count (#3120)', () => {
+ // The funnel measures the APPROVER's throughput, not LI's self-knowledge — a rich
+ // funnel must not make a signal-less loop look well-informed.
+ const now = Date.parse('2026-07-20T12:00:00.000Z');
+ const report = computeSelfEvalSummary({
+ outcomes: [
+ { slug: 'a', outcome: 'merged', filedAt: new Date(now - 4 * DAY_AGO_MS).toISOString(), outcomeAt: new Date(now - 2 * DAY_AGO_MS).toISOString() }
+ ],
+ now
+ });
+ expect(report).toContain('Reasoning confidence: low');
+ });
+
it('rates confidence high with all three signals, and drops guidance', () => {
const outcomes = Array.from({ length: 6 }, () => ({ outcome: 'merged' }));
const report = computeSelfEvalSummary({
diff --git a/server/services/layeredIntelligence/approvalFunnel.js b/server/services/layeredIntelligence/approvalFunnel.js
new file mode 100644
index 0000000000..73e1718b2f
--- /dev/null
+++ b/server/services/layeredIntelligence/approvalFunnel.js
@@ -0,0 +1,241 @@
+/**
+ * Layered Intelligence — proposal APPROVAL FUNNEL metrics (#3120).
+ *
+ * The outcome store already answers "how did my resolved proposals fare?"
+ * (`summarizeOutcomeStats`) and "did my approved proposals get delivered?"
+ * (`computeProposalOutcomeMetrics`). Neither can answer the question this module exists
+ * for: **where in the human-approval funnel are my proposals stuck, and is the user's
+ * triage behavior changing?** Those are the loop's own bottleneck signals —
+ * a backlog of undecided proposals is a reason to STOP filing, and neither a lifetime
+ * merge rate nor a delivery rate makes it visible.
+ *
+ * Five metrics, all derived from the proposal LIFECYCLE (`filedAt` → `outcome` +
+ * `outcomeAt`) that `data/cos/li-outcomes/` already persists — explicitly NOT from
+ * tracker labels, and with no second on-disk aggregate to drift from its source:
+ * 1. Approval rate over a sliding window — measured over the decisions the user made
+ * INSIDE the window, so it tracks current triage behavior rather than restating the
+ * lifetime rate.
+ * 2. Pending-review count — proposals awaiting a human decision right now.
+ * 3. Median time from filing to a human decision (and, separately, to an APPROVAL).
+ * 4. Approver-delay buckets — how many undecided proposals are past 1 / 3 / 7 days.
+ * 5. Proposal-PHASE delivery: what share of everything LI filed has received any
+ * verdict at all. Deliberately distinct from `cosMetrics`, which measures the
+ * AGENT-TASK lifecycle ("did the run finish?") and says nothing about whether a
+ * filed proposal was ever looked at.
+ *
+ * Pure + side-effect-free, and NO LLM call: every number is a read of records the loop
+ * already keeps (the "no cold-bootstrap LLM calls" policy). `now` is an injected clock
+ * seam so the ages are testable and so one selfEval run reasons against a single "now".
+ *
+ * SENTINEL DISCIPLINE throughout — a rate whose denominator is zero is `null`, never 0:
+ * "no decision has been made in this window" and "every decision was a rejection" are
+ * opposite facts, and a 0% approval rate in the prompt is a direct instruction to the
+ * reasoner to hold back. A record whose timestamp cannot be parsed is counted in an
+ * explicit `undated` slot rather than being placed in a window or an age bucket it
+ * cannot be shown to belong to.
+ */
+
+import { DAY, formatDuration } from '../../lib/fileUtils.js';
+import { LI_APPROVAL_FUNNEL_WINDOW_MS, LI_APPROVAL_DELAY_BUCKET_DAYS } from './constants.js';
+import { summarizeDurations } from './awareness.js';
+
+// The bucket key for an age threshold — `1` → `'1d'`. One place so the computed object's
+// keys and the rendered line can't disagree.
+export const delayBucketKey = (days) => `${days}d`;
+
+/** A parsed epoch-ms timestamp, or null when the value is absent/unparseable. */
+const parsedMs = (value) => {
+ const ms = Date.parse(value);
+ return Number.isFinite(ms) ? ms : null;
+};
+
+/**
+ * Compute the approval-funnel metrics for one app's outcome records.
+ *
+ * @param {Array} [outcomes] - the app's li-outcomes records (from listOutcomes). A
+ * NON-array is treated as an empty set here; callers that must distinguish a FAILED
+ * store read from a genuinely empty history check that BEFORE calling (the report
+ * formatter below does).
+ * @param {object} [opts]
+ * @param {number} [opts.now] - clock seam for ages and the window edge.
+ * @param {number} [opts.windowMs] - sliding-window span (default the shared constant).
+ * @returns {{ windowMs: number, windowDays: number,
+ * window: { decided: number, approved: number, rejected: number, abandoned: number,
+ * undated: number, approvalRate: number|null, timeToDecision: object,
+ * timeToApproval: object },
+ * pending: { count: number, oldestAgeMs: number|null, undated: number,
+ * byAge: Object<string, number> },
+ * proposalPhase: { totalFiled: number, totalDecided: number, totalPending: number,
+ * decisionRate: number|null } }}
+ */
+export function computeApprovalFunnel(outcomes = [], { now = Date.now(), windowMs = LI_APPROVAL_FUNNEL_WINDOW_MS } = {}) {
+ const records = (Array.isArray(outcomes) ? outcomes : []).filter(r => r && typeof r === 'object');
+ const windowStart = now - windowMs;
+
+ // --- Decision cohort: verdicts the user issued inside the window --------------
+ // Keyed on `outcomeAt` (WHEN the user decided), not `filedAt`: the metric is about the
+ // user's current triage behavior, so a 5-month-old proposal decided yesterday belongs
+ // in this window and a proposal filed yesterday and still open does not.
+ const decided = records.filter(r => r.outcome);
+ const decidedInWindow = [];
+ let undatedDecisions = 0;
+ for (const r of decided) {
+ const decidedMs = parsedMs(r.outcomeAt);
+ // An undatable decision cannot be placed in or out of the window. Counting it in
+ // would inflate a "recent" rate with an unknown-age verdict; counting it out
+ // silently would undercount the user's activity. It gets its own slot.
+ if (decidedMs === null) { undatedDecisions += 1; continue; }
+ if (decidedMs >= windowStart) decidedInWindow.push({ record: r, decidedMs });
+ }
+ const countOutcome = (name) => decidedInWindow.filter(({ record }) => record.outcome === name).length;
+ const approvedInWindow = decidedInWindow.filter(({ record }) => record.outcome === 'merged');
+ // Filing-to-decision latency. Only measurable when BOTH timestamps parse and the
+ // decision does not precede the filing (a clock-skewed or hand-edited record);
+ // summarizeDurations drops the NaN/negative values for us.
+ const latency = (entries) => summarizeDurations(
+ entries.map(({ record, decidedMs }) => {
+ const filedMs = parsedMs(record.filedAt);
+ return filedMs === null ? NaN : decidedMs - filedMs;
+ })
+ );
+
+ // --- Right-now snapshot: what is awaiting a human decision -------------------
+ // Deliberately NOT windowed: a proposal that has sat undecided for 40 days is the
+ // single most important thing in this block, and a window would hide it.
+ const pending = records.filter(r => !r.outcome);
+ const byAge = Object.create(null);
+ for (const days of LI_APPROVAL_DELAY_BUCKET_DAYS) byAge[delayBucketKey(days)] = 0;
+ let oldestAgeMs = null;
+ let undatedPending = 0;
+ for (const r of pending) {
+ const filedMs = parsedMs(r.filedAt);
+ if (filedMs === null) { undatedPending += 1; continue; }
+ const ageMs = now - filedMs;
+ if (oldestAgeMs === null || ageMs > oldestAgeMs) oldestAgeMs = ageMs;
+ // CUMULATIVE buckets: a 9-day-old proposal counts in 1d, 3d AND 7d, so the three
+ // numbers read as a decay curve. `>=` so an age exactly at the threshold counts —
+ // "older than 1 day" at precisely 24h is past the mark, not short of it.
+ for (const days of LI_APPROVAL_DELAY_BUCKET_DAYS) {
+ if (ageMs >= days * DAY) byAge[delayBucketKey(days)] += 1;
+ }
+ }
+
+ return {
+ windowMs,
+ windowDays: Math.round(windowMs / DAY),
+ window: {
+ decided: decidedInWindow.length,
+ approved: approvedInWindow.length,
+ rejected: countOutcome('rejected'),
+ abandoned: countOutcome('abandoned'),
+ // Decisions the store holds but cannot date — reported so a window that looks
+ // empty is distinguishable from a store full of undatable verdicts.
+ undated: undatedDecisions,
+ // Null, never 0, when the user decided nothing in the window.
+ approvalRate: decidedInWindow.length > 0
+ ? (approvedInWindow.length / decidedInWindow.length) * 100
+ : null,
+ timeToDecision: latency(decidedInWindow),
+ timeToApproval: latency(approvedInWindow)
+ },
+ pending: {
+ count: pending.length,
+ oldestAgeMs,
+ undated: undatedPending,
+ byAge
+ },
+ proposalPhase: {
+ totalFiled: records.length,
+ totalDecided: decided.length,
+ totalPending: pending.length,
+ // The proposal-phase analogue of a delivery rate: of everything LI filed, what
+ // share ever got a human verdict? Null (not 0) when nothing has been filed.
+ decisionRate: records.length > 0 ? (decided.length / records.length) * 100 : null
+ }
+ };
+}
+
+/**
+ * Render the funnel as the lines folded into the `liSelfEval` block (#3120), so the
+ * reasoner sees its own approval bottleneck on EVERY run rather than only in a dashboard.
+ *
+ * Takes the SAME three-valued `outcomes` argument `computeSelfEvalSummary` receives:
+ * - not an array → the outcomes source is off / the store was unreadable. Reported as
+ * UNAVAILABLE. A failed read must never render as a clean zero-proposal funnel.
+ * - `[]` → read fine, genuinely nothing filed. Reported as such.
+ * Returns an array of lines (never a bare string) so the caller splices them into its
+ * own list without re-splitting.
+ */
+export function formatApprovalFunnelLines({ outcomes = null, now = Date.now(), windowMs = LI_APPROVAL_FUNNEL_WINDOW_MS } = {}) {
+ if (!Array.isArray(outcomes)) {
+ return ['- LI approval funnel: UNAVAILABLE — no outcome history was gathered this run, so how your proposals move through human review is unknown.'];
+ }
+ const funnel = computeApprovalFunnel(outcomes, { now, windowMs });
+ if (funnel.proposalPhase.totalFiled === 0) {
+ return [`- LI approval funnel: no proposals filed yet for this app — nothing has entered human review, so there is no approval bottleneck to read (this is an empty history, NOT a failed read).`];
+ }
+
+ const { window, pending, proposalPhase, windowDays } = funnel;
+ const lines = [];
+
+ lines.push(
+ `- LI approval rate (last ${windowDays}d): `
+ + (window.approvalRate === null
+ // Deliberately free of any literal percentage: an idle approver means the rate is
+ // UNKNOWN, and even a rate quoted inside a disclaimer is a number the reasoner can
+ // latch onto as its own record.
+ ? `no decisions in the window — ${proposalPhase.totalPending} proposal(s) awaiting review; rate unknown. An idle approver is not a poor approval rate.`
+ : `${Math.round(window.approvalRate)}% — ${window.approved} of ${window.decided} decisions were approvals`
+ + `${window.rejected ? `, ${window.rejected} rejected` : ''}${window.abandoned ? `, ${window.abandoned} abandoned` : ''}.`)
+ + (window.undated ? ` (${window.undated} recorded decision(s) carry no usable timestamp and are excluded from the window.)` : '')
+ );
+
+ lines.push(
+ '- LI time-to-decision: '
+ + (window.timeToDecision.medianMs === null
+ ? 'no dated decision in the window — median unknown.'
+ : `median ${formatDuration(window.timeToDecision.medianMs)} from filing to a human decision (p90 ${formatDuration(window.timeToDecision.p90Ms)}, ${window.timeToDecision.count} decided).`)
+ + (window.timeToApproval.medianMs === null
+ ? ' No approval in the window, so time-to-APPROVAL is unknown.'
+ : ` Median time-to-APPROVAL ${formatDuration(window.timeToApproval.medianMs)} (${window.timeToApproval.count} approved).`)
+ );
+
+ // "Pending human review" indicator — emitted ONLY when something is actually pending
+ // (the issue's explicit requirement). A "0 awaiting review" line every run would be
+ // noise, and worse, would read as reassurance in exactly the case where the real
+ // signal is elsewhere.
+ if (pending.count > 0) {
+ const stalled = LI_APPROVAL_DELAY_BUCKET_DAYS
+ .map(days => ({ days, count: pending.byAge[delayBucketKey(days)] }))
+ .filter(({ count }) => count > 0)
+ .map(({ days, count }) => `${count} past ${days}d`)
+ .join(', ');
+ lines.push(
+ `- PENDING HUMAN REVIEW: ${pending.count} filed proposal(s) are awaiting your approver's decision`
+ + `${stalled ? ` (${stalled})` : ''}`
+ + `${pending.oldestAgeMs === null ? '' : `; oldest has waited ${formatDuration(pending.oldestAgeMs)}`}.`
+ + `${pending.undated ? ` ${pending.undated} of them carry no usable filing date and are excluded from the age buckets.` : ''}`
+ // The actionable read: an approval backlog means the constraint is human review
+ // capacity, not idea supply. Filing more into a full queue lowers the odds any of
+ // it is read — so the correct response is a higher bar, not more volume.
+ + `${pending.byAge[delayBucketKey(LI_APPROVAL_DELAY_BUCKET_DAYS.at(-1))] > 0
+ ? ` Proposals are sitting past ${LI_APPROVAL_DELAY_BUCKET_DAYS.at(-1)} days without a verdict — your bottleneck is human review, not idea supply. Adding to this queue makes it LESS likely any of it is read: file only something clearly more valuable than what is already waiting, or return proposal: null.`
+ : ''}`
+ );
+ }
+
+ lines.push(
+ `- LI proposal-phase throughput (distinct from the cosMetrics agent-task lifecycle): `
+ + `${proposalPhase.totalDecided} of ${proposalPhase.totalFiled} filed proposals have received any verdict`
+ // The percentage is only rendered once a verdict exists. At zero decisions the
+ // fraction already says everything ("0 of 2"), and a bare "0%" in the self-eval
+ // block reads to the reasoner as a failure verdict on a pipeline that may simply be
+ // young — the same reason `computeSelfEvalSummary` keeps an unresolved merge rate
+ // out of percentage form. The computed `decisionRate` is unchanged for the
+ // queryable route payload, where a numeric 0 over a real denominator is correct.
+ + `${proposalPhase.totalDecided > 0 ? ` (${Math.round(proposalPhase.decisionRate)}%)` : ''}`
+ + `${proposalPhase.totalPending ? `; ${proposalPhase.totalPending} still unjudged` : ''}.`
+ );
+
+ return lines;
+}
diff --git a/server/services/layeredIntelligence/approvalFunnel.test.js b/server/services/layeredIntelligence/approvalFunnel.test.js
new file mode 100644
index 0000000000..c4c4991639
--- /dev/null
+++ b/server/services/layeredIntelligence/approvalFunnel.test.js
@@ -0,0 +1,254 @@
+import { describe, it, expect } from 'vitest';
+import { computeApprovalFunnel, formatApprovalFunnelLines, delayBucketKey } from './approvalFunnel.js';
+import { summarizeDurations } from './awareness.js';
+import { LI_APPROVAL_DELAY_BUCKET_DAYS, LI_APPROVAL_FUNNEL_WINDOW_MS } from './constants.js';
+import { DAY } from '../../lib/fileUtils.js';
+
+// A fixed clock so every age/window assertion is deterministic.
+const NOW = Date.parse('2026-07-20T12:00:00.000Z');
+const iso = (msAgo) => new Date(NOW - msAgo).toISOString();
+
+// Records use invented placeholder slugs/scopes — never live instance data.
+const pendingRecord = (slug, filedMsAgo) => ({
+ appId: 'app-example', slug, scope: 'app-improvement', filedAt: iso(filedMsAgo), outcome: null, outcomeAt: null
+});
+const decidedRecord = (slug, outcome, filedMsAgo, decidedMsAgo) => ({
+ appId: 'app-example', slug, scope: 'app-improvement', filedAt: iso(filedMsAgo), outcome, outcomeAt: iso(decidedMsAgo)
+});
+
+describe('computeApprovalFunnel (#3120)', () => {
+ it('reports null rates — never zeros — for an EMPTY proposal set', () => {
+ const funnel = computeApprovalFunnel([], { now: NOW });
+ // A zero-proposal window must not read as a failure: every rate is the null
+ // sentinel, and the counts are honestly zero.
+ expect(funnel.window.approvalRate).toBeNull();
+ expect(funnel.window.timeToDecision).toMatchObject({ count: 0, medianMs: null, p90Ms: null });
+ expect(funnel.window.timeToApproval.medianMs).toBeNull();
+ expect(funnel.pending).toMatchObject({ count: 0, oldestAgeMs: null, undated: 0 });
+ expect(funnel.proposalPhase).toMatchObject({ totalFiled: 0, totalDecided: 0, totalPending: 0, decisionRate: null });
+ });
+
+ it('treats a non-array (failed read) the same as empty at the math layer', () => {
+ // The read/empty distinction is the FORMATTER's job (asserted below); the pure
+ // math must not throw on a null and must not invent records.
+ expect(computeApprovalFunnel(null, { now: NOW }).proposalPhase.totalFiled).toBe(0);
+ expect(computeApprovalFunnel(undefined, { now: NOW }).pending.count).toBe(0);
+ });
+
+ it('computes a 100% approval rate when every windowed decision was an approval', () => {
+ const outcomes = [
+ decidedRecord('alpha', 'merged', 3 * DAY, 2 * DAY),
+ decidedRecord('beta', 'merged', 5 * DAY, DAY)
+ ];
+ const funnel = computeApprovalFunnel(outcomes, { now: NOW });
+ expect(funnel.window).toMatchObject({ decided: 2, approved: 2, rejected: 0, abandoned: 0, approvalRate: 100 });
+ expect(funnel.pending.count).toBe(0);
+ expect(funnel.proposalPhase).toMatchObject({ totalFiled: 2, totalDecided: 2, totalPending: 0, decisionRate: 100 });
+ // Median over an ODD sample is the middle value: durations are 1d and 4d.
+ expect(funnel.window.timeToDecision.count).toBe(2);
+ expect(funnel.window.timeToApproval.medianMs).toBe(Math.round((DAY + 4 * DAY) / 2));
+ });
+
+ it('keeps the approval rate NULL when everything is pending (not 0%)', () => {
+ const outcomes = [pendingRecord('alpha', 2 * DAY), pendingRecord('beta', 4 * DAY)];
+ const funnel = computeApprovalFunnel(outcomes, { now: NOW });
+ // The decisive assertion: an idle approver is unknown, not a 0% approval rate.
+ expect(funnel.window.approvalRate).toBeNull();
+ expect(funnel.window.decided).toBe(0);
+ expect(funnel.pending).toMatchObject({ count: 2, oldestAgeMs: 4 * DAY });
+ expect(funnel.proposalPhase).toMatchObject({ totalFiled: 2, totalDecided: 0, decisionRate: 0 });
+ });
+
+ it('averages the two middle values for an EVEN-count median', () => {
+ // Four decisions with filing-to-decision latencies of 1d, 2d, 4d, 8d → median 3d.
+ const outcomes = [
+ decidedRecord('a', 'merged', 10 * DAY, 9 * DAY), // 1d
+ decidedRecord('b', 'rejected', 9 * DAY, 7 * DAY), // 2d
+ decidedRecord('c', 'merged', 8 * DAY, 4 * DAY), // 4d
+ decidedRecord('d', 'abandoned', 10 * DAY, 2 * DAY) // 8d
+ ];
+ const funnel = computeApprovalFunnel(outcomes, { now: NOW });
+ expect(funnel.window).toMatchObject({ decided: 4, approved: 2, rejected: 1, abandoned: 1, approvalRate: 50 });
+ expect(funnel.window.timeToDecision.count).toBe(4);
+ expect(funnel.window.timeToDecision.medianMs).toBe(3 * DAY);
+ // Approvals alone (1d, 4d) — also even, so also a mean of the middle pair.
+ expect(funnel.window.timeToApproval.medianMs).toBe(Math.round((DAY + 4 * DAY) / 2));
+ });
+
+ it('counts a pending proposal at EXACTLY 1/3/7 days in the boundary buckets', () => {
+ const outcomes = [
+ pendingRecord('exactly-1d', 1 * DAY),
+ pendingRecord('exactly-3d', 3 * DAY),
+ pendingRecord('exactly-7d', 7 * DAY),
+ pendingRecord('fresh', 6 * 60 * 60 * 1000)
+ ];
+ const { pending } = computeApprovalFunnel(outcomes, { now: NOW });
+ // CUMULATIVE and inclusive at the boundary: the 7d record counts in all three,
+ // the 3d record in 1d+3d, the 1d record only in 1d, and the 6h record in none.
+ expect(pending.byAge[delayBucketKey(1)]).toBe(3);
+ expect(pending.byAge[delayBucketKey(3)]).toBe(2);
+ expect(pending.byAge[delayBucketKey(7)]).toBe(1);
+ expect(pending.count).toBe(4);
+ expect(pending.oldestAgeMs).toBe(7 * DAY);
+ });
+
+ it('windows on the DECISION date, so an old decision outside the window is excluded', () => {
+ const outsideMsAgo = LI_APPROVAL_FUNNEL_WINDOW_MS + DAY;
+ const outcomes = [
+ decidedRecord('old-reject', 'rejected', outsideMsAgo + DAY, outsideMsAgo),
+ decidedRecord('recent-merge', 'merged', 60 * DAY, DAY)
+ ];
+ const funnel = computeApprovalFunnel(outcomes, { now: NOW });
+ // Only the in-window decision counts → 100%, even though lifetime is 50%. A
+ // long-open-then-approved proposal still belongs to the window it was DECIDED in.
+ expect(funnel.window).toMatchObject({ decided: 1, approved: 1, approvalRate: 100 });
+ // Proposal-phase throughput is lifetime, so it still sees both.
+ expect(funnel.proposalPhase).toMatchObject({ totalFiled: 2, totalDecided: 2, decisionRate: 100 });
+ });
+
+ it('does NOT hide a long-stalled pending proposal behind the window', () => {
+ const outcomes = [pendingRecord('ancient', 40 * DAY)];
+ const { pending } = computeApprovalFunnel(outcomes, { now: NOW });
+ expect(pending.count).toBe(1);
+ expect(pending.byAge[delayBucketKey(7)]).toBe(1);
+ expect(pending.oldestAgeMs).toBe(40 * DAY);
+ });
+
+ it('segregates undatable records instead of laundering them into a bucket', () => {
+ const outcomes = [
+ { appId: 'app-example', slug: 'no-filed-date', filedAt: null, outcome: null, outcomeAt: null },
+ { appId: 'app-example', slug: 'no-decision-date', filedAt: iso(5 * DAY), outcome: 'merged', outcomeAt: 'not-a-date' },
+ pendingRecord('dated', 2 * DAY)
+ ];
+ const funnel = computeApprovalFunnel(outcomes, { now: NOW });
+ expect(funnel.pending).toMatchObject({ count: 2, undated: 1, oldestAgeMs: 2 * DAY });
+ // The undated decision is excluded from the window (rate stays null) but is
+ // reported so an "empty window" is distinguishable from undatable history.
+ expect(funnel.window).toMatchObject({ decided: 0, undated: 1, approvalRate: null });
+ expect(funnel.proposalPhase).toMatchObject({ totalFiled: 3, totalDecided: 1 });
+ });
+
+ it('drops a decision that predates its filing rather than reporting a negative latency', () => {
+ const outcomes = [decidedRecord('skewed', 'merged', 2 * DAY, 5 * DAY)];
+ const funnel = computeApprovalFunnel(outcomes, { now: NOW });
+ expect(funnel.window).toMatchObject({ decided: 1, approved: 1, approvalRate: 100 });
+ // The verdict still counts toward the rate; only its unusable latency is dropped.
+ expect(funnel.window.timeToDecision).toMatchObject({ count: 0, medianMs: null });
+ });
+
+ it('honors an injected window span', () => {
+ const outcomes = [decidedRecord('mid', 'merged', 6 * DAY, 5 * DAY)];
+ expect(computeApprovalFunnel(outcomes, { now: NOW, windowMs: 3 * DAY }).window.approvalRate).toBeNull();
+ expect(computeApprovalFunnel(outcomes, { now: NOW, windowMs: 10 * DAY }).window.approvalRate).toBe(100);
+ });
+
+ it('seeds every configured delay bucket even when nothing is pending', () => {
+ const { pending } = computeApprovalFunnel([decidedRecord('a', 'merged', 2 * DAY, DAY)], { now: NOW });
+ for (const days of LI_APPROVAL_DELAY_BUCKET_DAYS) {
+ expect(pending.byAge[delayBucketKey(days)]).toBe(0);
+ }
+ });
+});
+
+describe('formatApprovalFunnelLines (#3120)', () => {
+ it('reports UNAVAILABLE for a failed/absent read, never a clean empty funnel', () => {
+ const lines = formatApprovalFunnelLines({ outcomes: null, now: NOW });
+ expect(lines.join('\n')).toContain('LI approval funnel: UNAVAILABLE');
+ // A failed read must NOT render a pending indicator or a rate.
+ expect(lines.join('\n')).not.toContain('PENDING HUMAN REVIEW');
+ });
+
+ it('distinguishes a genuinely empty history from a failed read', () => {
+ const text = formatApprovalFunnelLines({ outcomes: [], now: NOW }).join('\n');
+ expect(text).toContain('no proposals filed yet');
+ expect(text).toContain('NOT a failed read');
+ });
+
+ it('omits the pending indicator entirely when nothing is awaiting review', () => {
+ const text = formatApprovalFunnelLines({
+ outcomes: [decidedRecord('a', 'merged', 3 * DAY, 2 * DAY)],
+ now: NOW
+ }).join('\n');
+ expect(text).not.toContain('PENDING HUMAN REVIEW');
+ expect(text).toContain('LI approval rate');
+ });
+
+ it('shows the pending count with its age buckets when the count is > 0', () => {
+ const text = formatApprovalFunnelLines({
+ outcomes: [pendingRecord('stalled', 9 * DAY), pendingRecord('fresh', 2 * 60 * 60 * 1000)],
+ now: NOW
+ }).join('\n');
+ expect(text).toContain('PENDING HUMAN REVIEW: 2 filed proposal(s)');
+ expect(text).toContain('1 past 1d');
+ expect(text).toContain('1 past 7d');
+ // Past the last bucket → the "your bottleneck is human review" guidance arms.
+ expect(text).toContain('bottleneck is human review');
+ });
+
+ it('does not arm the bottleneck guidance for a young pending queue', () => {
+ const text = formatApprovalFunnelLines({
+ outcomes: [pendingRecord('fresh', 2 * 60 * 60 * 1000)],
+ now: NOW
+ }).join('\n');
+ expect(text).toContain('PENDING HUMAN REVIEW: 1 filed proposal(s)');
+ expect(text).not.toContain('bottleneck is human review');
+ });
+
+ it('says the rate is unknown — not 0% — when the window holds no decision', () => {
+ const text = formatApprovalFunnelLines({
+ outcomes: [pendingRecord('alpha', 2 * DAY)],
+ now: NOW
+ }).join('\n');
+ expect(text).toContain('rate unknown');
+ expect(text).not.toContain('0% —');
+ });
+
+ it('never renders a bare 0% when nothing has been decided yet', () => {
+ // A young pipeline must not be told it is at 0% — the fraction ("0 of 2") carries
+ // the fact without the failure verdict a percentage implies.
+ const text = formatApprovalFunnelLines({
+ outcomes: [pendingRecord('a', DAY), pendingRecord('b', 2 * DAY)],
+ now: NOW
+ }).join('\n');
+ expect(text).not.toContain('0%');
+ expect(text).toContain('0 of 2 filed proposals have received any verdict');
+ });
+
+ it('DOES render 0% when the approver really rejected everything in the window', () => {
+ // The inverse of the case above: a measured 0% approval rate over real decisions is
+ // evidence, and must be stated plainly rather than softened into "unknown".
+ const text = formatApprovalFunnelLines({
+ outcomes: [decidedRecord('a', 'rejected', 4 * DAY, 3 * DAY), decidedRecord('b', 'rejected', 3 * DAY, DAY)],
+ now: NOW
+ }).join('\n');
+ expect(text).toContain('LI approval rate (last 14d): 0% — 0 of 2 decisions were approvals');
+ });
+
+ it('names the proposal-phase line as distinct from cosMetrics', () => {
+ const text = formatApprovalFunnelLines({
+ outcomes: [decidedRecord('a', 'merged', 3 * DAY, 2 * DAY), pendingRecord('b', DAY)],
+ now: NOW
+ }).join('\n');
+ expect(text).toContain('LI proposal-phase throughput (distinct from the cosMetrics agent-task lifecycle)');
+ expect(text).toContain('1 of 2 filed proposals have received any verdict');
+ });
+});
+
+describe('summarizeDurations (shared duration stats)', () => {
+ it('returns nulls with count 0 for an empty sample', () => {
+ expect(summarizeDurations([])).toEqual({ count: 0, averageMs: null, medianMs: null, p90Ms: null, minMs: null, maxMs: null });
+ });
+
+ it('drops NaN and negative values rather than treating them as 0ms', () => {
+ expect(summarizeDurations([NaN, -5, 10])).toMatchObject({ count: 1, medianMs: 10, minMs: 10, maxMs: 10 });
+ });
+
+ it('averages the middle pair for an even sample and takes the middle for an odd one', () => {
+ expect(summarizeDurations([4, 1, 3, 2]).medianMs).toBe(3); // mean of 2 and 3 → 2.5 → 3
+ expect(summarizeDurations([5, 1, 3]).medianMs).toBe(3);
+ });
+
+ it('takes p90 at the nearest rank', () => {
+ expect(summarizeDurations([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).p90Ms).toBe(9);
+ });
+});
diff --git a/server/services/layeredIntelligence/awareness.js b/server/services/layeredIntelligence/awareness.js
index 167fee41cd..d94937c3f5 100644
--- a/server/services/layeredIntelligence/awareness.js
+++ b/server/services/layeredIntelligence/awareness.js
@@ -197,6 +197,39 @@ export function computeExecutionByDomain(outcomes = []) {
return byDomain;
}
+/**
+ * Summarize a list of millisecond durations into the `{ count, averageMs, medianMs,
+ * p90Ms, minMs, maxMs }` shape every LI duration report uses. Pure; shared by the
+ * post-approval filed-to-completed durations and the approval-funnel time-to-decision
+ * medians (#3120) so the two can never disagree on how a median or p90 is picked.
+ *
+ * The input is filtered to finite, non-negative values (a record with an unparseable
+ * timestamp yields NaN and must not be laundered into a 0ms duration) and sorted, so
+ * callers can pass raw differences. An EMPTY sample reports `count: 0` with NULL
+ * statistics — the sentinel rule: "nothing has completed yet" is not "it completed
+ * instantly". The median of an even-length sample is the rounded mean of the two middle
+ * values; p90 is the nearest-rank value at ceil(n * 0.9).
+ */
+export function summarizeDurations(values = []) {
+ const durations = (Array.isArray(values) ? values : [])
+ .filter(value => Number.isFinite(value) && value >= 0)
+ .sort((a, b) => a - b);
+ if (durations.length === 0) {
+ return { count: 0, averageMs: null, medianMs: null, p90Ms: null, minMs: null, maxMs: null };
+ }
+ const median = durations.length % 2 === 1
+ ? durations[Math.floor(durations.length / 2)]
+ : Math.round((durations[(durations.length / 2) - 1] + durations[durations.length / 2]) / 2);
+ return {
+ count: durations.length,
+ averageMs: Math.round(durations.reduce((sum, value) => sum + value, 0) / durations.length),
+ medianMs: median,
+ p90Ms: durations[Math.max(0, Math.ceil(durations.length * 0.9) - 1)],
+ minMs: durations[0],
+ maxMs: durations.at(-1)
+ };
+}
+
/**
* Summarize what happens after a proposal has been approved/merged. The existing
* outcome store already persists both sides of this lifecycle: `outcome: 'merged'`
@@ -231,27 +264,9 @@ export function computePostApprovalCompletion(outcomes = []) {
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)
- };
+ const duration = summarizeDurations(
+ completedRecords.map(record => Date.parse(record.executionAt) - Date.parse(record.filedAt))
+ );
return {
approved: records.length,
completed,
diff --git a/server/services/layeredIntelligence/constants.js b/server/services/layeredIntelligence/constants.js
index fd84d295c0..e7c99ee1d2 100644
--- a/server/services/layeredIntelligence/constants.js
+++ b/server/services/layeredIntelligence/constants.js
@@ -172,6 +172,22 @@ export const LI_DEGRADED_MIN_SAMPLE = 4;
// CONFIDENT read (>= LI_DEGRADED_MIN_SAMPLE runs) — a cold loop is never locked out.
export const LI_HARD_GATE_EXECUTION_THRESHOLD = 75;
+// Sliding window for the approval-funnel metrics (#3120) — the span over which the
+// approval rate and the time-to-decision medians are measured. Deliberately SHORTER
+// than the 30-day record retention (CLOSED_SUPPRESSION_MS, which is the hard ceiling on
+// what the store can still see): a window equal to retention would make the "recent"
+// rate identical to the lifetime rate summarizeOutcomeStats already reports, so it would
+// never move when the user's triage behavior changes. Two weeks is long enough to hold
+// several proposals from a loop that files at most one per run, short enough that a
+// change in triage habits shows up within a couple of runs.
+export const LI_APPROVAL_FUNNEL_WINDOW_MS = 14 * DAY;
+
+// Age thresholds (in days) for the approver-delay buckets (#3120): how many proposals
+// are sitting undecided past each mark. CUMULATIVE and ascending — a proposal 9 days old
+// counts in all three — so the buckets read as a decay curve rather than a partition.
+// Ascending order is load-bearing for the rendered line and the bucket keys.
+export const LI_APPROVAL_DELAY_BUCKET_DAYS = [1, 3, 7];
+
// Approved proposals need a separate evidence floor from LI's own reasoning runs:
// a single accepted proposal that is still awaiting execution is not enough evidence
// to lock the loop out of self-directed work. Once five approvals exist, a poor
diff --git a/server/services/layeredIntelligence/outcomes.js b/server/services/layeredIntelligence/outcomes.js
index 8be744365b..c5a4b1de1c 100644
--- a/server/services/layeredIntelligence/outcomes.js
+++ b/server/services/layeredIntelligence/outcomes.js
@@ -17,6 +17,7 @@ import {
} from './constants.js';
import { normalizeSlug, extractSlugFromBody, isIssueWithinDedupWindow } from './dedup.js';
import { computePostApprovalCompletion, scopeKeyOf } from './awareness.js';
+import { formatApprovalFunnelLines } from './approvalFunnel.js';
/**
* Derive a resolved outcome for a filed proposal from its live tracker issue.
@@ -453,6 +454,10 @@ export function describeSuppressedIssue(issue, reasonBySlug = null) {
* 1. Proposal merge rate — do the user's triage decisions validate my picks?
* 2. Already-filed proposals — what have I said already that I must not repeat?
* 3. LI execution health — are my own agent runs even succeeding?
+ * Plus the APPROVAL FUNNEL (#3120) — approval rate over a sliding window, the
+ * pending-human-review backlog and its age buckets, time-to-decision, and
+ * proposal-phase throughput. Reported alongside the three but NOT counted toward
+ * `confidence`: it measures the approver's throughput, not LI's self-knowledge.
*
* Unlike computeOutcomesReport this ALWAYS returns a block when called: "you are
* reasoning with no signal about yourself, hold a higher bar" is the single most
@@ -636,6 +641,17 @@ export function computeSelfEvalSummary({
);
}
+ // --- Signal 4: where are my proposals stuck in HUMAN review? ----------------
+ // The approval funnel (#3120): approval rate over a sliding window, the pending-review
+ // backlog with its age buckets, time-to-decision, and proposal-phase throughput. This
+ // is the one signal above that is about the APPROVER rather than about LI — a full
+ // review queue is a reason to file less, which no merge rate or delivery rate shows.
+ // Deliberately NOT folded into the confidence count below: the funnel measures the
+ // human's throughput, and "my approver is behind" is not evidence about LI's own
+ // reasoning quality, so letting it raise `confidence` would misreport the loop's
+ // self-knowledge. It carries its own guidance inline instead.
+ lines.push(...formatApprovalFunnelLines({ outcomes, now }));
+
// --- Confidence: how much do I actually know about myself? ------------------
// Purely a count of PRESENT signals — it rates the evidence available to the
// reasoner, NOT whether that evidence is flattering. A loop with a well-measured
diff --git a/server/services/layeredIntelligenceBarrel.test.js b/server/services/layeredIntelligenceBarrel.test.js
index ebbc47b0fb..e039236746 100644
--- a/server/services/layeredIntelligenceBarrel.test.js
+++ b/server/services/layeredIntelligenceBarrel.test.js
@@ -61,6 +61,7 @@ describe('layeredIntelligence barrel re-exports (issue #2842)', () => {
'computeHardExclusionGate', 'computeHardExclusionNotice', 'buildPrompt',
'gatherSources', 'gatherPlannedWork', 'readLiTaskMetrics',
'computeDeliveryMetrics', 'renderCosMetricsSource',
+ 'computeApprovalFunnel', 'formatApprovalFunnelLines', 'summarizeDurations',
'listForgeIssues', 'fileProposalToForge', 'listJiraIssues',
'fileProposalToJira', 'appendProposalToPlan', 'extractPlanSlugs',
]) {