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(layered-intelligence): render the delivery block even with no CoS run history (#3085)
[._.]/ Adam Eivy0a8e493d05a0
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex 531f3481b2..a66286cc9e 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -370,13 +370,16 @@ export async function buildTaskInput({ app } = {}) {// prompt. `cosMetricsByType` is gatherSources' internal hand-off for exactly this// re-render; drop it so it can never leak into buildPrompt as a source block.if (sources.cosMetricsByType) {- sources.cosMetrics = renderCosMetricsSource({+ const rendered = renderCosMetricsSource({metricsByType: sources.cosMetricsByType,// Not an array = the outcomes source is off / the tracker can't report outcomes /// the store was unreadable. Omit the block rather than emitting zeros that would// read as "nothing has ever been approved".delivery: Array.isArray(outcomes) ? computeDeliveryMetrics(outcomes) : null})+ // '' when BOTH halves are empty (no task types, no delivery data) — buildPrompt+ // drops a blank source, so the block is omitted rather than rendering a hollow `{}`.+ sources.cosMetrics = rendereddelete sources.cosMetricsByType}diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.jsindex 0dd0608f82..15499a0d98 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js@@ -129,6 +129,8 @@ beforeEach(() => {// set, so restore the module default here — otherwise a test that hands back a// `cosMetricsByType` (#3085) leaks the re-render into every later assertion on sources.li.gatherSources.mockResolvedValue({ goals: 'be great' });+ li.renderCosMetricsSource.mockReturnValue('RE-RENDERED COS METRICS');+ listOutcomesResult.mockResolvedValue({ read: true, outcomes: [] });li.listBlockingIssues.mockResolvedValue({ ok: true, issues: [] });li.listForgeIssues.mockResolvedValue({ ok: true, issues: [] });li.isAppParked.mockReturnValue(false);@@ -359,6 +361,31 @@ describe('buildTaskInput', () => {expect(li.renderCosMetricsSource).toHaveBeenCalledWith(expect.objectContaining({ delivery: null }));});+ it('renders NO delivery block when the outcome store was unreadable (#3085)', async () => {+ // A FAILED read is not an empty history: `read: false` must not project as+ // "0 approved", which would tell the reasoner delivery is fine when we simply+ // cannot see it. Distinct from the source-off case above — same required outcome,+ // different cause, and only this one goes through the outcomes pipeline.+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { cosMetrics: true, outcomes: true } })+ li.gatherSources.mockResolvedValue({ cosMetrics: 'FIRST PASS', cosMetricsByType: { 'user-task': {} } })+ listOutcomesResult.mockResolvedValue({ read: false, outcomes: [] })+ await buildTaskInput({ app: APP })+ expect(li.computeDeliveryMetrics).not.toHaveBeenCalled()+ expect(li.renderCosMetricsSource).toHaveBeenCalledWith(expect.objectContaining({ delivery: null }))+ })++ it('omits the cosMetrics block entirely when neither half has data (#3085)', async () => {+ // No CoS run history AND no delivery data → renderCosMetricsSource returns '',+ // which buildPrompt drops rather than emitting a hollow `{}` source block.+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { cosMetrics: true } })+ li.gatherSources.mockResolvedValue({ goals: 'be great', cosMetricsByType: {} })+ li.renderCosMetricsSource.mockReturnValue('')+ await buildTaskInput({ app: APP })+ const { sources } = li.buildPrompt.mock.calls.at(-1)[0]+ expect(sources.cosMetrics).toBe('')+ expect('cosMetricsByType' in sources).toBe(false)+ })+it('leaves cosMetrics alone when the source is off (#3085)', async () => {li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { outcomes: true } });li.gatherSources.mockResolvedValue({ goals: 'be great' });diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex fa19421fa1..1b35738398 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -754,6 +754,23 @@ describe('renderCosMetricsSource (#3085)', () => {expect(parsed.delivery).toBeUndefined();});+ it('renders delivery alone when the install has no CoS run history yet', () => {+ // The two halves are independently optional: an install with no learning.json can+ // still have approved-but-undelivered proposals, and that is exactly the signal+ // that arms the exclusion gate — it must not be withheld for lack of run stats.+ const parsed = JSON.parse(renderCosMetricsSource({+ metricsByType: {},+ delivery: computeDeliveryMetrics([{ scope: 'loop-meta', outcome: 'merged', executionOutcome: null, filedAt: '2026-07-01T00:00:00.000Z' }])+ }));+ expect(parsed.delivery).toEqual({ totalApproved: 1, totalDelivered: 0, currentDeliveryRate: 0 });+ });++ it('returns an empty string when both halves are empty so the source is omitted', () => {+ // A hollow `{}` block would tell the reasoner nothing while costing prompt budget.+ expect(renderCosMetricsSource()).toBe('');+ expect(renderCosMetricsSource({ metricsByType: {}, delivery: null })).toBe('');+ });+it('folds delivery into the same document as the run rates', () => {const delivery = computeDeliveryMetrics([{ scope: 'app-improvement', outcome: 'merged', executionOutcome: 'success', filedAt: '2026-07-01T00:00:00.000Z', executionAt: '2026-07-01T01:00:00.000Z' }@@ -2986,6 +3003,16 @@ describe('gatherSources cosMetrics windowed rate (issue #2460)', () => {expect(JSON.parse(out.cosMetrics).delivery).toBeUndefined();});+ it('still hands off an empty per-type map when learning.json is missing, so delivery can render (#3085)', async () => {+ // No learning.json at all: the source used to be skipped outright, which would have+ // withheld the delivery half too — and that half comes from the outcome records, not+ // from here. Hand back an empty map so the hook can still render delivery; the+ // rendered document stays omitted while BOTH halves are empty.+ const out = await gatherSources({ repoPath: dir }, { sources: { cosMetrics: true } }, { cosPath: dir });+ expect(out.cosMetricsByType).toEqual({});+ expect(out.cosMetrics).toBeUndefined();+ });+it('does not emit scopeGuidance when cosMetrics is off (#2760)', async () => {await writeLearning({byTaskType: { 'accessibility': { completed: 4, succeeded: 0, failed: 4, successRate: 0, recentOutcomes: [] } }diff --git a/server/services/layeredIntelligence/sources.js b/server/services/layeredIntelligence/sources.jsindex 789e86120a..184a5441c4 100644--- a/server/services/layeredIntelligence/sources.js+++ b/server/services/layeredIntelligence/sources.js@@ -199,14 +199,21 @@ const COS_METRICS_DELIVERY_KEYS = ['delivery', 'deliveryByScope'];* `currentDeliveryRate`, so "we have no delivery data" stays distinguishable from* "nothing has been approved yet".*+ * Returns '' when there is nothing at all to report (no task types AND no delivery+ * data) so the caller omits the source rather than injecting a hollow `{}` block —+ * both halves of this document are independently optional. A fresh install with no+ * CoS run history can still have approved-but-undelivered proposals worth surfacing,+ * and vice versa.+ ** @param {object} args* @param {Object} [args.metricsByType] - per-task-type run stats (see gatherSources).* @param {{ delivery: object, deliveryByScope: object }|null} [args.delivery] - a* `computeDeliveryMetrics(outcomes)` result, or null when none was gathered.- * @returns {string} the JSON document, capped at COS_METRICS_MAX_CHARS.+ * @returns {string} the JSON document capped at COS_METRICS_MAX_CHARS, or ''.*/export function renderCosMetricsSource({ metricsByType = {}, delivery = null } = {}) {const payload = {};+ if (!delivery && Object.keys(metricsByType || {}).length === 0) return '';// Reserved keys are INSERTED first (JSON.stringify follows insertion order, so the// cap above can't cut them) but ASSIGNED last, so a task type that happens to share// one of their names can't shadow the delivery block.@@ -272,48 +279,53 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShe// the app being analyzed — see the default-config note for the PortOS-vs-managed// rationale (default-off for managed apps).const learning = await readJSONFile(join(cosPath, 'learning.json'), null);- if (learning?.byTaskType) {- // Surface BOTH the lifetime rate (the cumulative dashboard/telemetry truth)- // AND a recency-windowed rate (issue #2460) per task type, labeled distinctly- // so the reasoner doesn't conflate them. The windowed rate lets a- // since-resolved failure burst age out of the "is work needed" signal instead- // of permanently depressing it; `recentSuccessRate` is null when there are no- // in-window runs, in which case the reasoner leans on the lifetime rate.- // Note the intentional rename: computeWindowedStats' internal `windowed*`- // fields are surfaced to the reasoner as `recent*` (reads more naturally in- // the prompt context) — same concept, deliberately different label here.- const summary = {};- for (const [type, m] of Object.entries(learning.byTaskType)) {- const windowed = computeWindowedStats(m?.recentOutcomes);- summary[type] = {- lifetimeSuccessRate: typeof m?.successRate === 'number' ? m.successRate : null,- lifetimeCompleted: m?.completed || 0,- recentSuccessRate: windowed.windowedSuccessRate,- recentCompleted: windowed.windowedCompleted,- avgDurationMs: m?.avgDurationMs || 0- };- }- // No delivery block yet: the approval → delivery numbers come from the app's- // outcome records, which the hook only has AFTER it has reconciled them against- // this run's tracker read. The raw per-type map rides along on- // `cosMetricsByType` so the hook can re-render the document once with both- // halves (see renderCosMetricsSource) rather than emitting a delivery figure- // one cycle stale — two blocks in one prompt disagreeing about how many- // proposals are approved is worse than either number alone.- out.cosMetricsByType = summary;- out.cosMetrics = renderCosMetricsSource({ metricsByType: summary });- // Scope-awareness guidance (#2760): a deterministic low/high-completion split- // derived from the SAME per-type rates above, so the reasoner gets an interpreted- // signal alongside the raw JSON instead of being asked to spot the pattern itself.- // Rendered as its own prompt block (see buildPrompt). Gated on isPortos (codex P2):- // these are THIS install's own CoS completion rates, meaningless to a managed app —- // and a managed app CAN enable the cosMetrics source, so the cosMetrics toggle- // alone is not the PortOS boundary. buildPrompt re-checks isPortos as defense in- // depth; deriving it here only for PortOS also avoids the wasted work.- if (isPortos) {- const scopeGuidance = computeScopeAwareness({ metricsByType: summary });- if (scopeGuidance) out.scopeGuidance = scopeGuidance;- }+ // Surface BOTH the lifetime rate (the cumulative dashboard/telemetry truth)+ // AND a recency-windowed rate (issue #2460) per task type, labeled distinctly+ // so the reasoner doesn't conflate them. The windowed rate lets a+ // since-resolved failure burst age out of the "is work needed" signal instead+ // of permanently depressing it; `recentSuccessRate` is null when there are no+ // in-window runs, in which case the reasoner leans on the lifetime rate.+ // Note the intentional rename: computeWindowedStats' internal `windowed*`+ // fields are surfaced to the reasoner as `recent*` (reads more naturally in+ // the prompt context) — same concept, deliberately different label here.+ //+ // An unreadable / byTaskType-less learning store yields an EMPTY map rather than+ // skipping the source: the delivery half of this document (#3085) comes from the+ // outcome records, not learning.json, so an install with no CoS run history can+ // still have approved-but-undelivered proposals worth surfacing. When both halves+ // are empty renderCosMetricsSource returns '' and the source is omitted as before.+ const summary = {};+ for (const [type, m] of Object.entries(learning?.byTaskType || {})) {+ const windowed = computeWindowedStats(m?.recentOutcomes);+ summary[type] = {+ lifetimeSuccessRate: typeof m?.successRate === 'number' ? m.successRate : null,+ lifetimeCompleted: m?.completed || 0,+ recentSuccessRate: windowed.windowedSuccessRate,+ recentCompleted: windowed.windowedCompleted,+ avgDurationMs: m?.avgDurationMs || 0+ };+ }+ // No delivery block yet: the approval → delivery numbers come from the app's+ // outcome records, which the hook only has AFTER it has reconciled them against+ // this run's tracker read. The raw per-type map rides along on `cosMetricsByType`+ // so the hook can re-render the document once with both halves (see+ // renderCosMetricsSource) rather than emitting a delivery figure one cycle stale —+ // two blocks in one prompt disagreeing about how many proposals are approved is+ // worse than either number alone.+ out.cosMetricsByType = summary;+ const rendered = renderCosMetricsSource({ metricsByType: summary });+ if (rendered) out.cosMetrics = rendered;+ // Scope-awareness guidance (#2760): a deterministic low/high-completion split+ // derived from the SAME per-type rates above, so the reasoner gets an interpreted+ // signal alongside the raw JSON instead of being asked to spot the pattern itself.+ // Rendered as its own prompt block (see buildPrompt). Gated on isPortos (codex P2):+ // these are THIS install's own CoS completion rates, meaningless to a managed app —+ // and a managed app CAN enable the cosMetrics source, so the cosMetrics toggle+ // alone is not the PortOS boundary. buildPrompt re-checks isPortos as defense in+ // depth; deriving it here only for PortOS also avoids the wasted work.+ if (isPortos) {+ const scopeGuidance = computeScopeAwareness({ metricsByType: summary });+ if (scopeGuidance) out.scopeGuidance = scopeGuidance;}}for (const custom of src.custom || []) {