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 deterministic selfEval source to layered intelligence (#2700)
[._.]/ Adam Eivya7d1ffae8020
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 5f849a65a8..31a598895f 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,6 +12,8 @@- [issue-2698] **Layered Intelligence now sees the work you've already committed to, and won't propose against it.** A new **Planned work** source feeds the loop your `plan`-labeled tracker issues (or your prioritized Jira backlog, or PLAN.md's unchecked items) alongside the flat open-issue list it used to get, with the instruction to cross-reference its proposal and file nothing when it overlaps something already in scope. It also gets told when its own merge rate falls below 20% and pointed at that backlog as the likely reason — LI's most common rejection was "not planned", which is what filing into work you'd already scheduled looks like from the tracker's side. A tracker that can't be read says so explicitly rather than reading as "nothing is planned", so a transient `gh` blip can't hand the loop a blank cheque. On by default for every app; toggle it off per-app under the app's Intelligence tab.+- [issue-2700] **Layered Intelligence now checks its own work before it files.** A new **Self-evaluation** source hands the loop a deterministic read of its own record — how many of its proposals you actually merged (and the reasons you rejected the rest), which proposals it has already filed that are still suppressed, and whether its own agent runs are even succeeding — so it can judge a proposal's quality *before* filing instead of only learning from your rejections afterward. When it's reasoning with little evidence about itself it's told to hold a higher bar and file nothing rather than guess; when its own runs are failing more than half the time it's told the problem may be the loop rather than the app, and to stop marking work for unattended hand-off. Every signal is either present or explicitly reported missing: "no proposal has been triaged yet" never reads as "everything I file gets rejected", and a tracker that couldn't be read never reads as "I've filed nothing" (which would license a duplicate re-file). Costs no extra AI calls — it's computed from data the loop already has. On by default for PortOS, off for managed apps; toggle it per-app under the app's Intelligence tab.+## Changed- [issue-2702] **The Creative Director now shows you what it made.** Project cards on `/creative-director` lead with a preview of the produced media — the final video's poster with a play badge (click the artwork to open the project, the badge to play it inline), a rendered scene, or a produced image from a directive plan — falling back to a tidy "no render yet" placeholder instead of a wall of text. The Overview tab renders the final cut inline instead of showing only a job id, keeping the Media History link alongside it; plans that emit images show the image. Previews respect each project's aspect ratio (16:9 / 9:16 / 1:1), and the grid never downloads a video until you actually press play.diff --git a/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsxindex 47804b9a07..17238713ed 100644--- a/client/src/components/apps/LayeredIntelligenceTab.jsx+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx@@ -20,7 +20,8 @@ export const LI_SOURCE_FIELDS = [{ key: 'planMd', label: 'PLAN.md', hint: 'The app\'s open work-plan items' },{ key: 'openIssues', label: 'Open issues', hint: 'Currently open tracker issues' },{ key: 'plannedWork', label: 'Planned work', hint: 'The backlog you\'ve already committed to (plan-labeled issues / prioritized Jira backlog / unchecked PLAN.md items), so the loop won\'t propose work that\'s already in scope' },- { key: 'outcomes', label: 'Proposal outcomes', hint: 'Past LI proposals + how they fared (merge rate), fed back so the loop calibrates on its own results' }+ { key: 'outcomes', label: 'Proposal outcomes', hint: 'Past LI proposals + how they fared (merge rate), fed back so the loop calibrates on its own results' },+ { key: 'selfEval', label: 'Self-evaluation', hint: 'A deterministic check of the loop\'s own record — merge rate, proposals it has already filed, and whether its own runs are succeeding — so it can judge proposal quality before filing instead of only learning from rejections' }];// The proposal scopes the loop may file. loop-meta / portos-self extend the loopdiff --git a/server/lib/validation.js b/server/lib/validation.jsindex 2ef08c293f..5e64c1b45c 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -136,6 +136,10 @@ export const layeredIntelligenceConfigSchema = z.object({// 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(),+ // Self-evaluation (#2700): fold LI's own merge rate, already-filed proposal+ // count, and agent-run health back into the prompt so the loop can judge its+ // proposal quality before filing. Default on for PortOS, off for managed apps.+ selfEval: 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 afae5ad3cf..c3e038c163 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -53,6 +53,8 @@ import {resolveJiraBlockKey,applyJiraBlockingLabel,computeOutcomesReport,+ computeSelfEvalSummary,+ readLiTaskMetrics,hasPlannedWorkListing} from '../layeredIntelligence.js'import { recordFiledProposal, listOutcomes, reconcileOutcomes } from '../layeredIntelligenceOutcomes.js'@@ -311,10 +313,14 @@ export async function buildTaskInput({ app } = {}) {// AND an outcomes-capable tracker (forge / jira / plan — #2435 taught the plan// parse to read a checked `- [x]` item as closed). A failed tracker read skips// reconciliation (never mark closed on a blind read).+ // `null` (not `[]`) until the outcomes pipeline actually runs this cycle: selfEval+ // reads this too, and "the outcomes source is off" must not reach it looking like+ // "this app has never had a proposal merged" (#2700).+ let outcomes = nulllet outcomesReport = ''if (config.sources?.outcomes && outcomesTrackerSupported(filer)) {if (!trackerReadFailed) await reconcileOutcomes({ appId: app.id, existingIssues })- const outcomes = await listOutcomes({ appId: app.id })+ outcomes = await listOutcomes({ appId: app.id })// The low-merge-rate warning cites the plannedWork block by name — only let it// do that when a real BACKLOG LISTING was gathered. The source is// per-app-toggleable, yields nothing on an unresolvable tracker, and renders a@@ -326,7 +332,21 @@ export async function buildTaskInput({ app } = {}) {})}- const prompt = buildPrompt({ app, config, sources, openIssues, isPortos, outcomesReport }) + buildCompletionContract()+ // Self-evaluation (#2700): the loop's deterministic pre-filing check on its own+ // reasoning — no LLM call, just a read of the record it already keeps. Note+ // `existingIssues` is passed as null on a FAILED tracker read: readIssues returns+ // `[]` in that case, which would otherwise tell selfEval "you have filed nothing"+ // and license a duplicate re-file off a blind read.+ let selfEvalReport = ''+ if (config.sources?.selfEval) {+ selfEvalReport = computeSelfEvalSummary({+ outcomes,+ existingIssues: trackerReadFailed ? null : existingIssues,+ liTaskStats: await readLiTaskMetrics()+ })+ }++ const prompt = buildPrompt({ app, config, sources, openIssues, isPortos, outcomesReport, selfEvalReport }) + 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 0c82a72960..a701d92e9c 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js@@ -56,6 +56,11 @@ vi.mock('../layeredIntelligence.js', () => ({resolveJiraBlockKey: vi.fn(() => null),applyJiraBlockingLabel: vi.fn().mockResolvedValue({ success: true }),computeOutcomesReport: vi.fn(() => ''),+ // selfEval (#2700). The summary's own semantics (signal sentinels, confidence,+ // degraded guidance) are unit-tested in layeredIntelligence.test.js; these are+ // spies so the hook's WIRING can be asserted — which inputs it feeds in.+ computeSelfEvalSummary: vi.fn(() => 'LI self-evaluation:\n- Reasoning confidence: low'),+ 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// asserted — that the gathered plannedWork string is what gets classified.@@ -283,6 +288,57 @@ describe('buildTaskInput', () => {expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({ outcomesReport: expect.stringContaining('Total filed: 1') }));});+ it('skips selfEval when the source toggle is off (#2700)', async () => {+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: {} });+ await buildTaskInput({ app: APP });+ expect(li.computeSelfEvalSummary).not.toHaveBeenCalled();+ expect(li.readLiTaskMetrics).not.toHaveBeenCalled();+ expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({ selfEvalReport: '' }));+ });++ it('folds the selfEval summary into the prompt when enabled (#2700)', async () => {+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { selfEval: true } });+ li.computeSelfEvalSummary.mockReturnValue('LI self-evaluation:\n- Reasoning confidence: high');+ await buildTaskInput({ app: APP });+ expect(li.readLiTaskMetrics).toHaveBeenCalled();+ expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({+ selfEvalReport: expect.stringContaining('Reasoning confidence: high')+ }));+ });++ it('passes outcomes to selfEval as null (not []) when the outcomes source is off (#2700)', async () => {+ // The sentinel that keeps "we never gathered outcomes" from reaching the+ // reasoner as "this app has never had a proposal merged".+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { selfEval: true } });+ await buildTaskInput({ app: APP });+ expect(li.computeSelfEvalSummary).toHaveBeenCalledWith(expect.objectContaining({ outcomes: null }));+ });++ it('passes the gathered outcomes to selfEval when both sources are on (#2700)', async () => {+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { outcomes: true, selfEval: true } });+ listOutcomes.mockResolvedValue([{ slug: 's', outcome: 'merged', scope: 'app-improvement' }]);+ await buildTaskInput({ app: APP });+ expect(li.computeSelfEvalSummary).toHaveBeenCalledWith(expect.objectContaining({+ outcomes: [{ slug: 's', outcome: 'merged', scope: 'app-improvement' }]+ }));+ });++ it('passes existingIssues to selfEval, and null when the tracker read failed (#2700)', async () => {+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { selfEval: true } });+ li.listForgeIssues.mockResolvedValue({ ok: true, issues: [{ slug: 'a', state: 'open' }] });+ await buildTaskInput({ app: APP });+ expect(li.computeSelfEvalSummary).toHaveBeenCalledWith(expect.objectContaining({+ existingIssues: [{ slug: 'a', state: 'open' }]+ }));++ // A blown read yields `[]` from readIssues — which must NOT reach selfEval as+ // "you have filed nothing", or it licenses a duplicate re-file off a blind read.+ li.computeSelfEvalSummary.mockClear();+ li.listForgeIssues.mockResolvedValue({ ok: false, issues: [] });+ await buildTaskInput({ app: APP });+ expect(li.computeSelfEvalSummary).toHaveBeenCalledWith(expect.objectContaining({ existingIssues: null }));+ });+it('runs the feedback loop on a plan tracker when outcomes is enabled (#2435)', async () => {resolveAppWorkTracker.mockResolvedValue({ resolved: 'plan', forge: null });li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { outcomes: true } });diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex 2cb295abbb..f1b9b84ca7 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -29,7 +29,7 @@ import { fetchPublicText } from '../lib/safeUrlFetch.js';import { validateCommand } from '../lib/commandSecurity.js';import { getSettings } from './settings.js';import { createTicket, searchIssues, addLabels, escapeJql } from './jira.js';-import { computeWindowedStats } from './taskLearning/store.js';+import { computeWindowedStats, computeEffectiveSuccessRate } from './taskLearning/store.js';// Tracker labels + slug marker. The slug is the stable dedup key the reasoner// chooses; it is embedded in each filed issue body so a later run (or the@@ -124,6 +124,25 @@ export const LOW_MERGE_RATE_THRESHOLD = 20;// it stops proposing. A rate needs a sample before it means anything.export const LOW_MERGE_RATE_MIN_SAMPLE = 4;+// The `learning.json` byTaskType key the LI loop's own agent runs land under —+// LI's scheduled task type (see taskSchedule.js SELF_IMPROVEMENT_TASK_TYPES).+// This is the bucket computeSelfEvalSummary reads to judge whether the LI+// machinery ITSELF is healthy, as opposed to how its proposals fare downstream.+export const LI_TASK_TYPE = 'layered-intelligence';++// LI-task success rate (%) below which selfEval reports the loop's own execution+// as DEGRADED (#2700) — a separate failure mode from a low merge rate: the merge+// rate says "the user rejects what I propose", this says "my own runs are+// failing". Kept at 50 (a coin flip) rather than the merge-rate's 20: a proposal+// being rejected is normal triage, an LI run outright failing is not.+export const LI_DEGRADED_SUCCESS_THRESHOLD = 50;++// Minimum recorded LI runs before the degraded-execution signal is allowed to+// fire, for the same reason as LOW_MERGE_RATE_MIN_SAMPLE: 0-of-1 and 0-of-50 are+// both "0%", but only the second is evidence. Below the floor the rate is+// reported as-is but is NOT treated as a confidence signal either way.+export const LI_DEGRADED_MIN_SAMPLE = 4;+// The resolved outcomes a filed proposal can reach (the feedback loop, #2428).// A record with a null outcome is still open/unresolved. All three are// auto-derived from the tracker's closed state by deriveOutcome: completed →@@ -175,6 +194,14 @@ export function defaultLayeredIntelligenceConfig(isPortos = false) {// 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,+ // The loop's self-awareness signal (#2700): a deterministic read of LI's OWN+ // record — proposal merge rate, how many of its proposals are already filed+ // and suppressed, and whether its own agent runs are succeeding — folded back+ // so the reasoner can judge its proposal quality BEFORE filing rather than+ // only learning from rejections after. Same PortOS-only default as `outcomes`:+ // it is built from LI's own history, which only the self-improving install+ // accumulates meaningfully; managed apps opt in per-app.+ selfEval: isPortos,custom: []},rules: '',@@ -504,6 +531,38 @@ export function deriveOutcome(issue) {return 'abandoned';}+/**+ * Tally a recorded-outcome list into the counts BOTH the outcomes report (#2428)+ * and the self-eval summary (#2700) reason over. Pure; the single place the+ * merge-rate math lives so the two blocks can never disagree about LI's record.+ *+ * `rawMergeRate` is measured over RESOLVED proposals only and is `null` when+ * nothing has resolved yet — the sentinel rule: "no proposal has been judged" must+ * not collapse into the same 0 as "every judged proposal was rejected". Callers+ * round only for display (rounding before a threshold compare would let 19.6%+ * read as 20% and suppress a warning that should fire).+ */+export function summarizeOutcomeStats(outcomes = []) {+ const filed = (Array.isArray(outcomes) ? outcomes : []).filter(o => o && typeof o === 'object');+ const total = filed.length;+ const count = (name) => filed.filter(o => o.outcome === name).length;+ const merged = count('merged');+ const rejected = count('rejected');+ const abandoned = count('abandoned');+ const resolved = merged + rejected + abandoned;+ return {+ filed,+ total,+ merged,+ rejected,+ abandoned,+ // Anything filed but not yet resolved — still awaiting triage, NOT a failure.+ pending: total - resolved,+ resolved,+ rawMergeRate: resolved > 0 ? (merged / resolved) * 100 : null+ };+}+/*** Format the LI outcome-feedback report (#2428) from this app's recorded* proposals + their reconciled outcomes. Pure + side-effect-free: the LI hook@@ -512,15 +571,10 @@ export function deriveOutcome(issue) {* the block entirely rather than injecting an empty section.*/export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false } = {}) {- const filed = (Array.isArray(outcomes) ? outcomes : []).filter(o => o && typeof o === 'object');- if (filed.length === 0) return '';- const total = filed.length;+ const { filed, total, merged, rejected, abandoned, pending, resolved, rawMergeRate } =+ summarizeOutcomeStats(outcomes);+ if (total === 0) return '';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();@@ -540,19 +594,11 @@ export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false }.filter(o => o.outcome === 'rejected' && o.outcomeReason).map(o => o.outcomeReason))].slice(0, 5);- // Low-merge-rate alarm (#2698). Measured over RESOLVED proposals only- // (merged + rejected + abandoned), NOT over `total`: a still-open proposal has- // not failed, it just hasn't been judged yet, and dividing by `total` would let- // "filed yesterday, nobody has triaged it" read exactly like "the user threw it- // out" — the sentinel rule (pending ≠ rejected). `null` means "no resolved- // sample yet", which is distinct from a genuine 0% and stays silent rather than- // alarming an app whose first proposal is simply still in flight. The sample- // floor is the same idea one step further out: 0-of-1 is not evidence of a rate.- const resolved = merged + rejected + abandoned;- // Compare the RAW ratio and round only for display: rounding first would let- // 10-of-51 (19.6%) round up to 20 and suppress a warning the threshold says- // should fire.- const rawMergeRate = resolved > 0 ? (merged / resolved) * 100 : null;+ // Low-merge-rate alarm (#2698). `rawMergeRate` is measured over RESOLVED+ // proposals only and is null when none have resolved — see summarizeOutcomeStats+ // for the sentinel rationale (pending ≠ rejected). A null rate stays silent+ // rather than alarming an app whose first proposal is simply still in flight.+ // The sample floor is the same idea one step further out: 0-of-1 is not evidence.const lowMergeWarning = (rawMergeRate !== null&& resolved >= LOW_MERGE_RATE_MIN_SAMPLE@@ -586,14 +632,151 @@ export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false }].join('\n');}+/**+ * Format LI's self-evaluation block (#2700) — the loop's pre-filing quality check+ * on its OWN reasoning. Pure + side-effect-free and NO LLM call: every line is+ * derived from data the loop already has, so this never adds a provider round-trip+ * (the "no cold-bootstrap LLM calls" policy). The hook loads the inputs and feeds+ * the string to buildPrompt, exactly like computeOutcomesReport.+ *+ * Three independent self-signals, each of which is either PRESENT or explicitly+ * reported ABSENT — never silently defaulted, because "I have no data about myself"+ * and "the data says I am doing badly" demand opposite responses from the reasoner:+ * 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?+ *+ * 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+ * useful thing to tell a cold loop, so an empty-handed run is exactly when the+ * block matters most.+ *+ * @param {Object} args+ * @param {Array|null} args.outcomes - recorded proposals; `null` = NOT gathered+ * (source off / outcomes-incapable tracker), `[]` = gathered and genuinely none.+ * @param {Array|null} args.existingIssues - LI-labeled tracker issues; `null` = the+ * tracker read FAILED or never ran, `[]` = read fine and LI has filed nothing.+ * The caller MUST pass null on a failed read: readIssues returns `[]` for a blown+ * read, which would otherwise read as "nothing filed" and license a re-file.+ * @param {{ read: boolean, metrics: Object|null }|null} args.liTaskStats - from+ * readLiTaskMetrics. `null`/`read:false` = the learning store was unreadable;+ * `read:true, metrics:null` = read fine and LI has simply never run a task.+ * @param {number} [args.now] - clock seam for the suppression window.+ * @returns {string} the liSelfEval block body.+ */+export function computeSelfEvalSummary({+ outcomes = null,+ existingIssues = null,+ liTaskStats = null,+ now = Date.now()+} = {}) {+ const lines = [];++ // --- Signal 1: does the user actually merge what I propose? -----------------+ let mergeSignal = false;+ if (!Array.isArray(outcomes)) {+ lines.push('- Proposal merge rate: UNAVAILABLE — no outcome history was gathered this run (the outcomes source is off, or this tracker cannot report outcomes). You cannot see how your past proposals fared; do not assume they went well.');+ } else {+ const { total, merged, rejected, resolved, rawMergeRate, filed } = summarizeOutcomeStats(outcomes);+ if (total === 0) {+ lines.push('- Proposal merge rate: no proposals filed yet for this app — you have no track record here to calibrate against.');+ } else if (rawMergeRate === null) {+ lines.push(`- Proposal merge rate: ${total} filed, none resolved yet — rate unknown. Awaiting triage is NOT rejection; do not read this as failure.`);+ } else {+ mergeSignal = resolved >= LOW_MERGE_RATE_MIN_SAMPLE;+ const reasons = [...new Set(filed+ .filter(o => o.outcome === 'rejected' && o.outcomeReason)+ .map(o => o.outcomeReason))].slice(0, 3);+ lines.push(+ `- Proposal merge rate: ${merged} of ${resolved} resolved proposals merged (${Math.round(rawMergeRate)}%)`+ + `${resolved < LOW_MERGE_RATE_MIN_SAMPLE ? ' — too small a sample to read a rate from yet' : ''}.`+ + (rejected > 0 && reasons.length ? ` Recurring rejection reasons: ${reasons.join('; ')}.` : '')+ );+ }+ }++ // --- Signal 2: what have I already said? (dedup awareness) ------------------+ let trackerSignal = false;+ if (!Array.isArray(existingIssues)) {+ lines.push('- Your already-filed proposals: UNKNOWN — the tracker could not be read this run. You may be about to re-file something that already exists; hold a higher bar than usual.');+ } else {+ trackerSignal = true;+ const open = existingIssues.filter(i => (i?.state || '').toLowerCase() === 'open');+ // Closed but still inside the 30-day suppression window: re-proposing one of+ // these gets deterministically dropped downstream, so spending the run on it is+ // a wasted run. Surfaced so the reasoner can route around it BEFORE proposing.+ const closedSuppressed = existingIssues.filter(i =>+ (i?.state || '').toLowerCase() !== 'open' && isIssueWithinDedupWindow(i, now));+ lines.push(+ `- Your already-filed proposals: ${open.length} open`+ + `${closedSuppressed.length ? `, plus ${closedSuppressed.length} closed but still within the ${Math.round(CLOSED_SUPPRESSION_MS / DAY)}-day suppression window` : ''}.`+ + ` ${open.length + closedSuppressed.length+ ? 'Re-proposing any of these is deterministically suppressed — the run is wasted. Propose something genuinely new.'+ : 'Nothing is currently suppressed.'}`+ );+ }++ // --- Signal 3: is the LI machinery itself healthy? --------------------------+ let taskSignal = false;+ let liDegraded = false;+ if (!liTaskStats?.read) {+ lines.push('- LI execution health: UNAVAILABLE — the CoS learning store could not be read.');+ } else if (!liTaskStats.metrics) {+ lines.push('- LI execution health: no LI runs recorded yet — this loop has no execution history.');+ } else {+ const { successRate, source, windowedCompleted } = computeEffectiveSuccessRate(liTaskStats.metrics);+ const sample = source === 'windowed' ? windowedCompleted : (liTaskStats.metrics.completed || 0);+ if (successRate === null) {+ lines.push('- LI execution health: no completed LI runs recorded yet — success rate unknown.');+ } else {+ taskSignal = sample >= LI_DEGRADED_MIN_SAMPLE;+ liDegraded = taskSignal && successRate < LI_DEGRADED_SUCCESS_THRESHOLD;+ lines.push(+ `- LI execution health: ${successRate}% of ${sample} ${source} LI runs succeeded`+ + `${taskSignal ? '' : ' — too small a sample to judge'}${liDegraded ? ' — DEGRADED' : ''}.`+ );+ }+ }++ // --- 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+ // 0% merge rate has HIGH confidence in a bad result, which is precisely the state+ // where it should act decisively rather than hedge.+ const signalCount = [mergeSignal, trackerSignal, taskSignal].filter(Boolean).length;+ const confidence = signalCount >= 3 ? 'high' : signalCount === 2 ? 'medium' : 'low';++ const guidance = [];+ if (confidence === 'low') {+ guidance.push(+ '',+ `GUIDANCE — low self-confidence (${signalCount} of 3 self-signals available): you are reasoning about this app with little evidence about your own track record. Do NOT compensate by proposing something speculative or sweeping. Prefer a small, concretely-grounded proposal you can justify from the gathered sources alone, and return proposal: null rather than filing a guess.`+ );+ }+ if (liDegraded) {+ guidance.push(+ '',+ `GUIDANCE — your own execution is degraded (LI run success is under ${LI_DEGRADED_SUCCESS_THRESHOLD}%): the problem may be THIS LOOP, not the app. Favor a narrowly-scoped, low-risk proposal that a coding agent can finish, and do not mark anything trivial+safe for hand-off while your runs are failing this often. A loop-meta proposal that fixes the failure mode may be the highest-value item this run.`+ );+ }++ return [+ 'LI self-evaluation (deterministic — computed from this loop\'s own record, not a model\'s opinion):',+ `- Reasoning confidence: ${confidence} (${signalCount} of 3 self-signals available)`,+ ...lines,+ ...guidance+ ].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).+ * block with calibration guidance when non-empty (#2428). `selfEvalReport` (from+ * computeSelfEvalSummary) is injected as a `liSelfEval` block the same way (#2700).*/-export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '' }) {+export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '', selfEvalReport = '' }) {const allowed = (config.allowedScopes || []).filter(s =>isScopeAllowed({ scope: s, allowedScopes: config.allowedScopes, isPortos }));@@ -641,6 +824,15 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort? `\n### liOutcomes\n${outcomesReport.trim()}\n\nUse this data to calibrate your proposal: prefer scopes with higher merge rates, avoid patterns that were repeatedly rejected, and consider that lower-merge scopes may need more justification.\n`: '';+ // Self-evaluation (#2700): the loop's own quality check BEFORE it files, so it+ // can decline instead of learning only from a later rejection. Carries its own+ // low-confidence / degraded-execution guidance (computeSelfEvalSummary), which is+ // why no extra instruction sentence is appended here — the block is self-contained+ // and its guidance is conditional on what the signals actually say.+ const selfEvalBlock = (typeof selfEvalReport === 'string' && selfEvalReport.trim())+ ? `\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`+ : '';+return `You are the Layered Intelligence reasoner for the app "${app.name}". Your job is to evaluate how THIS app is performing against its OWN goals and purpose${isPortos ? '' : ', not how well PortOS\'s tooling manages it'}. Decide the SINGLE highest-value improvement to propose this run (signal, not noise), grounded in the app's own goals and its own performance metrics (user success, KPIs, production telemetry). You never write code; you return structured JSON that a deterministic system files as ONE tracker issue.${handoffNote}${metricsGuidance}Rules & guidance from the operator:@@ -654,7 +846,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}+${plannedWorkBlock}${outcomesBlock}${selfEvalBlock}Respond with JSON only (no markdown fences):{"analysis": "brief reasoning summary",@@ -934,6 +1126,33 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShereturn out;}+/**+ * Read the LI loop's OWN agent-run metrics out of the CoS learning store (#2700).+ * Deterministic file read; no LLM call. Feeds computeSelfEvalSummary's execution-+ * health signal.+ *+ * Returns a discriminated result rather than a bare bucket-or-null, because the two+ * empty cases are NOT the same fact and the reasoner is told them differently:+ * `{ read: false, metrics: null }` — the store is missing/unreadable/malformed:+ * we do not know how LI's runs are going.+ * `{ read: true, metrics: null }` — the store is fine, LI has simply never run.+ * `{ read: true, metrics: {...} }` — real history.+ * Collapsing these to one `null` would let "cannot read the store" masquerade as+ * "healthy loop with no history" (or vice versa) — the sentinel rule.+ */+export async function readLiTaskMetrics({ cosPath = PATHS.cos } = {}) {+ const learning = await readJSONFile(join(cosPath, 'learning.json'), null);+ const byTaskType = learning?.byTaskType;+ if (!byTaskType || typeof byTaskType !== 'object' || Array.isArray(byTaskType)) {+ return { read: false, metrics: null };+ }+ const bucket = byTaskType[LI_TASK_TYPE];+ return {+ read: true,+ metrics: (bucket && typeof bucket === 'object' && !Array.isArray(bucket)) ? bucket : null+ };+}+/*** Stable map key for a custom source. Namespaced by type so a `file` ref and an* `http` url that share a string can't collide, and so the prompt's source blockdiff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex c738941276..5d4e590159 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -30,6 +30,12 @@ import {buildPrompt,deriveOutcome,computeOutcomesReport,+ computeSelfEvalSummary,+ summarizeOutcomeStats,+ readLiTaskMetrics,+ LI_TASK_TYPE,+ LI_DEGRADED_SUCCESS_THRESHOLD,+ LI_DEGRADED_MIN_SAMPLE,PROPOSAL_OUTCOMES,extractPlanSlugs,appendProposalToPlan,@@ -104,6 +110,11 @@ describe('defaultLayeredIntelligenceConfig', () => {expect(defaultLayeredIntelligenceConfig(true).sources.outcomes).toBe(true);});+ it('defaults the selfEval source on for PortOS, off for managed apps (#2700)', () => {+ expect(defaultLayeredIntelligenceConfig(false).sources.selfEval).toBe(false);+ expect(defaultLayeredIntelligenceConfig(true).sources.selfEval).toBe(true);+ });+it('defaults cosMetrics on for PortOS, off for managed apps (it is a PortOS-side agent-perf metric)', () => {expect(defaultLayeredIntelligenceConfig(false).sources.cosMetrics).toBe(false);expect(defaultLayeredIntelligenceConfig(true).sources.cosMetrics).toBe(true);@@ -487,6 +498,26 @@ describe('buildPrompt', () => {expect(withReport).toContain('calibrate your proposal');});+ it('injects the selfEval block only when non-empty (#2700)', () => {+ const base = { app, isPortos: false, config: { allowedScopes: ['app-improvement'], rules: '' } };+ expect(buildPrompt(base)).not.toContain('liSelfEval');+ expect(buildPrompt({ ...base, selfEvalReport: ' ' })).not.toContain('liSelfEval');+ const withReport = buildPrompt({ ...base, selfEvalReport: 'LI self-evaluation:\n- Reasoning confidence: low' });+ expect(withReport).toContain('### liSelfEval');+ expect(withReport).toContain('Reasoning confidence: low');+ expect(withReport).toContain('Filing nothing (proposal: null) is a legitimate');+ });++ 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' });+ expect(selfOnly).toContain('### liSelfEval');+ expect(selfOnly).not.toContain('### liOutcomes');+ const both = buildPrompt({ ...base, outcomesReport: 'outcomes body', selfEvalReport: 'self-eval body' });+ expect(both).toContain('### liOutcomes');+ expect(both).toContain('### liSelfEval');+ });+it('frames the mission around the app\'s own goals and performance', () => {const out = buildPrompt({ app, isPortos: false, config: { allowedScopes: ['app-improvement'], rules: '' } });expect(out).toContain('its OWN goals and purpose');@@ -590,6 +621,214 @@ describe('computeOutcomesReport', () => {});});+describe('summarizeOutcomeStats', () => {+ it('reports a null merge rate (not 0) when nothing has resolved yet', () => {+ const stats = summarizeOutcomeStats([{ outcome: null }, { outcome: null }]);+ expect(stats.total).toBe(2);+ expect(stats.pending).toBe(2);+ expect(stats.resolved).toBe(0);+ // The sentinel that keeps "awaiting triage" from reading as "all rejected".+ expect(stats.rawMergeRate).toBeNull();+ });++ it('measures the merge rate over resolved proposals only, unrounded', () => {+ const stats = summarizeOutcomeStats([+ { outcome: 'merged' },+ { outcome: 'rejected' },+ { outcome: 'abandoned' },+ { outcome: null }+ ]);+ expect(stats.resolved).toBe(3);+ expect(stats.pending).toBe(1);+ expect(stats.rawMergeRate).toBeCloseTo(33.33, 1);+ });++ it('tolerates a non-array / junk input', () => {+ expect(summarizeOutcomeStats(null).total).toBe(0);+ expect(summarizeOutcomeStats([null, 'x', { outcome: 'merged' }]).total).toBe(1);+ });+});++describe('computeSelfEvalSummary (#2700)', () => {+ const liMetrics = (over = {}) => ({+ read: true,+ metrics: { completed: 10, succeeded: 8, failed: 2, successRate: 80, recentOutcomes: [], ...over }+ });++ it('reports every signal as explicitly unavailable — and low confidence — with no data', () => {+ const report = computeSelfEvalSummary();+ expect(report).toContain('Reasoning confidence: low (0 of 3 self-signals available)');+ expect(report).toContain('Proposal merge rate: UNAVAILABLE');+ expect(report).toContain('Your already-filed proposals: UNKNOWN');+ expect(report).toContain('LI execution health: UNAVAILABLE');+ expect(report).toContain('GUIDANCE — low self-confidence');+ // A blind run must never be told it has a 0% rate.+ expect(report).not.toContain('(0%)');+ });++ it('distinguishes "outcomes not gathered" from "gathered, none filed"', () => {+ expect(computeSelfEvalSummary({ outcomes: null })).toContain('Proposal merge rate: UNAVAILABLE');+ expect(computeSelfEvalSummary({ outcomes: [] })).toContain('no proposals filed yet for this app');+ });++ it('does not read filed-but-unresolved proposals as a 0% merge rate', () => {+ const report = computeSelfEvalSummary({ outcomes: [{ outcome: null }, { outcome: null }] });+ expect(report).toContain('2 filed, none resolved yet — rate unknown');+ expect(report).toContain('Awaiting triage is NOT rejection');+ expect(report).not.toContain('0%');+ });++ it('reports a real merge rate with its recurring rejection reasons', () => {+ const outcomes = [+ { outcome: 'merged' },+ { outcome: 'rejected', outcomeReason: 'NOT_PLANNED' },+ { outcome: 'rejected', outcomeReason: 'NOT_PLANNED' },+ { outcome: 'rejected', outcomeReason: 'too vague' }+ ];+ const report = computeSelfEvalSummary({ outcomes });+ expect(report).toContain('1 of 4 resolved proposals merged (25%)');+ // De-duplicated reasons.+ expect(report).toContain('Recurring rejection reasons: NOT_PLANNED; too vague');+ });++ it('flags a below-floor sample as unreadable rather than as evidence', () => {+ const report = computeSelfEvalSummary({ outcomes: [{ outcome: 'rejected' }] });+ expect(report).toContain('too small a sample to read a rate from yet');+ // One rejection is not a merge-rate signal → confidence must not count it.+ expect(report).toContain('Reasoning confidence: low');+ });++ it('counts open and still-suppressed closed proposals so the loop does not re-file', () => {+ const now = Date.now();+ const report = computeSelfEvalSummary({+ existingIssues: [+ { slug: 'a', state: 'open' },+ { slug: 'b', state: 'open' },+ { slug: 'c', state: 'closed', closedAt: new Date(now - 5 * 24 * 60 * 60 * 1000).toISOString() },+ // Closed long ago → out of the window → re-proposable, so NOT counted.+ { slug: 'd', state: 'closed', closedAt: new Date(now - 90 * 24 * 60 * 60 * 1000).toISOString() }+ ],+ now+ });+ expect(report).toContain('2 open, plus 1 closed but still within the 30-day suppression window');+ expect(report).toContain('deterministically suppressed');+ });++ it('says so plainly when nothing is suppressed', () => {+ const report = computeSelfEvalSummary({ existingIssues: [] });+ expect(report).toContain('0 open');+ expect(report).toContain('Nothing is currently suppressed');+ });++ it('treats a failed tracker read (null) as unknown, never as "nothing filed"', () => {+ const report = computeSelfEvalSummary({ existingIssues: null });+ expect(report).toContain('Your already-filed proposals: UNKNOWN');+ expect(report).toContain('may be about to re-file something that already exists');+ expect(report).not.toContain('0 open');+ });++ it('distinguishes an unreadable learning store from a loop that has never run', () => {+ expect(computeSelfEvalSummary({ liTaskStats: { read: false, metrics: null } }))+ .toContain('LI execution health: UNAVAILABLE');+ expect(computeSelfEvalSummary({ liTaskStats: { read: true, metrics: null } }))+ .toContain('no LI runs recorded yet');+ });++ it('adds degraded-execution guidance when LI run success is under the threshold', () => {+ const report = computeSelfEvalSummary({+ liTaskStats: liMetrics({ completed: 9, succeeded: 3, failed: 6, successRate: 33 })+ });+ expect(report).toContain('33% of 9 lifetime LI runs succeeded — DEGRADED');+ expect(report).toContain('GUIDANCE — your own execution is degraded');+ expect(report).toContain('the problem may be THIS LOOP, not the app');+ expect(report).toContain('do not mark anything trivial+safe for hand-off');+ });++ it('does not fire the degraded warning on a healthy loop', () => {+ const report = computeSelfEvalSummary({ liTaskStats: liMetrics() });+ expect(report).toContain('80% of 10 lifetime LI runs succeeded');+ expect(report).not.toContain('DEGRADED');+ expect(report).not.toContain('execution is degraded');+ });++ it('does not fire the degraded warning below the sample floor', () => {+ const report = computeSelfEvalSummary({+ liTaskStats: liMetrics({ completed: 1, succeeded: 0, failed: 1, successRate: 0 })+ });+ expect(report).toContain('too small a sample to judge');+ expect(report).not.toContain('DEGRADED');+ });++ it('rates confidence high with all three signals, and drops guidance', () => {+ const outcomes = Array.from({ length: 6 }, () => ({ outcome: 'merged' }));+ const report = computeSelfEvalSummary({+ outcomes,+ existingIssues: [{ slug: 'a', state: 'open' }],+ liTaskStats: liMetrics()+ });+ expect(report).toContain('Reasoning confidence: high (3 of 3 self-signals available)');+ expect(report).not.toContain('GUIDANCE — low self-confidence');+ });++ it('rates a well-measured 0% merge rate as HIGH confidence in a bad result, not low', () => {+ // Confidence rates the EVIDENCE, not the news. A loop with solid evidence that+ // it is failing should act decisively, not hedge as if it were flying blind.+ const outcomes = Array.from({ length: 8 }, () => ({ outcome: 'rejected', outcomeReason: 'NOT_PLANNED' }));+ const report = computeSelfEvalSummary({+ outcomes,+ existingIssues: [{ slug: 'a', state: 'open' }],+ liTaskStats: liMetrics()+ });+ expect(report).toContain('0 of 8 resolved proposals merged (0%)');+ expect(report).toContain('Reasoning confidence: high');+ expect(report).not.toContain('GUIDANCE — low self-confidence');+ });++ it('rates confidence medium with two of three signals', () => {+ const report = computeSelfEvalSummary({+ outcomes: Array.from({ length: 5 }, () => ({ outcome: 'merged' })),+ existingIssues: [],+ liTaskStats: { read: false, metrics: null }+ });+ expect(report).toContain('Reasoning confidence: medium (2 of 3 self-signals available)');+ expect(report).not.toContain('GUIDANCE — low self-confidence');+ });++ it('exposes the LI task-type key and degraded thresholds', () => {+ expect(LI_TASK_TYPE).toBe('layered-intelligence');+ expect(LI_DEGRADED_SUCCESS_THRESHOLD).toBe(50);+ expect(LI_DEGRADED_MIN_SAMPLE).toBe(4);+ });+});++describe('readLiTaskMetrics (#2700)', () => {+ let dir;+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'lil-selfeval-')); });+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });++ it('reports read:false when the learning store is missing', async () => {+ expect(await readLiTaskMetrics({ cosPath: dir })).toEqual({ read: false, metrics: null });+ });++ it('reports read:false when the store is malformed (no byTaskType map)', async () => {+ await writeFile(join(dir, 'learning.json'), JSON.stringify({ byTaskType: [] }));+ expect(await readLiTaskMetrics({ cosPath: dir })).toEqual({ read: false, metrics: null });+ });++ it('reports read:true with a null bucket when LI has never run (distinct from unreadable)', async () => {+ await writeFile(join(dir, 'learning.json'), JSON.stringify({ byTaskType: { 'idle-review': { completed: 3 } } }));+ expect(await readLiTaskMetrics({ cosPath: dir })).toEqual({ read: true, metrics: null });+ });++ it('returns the layered-intelligence bucket when present', async () => {+ const bucket = { completed: 4, succeeded: 1, failed: 3, successRate: 25, recentOutcomes: [] };+ await writeFile(join(dir, 'learning.json'), JSON.stringify({ byTaskType: { [LI_TASK_TYPE]: bucket } }));+ const stats = await readLiTaskMetrics({ cosPath: dir });+ expect(stats.read).toBe(true);+ expect(stats.metrics.successRate).toBe(25);+ });+});+describe('extractPlanSlugs', () => {it('collects lil-tagged slugs with their checkbox state from PLAN.md content', () => {const plan = `## Next Up\n- [ ] [lil-add-metrics] Add metrics\n- [ ] [lil-fix-thing] Fix\n- [ ] [ref-watch-other] not ours`;