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
fix: purge the poisoned LI learning bucket and preserve outcome-store read failures (#2700)
[._.]/ Adam Eivye3c97b5e2a38
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex cb1e46d1ae..b63ae0348d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -26,7 +26,7 @@## Fixed-- [issue-2700] **Layered Intelligence runs were being recorded as failures even when they succeeded.** An LI run is a *reasoning* run: it's explicitly told not to commit or open a PR, and hands its result back through a sentinel file instead. But the shared success check only knows how to look for a code commit, and its verdict overrides the run's actual exit code — so every correct LI run was filed as a failure, dragging the loop's success rate toward 0% and skewing anything built on it (task routing, the CoS Learning card, duration estimates). Task types that hand back results programmatically rather than as a commit are now exempt from the commit check, the same way pipeline and media jobs already were. Ordinary code tasks are still held to it.+- [issue-2700] **Layered Intelligence runs were being recorded as failures even when they succeeded.** An LI run is a *reasoning* run: it's explicitly told not to commit or open a PR, and hands its result back through a sentinel file instead. But the shared success check only knows how to look for a code commit, and its verdict overrides the run's actual exit code — so every correct LI run was filed as a failure, dragging the loop's success rate toward 0% and skewing anything built on it (task routing, the CoS Learning card, duration estimates). Task types that hand back results programmatically rather than as a commit are now exempt from the commit check, the same way pipeline and media jobs already were. Ordinary code tasks are still held to it. Because the mis-recorded history can't be reconstructed after the fact, installs that already ran the loop get that one bucket cleared on upgrade, so it starts from an honest "no runs recorded yet" rather than a fabricated 0% — no other task type's stats are touched.- **The Scene evaluation model dropdown no longer comes up empty when you have vision models installed.** Picking Ollama for a Creative Director project's Scene evaluation showed an empty model list (and a bare text box) even with vision-capable models pulled, because the browser decided what counts as a vision model from a hard-coded list of model-name patterns that knew `gemma-3` but not `gemma4` — so `gemma4:e4b` and `qwen3.6:35b` were filtered out as if they were text-only. Vision pickers now ask the server, which reads each model's real capabilities from the backend itself (Ollama's `/api/show`, LM Studio's `vlm` tag), and union that with the old name matching — so a newer model family shows up without waiting for the pattern list to catch up, and nothing that used to be offered disappears. The AI Assignments table's vision rows get the same fix. Also, the Scene evaluation stage now explains that it needs an API provider (Ollama / LM Studio) and can't use an agent CLI/TUI provider such as Claude Ollama TUI — pinning one there was silently ignored at run time — and a provider with no vision model installed now says so, with a link to install one, instead of showing an empty dropdown.- The Chief of Staff status panel's Learning card no longer spills its skipped-task count outside the card on mobile. The "(3 skipped)" note used to sit beside the success rate on one line, where it was too wide to fit a narrow card and rendered past the border; it now sits on its own line under the percentage and truncates if it can't fit.diff --git a/scripts/migrations/197-purge-poisoned-li-learning-bucket.js b/scripts/migrations/197-purge-poisoned-li-learning-bucket.jsnew file mode 100644index 0000000000..6336a2b4cf--- /dev/null+++ b/scripts/migrations/197-purge-poisoned-li-learning-bucket.js@@ -0,0 +1,104 @@+/**+ * Purge the Layered Intelligence learning bucket poisoned by the commit-criterion+ * bug (#2700).+ *+ * Background:+ * An LI run is a REASONING run: its prompt explicitly forbids committing or+ * opening a PR (the worktree is discarded), and it returns its result through the+ * `.agent-done` sentinel for an output hook to file. But `evaluateSuccessCriteria`+ * only knew one machine-checkable criterion — a `[task-<id>]` commit — and fell+ * through to it for LI. Since a declared verdict OVERRIDES the runner's exit code+ * in task-learning (`outcomeSuccess` in taskLearning/metrics.js), every correctly+ * executed LI run was recorded as a FAILURE.+ *+ * `agentLifecycle.js` now exempts programmatic-I/O task types from that criterion,+ * the same way pipeline/media jobs already were. But that fix is PROSPECTIVE: an+ * install that has already run the agent-backed LI task carries a bucket whose+ * `succeeded`/`successRate`/`recentOutcomes` are fabricated failures.+ *+ * That stale data is not inert. The new `selfEval` LI source (#2700, default-ON+ * for the PortOS install) reads this exact bucket to judge whether the loop's own+ * execution is healthy, and would read the poisoned history as a ~0% success rate+ * — permanently reporting "your execution is DEGRADED" and steering the reasoner+ * away from filing, on evidence that was never true. The same numbers also feed+ * routing, the CoS Learning card, and duration estimates.+ *+ * Approach:+ * DELETE the bucket rather than trying to repair it. The recorded outcomes cannot+ * be reconstructed: `validationPassed:false` overwrote the runner's real verdict,+ * so the truth of each historical run is simply not on disk. Deleting resets LI to+ * an honest "no runs recorded yet" — which the readers already model correctly+ * (`readLiTaskMetrics` returns `{ read: true, metrics: null }` for an absent+ * bucket, and selfEval renders "no LI runs recorded yet" and withholds the+ * execution-health signal from its confidence math). Inventing a success rate to+ * replace it would be the same sin in the opposite direction.+ *+ * Scoped to `self-improve:layered-intelligence` — the ONLY registered+ * programmatic-I/O task type (taskTypeHooks.js `HOOK_MODULES`), so no other+ * bucket was affected by the bug and none are touched here. Environmental-failure+ * entries keyed to the type are purged alongside it via the existing+ * `purgeEnvironmentalFailuresForType` helper, so the ledger can't keep pointing at+ * failures whose bucket is gone.+ *+ * No-op by construction on installs that never ran LI (the common case) — the+ * file is only rewritten when the bucket is actually present.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++import { purgeEnvironmentalFailuresForType } from '../../server/services/taskLearning/metrics.js';++const LEARNING_REL = 'data/cos/learning.json';++// The key LI's runs are recorded under. A scheduled LI task carries+// `metadata.analysisType = 'layered-intelligence'`, and extractTaskType's first+// branch prefixes any such task into `self-improve:<type>` — so this, not the bare+// schedule name, is the poisoned bucket.+const LI_BUCKET = 'self-improve:layered-intelligence';++export default {+ async up({ rootDir }) {+ const path = join(rootDir, LEARNING_REL);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) {+ console.log('✅ LI learning: no learning store — nothing to purge');+ return { purged: 0, reason: 'no-file' };+ }++ let data;+ try {+ data = JSON.parse(raw);+ } catch {+ // A corrupt learning store is not this migration's problem to fix, and+ // rewriting it would risk destroying recoverable data.+ console.warn('⚠️ LI learning: store is not valid JSON — skipping');+ return { purged: 0, reason: 'unparseable' };+ }+ if (!data || typeof data !== 'object' || Array.isArray(data)) {+ console.warn('⚠️ LI learning: store is not an object — skipping');+ return { purged: 0, reason: 'unexpected-shape' };+ }++ const byTaskType = data.byTaskType;+ const hasBucket = byTaskType && typeof byTaskType === 'object' && !Array.isArray(byTaskType)+ && Object.hasOwn(byTaskType, LI_BUCKET);+ if (!hasBucket) {+ console.log('✅ LI learning: no layered-intelligence bucket — no changes');+ return { purged: 0 };+ }++ const completed = byTaskType[LI_BUCKET]?.completed || 0;+ delete byTaskType[LI_BUCKET];+ // Keep the environmental-failure ledger consistent with the bucket we just+ // dropped — reuses the runtime helper rather than re-encoding its shape here.+ purgeEnvironmentalFailuresForType(data, LI_BUCKET);++ await writeFile(path, JSON.stringify(data, null, 2) + '\n');+ console.log(`🧹 LI learning: purged ${completed} mis-recorded layered-intelligence run(s) (#2700)`);+ return { purged: completed };+ },+};diff --git a/scripts/migrations/197-purge-poisoned-li-learning-bucket.test.js b/scripts/migrations/197-purge-poisoned-li-learning-bucket.test.jsnew file mode 100644index 0000000000..3b76cdaa04--- /dev/null+++ b/scripts/migrations/197-purge-poisoned-li-learning-bucket.test.js@@ -0,0 +1,92 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, mkdir, rm, readFile, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './197-purge-poisoned-li-learning-bucket.js';++let rootDir;++const LEARNING_REL = 'data/cos/learning.json';+const LI_BUCKET = 'self-improve:layered-intelligence';++async function seed(data) {+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ await writeFile(join(rootDir, LEARNING_REL), JSON.stringify(data, null, 2));+}++async function readLearning() {+ return JSON.parse(await readFile(join(rootDir, LEARNING_REL), 'utf-8'));+}++beforeEach(async () => { rootDir = await mkdtemp(join(tmpdir(), 'mig197-')); });+afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });++describe('197-purge-poisoned-li-learning-bucket (#2700)', () => {+ it('drops the poisoned LI bucket and leaves every other task type untouched', async () => {+ await seed({+ byTaskType: {+ [LI_BUCKET]: { completed: 12, succeeded: 0, failed: 12, successRate: 0, recentOutcomes: [{ t: '2026-07-01T00:00:00Z', s: false }] },+ 'self-improve:ui': { completed: 5, succeeded: 4, failed: 1, successRate: 80, recentOutcomes: [] },+ 'idle-review': { completed: 3, succeeded: 3, failed: 0, successRate: 100 }+ }+ });+ const out = await migration.up({ rootDir });+ expect(out.purged).toBe(12);+ const data = await readLearning();+ expect(data.byTaskType[LI_BUCKET]).toBeUndefined();+ // An absent bucket is what readLiTaskMetrics reads as an honest "never ran".+ expect(Object.keys(data.byTaskType).sort()).toEqual(['idle-review', 'self-improve:ui']);+ expect(data.byTaskType['self-improve:ui'].successRate).toBe(80);+ });++ it('purges the environmental-failure ledger entries for the dropped bucket', async () => {+ await seed({+ byTaskType: { [LI_BUCKET]: { completed: 2, succeeded: 0, failed: 2, successRate: 0 } },+ environmentalFailures: {+ 'network': { count: 3, lastOccurred: '2026-07-01T00:00:00Z', taskTypes: { [LI_BUCKET]: 2, 'idle-review': 1 } },+ 'disk': { count: 1, lastOccurred: '2026-07-01T00:00:00Z', taskTypes: { [LI_BUCKET]: 1 } }+ }+ });+ await migration.up({ rootDir });+ const data = await readLearning();+ // The LI share is removed; the unrelated task type's entry survives.+ expect(data.environmentalFailures.network.taskTypes).toEqual({ 'idle-review': 1 });+ expect(data.environmentalFailures.network.count).toBe(1);+ // A category that only ever held LI failures goes away entirely.+ expect(data.environmentalFailures.disk).toBeUndefined();+ });++ it('is a no-op on an install that never ran LI', async () => {+ await seed({ byTaskType: { 'idle-review': { completed: 3, succeeded: 3, failed: 0, successRate: 100 } } });+ const before = await readFile(join(rootDir, LEARNING_REL), 'utf-8');+ const out = await migration.up({ rootDir });+ expect(out.purged).toBe(0);+ // Untouched byte-for-byte — no rewrite when nothing matched.+ expect(await readFile(join(rootDir, LEARNING_REL), 'utf-8')).toBe(before);+ });++ it('no-ops when the learning store does not exist yet', async () => {+ const out = await migration.up({ rootDir });+ expect(out).toEqual({ purged: 0, reason: 'no-file' });+ });++ it('skips (never rewrites) a corrupt or unexpectedly-shaped store', async () => {+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ await writeFile(join(rootDir, LEARNING_REL), '{ not json');+ expect(await migration.up({ rootDir })).toEqual({ purged: 0, reason: 'unparseable' });+ expect(await readFile(join(rootDir, LEARNING_REL), 'utf-8')).toBe('{ not json');++ await writeFile(join(rootDir, LEARNING_REL), JSON.stringify([1, 2]));+ expect(await migration.up({ rootDir })).toEqual({ purged: 0, reason: 'unexpected-shape' });+ });++ it('does not confuse the bare schedule name for the recorded bucket key', async () => {+ // 'layered-intelligence' is the SCHEDULE key (and the type-failure ledger's),+ // and was never the bucket the runs landed in — it must not be purged.+ await seed({ byTaskType: { 'layered-intelligence': { completed: 4, succeeded: 4, failed: 0, successRate: 100 } } });+ const out = await migration.up({ rootDir });+ expect(out.purged).toBe(0);+ expect((await readLearning()).byTaskType['layered-intelligence']).toBeDefined();+ });+});diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex 03167d67d4..60f25742e5 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -57,7 +57,7 @@ import {readLiTaskMetrics,hasPlannedWorkListing} from '../layeredIntelligence.js'-import { recordFiledProposal, listOutcomes, reconcileOutcomes } from '../layeredIntelligenceOutcomes.js'+import { recordFiledProposal, listOutcomesResult, reconcileOutcomes } from '../layeredIntelligenceOutcomes.js'// The outcome feedback loop (#2428) can only reconcile a proposal's fate on a// tracker that reports closed-state. All three now qualify: a forge (gh/glab@@ -320,7 +320,11 @@ export async function buildTaskInput({ app } = {}) {let outcomesReport = ''if (config.sources?.outcomes && outcomesTrackerSupported(filer)) {if (!trackerReadFailed) await reconcileOutcomes({ appId: app.id, existingIssues })- outcomes = await listOutcomes({ appId: app.id })+ // Discriminated read: an unreadable outcome store stays `null` here rather than+ // collapsing to `[]`, so selfEval reports its merge rate as UNAVAILABLE instead+ // of telling the reasoner it has never filed a proposal.+ const outcomesRead = await listOutcomesResult({ appId: app.id })+ outcomes = outcomesRead.read ? outcomesRead.outcomes : null// 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 adiff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.jsindex a701d92e9c..bb5e7fa820 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js@@ -71,13 +71,13 @@ vi.mock('../layeredIntelligence.js', () => ({// asserted without touching the real collection store on disk.vi.mock('../layeredIntelligenceOutcomes.js', () => ({recordFiledProposal: vi.fn().mockResolvedValue(true),- listOutcomes: vi.fn().mockResolvedValue([]),+ listOutcomesResult: vi.fn().mockResolvedValue({ read: true, outcomes: [] }),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 { recordFiledProposal, listOutcomesResult, reconcileOutcomes } from '../layeredIntelligenceOutcomes.js';import * as apps from '../apps.js';import { resolveAppWorkTracker } from '../../lib/workTracker.js';import { tryReadFile } from '../../lib/fileUtils.js';@@ -274,17 +274,17 @@ describe('buildTaskInput', () => {li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: {} });await buildTaskInput({ app: APP });expect(reconcileOutcomes).not.toHaveBeenCalled();- expect(listOutcomes).not.toHaveBeenCalled();+ expect(listOutcomesResult).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' }]);+ listOutcomesResult.mockResolvedValue({ read: true, outcomes: [{ slug: 's', outcome: 'merged', scope: 'app-improvement' }] });li.computeOutcomesReport.mockReturnValue('Recent LI proposals:\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(listOutcomesResult).toHaveBeenCalledWith(expect.objectContaining({ appId: 'app-1' }));expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({ outcomesReport: expect.stringContaining('Total filed: 1') }));});@@ -316,13 +316,30 @@ describe('buildTaskInput', () => {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' }]);+ listOutcomesResult.mockResolvedValue({ read: true, outcomes: [{ 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 outcomes to selfEval as null when the outcome STORE could not be read (#2700)', async () => {+ // An unreadable store must not reach the reasoner as "you have never filed a+ // proposal" — that invites it to re-file work it already filed.+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { outcomes: true, selfEval: true } });+ listOutcomesResult.mockResolvedValue({ read: false, outcomes: [] });+ await buildTaskInput({ app: APP });+ expect(li.computeSelfEvalSummary).toHaveBeenCalledWith(expect.objectContaining({ outcomes: null }));+ });++ it('distinguishes a read-but-empty outcome store from an unreadable one (#2700)', async () => {+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { outcomes: true, selfEval: true } });+ listOutcomesResult.mockResolvedValue({ read: true, outcomes: [] });+ await buildTaskInput({ app: APP });+ // Read fine, nothing filed → `[]`, NOT the null "unavailable" sentinel.+ expect(li.computeSelfEvalSummary).toHaveBeenCalledWith(expect.objectContaining({ outcomes: [] }));+ });+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' }] });@@ -345,14 +362,14 @@ describe('buildTaskInput', () => {// The plan branch reads PLAN.md → a checked item reconciles like a forge issue.tryReadFile.mockResolvedValue('- [x] [lil-add-metrics] done');li.extractPlanSlugs.mockReturnValue([{ slug: 'add-metrics', state: 'closed' }]);- listOutcomes.mockResolvedValue([{ slug: 'add-metrics', outcome: 'merged', scope: 'app-improvement' }]);+ listOutcomesResult.mockResolvedValue({ read: true, outcomes: [{ slug: 'add-metrics', outcome: 'merged', scope: 'app-improvement' }] });li.computeOutcomesReport.mockReturnValue('Recent LI proposals:\n- Total filed: 1');await buildTaskInput({ app: APP });expect(reconcileOutcomes).toHaveBeenCalledWith(expect.objectContaining({appId: 'app-1',existingIssues: [{ slug: 'add-metrics', state: 'closed' }]}));- expect(listOutcomes).toHaveBeenCalledWith(expect.objectContaining({ appId: 'app-1' }));+ expect(listOutcomesResult).toHaveBeenCalledWith(expect.objectContaining({ appId: 'app-1' }));expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({ outcomesReport: expect.stringContaining('Total filed: 1') }));});});diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.jsindex 396486df03..a62f82db42 100644--- a/server/services/layeredIntelligenceOutcomes.js+++ b/server/services/layeredIntelligenceOutcomes.js@@ -131,10 +131,32 @@ export async function recordFiledProposal({ appId, slug, tracker = null, issueRe* closes. A RESOLVED record expires OUTCOME_RETENTION_MS after its resolution* (outcomeAt), not its filing, so a long-open-then-merged proposal isn't dropped* the moment it resolves. Returns survivors sorted newest-filed-first. Never throws.+ *+ * Prefer `listOutcomesResult` when the caller must be able to tell a FAILED store+ * read from a genuinely empty history — this wrapper flattens the two together for+ * back-compat with callers that can't act on the difference anyway.+ */+export async function listOutcomes(args = {}, store = outcomesStore()) {+ return (await listOutcomesResult(args, store)).outcomes;+}++/**+ * `listOutcomes` with a discriminated read status (#2700):+ * `{ read: true, outcomes: [...] }` — the store was read; the list is the truth+ * (an empty one means nothing was ever filed).+ * `{ read: false, outcomes: [] }` — the store could NOT be read.+ *+ * The distinction is load-bearing for selfEval, which reports LI's merge rate to the+ * reasoner: a corrupt/unreadable store flattened to `[]` would tell the loop "you+ * have never filed a proposal" and invite it to re-file work it already filed, on+ * evidence that doesn't exist. Same sentinel rule as readLiTaskMetrics.*/-export async function listOutcomes({ appId, now = Date.now() } = {}, store = outcomesStore()) {- if (!appId) return [];- const all = await store.loadAll().catch(() => []);+export async function listOutcomesResult({ appId, now = Date.now() } = {}, store = outcomesStore()) {+ // No appId is a caller bug, not a store failure: nothing was asked for, so the+ // honest answer is an empty (successful) read, not "the store is broken".+ if (!appId) return { read: true, outcomes: [] };+ const all = await store.loadAll().catch(() => null);+ if (!Array.isArray(all)) return { read: false, outcomes: [] };const mine = all.filter(r => r && r.appId === appId);const kept = [];for (const r of mine) {@@ -147,7 +169,7 @@ export async function listOutcomes({ appId, now = Date.now() } = {}, store = out}kept.push(r);}- return kept.sort((a, b) => (Date.parse(b.filedAt) || 0) - (Date.parse(a.filedAt) || 0));+ return { read: true, outcomes: kept.sort((a, b) => (Date.parse(b.filedAt) || 0) - (Date.parse(a.filedAt) || 0)) };}/**diff --git a/server/services/layeredIntelligenceOutcomes.test.js b/server/services/layeredIntelligenceOutcomes.test.jsindex 058ebb20d5..a03f8ebe1e 100644--- a/server/services/layeredIntelligenceOutcomes.test.js+++ b/server/services/layeredIntelligenceOutcomes.test.js@@ -7,6 +7,7 @@ import {sanitizeOutcomeRecord,recordFiledProposal,listOutcomes,+ listOutcomesResult,reconcileOutcomes,OUTCOME_RETENTION_MS,LI_OUTCOMES_SCHEMA_VERSION@@ -188,3 +189,38 @@ describe('reconcileOutcomes', () => {expect(await reconcileOutcomes({ appId: 'app-1', existingIssues: [] }, store)).toBe(0);});});++describe('listOutcomesResult read sentinel (#2700)', () => {+ it('reports read:true with the records on a successful read', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 'add-metrics', tracker: 'github', issueRef: '#42' }, store);+ const res = await listOutcomesResult({ appId: 'app-1' }, store);+ expect(res.read).toBe(true);+ expect(res.outcomes).toHaveLength(1);+ });++ it('reports read:true with [] when the store is readable but this app filed nothing', async () => {+ // "Nothing filed" is a real, trustworthy answer — distinct from a failed read.+ expect(await listOutcomesResult({ appId: 'app-1' }, store)).toEqual({ read: true, outcomes: [] });+ });++ it('reports read:false when the store read throws — never a fabricated empty history', async () => {+ const broken = { loadAll: () => Promise.reject(new Error('disk on fire')), deleteOne: () => Promise.resolve() };+ expect(await listOutcomesResult({ appId: 'app-1' }, broken)).toEqual({ read: false, outcomes: [] });+ });++ it('reports read:false when the store returns a non-array', async () => {+ const broken = { loadAll: () => Promise.resolve(null), deleteOne: () => Promise.resolve() };+ expect(await listOutcomesResult({ appId: 'app-1' }, broken)).toEqual({ read: false, outcomes: [] });+ });++ it('treats a missing appId as an empty successful read, not a store failure', async () => {+ expect(await listOutcomesResult({}, store)).toEqual({ read: true, outcomes: [] });+ });++ it('listOutcomes still flattens to the bare array for back-compat', async () => {+ await recordFiledProposal({ appId: 'app-1', slug: 'add-metrics', tracker: 'github', issueRef: '#42' }, store);+ expect(await listOutcomes({ appId: 'app-1' }, store)).toHaveLength(1);+ const broken = { loadAll: () => Promise.reject(new Error('nope')), deleteOne: () => Promise.resolve() };+ expect(await listOutcomes({ appId: 'app-1' }, broken)).toEqual([]);+ });+});