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

feat(layered-intelligence): surface approved-proposal delivery alongside run success in cosMetrics (#3085)

[._.]/ Adam Eivy30eee94b1217
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9de9def95a..205a170efa 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -54,3 +54,7 @@
## Video generation
- **[issue-3100] New Control mode for local video generation** — feed a control clip (a depth pass, a pose track, edges) alongside your prompt and the render follows its structure and motion instead of inventing them. The reference can be a fresh upload or any prior render from your history, and a strength slider dials how tightly the output tracks it. A half-res preview toggle skips the refinement pass so you can check whether a control clip fits before committing to a full render. Requires an LTX-2 model; the ~654 MB Control weight downloads with progress from the mode panel and is covered by the existing model verify/repair buttons.
+
+## Layered Intelligence
+
+- **[issue-3085] The self-improvement loop can now see whether its approved proposals actually get delivered, not just whether its agent runs finish.** The `cosMetrics` block it reasons over reported per-task-type run success — "did the agent's task complete?" — and nothing about delivery, so a 90% run rate sat there looking healthy beside a pipeline that had landed none of ten approved proposals. That same block now carries a `delivery` figure (approved, delivered, and the current delivery rate) plus a per-scope breakdown, so the two numbers are read side by side. The rate is reported as unknown rather than 0% until something has actually been approved — a loop with no track record shouldn't read as a loop that fails everything.
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index c94ff8d1dc..531f3481b2 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -53,6 +53,8 @@ import {
resolveJiraBlockKey,
applyJiraBlockingLabel,
computeOutcomesReport,
+ computeDeliveryMetrics,
+ renderCosMetricsSource,
computeSelfEvalSummary,
computeProposalExecutionAwareness,
computeCrossReferenceAnalysis,
@@ -360,6 +362,24 @@ export async function buildTaskInput({ app } = {}) {
}
}
+ // Delivery block (#3085): fold the approval → delivery numbers into the SAME
+ // cosMetrics document the per-task-type run rates live in, so a healthy run rate can
+ // 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.
+ if (sources.cosMetricsByType) {
+ sources.cosMetrics = 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
+ })
+ delete sources.cosMetricsByType
+ }
+
// 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
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
index a7c6ccf5b0..0dd0608f82 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
@@ -56,6 +56,15 @@ vi.mock('../layeredIntelligence.js', () => ({
resolveJiraBlockKey: vi.fn(() => null),
applyJiraBlockingLabel: vi.fn().mockResolvedValue({ success: true }),
computeOutcomesReport: vi.fn(() => ''),
+ // Delivery block folded into cosMetrics (#3085). Both are pure and unit-tested in
+ // layeredIntelligence.test.js; spies here so the hook's WIRING can be asserted —
+ // that the POST-reconciliation outcomes are what get projected, and that the
+ // re-rendered document (not gatherSources' first pass) reaches buildPrompt.
+ computeDeliveryMetrics: vi.fn(() => ({
+ delivery: { totalApproved: 3, totalDelivered: 0, currentDeliveryRate: 0 },
+ deliveryByScope: { 'app-improvement': { approved: 3, delivered: 0 } }
+ })),
+ renderCosMetricsSource: vi.fn(() => 'RE-RENDERED COS METRICS'),
// 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.
@@ -116,6 +125,10 @@ beforeEach(() => {
li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: {} });
li.filerForTracker.mockImplementation((r) => (r === 'github' || r === 'gitlab') ? 'forge' : (r === 'jira' ? 'jira' : 'plan'));
li.trackerSupportsPause.mockImplementation((r) => r !== 'plan');
+ // clearAllMocks resets call history but NOT a mockResolvedValue an individual test
+ // 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.listBlockingIssues.mockResolvedValue({ ok: true, issues: [] });
li.listForgeIssues.mockResolvedValue({ ok: true, issues: [] });
li.isAppParked.mockReturnValue(false);
@@ -315,6 +328,44 @@ describe('buildTaskInput', () => {
expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({ outcomesReport: expect.stringContaining('Total filed: 1') }));
});
+ it('re-renders cosMetrics with the post-reconciliation delivery block (#3085)', async () => {
+ const metricsByType = { 'user-task': { lifetimeSuccessRate: 92, lifetimeCompleted: 25 } };
+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { cosMetrics: true, outcomes: true } });
+ li.gatherSources.mockResolvedValue({ goals: 'be great', cosMetrics: 'FIRST PASS', cosMetricsByType: metricsByType });
+ const outcomes = [{ slug: 's', outcome: 'merged', scope: 'app-improvement' }];
+ listOutcomesResult.mockResolvedValue({ read: true, outcomes });
+ await buildTaskInput({ app: APP });
+ // The records projected must be the reconciled ones the liOutcomes block also reads —
+ // a pre-reconcile snapshot would report a different approval count in the same prompt.
+ expect(li.computeDeliveryMetrics).toHaveBeenCalledWith(outcomes);
+ expect(li.renderCosMetricsSource).toHaveBeenCalledWith({
+ metricsByType,
+ delivery: expect.objectContaining({ delivery: expect.objectContaining({ totalApproved: 3 }) })
+ });
+ const { sources } = li.buildPrompt.mock.calls.at(-1)[0];
+ expect(sources.cosMetrics).toBe('RE-RENDERED COS METRICS');
+ // The hand-off key is internal to the re-render — it must never reach buildPrompt,
+ // where it would render as a bogus `### cosMetricsByType` source block.
+ expect('cosMetricsByType' in sources).toBe(false);
+ });
+
+ it('re-renders cosMetrics with NO delivery block when outcomes were not gathered (#3085)', async () => {
+ // Outcomes source off: omit the block rather than emit zeros, which would read as
+ // "nothing has ever been approved" instead of "we have no delivery data".
+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { cosMetrics: true } });
+ li.gatherSources.mockResolvedValue({ cosMetrics: 'FIRST PASS', cosMetricsByType: { 'user-task': {} } });
+ await buildTaskInput({ app: APP });
+ expect(li.computeDeliveryMetrics).not.toHaveBeenCalled();
+ expect(li.renderCosMetricsSource).toHaveBeenCalledWith(expect.objectContaining({ delivery: null }));
+ });
+
+ 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' });
+ await buildTaskInput({ app: APP });
+ expect(li.renderCosMetricsSource).not.toHaveBeenCalled();
+ });
+
it('skips the selfEval REPORT when the source toggle is off, but still arms the hard-exclusion notice (#2700/#2824)', async () => {
li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: {} });
await buildTaskInput({ app: APP });
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index 586096aff9..fa19421fa1 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -49,6 +49,9 @@ import {
computeExecutionByDomain,
computePostApprovalCompletion,
computeProposalOutcomeMetrics,
+ computeDeliveryMetrics,
+ renderCosMetricsSource,
+ COS_METRICS_MAX_CHARS,
computeProposalExecutionAwareness,
computeCrossReferenceAnalysis,
computeHandoffRouting,
@@ -689,6 +692,104 @@ describe('computeProposalOutcomeMetrics (#3014)', () => {
});
});
+describe('computeDeliveryMetrics (#3085)', () => {
+ const RECORDS = [
+ { scope: 'app-improvement', outcome: 'merged', executionOutcome: 'success', filedAt: '2026-07-01T00:00:00.000Z', executionAt: '2026-07-01T01:00:00.000Z' },
+ { scope: 'app-improvement', outcome: 'merged', executionOutcome: 'failure', filedAt: '2026-07-01T00:00:00.000Z', executionAt: '2026-07-01T02:00:00.000Z' },
+ { scope: 'app-data-gap', outcome: 'merged', executionOutcome: null, filedAt: '2026-07-01T00:00:00.000Z' },
+ // Rejected-only scope: it has a filing record but nothing was ever approved there.
+ { scope: 'loop-meta', outcome: 'rejected', filedAt: '2026-07-01T00:00:00.000Z' }
+ ];
+
+ it('projects the approval → delivery totals and rate', () => {
+ const { delivery } = computeDeliveryMetrics(RECORDS);
+ // 3 approved, 1 delivered → 33%. The run-success rates sitting beside this in the
+ // same document say nothing about that gap, which is the whole point of the block.
+ expect(delivery).toEqual({ totalApproved: 3, totalDelivered: 1, currentDeliveryRate: 33 });
+ });
+
+ it('breaks delivery down per scope, omitting scopes with no approvals', () => {
+ const { deliveryByScope } = computeDeliveryMetrics(RECORDS);
+ expect(deliveryByScope).toEqual({
+ 'app-improvement': { approved: 2, delivered: 1 },
+ 'app-data-gap': { approved: 1, delivered: 0 }
+ });
+ // A scope whose every proposal was rejected carries no delivery signal — its
+ // 0-of-0 row would only restate the merge-rate block.
+ expect(deliveryByScope['loop-meta']).toBeUndefined();
+ });
+
+ it('reports a NULL rate (never 0%) when nothing has been approved yet', () => {
+ // The sentinel rule: "no approvals to deliver on" is not "every approval was lost".
+ // This rate arms the hard exclusion gate, so a 0 here would lock out a cold loop.
+ for (const input of [[], null, [{ scope: 'loop-meta', outcome: 'rejected' }]]) {
+ const { delivery, deliveryByScope } = computeDeliveryMetrics(input);
+ expect(delivery).toEqual({ totalApproved: 0, totalDelivered: 0, currentDeliveryRate: null });
+ expect(Object.keys(deliveryByScope)).toEqual([]);
+ }
+ });
+
+ it('reuses a pre-computed roll-up instead of re-deriving it', () => {
+ const metrics = computeProposalOutcomeMetrics(RECORDS);
+ expect(computeDeliveryMetrics([], { metrics })).toEqual(computeDeliveryMetrics(RECORDS));
+ });
+
+ 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' }
+ ]);
+ expect(Object.keys(deliveryByScope)).toContain('__proto__');
+ expect({}.approved).toBeUndefined();
+ });
+});
+
+describe('renderCosMetricsSource (#3085)', () => {
+ const BY_TYPE = { 'user-task': { lifetimeSuccessRate: 92, lifetimeCompleted: 25 } };
+
+ it('leaves the per-task-type document unchanged when no delivery data was gathered', () => {
+ // Outcomes source off / tracker can't report outcomes / store unreadable: OMIT the
+ // block rather than emit zeros, which would read as "nothing has ever been approved".
+ const parsed = JSON.parse(renderCosMetricsSource({ metricsByType: BY_TYPE }));
+ expect(parsed).toEqual(BY_TYPE);
+ expect(parsed.delivery).toBeUndefined();
+ });
+
+ 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' }
+ ]);
+ const parsed = JSON.parse(renderCosMetricsSource({ metricsByType: BY_TYPE, delivery }));
+ expect(parsed['user-task'].lifetimeSuccessRate).toBe(92);
+ expect(parsed.delivery).toEqual({ totalApproved: 1, totalDelivered: 1, currentDeliveryRate: 100 });
+ expect(parsed.deliveryByScope).toEqual({ 'app-improvement': { approved: 1, delivered: 1 } });
+ });
+
+ it('keeps the delivery block ahead of the per-type map so the cap cannot cut it', () => {
+ // An install with dozens of task types can fill COS_METRICS_MAX_CHARS on its own.
+ // The per-type tail has an interpreted sibling in the prompt (liScopeAwareness,
+ // derived from the untruncated map); the delivery block has none, so it must survive.
+ const metricsByType = {};
+ for (let i = 0; i < 200; i++) {
+ metricsByType[`self-improve:scope-${i}`] = { lifetimeSuccessRate: 50, lifetimeCompleted: 10, recentSuccessRate: null, recentCompleted: 0, avgDurationMs: 1000 };
+ }
+ const rendered = renderCosMetricsSource({
+ metricsByType,
+ delivery: computeDeliveryMetrics([{ scope: 'loop-meta', outcome: 'merged', executionOutcome: null, filedAt: '2026-07-01T00:00:00.000Z' }])
+ });
+ expect(rendered.length).toBe(COS_METRICS_MAX_CHARS); // genuinely truncated
+ expect(rendered).toContain('"currentDeliveryRate":0');
+ expect(rendered.indexOf('"delivery"')).toBeLessThan(rendered.indexOf('self-improve:scope-0'));
+ });
+
+ it('does not let a task type named "delivery" shadow the delivery block', () => {
+ const parsed = JSON.parse(renderCosMetricsSource({
+ metricsByType: { delivery: { lifetimeSuccessRate: 10 } },
+ delivery: computeDeliveryMetrics([{ scope: 'loop-meta', outcome: 'merged', executionOutcome: 'success', filedAt: '2026-07-01T00:00:00.000Z', executionAt: '2026-07-01T01:00:00.000Z' }])
+ }));
+ expect(parsed.delivery).toEqual({ totalApproved: 1, totalDelivered: 1, currentDeliveryRate: 100 });
+ });
+});
+
describe('computeProposalExecutionAwareness (#2765)', () => {
const execRecords = (scope, successes, failures) => [
...Array.from({ length: successes }, () => ({ scope, executionOutcome: 'success' })),
@@ -2872,6 +2973,19 @@ describe('gatherSources cosMetrics windowed rate (issue #2460)', () => {
expect(out.scopeGuidance).toContain(`and ${overflow} more`);
});
+ it('hands the raw per-type map back for the delivery re-render, with no delivery block yet (#3085)', async () => {
+ // gatherSources runs BEFORE outcomes are reconciled against this run's tracker read,
+ // so it cannot know the approval count yet — emitting one here would let the
+ // cosMetrics and liOutcomes blocks in the SAME prompt disagree. The hook re-renders
+ // with `cosMetricsByType` once it has post-reconciliation records.
+ await writeLearning({
+ byTaskType: { 'user-task': { completed: 10, succeeded: 9, failed: 1, successRate: 90, recentOutcomes: [] } }
+ });
+ const out = await gatherSources({ repoPath: dir }, { sources: { cosMetrics: true } }, { cosPath: dir });
+ expect(out.cosMetricsByType['user-task'].lifetimeSuccessRate).toBe(90);
+ expect(JSON.parse(out.cosMetrics).delivery).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/outcomes.js b/server/services/layeredIntelligence/outcomes.js
index 58716eba85..98f34fad49 100644
--- a/server/services/layeredIntelligence/outcomes.js
+++ b/server/services/layeredIntelligence/outcomes.js
@@ -199,6 +199,61 @@ export function computeProposalOutcomeMetrics(outcomes = [], { stats = null, exe
};
}
+/**
+ * Project the outcome metrics down to the compact delivery block folded into the
+ * `cosMetrics` prompt source (#3085). The `cosMetrics` document reports per-task-type
+ * RUN success ("did the agent's task finish?") and nothing about DELIVERY ("did the
+ * approved work actually land?") — so a healthy 90% run rate sitting beside a pipeline
+ * that has delivered 0 of 10 approvals reads as a healthy pipeline. This is the second
+ * number, in the same document.
+ *
+ * DERIVED, not stored — for the same reason `computeProposalOutcomeMetrics` is: the
+ * 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.
+ *
+ * `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.
+ *
+ * `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`
+ * would both be 0, saying only "nothing was approved here"), and the merge-rate block
+ * 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);
+ // 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.
+ const deliveryByScope = Object.create(null);
+ for (const [scope, bucket] of Object.entries(rolled.byScope)) {
+ if (!bucket.approved) continue;
+ deliveryByScope[scope] = { approved: bucket.approved, delivered: bucket.completed };
+ }
+ return {
+ delivery: {
+ totalApproved: rolled.totalApproved,
+ totalDelivered: rolled.totalCompleted,
+ currentDeliveryRate: rolled.approvalToCompletionRate === null
+ ? null
+ : Math.round(rolled.approvalToCompletionRate)
+ },
+ deliveryByScope
+ };
+}
+
/**
* Format the LI outcome-feedback report (#2428) from this app's recorded
* proposals + their reconciled outcomes. Pure + side-effect-free: the LI hook
diff --git a/server/services/layeredIntelligence/sources.js b/server/services/layeredIntelligence/sources.js
index cc818bd6b5..789e86120a 100644
--- a/server/services/layeredIntelligence/sources.js
+++ b/server/services/layeredIntelligence/sources.js
@@ -173,6 +173,52 @@ export async function gatherPlannedWork({
return null;
}
+// Prompt-budget cap on the rendered cosMetrics document, unchanged from when the
+// per-task-type map was the whole payload.
+export const COS_METRICS_MAX_CHARS = 4000;
+
+// The two `cosMetrics` keys that are NOT task types (#3085). Named so the reserved-key
+// contract is stated once rather than implied by assignment order below.
+const COS_METRICS_DELIVERY_KEYS = ['delivery', 'deliveryByScope'];
+
+/**
+ * Render the `cosMetrics` prompt source: this install's per-task-type agent RUN stats,
+ * plus — when the caller has outcome records — the approval → DELIVERY block (#3085).
+ * Pure; the single place the document's shape is decided, so gatherSources' first pass
+ * and the hook's delivery-aware re-render can never produce different shapes.
+ *
+ * The delivery keys are serialized FIRST so the `COS_METRICS_MAX_CHARS` cap can never
+ * truncate them away: an install with dozens of task types can fill the budget on its
+ * own, and the per-task-type tail is the half that already has an interpreted sibling
+ * in the prompt (liScopeAwareness, derived server-side from the untruncated map),
+ * whereas the delivery block has none.
+ *
+ * `delivery` is OMITTED entirely (not zeroed) when no outcome records were gathered —
+ * the outcomes source is off, the tracker cannot report outcomes, or the store was
+ * unreadable. A gathered-but-empty history still emits the block with a null
+ * `currentDeliveryRate`, so "we have no delivery data" stays distinguishable from
+ * "nothing has been approved yet".
+ *
+ * @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.
+ */
+export function renderCosMetricsSource({ metricsByType = {}, delivery = null } = {}) {
+ const payload = {};
+ // 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.
+ if (delivery) for (const key of COS_METRICS_DELIVERY_KEYS) payload[key] = null;
+ Object.assign(payload, metricsByType);
+ if (delivery) {
+ payload.delivery = delivery.delivery;
+ payload.deliveryByScope = delivery.deliveryByScope;
+ }
+ return JSON.stringify(payload).slice(0, COS_METRICS_MAX_CHARS);
+}
+
/**
* Gather the enabled Layer-1 sources for one app into a `{ key: string }` map.
* Deterministic reads only (files + CoS metric JSON + tracker lists); NO LLM calls.
@@ -247,7 +293,15 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShe
avgDurationMs: m?.avgDurationMs || 0
};
}
- out.cosMetrics = JSON.stringify(summary).slice(0, 4000);
+ // 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.
diff --git a/server/services/layeredIntelligenceBarrel.test.js b/server/services/layeredIntelligenceBarrel.test.js
index e275eaeb77..ebbc47b0fb 100644
--- a/server/services/layeredIntelligenceBarrel.test.js
+++ b/server/services/layeredIntelligenceBarrel.test.js
@@ -60,6 +60,7 @@ describe('layeredIntelligence barrel re-exports (issue #2842)', () => {
'computeCrossReferenceAnalysis', 'computeHandoffRouting',
'computeHardExclusionGate', 'computeHardExclusionNotice', 'buildPrompt',
'gatherSources', 'gatherPlannedWork', 'readLiTaskMetrics',
+ 'computeDeliveryMetrics', 'renderCosMetricsSource',
'listForgeIssues', 'fileProposalToForge', 'listJiraIssues',
'fileProposalToJira', 'appendProposalToPlan', 'extractPlanSlugs',
]) {