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: close the LI feedback loop — track proposal outcomes, feed merge rates to the reasoner (#2428)
Adam Eivyb2e6f995756c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b56e6056e2..ca86e8130d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,8 @@## Features+- **Layered Intelligence now learns from its own results — the feedback loop is closed (#2428).** The LI reasoner used to file improvement proposals as tracker issues and then never read back whether they were merged, rejected, or abandoned, so it proposed in a vacuum (re-suggesting scopes with a 0% adoption rate). LI now records every filed proposal in a lightweight per-app outcome store (`data/cos/li-outcomes/`, a `createCollectionStore` collection with per-slug records and 30-day auto-GC), reconciles each proposal's outcome from the live tracker state on the next run (GitHub `stateReason` maps *not-planned* → rejected, any other close → merged; still-open stays unresolved), and folds a merge-rate report — totals, per-scope adoption, common rejection reasons — back into the reasoning prompt with guidance to prefer higher-merge scopes and justify low-merge ones. Gated behind a new `Proposal outcomes` telemetry source toggle in the per-app LI config (default **on** for the PortOS install, **off** for managed apps). No migration needed — the store is created on first use and existing LI behavior is unchanged when the toggle is off.+- **Audio → MIDI transcription now installs its runtime automatically on first use.** Clicking *Transcribe MIDI* (Rounds reference audio) or *MIDI* (Music Video source track) used to dead-end on a toast telling you to run `INSTALL_MUSCRIPTOR=1 bash scripts/setup-image-video.sh` in a terminal. Now, when the MuScriptor venv isn't provisioned yet, PortOS opens an in-app installer that streams the setup line-by-line — the same experience as the image and video model runtimes — and, on completion, automatically runs the transcription you originally asked for. A new `GET /api/midi-runtime/install` endpoint reuses the shared `RuntimeInstallModal`/SSE-install path (in-flight singleton, detached process group so a cancel kills pip/git children, post-install venv re-probe); `useMidiTranscription` catches the `503 MIDI_RUNTIME_MISSING` kickoff, gates the modal, and retries once installed (with a loop guard so a genuinely-failed install surfaces its error instead of relooping).- **PortOS now installs a service worker for offline app-shell loading and low-bandwidth caching** — the modern replacement for the long-deprecated AppCache manifest. After the first online visit, the built app shell (`index.html`) and the content-hashed JS/CSS chunks are cached, so the UI loads instantly on repeat visits, keeps rendering when the server is briefly unreachable (flaky Tailnet links), and stops re-pulling megabytes of vendor JS on every navigation over a slow connection. Google Fonts and static public assets (icons, textures, manifest) are cached too. Real-time and large/dynamic routes — `/api/*`, `/socket.io/*`, and `/data/*` media — are **never** cached, so live data and streamed assets always hit the network (HTTP Range preserved for `/data`). Navigations stay network-first so a fresh build is always picked up when online, and the existing build-id / stale-chunk-reload machinery still handles "the server rebuilt while a tab was open." The worker registers only in a production **secure context** (HTTPS, or `localhost`) — it is a progressive enhancement that silently no-ops over a plain-HTTP Tailnet hostname and in the Vite dev server (where it also tears down any stale worker). Implemented as a hand-rolled worker (`client/public/sw.js`) with no new dependency; registration lives in `client/src/lib/registerServiceWorker.js`. The PWA manifest gained explicit `id`/`scope` for a deterministic installed-app identity.diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsxindex bd0d1c14f3..e80314213e 100644--- a/client/src/components/apps/LayeredIntelligenceTab.jsx+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx@@ -17,7 +17,8 @@ export const LI_SOURCE_FIELDS = [{ key: 'cosMetrics', label: 'CoS metrics', hint: 'Recent autonomous-agent run stats for this app' },{ key: 'healthReport', label: 'Health report', hint: 'Latest health / lint / test summary' },{ key: 'planMd', label: 'PLAN.md', hint: 'The app\'s open work-plan items' },- { key: 'openIssues', label: 'Open issues', hint: 'Currently open tracker issues' }+ { key: 'openIssues', label: 'Open issues', hint: 'Currently open tracker issues' },+ { key: 'outcomes', label: 'Proposal outcomes', hint: 'Past LI proposals + how they fared (merge rate), fed back so the loop calibrates on its own results' }];// The proposal scopes the loop may file. loop-meta / portos-self extend the loopdiff --git a/server/index.js b/server/index.jsindex fc78689aeb..85b3fb5e58 100644--- a/server/index.js+++ b/server/index.js@@ -213,6 +213,7 @@ import { storyBuilderStore } from './services/storyBuilder.js';import { writersRoomStore } from './services/writersRoom/store.js';import { wrWorksDir } from './services/writersRoom/_shared.js';import { mediaCollectionStore } from './services/mediaCollections.js';+import { outcomesStore as liOutcomesStore } from './services/layeredIntelligenceOutcomes.js';import { createPortOSProviderRoutes } from './routes/providers.js';import { createPortOSRunsRoutes } from './routes/runs.js';import { createPortOSPromptsRoutes } from './routes/prompts.js';@@ -277,7 +278,7 @@ await runMigrations({ rootDir: resolveInstallRoot(join(__dirname, '..')) }).catc// but DO NOT crash the server. PortOS is single-user (CLAUDE.md "Security// Model"); a hard exit on startup is worse than a noisy log the user can act// on. Returns per-store statuses for downstream telemetry; we discard them.-await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore]).catch(err => {+await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore(), loraDatasetStore, liOutcomesStore()]).catch(err => {console.error(`❌ Collection version check failed at startup: ${err?.stack ?? err}`);});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 8f382a3c3f..3e949a2fcf 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -126,6 +126,9 @@ export const layeredIntelligenceConfigSchema = z.object({healthReport: z.boolean().optional(),planMd: z.boolean().optional(),openIssues: z.boolean().optional(),+ // Feedback loop (#2428): feed past LI proposals + their tracker outcomes back+ // into the reasoning prompt. Default on for PortOS, off for managed apps.+ outcomes: z.boolean().optional(),// Custom Layer-1 sources. Discriminated on `type`: a repo-relative `file`,// an `http`(s) URL, or a shell `cmd`. All three carry an optional display// `label`. gatherSources also re-enforces the file confinement + thediff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex f4d67d334b..ab59322cf9 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -51,8 +51,10 @@ import {listJiraBlockingIssues,fileProposalToJira,resolveJiraBlockKey,- applyJiraBlockingLabel+ applyJiraBlockingLabel,+ computeOutcomesReport} from '../layeredIntelligence.js'+import { recordFiledProposal, listOutcomes, reconcileOutcomes } from '../layeredIntelligenceOutcomes.js'import { resolveAppWorkTracker } from '../../lib/workTracker.js'import { tryReadFile } from '../../lib/fileUtils.js'import { join } from 'path'@@ -205,11 +207,24 @@ export async function buildTaskInput({ app } = {}) {// Independent reads (app source set vs the tracker's open-issue list) — overlap// them so the non-parked path pays one round-trip, not two.- const [sources, { openIssues }] = await Promise.all([+ const [sources, issuesRead] = await Promise.all([gatherSources(app, config),readIssues({ filer, forgeCli, cwd, jira, config })])- const prompt = buildPrompt({ app, config, sources, openIssues, isPortos }) + buildCompletionContract()+ const { openIssues, existingIssues, trackerReadFailed } = issuesRead++ // Feedback loop (#2428): reconcile past proposals' outcomes against the fresh+ // tracker read, then fold the merge-rate report into the prompt so the reasoner+ // calibrates on its own history. Gated on the per-app `outcomes` source toggle;+ // a failed tracker read skips reconciliation (never mark closed on a blind read).+ let outcomesReport = ''+ if (config.sources?.outcomes) {+ if (!trackerReadFailed) await reconcileOutcomes({ appId: app.id, existingIssues })+ const outcomes = await listOutcomes({ appId: app.id })+ outcomesReport = computeOutcomesReport({ outcomes })+ }++ const prompt = buildPrompt({ app, config, sources, openIssues, isPortos, outcomesReport }) + buildCompletionContract()// Option A: surface the per-app provider/model (resolved onto config in// resolveLiContext) so the generator pins the AGENT to the app's choice — LI// keeps provider/model in taskTypeOverrides, not the global schedule interval.@@ -299,7 +314,7 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {if (success === false) return settle({ action: 'no-op', reason: 'agent-failed' })const ctx = await resolveLiContext(app)- const { isPortos, config, filer, forgeCli, cwd, jira } = ctx+ const { isPortos, config, tracker, filer, forgeCli, cwd, jira } = ctx// The payload IS the reasoner's JSON object (parsed from the sentinel). A null/// malformed payload is the "returned nothing usable" case.@@ -342,6 +357,14 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {reason = nullconst ref = filedRef(filedKey, filedNumber) ?? ''console.log(`📌 Layered Intelligence: ${app.name} filed "${proposal.title}" [${proposal.slug}]${ref ? ` (${ref})` : ''}`)+ // Feedback loop (#2428): remember what we just filed so a later run can+ // read back its outcome. Gated on the app's `outcomes` source toggle.+ if (config.sources?.outcomes) {+ await recordFiledProposal({+ appId: app.id, slug: proposal.slug, tracker: tracker.resolved,+ issueRef: filedRef(filedKey, filedNumber), scope: proposal.scope+ })+ }const issueRef = filedKey || filedNumberif (isHandoffEligible({ proposal, config, filed: issueRef })) {const task = await enqueueHandoff(buildHandoffTask({ app, proposal, issueRef }))diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.jsindex 186b4f152d..1149ec5f84 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js@@ -53,11 +53,21 @@ vi.mock('../layeredIntelligence.js', () => ({listJiraBlockingIssues: vi.fn().mockResolvedValue({ ok: true, issues: [] }),fileProposalToJira: vi.fn().mockResolvedValue({ success: true, key: 'PROJ-1' }),resolveJiraBlockKey: vi.fn(() => null),- applyJiraBlockingLabel: vi.fn().mockResolvedValue({ success: true })+ applyJiraBlockingLabel: vi.fn().mockResolvedValue({ success: true }),+ computeOutcomesReport: vi.fn(() => '')+}));++// Outcome-store I/O (#2428) — spies so the hook's feedback-loop wiring can be+// asserted without touching the real collection store on disk.+vi.mock('../layeredIntelligenceOutcomes.js', () => ({+ recordFiledProposal: vi.fn().mockResolvedValue(true),+ listOutcomes: vi.fn().mockResolvedValue([]),+ reconcileOutcomes: vi.fn().mockResolvedValue(0)}));import { buildTaskInput, processTaskOutput } from './layeredIntelligenceHooks.js';import * as li from '../layeredIntelligence.js';+import { recordFiledProposal, listOutcomes, reconcileOutcomes } from '../layeredIntelligenceOutcomes.js';import * as apps from '../apps.js';import { resolveAppWorkTracker } from '../../lib/workTracker.js';import { getProviderById } from '../providers.js';@@ -138,6 +148,24 @@ describe('buildTaskInput', () => {expect(res.providerId).toBe('ollama');expect(res.model).toBe('qwen');});++ it('skips the outcomes feedback loop when the source toggle is off', async () => {+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: {} });+ await buildTaskInput({ app: APP });+ expect(reconcileOutcomes).not.toHaveBeenCalled();+ expect(listOutcomes).not.toHaveBeenCalled();+ expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({ outcomesReport: '' }));+ });++ it('reconciles + folds the outcomes report into the prompt when enabled', async () => {+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { outcomes: true } });+ listOutcomes.mockResolvedValue([{ slug: 's', outcome: 'merged', scope: 'app-improvement' }]);+ li.computeOutcomesReport.mockReturnValue('Past LI proposals (last 30 days):\n- Total filed: 1');+ await buildTaskInput({ app: APP });+ expect(reconcileOutcomes).toHaveBeenCalledWith(expect.objectContaining({ appId: 'app-1' }));+ expect(listOutcomes).toHaveBeenCalledWith(expect.objectContaining({ appId: 'app-1' }));+ expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({ outcomesReport: expect.stringContaining('Total filed: 1') }));+ });});describe('processTaskOutput', () => {@@ -170,6 +198,26 @@ describe('processTaskOutput', () => {expect(apps.updateAppLayeredIntelligence).toHaveBeenCalledWith('app-1', expect.objectContaining({ lastRunAction: 'filed', lastRunRef: '#77' }));});+ it('records the filed proposal for the feedback loop only when outcomes is enabled', async () => {+ li.validateReasonerResponse.mockReturnValue({+ proposal: { scope: 'app-improvement', slug: 'add-telemetry', title: 'Add telemetry', body: 'do it' },+ pause: null+ });+ li.fileProposalToForge.mockResolvedValue({ success: true, number: 77 });++ // Off: no outcome record written.+ li.getEffectiveConfig.mockReturnValue({ allowedScopes: ['app-improvement'], sources: {} });+ await processTaskOutput({ appId: 'app-1', success: true, payload: { proposal: {} } });+ expect(recordFiledProposal).not.toHaveBeenCalled();++ // On: the filed proposal is recorded with its ref, scope, and tracker.+ li.getEffectiveConfig.mockReturnValue({ allowedScopes: ['app-improvement'], sources: { outcomes: true } });+ await processTaskOutput({ appId: 'app-1', success: true, payload: { proposal: {} } });+ expect(recordFiledProposal).toHaveBeenCalledWith(expect.objectContaining({+ appId: 'app-1', slug: 'add-telemetry', issueRef: '#77', scope: 'app-improvement', tracker: 'github'+ }));+ });+it('suppresses an exact-duplicate proposal without filing', async () => {li.validateReasonerResponse.mockReturnValue({proposal: { scope: 'app-improvement', slug: 'dup', title: 'Dup', body: 'x' },diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex 7b18d1d149..e47194c719 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -78,6 +78,12 @@ export const PROPOSAL_COMPLEXITIES = ['trivial', 'moderate', 'complex'];// lets the loop enqueue a coding agent instead of only filing the issue.export const HANDOFF_COMPLEXITY = 'trivial';+// The resolved outcomes a filed proposal can reach (the feedback loop, #2428).+// A record with a null outcome is still open/unresolved. `abandoned` is reserved+// for a superseded proposal — auto-derivation only distinguishes merged/rejected+// from the tracker's closed state; `abandoned` is set by a user/future path.+export const PROPOSAL_OUTCOMES = ['merged', 'rejected', 'abandoned'];+/*** The default per-app config. PortOS (isPortos) additionally gets the meta/self* scopes so the loop can extend itself; every other app is capped at its own@@ -96,6 +102,11 @@ export function defaultLayeredIntelligenceConfig(isPortos = false) {healthReport: true,planMd: true,openIssues: true,+ // The self-feedback signal (#2428): past LI proposals + their tracker+ // outcomes, fed back so the reasoner calibrates on its own merge rate.+ // Default ON for the PortOS install (it improves itself), OFF for managed+ // apps — the user opts in per-app via the LI config UI.+ outcomes: isPortos,custom: []},rules: '',@@ -394,12 +405,82 @@ export function trackerSupportsPause(resolved) {return filerForTracker(resolved) !== 'plan';}+/**+ * Derive a resolved outcome for a filed proposal from its live tracker issue.+ * Pure — the reconciler feeds it a `{ state, stateReason, closedAt }` issue:+ * - still open (or unknown state) → null (unresolved)+ * - closed as "not planned" → 'rejected'+ * - closed for any other reason → 'merged' (the common auto-close-on-merge+ * path; glab/jira report no stateReason)+ * GitHub reports `stateReason` ('completed' | 'not_planned' | 'reopened'); other+ * forges omit it, so a bare closed issue reads as merged.+ */+export function deriveOutcome(issue) {+ if ((issue?.state || '').toLowerCase() !== 'closed') return null;+ const reason = (issue?.stateReason || '').toLowerCase().replace(/[\s-]+/g, '_');+ if (reason === 'not_planned') return 'rejected';+ return 'merged';+}++/**+ * Format the LI outcome-feedback report (#2428) from this app's recorded+ * proposals + their reconciled outcomes. Pure + side-effect-free: the LI hook+ * loads the outcomes and passes them here, then feeds the string into buildPrompt.+ * Returns '' when there's nothing to report (no filed history) so the caller omits+ * the block entirely rather than injecting an empty section.+ */+export function computeOutcomesReport({ outcomes = [] } = {}) {+ const filed = (Array.isArray(outcomes) ? outcomes : []).filter(o => o && typeof o === 'object');+ if (filed.length === 0) return '';+ const total = filed.length;+ const pct = (n) => Math.round((n / total) * 100);+ const count = (name) => filed.filter(o => o.outcome === name).length;+ const merged = count('merged');+ const rejected = count('rejected');+ const abandoned = count('abandoned');+ const pending = total - merged - rejected - abandoned;++ // Per-scope merge rate — the calibration signal the reasoner acts on.+ const scopes = new Map();+ for (const o of filed) {+ const s = o.scope || 'unknown';+ const agg = scopes.get(s) || { filed: 0, merged: 0 };+ agg.filed += 1;+ if (o.outcome === 'merged') agg.merged += 1;+ scopes.set(s, agg);+ }+ const scopeLines = [...scopes.entries()]+ .sort((a, b) => b[1].filed - a[1].filed)+ .map(([s, v]) => `- ${s}: ${v.filed} filed, ${v.merged} merged (${v.filed ? Math.round((v.merged / v.filed) * 100) : 0}%)`)+ .join('\n');++ const reasons = [...new Set(filed+ .filter(o => o.outcome === 'rejected' && o.outcomeReason)+ .map(o => o.outcomeReason))].slice(0, 5);++ return [+ 'Past LI proposals (last 30 days):',+ `- Total filed: ${total}`,+ `- Merged/implemented: ${merged} (${pct(merged)}%)`,+ `- Rejected: ${rejected} (${pct(rejected)}%)`,+ `- Abandoned: ${abandoned} (${pct(abandoned)}%)`,+ `- Still open: ${pending} (${pct(pending)}%)`,+ '',+ 'By scope:',+ scopeLines || '- (none)',+ '',+ `Common rejection reasons: ${reasons.length ? reasons.join('; ') : 'none'}`+ ].join('\n');+}+/*** Build the JSON-only reasoning prompt for one app. Deterministic: given the* gathered sources, open issues, and config, produces the exact string sent to* the model. Meta/self scopes are only offered when the app is PortOS.+ * `outcomesReport` (from computeOutcomesReport) is injected as a `liOutcomes`+ * block with calibration guidance when non-empty (#2428).*/-export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false }) {+export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '' }) {const allowed = (config.allowedScopes || []).filter(s =>isScopeAllowed({ scope: s, allowedScopes: config.allowedScopes, isPortos }));@@ -416,6 +497,12 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort? '\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': '';+ // Feedback loop (#2428): show the reasoner how its own past proposals fared so+ // it can calibrate scope/merge-rate instead of proposing in a vacuum.+ const outcomesBlock = (typeof outcomesReport === 'string' && outcomesReport.trim())+ ? `\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}Rules & guidance from the operator:@@ -429,7 +516,7 @@ ${openList}Gathered sources:${sourceBlocks || '(no sources available — you may propose an app-data-gap to add telemetry)'}-+${outcomesBlock}Respond with JSON only (no markdown fences):{"analysis": "brief reasoning summary",@@ -667,7 +754,7 @@ export function normalizeIssueState(state) {export async function listForgeIssues({ cli, cwd, env, exec = runCli } = {}) {const args = cli === 'glab'? ['issue', 'list', '--label', LI_LABEL, '--all', '-P', '100', '-F', 'json']- : ['issue', 'list', '--label', LI_LABEL, '--state', 'all', '--limit', '100', '--json', 'number,title,body,state,closedAt,url'];+ : ['issue', 'list', '--label', LI_LABEL, '--state', 'all', '--limit', '100', '--json', 'number,title,body,state,stateReason,closedAt,url'];const { code, stdout } = await exec(cli, args, { cwd, env });if (code !== 0) return { ok: false, issues: [] };if (!stdout.trim()) return { ok: true, issues: [] };@@ -680,6 +767,9 @@ export async function listForgeIssues({ cli, cwd, env, exec = runCli } = {}) {title: i.title || '',body: i.body || i.description || '',state: normalizeIssueState(i.state),+ // GitHub-only: 'completed' | 'not_planned' | 'reopened'. glab omits it, so+ // deriveOutcome falls back to treating any closed issue as merged.+ stateReason: i.stateReason || i.state_reason || null,closedAt: i.closedAt || i.closed_at || null,// gh reports `url`; glab reports `web_url`. Null when neither is present so// the overview's proposal links degrade to a plain count rather than adiff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex 047e691d05..34a4f5fd57 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -28,6 +28,9 @@ import {filerForTracker,trackerSupportsPause,buildPrompt,+ deriveOutcome,+ computeOutcomesReport,+ PROPOSAL_OUTCOMES,extractPlanSlugs,appendProposalToPlan,gatherSources,@@ -79,6 +82,11 @@ describe('defaultLayeredIntelligenceConfig', () => {expect(defaultLayeredIntelligenceConfig(false).handoff).toEqual({ enabled: false });expect(defaultLayeredIntelligenceConfig(true).handoff).toEqual({ enabled: false });});++ it('defaults the outcomes feedback source on for PortOS, off for managed apps', () => {+ expect(defaultLayeredIntelligenceConfig(false).sources.outcomes).toBe(false);+ expect(defaultLayeredIntelligenceConfig(true).sources.outcomes).toBe(true);+ });});describe('getEffectiveConfig', () => {@@ -432,6 +440,62 @@ describe('buildPrompt', () => {expect(on).toContain('Hand-off:');expect(on).toContain('"complexity":"trivial"');});++ it('injects the outcomes report + calibration guidance only when non-empty', () => {+ const base = { app, isPortos: false, config: { allowedScopes: ['app-improvement'], rules: '' } };+ const without = buildPrompt(base);+ expect(without).not.toContain('liOutcomes');+ const withReport = buildPrompt({ ...base, outcomesReport: 'Past LI proposals (last 30 days):\n- Total filed: 3' });+ expect(withReport).toContain('### liOutcomes');+ expect(withReport).toContain('Total filed: 3');+ expect(withReport).toContain('calibrate your proposal');+ });+});++describe('deriveOutcome', () => {+ it('leaves an open issue unresolved', () => {+ expect(deriveOutcome({ state: 'open' })).toBeNull();+ expect(deriveOutcome({ state: 'OPEN', stateReason: 'reopened' })).toBeNull();+ expect(deriveOutcome({})).toBeNull();+ });++ it('maps closed-not-planned to rejected', () => {+ expect(deriveOutcome({ state: 'closed', stateReason: 'not_planned' })).toBe('rejected');+ expect(deriveOutcome({ state: 'closed', stateReason: 'not planned' })).toBe('rejected');+ });++ it('maps any other closed reason (incl. glab/jira with no reason) to merged', () => {+ expect(deriveOutcome({ state: 'closed', stateReason: 'completed' })).toBe('merged');+ expect(deriveOutcome({ state: 'closed' })).toBe('merged');+ });+});++describe('computeOutcomesReport', () => {+ it('returns empty string when there is no filed history', () => {+ expect(computeOutcomesReport({ outcomes: [] })).toBe('');+ expect(computeOutcomesReport({})).toBe('');+ });++ it('summarizes totals, per-scope merge rates, and rejection reasons', () => {+ const outcomes = [+ { scope: 'app-data-gap', outcome: 'merged' },+ { scope: 'app-data-gap', outcome: 'merged' },+ { scope: 'app-improvement', outcome: 'rejected', outcomeReason: 'too complex' },+ { scope: 'app-improvement', outcome: null }+ ];+ const report = computeOutcomesReport({ outcomes });+ expect(report).toContain('Total filed: 4');+ expect(report).toContain('Merged/implemented: 2 (50%)');+ expect(report).toContain('Rejected: 1 (25%)');+ expect(report).toContain('Still open: 1 (25%)');+ expect(report).toContain('app-data-gap: 2 filed, 2 merged (100%)');+ expect(report).toContain('app-improvement: 2 filed, 0 merged (0%)');+ expect(report).toContain('Common rejection reasons: too complex');+ });++ it('exposes the recognized outcome set', () => {+ expect(PROPOSAL_OUTCOMES).toEqual(['merged', 'rejected', 'abandoned']);+ });});describe('extractPlanSlugs', () => {diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.jsnew file mode 100644index 0000000000..8283231fd1--- /dev/null+++ b/server/services/layeredIntelligenceOutcomes.js@@ -0,0 +1,169 @@+/**+ * Layered Intelligence outcome store — closes the loop's feedback gap (#2428).+ *+ * The LI reasoner files improvement proposals as tracker issues but historically+ * never read back whether those proposals were merged, rejected, or abandoned —+ * so it proposed in a vacuum, re-suggesting scopes with a 0% adoption rate. This+ * store records every filed proposal and reconciles its outcome from the live+ * tracker state, so `computeOutcomesReport` (in layeredIntelligence.js) can feed+ * merge-rate statistics back into the reasoning prompt.+ *+ * Storage: a `createCollectionStore` collection at `data/cos/li-outcomes/`, one+ * record per (app, slug). Per-record write queue → concurrent apps' outcomes+ * never clobber each other. Records auto-gc after CLOSED_SUPPRESSION_MS (30 days)+ * so the store stays bounded — the same window the dedup guard already uses.+ *+ * Runs OUTSIDE the request lifecycle (scheduler tick / agent completion), so per+ * the CLAUDE.md no-try/catch rule the LI hooks own the async boundary; these+ * helpers stay defensive (a failed read/write degrades to a recorded no-op) and+ * are gated behind the `sources.outcomes` config toggle by their callers.+ */++import { join } from 'path';+import { PATHS } from '../lib/fileUtils.js';+import { createCollectionStore } from '../lib/collectionStore.js';+import { normalizeSlug, deriveOutcome, PROPOSAL_OUTCOMES, CLOSED_SUPPRESSION_MS } from './layeredIntelligence.js';++// The report/retention window. Reuses the dedup suppression window so a proposal+// stays in the outcome report exactly as long as it still suppresses re-proposal —+// the two "LI remembers this" windows move in lockstep.+export const OUTCOME_RETENTION_MS = CLOSED_SUPPRESSION_MS;++// The collection's on-disk layout version. Bump only via a migration that+// changes the record directory shape (there is none yet).+export const LI_OUTCOMES_SCHEMA_VERSION = 1;++/**+ * Normalize one on-disk outcome record. Drops anything without a usable+ * appId+slug (the identity), coerces the outcome to a known value or null, and+ * defaults the timestamps. Returning null makes collectionStore treat the row as+ * invalid (loadOne → null), so a hand-corrupted file can't poison the report.+ */+export function sanitizeOutcomeRecord(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const appId = typeof raw.appId === 'string' ? raw.appId.trim() : '';+ const slug = normalizeSlug(raw.slug);+ if (!appId || !slug) return null;+ const outcome = PROPOSAL_OUTCOMES.includes(raw.outcome) ? raw.outcome : null;+ return {+ appId,+ slug,+ tracker: typeof raw.tracker === 'string' ? raw.tracker : null,+ issueRef: typeof raw.issueRef === 'string' ? raw.issueRef : (raw.issueRef != null ? String(raw.issueRef) : null),+ scope: typeof raw.scope === 'string' ? raw.scope : null,+ filedAt: typeof raw.filedAt === 'string' ? raw.filedAt : null,+ outcome,+ outcomeAt: outcome && typeof raw.outcomeAt === 'string' ? raw.outcomeAt : null,+ outcomeReason: outcome && typeof raw.outcomeReason === 'string' ? raw.outcomeReason : null+ };+}++// Composite record id — one row per (app, slug). appId matches the app-id regex+// (`[A-Za-z0-9_-]+`) and slug is normalized kebab, so the joined id is always a+// valid collectionStore id; sliced to the store's 128-char ceiling defensively.+function outcomeId(appId, slug) {+ return `${appId}--${slug}`.slice(0, 128);+}++let _store = null;+/**+ * Lazily construct the singleton outcome collection store. Lazy so the module+ * graph doesn't build a store (and touch PATHS) at import time; the boot-time+ * verifier in server/index.js and the LI hooks both call this.+ */+export function outcomesStore() {+ if (!_store) {+ _store = createCollectionStore({+ dir: join(PATHS.cos, 'li-outcomes'),+ type: 'li-outcomes',+ schemaVersion: LI_OUTCOMES_SCHEMA_VERSION,+ sanitizeRecord: sanitizeOutcomeRecord+ });+ }+ return _store;+}++/**+ * Record a freshly-filed proposal (outcome unknown). Idempotent per (app, slug):+ * a re-file overwrites the row with a fresh `filedAt` and clears the outcome, so+ * a re-opened proposal is tracked from its newest filing. Best-effort — a write+ * failure logs and returns false rather than throwing into the LI hook.+ */+export async function recordFiledProposal({ appId, slug, tracker = null, issueRef = null, scope = null, now = Date.now() } = {}, store = outcomesStore()) {+ const normSlug = normalizeSlug(slug);+ if (!appId || !normSlug) return false;+ const record = {+ appId,+ slug: normSlug,+ tracker,+ issueRef: issueRef != null ? String(issueRef) : null,+ scope,+ filedAt: new Date(now).toISOString(),+ outcome: null,+ outcomeAt: null,+ outcomeReason: null+ };+ const ok = await store.saveOne(outcomeId(appId, normSlug), record).then(() => true, (err) => {+ console.error(`❌ Layered Intelligence: failed to record outcome for ${appId}/${normSlug}: ${err.message}`);+ return false;+ });+ return ok;+}++/**+ * Load this app's outcome records, dropping (and GC-ing from disk) any filed+ * more than OUTCOME_RETENTION_MS ago so the store stays bounded. Returns the+ * surviving records sorted newest-filed-first. Never throws.+ */+export async function listOutcomes({ appId, now = Date.now() } = {}, store = outcomesStore()) {+ if (!appId) return [];+ const all = await store.loadAll().catch(() => []);+ const mine = all.filter(r => r && r.appId === appId);+ const kept = [];+ for (const r of mine) {+ const filedMs = r.filedAt ? Date.parse(r.filedAt) : NaN;+ const expired = Number.isFinite(filedMs) && (now - filedMs) > OUTCOME_RETENTION_MS;+ if (expired) {+ await store.deleteOne(outcomeId(r.appId, r.slug)).catch(() => {});+ continue;+ }+ kept.push(r);+ }+ return kept.sort((a, b) => (Date.parse(b.filedAt) || 0) - (Date.parse(a.filedAt) || 0));+}++/**+ * Reconcile still-unresolved outcome records against a FRESH tracker read. For+ * each stored record whose outcome is null, find the matching existing issue (by+ * slug) and, when the tracker now reports it closed, persist the derived outcome+ * (`merged` / `rejected`). Open issues stay unresolved. Returns the number of+ * records updated. Never throws — a per-record write failure is swallowed so one+ * bad row can't abort the whole reconciliation.+ */+export async function reconcileOutcomes({ appId, existingIssues = [], now = Date.now() } = {}, store = outcomesStore()) {+ if (!appId || !Array.isArray(existingIssues) || existingIssues.length === 0) return 0;+ // Index existing issues by normalized slug for O(1) lookup.+ const bySlug = new Map();+ for (const issue of existingIssues) {+ const slug = normalizeSlug(issue?.slug);+ if (slug && !bySlug.has(slug)) bySlug.set(slug, issue);+ }+ const records = await listOutcomes({ appId, now }, store);+ let updated = 0;+ for (const r of records) {+ if (r.outcome) continue;+ const issue = bySlug.get(r.slug);+ if (!issue) continue;+ const outcome = deriveOutcome(issue);+ if (!outcome) continue;+ const next = {+ ...r,+ outcome,+ outcomeAt: issue.closedAt || new Date(now).toISOString(),+ outcomeReason: issue.stateReason || 'auto-derived from tracker state'+ };+ const ok = await store.saveOne(outcomeId(appId, r.slug), next).then(() => true, () => false);+ if (ok) updated += 1;+ }+ return updated;+}diff --git a/server/services/layeredIntelligenceOutcomes.test.js b/server/services/layeredIntelligenceOutcomes.test.jsnew file mode 100644index 0000000000..22e8c9f5fe--- /dev/null+++ b/server/services/layeredIntelligenceOutcomes.test.js@@ -0,0 +1,122 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { createCollectionStore } from '../lib/collectionStore.js';+import {+ sanitizeOutcomeRecord,+ recordFiledProposal,+ listOutcomes,+ reconcileOutcomes,+ OUTCOME_RETENTION_MS,+ LI_OUTCOMES_SCHEMA_VERSION+} from './layeredIntelligenceOutcomes.js';++// Build an isolated store over a temp dir so the suite never touches the real+// data/cos/li-outcomes collection. The store functions all take an injectable+// `store` param exactly so tests can drive them without PATHS.cos.+let dir;+let store;+beforeEach(async () => {+ dir = await mkdtemp(join(tmpdir(), 'li-outcomes-'));+ store = createCollectionStore({+ dir,+ type: 'li-outcomes',+ schemaVersion: LI_OUTCOMES_SCHEMA_VERSION,+ sanitizeRecord: sanitizeOutcomeRecord+ });+});+afterEach(async () => {+ await rm(dir, { recursive: true, force: true });+});++describe('sanitizeOutcomeRecord', () => {+ it('drops rows without a usable appId + slug', () => {+ expect(sanitizeOutcomeRecord(null)).toBeNull();+ expect(sanitizeOutcomeRecord({ slug: 'x' })).toBeNull();+ expect(sanitizeOutcomeRecord({ appId: 'a' })).toBeNull();+ });++ it('normalizes the slug and coerces an unknown outcome to null', () => {+ const r = sanitizeOutcomeRecord({ appId: 'app-1', slug: 'Add Metrics', outcome: 'bogus' });+ expect(r.slug).toBe('add-metrics');+ expect(r.outcome).toBeNull();+ });++ it('keeps outcome metadata only alongside a valid outcome', () => {+ const resolved = sanitizeOutcomeRecord({ appId: 'a', slug: 's', outcome: 'merged', outcomeAt: 'x', outcomeReason: 'y' });+ expect(resolved.outcome).toBe('merged');+ expect(resolved.outcomeAt).toBe('x');+ const unresolved = sanitizeOutcomeRecord({ appId: 'a', slug: 's', outcome: null, outcomeAt: 'x', outcomeReason: 'y' });+ expect(unresolved.outcomeAt).toBeNull();+ expect(unresolved.outcomeReason).toBeNull();+ });+});++describe('recordFiledProposal + listOutcomes', () => {+ it('records a filed proposal with a null (unresolved) outcome', async () => {+ const ok = await recordFiledProposal({ appId: 'app-1', slug: 'add-metrics', tracker: 'github', issueRef: '#42', scope: 'app-data-gap' }, store);+ expect(ok).toBe(true);+ const rows = await listOutcomes({ appId: 'app-1' }, store);+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ appId: 'app-1', slug: 'add-metrics', tracker: 'github', issueRef: '#42', scope: 'app-data-gap', outcome: null });+ expect(rows[0].filedAt).toBeTruthy();+ });++ it('refuses a record with no appId or slug', async () => {+ expect(await recordFiledProposal({ slug: 's' }, store)).toBe(false);+ expect(await recordFiledProposal({ appId: 'a' }, store)).toBe(false);+ });++ it('scopes listOutcomes to one app', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 's1', scope: 'app-improvement' }, store);+ await recordFiledProposal({ appId: 'app-2', slug: 's2', scope: 'app-improvement' }, store);+ expect(await listOutcomes({ appId: 'app-1' }, store)).toHaveLength(1);+ expect(await listOutcomes({ appId: 'app-2' }, store)).toHaveLength(1);+ });++ it('gc-drops records filed beyond the retention window on read', async () => {+ const now = Date.now();+ await recordFiledProposal({ appId: 'app-1', slug: 'old', scope: 'app-improvement', now: now - OUTCOME_RETENTION_MS - 1000 }, store);+ await recordFiledProposal({ appId: 'app-1', slug: 'fresh', scope: 'app-improvement', now }, store);+ const rows = await listOutcomes({ appId: 'app-1', now }, store);+ expect(rows.map(r => r.slug)).toEqual(['fresh']);+ });+});++describe('reconcileOutcomes', () => {+ it('resolves unresolved records from the fresh tracker state', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 'merged-one', scope: 'app-data-gap' }, store);+ await recordFiledProposal({ appId: 'app-1', slug: 'rejected-one', scope: 'app-improvement' }, store);+ await recordFiledProposal({ appId: 'app-1', slug: 'still-open', scope: 'app-improvement' }, store);++ const existingIssues = [+ { slug: 'merged-one', state: 'closed', stateReason: 'completed', closedAt: '2026-07-01T00:00:00Z' },+ { slug: 'rejected-one', state: 'closed', stateReason: 'not_planned' },+ { slug: 'still-open', state: 'open' }+ ];+ const updated = await reconcileOutcomes({ appId: 'app-1', existingIssues }, store);+ expect(updated).toBe(2);++ const byslug = Object.fromEntries((await listOutcomes({ appId: 'app-1' }, store)).map(r => [r.slug, r]));+ expect(byslug['merged-one'].outcome).toBe('merged');+ expect(byslug['merged-one'].outcomeAt).toBe('2026-07-01T00:00:00Z');+ expect(byslug['rejected-one'].outcome).toBe('rejected');+ expect(byslug['still-open'].outcome).toBeNull();+ });++ it('does not re-resolve an already-resolved record', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 's', scope: 'app-improvement' }, store);+ await reconcileOutcomes({ appId: 'app-1', existingIssues: [{ slug: 's', state: 'closed', stateReason: 'completed' }] }, store);+ // Second pass with the issue now reported open should NOT flip it back.+ const updated = await reconcileOutcomes({ appId: 'app-1', existingIssues: [{ slug: 's', state: 'open' }] }, store);+ expect(updated).toBe(0);+ const rows = await listOutcomes({ appId: 'app-1' }, store);+ expect(rows[0].outcome).toBe('merged');+ });++ it('is a no-op with no existing issues', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 's', scope: 'app-improvement' }, store);+ expect(await reconcileOutcomes({ appId: 'app-1', existingIssues: [] }, store)).toBe(0);+ });+});