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: add LI delivery proposal throttle (#3160)
[._.]/ Adam Eivy80d5188c05c0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 079816d15c..081d255f67 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -82,6 +82,7 @@## Layered Intelligence+- **[issue-3160] The self-improvement loop now regulates how quickly it proposes work based on how reliably approved proposals get delivered.** Every run receives one clear filing throttle — full, a proportional percentage, stopped, or unavailable — derived from the current approval-to-completion rate and evidence count. A delivery rate below 20% after five approvals, or a sample still too small to trust, explicitly tells the loop to file nothing instead of adding to the undelivered queue; healthy delivery restores full proposal capacity at 75%.- **[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. Only a decision your tracker actually timestamped counts toward the window and the median — a PLAN.md item checked off months ago but first noticed today is recorded as such rather than passed off as a decision made today. 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.diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex 2adaeaffc3..b14ebd5764 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -54,6 +54,7 @@ import {applyJiraBlockingLabel,computeOutcomesReport,computeDeliveryMetrics,+ formatDeliveryThrottleGuidance,renderCosMetricsSource,computeSelfEvalSummary,computeProposalExecutionAwareness,@@ -61,6 +62,7 @@ import {computeHandoffRouting,computeHardExclusionGate,computeHardExclusionNotice,+ computeLiExecutionHealth,readLiTaskMetrics,hasPlannedWorkListing} from '../layeredIntelligence.js'@@ -427,8 +429,15 @@ export async function buildTaskInput({ app } = {}) {? outcomes: await listOutcomes({ appId: app.id }).catch(() => [])const hardExclusionNotice = computeHardExclusionNotice({ liTaskStats, outcomes: noticeOutcomes })-- const prompt = buildPrompt({ app, config, sources, openIssues, isPortos, outcomesReport, selfEvalReport, proposalExecutionReport, crossReferenceReport, hardExclusionNotice }) + buildCompletionContract()+ // Delivery throttle (#3160): unlike the optional selfEval report, this signal is+ // present on every LI prompt. It reads the same direct outcome snapshot as the hard+ // exclusion notice, so turning off the outcomes/selfEval prompt sources cannot hide+ // a stopped delivery pipeline from the reasoner.+ const deliveryThrottleReport = formatDeliveryThrottleGuidance(+ computeLiExecutionHealth(liTaskStats, noticeOutcomes)+ )++ const prompt = buildPrompt({ app, config, sources, openIssues, isPortos, outcomesReport, selfEvalReport, deliveryThrottleReport, proposalExecutionReport, crossReferenceReport, hardExclusionNotice }) + buildCompletionContract()// Option A: surface the fully-resolved LI agent provider/model (from// resolveLiAgentProvider — per-app override, else the resolved schedule pin) so// the generator pins the AGENT to it. Resolving the pin HERE (not delegating itdiff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.jsindex 07428831bf..eac557838c 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js@@ -64,6 +64,7 @@ vi.mock('../layeredIntelligence.js', () => ({delivery: { totalApproved: 3, totalDelivered: 0, currentDeliveryRate: 0 },deliveryByScope: { 'app-improvement': { approved: 3, delivered: 0 } }})),+ formatDeliveryThrottleGuidance: vi.fn(() => 'LI proposal throttle: unavailable — no delivery data'),renderCosMetricsSource: vi.fn(() => 'RE-RENDERED COS METRICS'),// selfEval (#2700). The summary's own semantics (signal sentinels, confidence,// degraded guidance) are unit-tested in layeredIntelligence.test.js; these are@@ -89,6 +90,10 @@ vi.mock('../layeredIntelligence.js', () => ({// path is unaffected.computeHardExclusionGate: vi.fn(() => ({ excluded: false, reason: null })),computeHardExclusionNotice: vi.fn(() => ''),+ computeLiExecutionHealth: vi.fn(() => ({+ rate: null, sample: 0, source: null, confident: false,+ deliveryRate: null, deliverySample: 0, deliveryConfident: false+ })),readLiTaskMetrics: vi.fn().mockResolvedValue({ read: true, metrics: null }),// The predicate's own semantics (listing vs. either sentinel) are unit-tested in// layeredIntelligence.test.js; here it's a spy so the hook's WIRING can be@@ -392,7 +397,17 @@ describe('buildTaskInput', () => {expect(li.computeHardExclusionNotice).toHaveBeenCalledWith(expect.objectContaining({liTaskStats: expect.objectContaining({ read: true })}));- expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({ selfEvalReport: '' }));+ // The delivery throttle is not part of the optional selfEval source: every LI+ // prompt gets it, including this source-off run (#3160).+ expect(li.computeLiExecutionHealth).toHaveBeenCalledWith(+ expect.objectContaining({ read: true }),+ []+ );+ expect(li.formatDeliveryThrottleGuidance).toHaveBeenCalled();+ expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({+ selfEvalReport: '',+ deliveryThrottleReport: expect.stringContaining('LI proposal throttle')+ }));});it('folds the selfEval summary into the prompt when enabled (#2700)', async () => {diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex c4b5e8af1e..f81a2bfeb6 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -50,6 +50,8 @@ import {computePostApprovalCompletion,computeProposalOutcomeMetrics,computeDeliveryMetrics,+ computeDeliveryThrottle,+ formatDeliveryThrottleGuidance,renderCosMetricsSource,COS_METRICS_MAX_CHARS,computeProposalExecutionAwareness,@@ -996,6 +998,48 @@ describe('computeHandoffRouting (#2764 §4)', () => {});});+describe('computeDeliveryThrottle (#3160)', () => {+ const health = (deliveryRate, deliverySample) => ({ deliveryRate, deliverySample });++ it('returns null when delivery data is unavailable', () => {+ expect(computeDeliveryThrottle(null)).toBeNull();+ expect(computeDeliveryThrottle(health(null, 0))).toBeNull();+ expect(computeDeliveryThrottle(health(Number.NaN, 5))).toBeNull();+ });++ it('stops below the evidence floor regardless of the observed rate', () => {+ expect(computeDeliveryThrottle(health(100, LI_DELIVERY_MIN_SAMPLE - 1))).toBe(0);+ expect(computeDeliveryThrottle(health(0, 1))).toBe(0);+ });++ it('stops a sufficiently-sampled delivery rate below 20%', () => {+ expect(computeDeliveryThrottle(health(0, LI_DELIVERY_MIN_SAMPLE))).toBe(0);+ expect(computeDeliveryThrottle(health(19.99, LI_DELIVERY_MIN_SAMPLE))).toBe(0);+ });++ it('scales proportionally from 0% to full throttle at 75%', () => {+ expect(computeDeliveryThrottle(health(20, LI_DELIVERY_MIN_SAMPLE))).toBeCloseTo(20 / 75);+ expect(computeDeliveryThrottle(health(50, 12))).toBeCloseTo(2 / 3);+ expect(computeDeliveryThrottle(health(75, 12))).toBe(1);+ expect(computeDeliveryThrottle(health(100, 12))).toBe(1);+ });++ it('formats full, degraded, stopped, cold-start, and unavailable prompt guidance', () => {+ expect(formatDeliveryThrottleGuidance(health(75, 12)))+ .toContain('LI proposal throttle: full — based on 75% delivery rate from 12 approved proposals');+ expect(formatDeliveryThrottleGuidance(health(50, 12)))+ .toContain('LI proposal throttle: 67% — based on 50% delivery rate from 12 approved proposals');+ expect(formatDeliveryThrottleGuidance(health(0, 12)))+ .toContain('LI proposal throttle: stopped — based on 0% delivery rate from 12 approved proposals');+ expect(formatDeliveryThrottleGuidance(health(0, 12))).toContain('return proposal: null');+ expect(formatDeliveryThrottleGuidance(health(19.99, 12))).toContain('return proposal: null');+ expect(formatDeliveryThrottleGuidance(health(100, LI_DELIVERY_MIN_SAMPLE - 1)))+ .toContain(`at least ${LI_DELIVERY_MIN_SAMPLE} approvals are required before filing resumes`);+ expect(formatDeliveryThrottleGuidance(health(null, 0)))+ .toContain('LI proposal throttle: unavailable');+ });+});+describe('computeLiExecutionHealth (#2824)', () => {const stats = (over = {}) => ({ read: true, metrics: { completed: 10, succeeded: 3, failed: 7, successRate: 30, recentOutcomes: [], ...over } });@@ -1473,6 +1517,18 @@ describe('buildPrompt', () => {expect(withReport).toContain('Filing nothing (proposal: null) is a legitimate');});+ it('injects delivery-throttle guidance under its own prompt heading (#3160)', () => {+ const base = { app, isPortos: false, config: { allowedScopes: ['app-improvement'], rules: '' } };+ expect(buildPrompt(base)).not.toContain('### liDeliveryThrottle');+ const withThrottle = buildPrompt({+ ...base,+ deliveryThrottleReport: 'LI proposal throttle: stopped — based on 0% delivery rate from 12 approved proposals. Return proposal: null.'+ });+ expect(withThrottle).toContain('### liDeliveryThrottle');+ expect(withThrottle).toContain('LI proposal throttle: stopped');+ expect(withThrottle).toContain('Return proposal: null');+ });+it('renders selfEval and outcomes as independent blocks (either can stand alone)', () => {const base = { app, isPortos: false, config: { allowedScopes: ['app-improvement'], rules: '' } };const selfOnly = buildPrompt({ ...base, selfEvalReport: 'self-eval body' });diff --git a/server/services/layeredIntelligence/outcomes.js b/server/services/layeredIntelligence/outcomes.jsindex c5a4b1de1c..1bc06bcbde 100644--- a/server/services/layeredIntelligence/outcomes.js+++ b/server/services/layeredIntelligence/outcomes.js@@ -19,6 +19,14 @@ import { normalizeSlug, extractSlugFromBody, isIssueWithinDedupWindow } from './import { computePostApprovalCompletion, scopeKeyOf } from './awareness.js';import { formatApprovalFunnelLines } from './approvalFunnel.js';+// Delivery throttle thresholds (#3160). Below 20% there is enough evidence that+// LI should stop filing; 75% is the healthy line where its filing budget is fully+// restored. Between those points the score remains deliveryRate / 75, preserving+// the issue's requested proportional 0%-to-75% scale (with the explicit <20% stop+// overriding its otherwise-small non-zero score).+const LI_DELIVERY_THROTTLE_STOP_THRESHOLD = 20;+const LI_DELIVERY_THROTTLE_FULL_THRESHOLD = 75;+/*** Derive a resolved outcome for a filed proposal from its live tracker issue.* Pure — the reconciler feeds it a `{ state, stateReason, closedAt }` issue:@@ -257,6 +265,51 @@ export function computeDeliveryMetrics(outcomes = []) {};}+/**+ * Translate LI's approval-to-completion health into a proposal-filing throttle+ * (#3160). Accepts `computeLiExecutionHealth` output directly.+ *+ * `null` preserves the unavailable-data sentinel. A real but undersized sample is+ * deliberately different: it returns 0, so LI does not expand its proposal queue+ * before it has enough delivery evidence. At/above the sample floor, delivery under+ * 20% is stopped; otherwise the score scales linearly to full throttle at 75%.+ *+ * @param {{ deliveryRate?: number|null, deliverySample?: number }|null} deliveryHealth+ * @returns {number|null} 0..1, or null when delivery health is unavailable.+ */+export function computeDeliveryThrottle(deliveryHealth) {+ const rate = deliveryHealth?.deliveryRate;+ const sample = deliveryHealth?.deliverySample;+ if (!Number.isFinite(rate) || !Number.isFinite(sample) || sample < 0) return null;+ if (sample < LI_DELIVERY_MIN_SAMPLE || rate < LI_DELIVERY_THROTTLE_STOP_THRESHOLD) return 0;+ return Math.min(1, Math.max(0, rate / LI_DELIVERY_THROTTLE_FULL_THRESHOLD));+}++/**+ * Render the numeric delivery throttle as direct prompt guidance. Kept beside the+ * computation so the label and the score cannot drift apart across prompt callers.+ */+export function formatDeliveryThrottleGuidance(deliveryHealth) {+ const score = computeDeliveryThrottle(deliveryHealth);+ if (score === null) {+ return 'LI proposal throttle: unavailable — no approval-to-completion delivery data is available this run. Do not assume the delivery pipeline is healthy.';+ }++ const rawRate = deliveryHealth.deliveryRate;+ const rate = Math.round(rawRate);+ const sample = deliveryHealth.deliverySample;+ const status = score === 0 ? 'stopped' : score === 1 ? 'full' : `${Math.round(score * 100)}%`;+ const basis = `based on ${rate}% delivery rate from ${sample} approved proposal${sample === 1 ? '' : 's'}`;++ if (sample < LI_DELIVERY_MIN_SAMPLE) {+ return `LI proposal throttle: ${status} — ${basis}; at least ${LI_DELIVERY_MIN_SAMPLE} approvals are required before filing resumes. Return proposal: null rather than adding work without a reliable delivery sample.`;+ }+ if (rawRate < LI_DELIVERY_THROTTLE_STOP_THRESHOLD) {+ return `LI proposal throttle: ${status} — ${basis}. Delivery is below ${LI_DELIVERY_THROTTLE_STOP_THRESHOLD}%; return proposal: null rather than adding to the undelivered queue.`;+ }+ return `LI proposal throttle: ${status} — ${basis}. Use this as the filing budget for this run.`;+}+/*** Format the LI outcome-feedback report (#2428) from this app's recorded* proposals + their reconciled outcomes. Pure + side-effect-free: the LI hookdiff --git a/server/services/layeredIntelligence/prompt.js b/server/services/layeredIntelligence/prompt.jsindex f7fbbc6593..a13e69fc89 100644--- a/server/services/layeredIntelligence/prompt.js+++ b/server/services/layeredIntelligence/prompt.js@@ -30,6 +30,8 @@ const BESPOKE_SOURCE_BLOCK_KEYS = new Set(['plannedWork', 'scopeGuidance']);* the TRUE per-proposal-domain execution record #2760 could only approximate (#2765).* `crossReferenceReport` (from computeCrossReferenceAnalysis) is injected as a* `liCrossReference` block that names domains LI proposes well but executes poorly (#2764 §3).+ * `deliveryThrottleReport` is injected as an always-on `liDeliveryThrottle` signal+ * by the LI hook, independent of the optional self-evaluation source (#3160).* `hardExclusionNotice` (from computeHardExclusionNotice, #2824) is injected as a* prominent `liHardExclusions` block ABOVE the allowed scopes when LI's execution* health is degraded — the reasoner-facing mirror of the deterministic filing gate.@@ -37,7 +39,7 @@ const BESPOKE_SOURCE_BLOCK_KEYS = new Set(['plannedWork', 'scopeGuidance']);* appended: the a-priori scope/task-type/goal rule set LI needs from run one, before* any per-app outcome data exists.*/-export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '', selfEvalReport = '', proposalExecutionReport = '', crossReferenceReport = '', hardExclusionNotice = '' }) {+export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '', selfEvalReport = '', deliveryThrottleReport = '', proposalExecutionReport = '', crossReferenceReport = '', hardExclusionNotice = '' }) {const allowed = (config.allowedScopes || []).filter(s =>isScopeAllowed({ scope: s, allowedScopes: config.allowedScopes, isPortos }));@@ -94,6 +96,14 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort? `\n### liSelfEval\n${selfEvalReport.trim()}\n\nWeigh this against the sources above before you commit to a proposal. Filing nothing (proposal: null) is a legitimate, and sometimes the correct, outcome — a marginal issue costs the user triage time and lowers your merge rate further.\n`: '';+ // Delivery throttle (#3160): a single numeric filing signal derived from LI's+ // approval-to-completion health. The hook supplies it on every run, even when the+ // optional selfEval source is off, so a source toggle cannot silently restore full+ // proposal volume while downstream delivery is stopped.+ const deliveryThrottleBlock = (typeof deliveryThrottleReport === 'string' && deliveryThrottleReport.trim())+ ? `\n### liDeliveryThrottle\n${deliveryThrottleReport.trim()}\n`+ : '';+// Scope-awareness (#2760): install-wide completion rates by CoS task TYPE — directional// context for how reliably different KINDS of work get finished here. PortOS-only// (codex P2): these rates are this install's own CoS execution history, meaningless to@@ -157,7 +167,7 @@ ${openList}Gathered sources:${sourceBlocks || (plannedWorkBlock ? '(no other sources available — you may propose an app-data-gap to add telemetry)' : '(no sources available — you may propose an app-data-gap to add telemetry)')}-${plannedWorkBlock}${outcomesBlock}${selfEvalBlock}${scopeGuidanceBlock}${proposalExecutionBlock}${crossReferenceBlock}${playbookBlock}+${plannedWorkBlock}${outcomesBlock}${selfEvalBlock}${deliveryThrottleBlock}${scopeGuidanceBlock}${proposalExecutionBlock}${crossReferenceBlock}${playbookBlock}Respond with JSON only (no markdown fences):{"analysis": "brief reasoning summary",