Skip to content

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

refactor(layered-intelligence): drop the unused roll-up seam and correct the delivery-block rationale (#3085)

[._.]/ Adam Eivy380b1672b2eb
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index a66286cc9e..2adaeaffc3 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -367,8 +367,10 @@ export async function buildTaskInput({ app } = {}) {
// never be read as a healthy pipeline. Done here rather than inside gatherSources
// because only this point has POST-reconciliation outcomes — a pre-reconcile snapshot
// would report a different approval count than the liOutcomes block in the same
- // 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.
+ // prompt. Present only when the `cosMetrics` source is enabled, so an app that turned
+ // that source off gets no block (its delivery signal rides liOutcomes / liSelfEval).
+ // `cosMetricsByType` is gatherSources' internal hand-off for exactly this re-render;
+ // drop it once consumed rather than leaving a spent key on the source map.
if (sources.cosMetricsByType) {
const rendered = renderCosMetricsSource({
metricsByType: sources.cosMetricsByType,
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
index 15499a0d98..07428831bf 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
@@ -374,18 +374,6 @@ describe('buildTaskInput', () => {
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.js
index 1b35738398..49cfb96298 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -729,17 +729,26 @@ describe('computeDeliveryMetrics (#3085)', () => {
}
});
- it('reuses a pre-computed roll-up instead of re-deriving it', () => {
- const metrics = computeProposalOutcomeMetrics(RECORDS);
- expect(computeDeliveryMetrics([], { metrics })).toEqual(computeDeliveryMetrics(RECORDS));
+ it('agrees with the roll-up it projects', () => {
+ // `scope` is LLM-authored, so the two must never disagree about which scope a
+ // record belongs to — the prompt and the exclusion gate both trace back here.
+ const rolled = computeProposalOutcomeMetrics(RECORDS);
+ const { delivery, deliveryByScope } = computeDeliveryMetrics(RECORDS);
+ expect(delivery.totalApproved).toBe(rolled.totalApproved);
+ expect(delivery.totalDelivered).toBe(rolled.totalCompleted);
+ expect(deliveryByScope['app-improvement'].delivered).toBe(rolled.byScope['app-improvement'].completed);
});
it('buckets a "__proto__" scope as data rather than rewriting the prototype', () => {
const { deliveryByScope } = computeDeliveryMetrics([
{ scope: '__proto__', outcome: 'merged', executionOutcome: 'success', filedAt: '2026-07-01T00:00:00.000Z', executionAt: '2026-07-01T01:00:00.000Z' }
]);
+ // On a plain object `bucket['__proto__'] = …` swaps the prototype instead of adding
+ // a key, so the bucket would vanish from Object.keys. The null prototype is what
+ // makes it data — assert the prototype directly, since a passing Object.keys check
+ // on Object.prototype pollution would be silent.
+ expect(Object.getPrototypeOf(deliveryByScope)).toBeNull();
expect(Object.keys(deliveryByScope)).toContain('__proto__');
- expect({}.approved).toBeUndefined();
});
});
@@ -1338,6 +1347,17 @@ describe('computeScopeAwareness (#2760)', () => {
describe('buildPrompt', () => {
const app = { name: 'TestApp' };
+ it('drops a blank cosMetrics document instead of rendering an empty block (#3085)', () => {
+ // renderCosMetricsSource returns '' when it has neither task types nor delivery
+ // data, and the hook assigns that straight onto sources — so the omission this
+ // relies on happens HERE. A rendered `### cosMetrics` with nothing under it would
+ // cost prompt budget and tell the reasoner nothing.
+ const base = { app, config: { allowedScopes: ['app-improvement'], rules: '' } };
+ expect(buildPrompt({ ...base, sources: { cosMetrics: '' } })).not.toContain('### cosMetrics');
+ expect(buildPrompt({ ...base, sources: { cosMetrics: '{"delivery":{"totalApproved":3}}' } }))
+ .toContain('### cosMetrics');
+ });
+
it('injects the scope-awareness block only when present, under its own heading (#2760)', () => {
const base = { app, isPortos: true, config: { allowedScopes: ['loop-meta'], rules: '' } };
const without = buildPrompt(base);
diff --git a/server/services/layeredIntelligence/outcomes.js b/server/services/layeredIntelligence/outcomes.js
index 98f34fad49..8be744365b 100644
--- a/server/services/layeredIntelligence/outcomes.js
+++ b/server/services/layeredIntelligence/outcomes.js
@@ -211,14 +211,18 @@ export function computeProposalOutcomeMetrics(outcomes = [], { stats = null, exe
* per-proposal records in `data/cos/li-outcomes/` already hold both sides of the
* lifecycle, so an on-disk counter pair incremented at each transition would be a
* second aggregate free to drift from the records it summarizes (and would need a
- * migration to seed on every existing install). Pass `metrics` when the caller has
- * already computed the full roll-up to skip a second pass.
+ * migration to seed on every existing install).
+ *
+ * PROMPT-DISPLAY ONLY. The hard exclusion gate reads its own delivery rate straight
+ * off the records via `computeLiExecutionHealth`, so nothing here is load-bearing for
+ * enforcement — which is why rounding is safe (a threshold compare must never see a
+ * rounded rate; that one does not).
*
* `currentDeliveryRate` is null — never 0 — when nothing has been approved yet: the
* sentinel rule. "No approvals to deliver on" and "every approval was lost" are
- * opposite facts, and this rate is what arms the hard exclusion gate
- * (LI_HARD_GATE_DELIVERY_THRESHOLD), so collapsing them would lock out a cold loop.
- * Rounded because this is display — the gate compares the unrounded rate itself.
+ * opposite facts, and a 0% delivery figure in the prompt is a direct instruction to
+ * the reasoner to hold back on self-directed work — exactly the wrong read for a loop
+ * that simply has no track record yet.
*
* `deliveryByScope` lists only scopes with at least one APPROVAL. A scope whose every
* proposal was rejected has no delivery signal to report (its `approved`/`delivered`
@@ -226,14 +230,12 @@ export function computeProposalOutcomeMetrics(outcomes = [], { stats = null, exe
* already covers the filing side.
*
* @param {Array} [outcomes] - the app's li-outcomes records (from listOutcomes).
- * @param {object} [opts]
- * @param {object} [opts.metrics] - a `computeProposalOutcomeMetrics(outcomes)` result.
* @returns {{ delivery: { totalApproved: number, totalDelivered: number,
* currentDeliveryRate: number|null },
* deliveryByScope: Object<string, { approved: number, delivered: number }> }}
*/
-export function computeDeliveryMetrics(outcomes = [], { metrics = null } = {}) {
- const rolled = metrics || computeProposalOutcomeMetrics(outcomes);
+export function computeDeliveryMetrics(outcomes = []) {
+ const rolled = computeProposalOutcomeMetrics(outcomes);
// Null prototype for the same reason the roll-up uses one: `scope` is an
// LLM-authored free string, so a literal "__proto__" key would rewrite the
// prototype instead of adding a bucket.
diff --git a/server/services/layeredIntelligence/sources.js b/server/services/layeredIntelligence/sources.js
index 184a5441c4..8e4a310e30 100644
--- a/server/services/layeredIntelligence/sources.js
+++ b/server/services/layeredIntelligence/sources.js
@@ -200,10 +200,13 @@ const COS_METRICS_DELIVERY_KEYS = ['delivery', 'deliveryByScope'];
* "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.
+ * data) so the caller omits the source rather than injecting a hollow `{}` block.
+ * Within the `cosMetrics` source the two halves are independently optional: a fresh
+ * install with no CoS run history can still have approved-but-undelivered proposals
+ * worth surfacing, and vice versa. Emitting the document at all still requires the
+ * `cosMetrics` source itself to be enabled — an app that turned it off gets no
+ * `### cosMetrics` block, delivery half included, and reads its delivery signal from
+ * the `liOutcomes` / `liSelfEval` blocks instead.
*
* @param {object} args
* @param {Object} [args.metricsByType] - per-task-type run stats (see gatherSources).