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([issue-2765]): key LI scope-awareness on per-proposal execution, not install-wide task buckets

[._.]/ Adam Eivy3118ba048328
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index bf8a81d0db..adbd5c4e21 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -102,3 +102,5 @@
### Changed
- [issue-2760] **Layered Intelligence now steers its proposals toward work it can actually finish.** Each run reads its own track record — which kinds of task it has historically completed versus consistently failed — and hands the reasoner an explicit "prefer these, avoid those" summary before it decides what to propose. So the loop stops repeatedly filing work in areas where its follow-through fails and concentrates on the kinds of improvement it lands reliably. The read is fresh every run, so an area recovers on its own the moment its success rate climbs back — nothing to reset by hand. This only kicks in once an area has enough completed runs to be meaningful, and applies to PortOS's own self-improvement loop (managed apps, which don't track these run stats, are unaffected).
+
+- [issue-2765] **Layered Intelligence's "prefer/avoid" steering now learns from its OWN proposals, not just install-wide task stats.** The earlier steering (above) borrowed how reliably each *kind* of task gets finished on this install — a useful-but-loose signal, since a given proposal doesn't map cleanly onto one task type. Now, when the loop hands one of its own proposals to a coding agent to implement, the outcome of that run is recorded against the proposal's *domain* (the scope it was filed under), and future runs get a direct "here's how your own proposals in each domain actually turned out" summary alongside the older directional one. So the loop can favor the domains where its proposals genuinely land and be more cautious in domains where its hand-offs stall even after the proposal was accepted — a true feedback loop rather than an approximation. This builds up only as the optional hand-off path runs, and never counts a run that failed for an outage or rate limit against a domain.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 640abb5a2e..9d0d1f23ad 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -461,6 +461,11 @@ async function runAgentSpawn(task) {
taskAnalysisType: task.metadata?.analysisType || null,
taskReviewType: task.metadata?.reviewType || null,
taskApp: task.metadata?.app || null,
+ // LI hand-off provenance (#2765): projected onto the agent so the completion
+ // hook (recordTaskCompletion) can attribute the run's success/failure back to
+ // the proposal's domain. agent.metadata is a hand-picked projection of
+ // task.metadata (not a full spread), so this must be listed explicitly.
+ taskLiProposal: task.metadata?.liProposal || null,
taskAppName: resolvedAppName,
selfImprovementType: task.metadata?.selfImprovementType || null,
jobId: task.metadata?.jobId || null,
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index deaf7b058f..009f28e37f 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -54,6 +54,7 @@ import {
applyJiraBlockingLabel,
computeOutcomesReport,
computeSelfEvalSummary,
+ computeProposalExecutionAwareness,
readLiTaskMetrics,
hasPlannedWorkListing
} from '../layeredIntelligence.js'
@@ -318,6 +319,11 @@ export async function buildTaskInput({ app } = {}) {
// "this app has never had a proposal merged" (#2700).
let outcomes = null
let outcomesReport = ''
+ // Per-proposal-domain execution record (#2765): the true avoid/prefer signal keyed
+ // on how LI's OWN proposals in each domain fared once handed off + executed. Derived
+ // from the SAME outcome records loaded below (no extra store read), so it's gated on
+ // the same outcomes source; stays '' until at least one domain clears the sample floor.
+ let proposalExecutionReport = ''
if (config.sources?.outcomes && outcomesTrackerSupported(filer)) {
if (!trackerReadFailed) await reconcileOutcomes({ appId: app.id, existingIssues })
// Discriminated read: an unreadable outcome store stays `null` here rather than
@@ -334,6 +340,11 @@ export async function buildTaskInput({ app } = {}) {
outcomes,
hasPlannedWork: hasPlannedWorkListing(sources.plannedWork)
})
+ // Only a successful read yields records to attribute; a failed read (outcomes ===
+ // null) leaves the block empty rather than claiming "no domain has executed".
+ if (Array.isArray(outcomes)) {
+ proposalExecutionReport = computeProposalExecutionAwareness({ outcomes })
+ }
}
// Self-evaluation (#2700): the loop's deterministic pre-filing check on its own
@@ -359,7 +370,7 @@ export async function buildTaskInput({ app } = {}) {
})
}
- const prompt = buildPrompt({ app, config, sources, openIssues, isPortos, outcomesReport, selfEvalReport }) + buildCompletionContract()
+ const prompt = buildPrompt({ app, config, sources, openIssues, isPortos, outcomesReport, selfEvalReport, proposalExecutionReport }) + 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 it
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
index 0fcc88324c..bbb36e44a6 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
@@ -60,6 +60,10 @@ vi.mock('../layeredIntelligence.js', () => ({
// 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'),
+ // Per-proposal-domain execution awareness (#2765). Semantics are unit-tested in
+ // layeredIntelligence.test.js; a spy here so the hook's WIRING (computed from the
+ // loaded outcomes and passed to buildPrompt) can be asserted.
+ computeProposalExecutionAwareness: vi.fn(() => ''),
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
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 201917ae44..bb1ff0121c 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -305,6 +305,14 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
if (taskData.diagnostics && typeof taskData.diagnostics === 'object' && !Array.isArray(taskData.diagnostics)) {
metadata.diagnostics = taskData.diagnostics;
}
+ // Layered-Intelligence hand-off provenance (#2765): the proposal's identity +
+ // domain, carried from buildHandoffTask so recordTaskCompletion can attribute this
+ // agent run's success/failure back to the proposal's DOMAIN (per-proposal execution
+ // record). A non-object / array (defensive) is ignored. Round-trips through the
+ // markdown store via the same JSON sentinel as `diagnostics` above.
+ if (taskData.liProposal && typeof taskData.liProposal === 'object' && !Array.isArray(taskData.liProposal)) {
+ metadata.liProposal = taskData.liProposal;
+ }
// Content-edit timestamp for cross-peer newest-edit-wins LWW (#1714). Stamped
// at creation so a freshly-added task always carries a stamp; the merge treats
// an absent stamp as oldest, so this also keeps a stamped task from losing a
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index 7035c51981..eabaa753bc 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -166,6 +166,24 @@ export const LI_DEGRADED_MIN_SAMPLE = 4;
// to merged for trackers that report no stateReason.
export const PROPOSAL_OUTCOMES = ['merged', 'rejected', 'abandoned'];
+// The EXECUTION outcomes an LI proposal reaches once it is handed off to a coding
+// agent and that agent's run completes (#2765). Distinct from PROPOSAL_OUTCOMES
+// (the FILING fate — did the issue get merged/closed): execution is "did LI's own
+// coding agent successfully implement the proposal it filed". Only populated for
+// proposals that took the Engine-A hand-off path (config.handoff.enabled + a
+// trivial+safe proposal); a filed-but-never-handed-off proposal keeps a null
+// executionOutcome. Environmental failures (rate-limit/outage) are NOT recorded —
+// they say nothing about the proposal's domain (same gate as #2618).
+export const PROPOSAL_EXECUTION_OUTCOMES = ['success', 'failure'];
+
+// Minimum recorded executions before a proposal DOMAIN's success rate is trusted
+// for the per-domain avoid/prefer split (#2765). Lower than SCOPE_AWARENESS_MIN_SAMPLE
+// (3) because each data point here is a REAL, high-signal LI-proposal execution — not
+// install-wide task-type telemetry that a proposal only loosely maps onto — and the
+// hand-off path is rare, so a floor of 2 lets a genuine per-domain signal surface
+// without letting a single fluke mint a list.
+export const PROPOSAL_EXECUTION_MIN_SAMPLE = 2;
+
// Scope-awareness thresholds (#2760). LI's own execution data shows several CoS
// task-type scopes it consistently fails at (e.g. self-improve:layered-intelligence,
// branch-reconcile, accessibility all sit at 0%) while others succeed reliably
@@ -538,7 +556,20 @@ export function buildHandoffTask({ app, proposal, issueRef } = {}) {
priority: 'MEDIUM',
context,
app: app?.id,
- approvalRequired: true
+ approvalRequired: true,
+ // Per-proposal-domain execution tracking (#2765): stamp the proposal's identity
+ // + domain onto the task so, when this agent run completes, recordTaskCompletion
+ // can attribute the execution success/failure back to the proposal's DOMAIN (not
+ // the generic `internal-task` bucket this hand-off would otherwise land in).
+ // addTask allowlists this top-level field into `metadata.liProposal`, and
+ // registerAgent projects it onto `agent.metadata.taskLiProposal`. Kept a
+ // dedicated key (not any of the extractTaskType-recognized metadata fields) so it
+ // never reclassifies the task's own byTaskType bucket.
+ liProposal: {
+ appId: app?.id ?? null,
+ slug: proposal?.slug ?? null,
+ scope: proposal?.scope ?? null
+ }
};
}
@@ -926,6 +957,43 @@ export function computeSelfEvalSummary({
].join('\n');
}
+/**
+ * Clamp a task-type / proposal-domain label so one pathological key (e.g. a mission
+ * task type embedding an unbounded mission name) can't blow the scope-awareness block
+ * budget. Shared by both avoid/prefer signals below.
+ */
+function clampScopeLabel(label) {
+ return label.length > SCOPE_AWARENESS_MAX_TYPE_LEN
+ ? `${label.slice(0, SCOPE_AWARENESS_MAX_TYPE_LEN - 1)}…`
+ : label;
+}
+
+/**
+ * Render an avoid/prefer prompt block from pre-classified item lists — the presentation
+ * both scope-awareness signals share (#2760 install-wide task-type rates, #2765
+ * per-proposal-domain execution rates). Owns the sort (worst-first avoid, best-first
+ * prefer), the per-list cap + "…and N more" overflow, and the empty-guard, so a tweak
+ * to any of those lands in one place. Callers supply their own classified `avoid`/
+ * `prefer` lists, the per-item `fmt`, and the two headers — the only parts that
+ * legitimately differ between the two signals. Returns '' when both lists are empty.
+ */
+function renderAvoidPreferSections({ avoid = [], prefer = [], fmt, avoidHeader, preferHeader }) {
+ if (!avoid.length && !prefer.length) return '';
+ avoid.sort((a, b) => a.rate - b.rate); // worst-first — sharpest signal at the top
+ prefer.sort((a, b) => b.rate - a.rate); // best-first
+ const section = (header, items) => {
+ const shown = items.slice(0, SCOPE_AWARENESS_MAX_PER_LIST);
+ const more = items.length - shown.length;
+ const lines = shown.map(fmt);
+ if (more > 0) lines.push(`- …and ${more} more`);
+ return `${header}\n${lines.join('\n')}`;
+ };
+ const sections = [];
+ if (avoid.length) sections.push(section(avoidHeader, avoid));
+ if (prefer.length) sections.push(section(preferHeader, prefer));
+ return sections.join('\n\n');
+}
+
/**
* Scope-awareness report (#2760). Classifies each CoS task TYPE by its completion rate
* into low-completion and high-completion lists, as directional context for the
@@ -988,33 +1056,78 @@ export function computeScopeAwareness({ metricsByType = {} } = {}) {
if (rate < SCOPE_AVOID_SUCCESS_THRESHOLD) avoid.push({ type, rate, n });
else if (rate >= SCOPE_PREFER_SUCCESS_THRESHOLD) prefer.push({ type, rate, n });
}
- if (!avoid.length && !prefer.length) return '';
- // Worst-first for avoid, best-first for prefer — the reasoner reads the sharpest
- // signal at the top of each list.
- avoid.sort((a, b) => a.rate - b.rate);
- prefer.sort((a, b) => b.rate - a.rate);
- // Cap each list (sharpest-first) and truncate a pathological task-type name so the
- // block stays bounded on a long-lived install.
- const clampType = (type) => type.length > SCOPE_AWARENESS_MAX_TYPE_LEN
- ? `${type.slice(0, SCOPE_AWARENESS_MAX_TYPE_LEN - 1)}…`
- : type;
- const fmt = ({ type, rate, n }) => `- ${clampType(type)}: ${Math.round(rate)}% completed over ${n} runs`;
- const section = (header, items) => {
- const shown = items.slice(0, SCOPE_AWARENESS_MAX_PER_LIST);
- const more = items.length - shown.length;
- const lines = shown.map(fmt);
- if (more > 0) lines.push(`- …and ${more} more`);
- return `${header}\n${lines.join('\n')}`;
- };
- const sections = [];
// Honest framing (#2760, codex P1): these are per-task-TYPE completion rates for the
// whole install — NOT a per-proposal execution record. An LI proposal is implemented
// through a claim/plan/handoff task whose type does not carry the proposal's domain,
// so this is directional context ("work of this kind tends to (not) get finished
// here"), not a claim that a given proposal maps 1:1 onto a listed type.
- if (avoid.length) sections.push(section(`LOW-COMPLETION task types — work of this kind is finished below ${SCOPE_AVOID_SUCCESS_THRESHOLD}% of the time on this install:`, avoid));
- if (prefer.length) sections.push(section(`HIGH-COMPLETION task types — finished at or above ${SCOPE_PREFER_SUCCESS_THRESHOLD}%:`, prefer));
- return sections.join('\n\n');
+ return renderAvoidPreferSections({
+ avoid,
+ prefer,
+ fmt: ({ type, rate, n }) => `- ${clampScopeLabel(type)}: ${Math.round(rate)}% completed over ${n} runs`,
+ avoidHeader: `LOW-COMPLETION task types — work of this kind is finished below ${SCOPE_AVOID_SUCCESS_THRESHOLD}% of the time on this install:`,
+ preferHeader: `HIGH-COMPLETION task types — finished at or above ${SCOPE_PREFER_SUCCESS_THRESHOLD}%:`
+ });
+}
+
+/**
+ * Aggregate LI proposal EXECUTION outcomes by proposal DOMAIN (scope) (#2765).
+ * Pure. Unlike computeScopeAwareness — which borrows install-wide CoS
+ * per-task-TYPE completion rates that a proposal only loosely maps onto — this is a
+ * TRUE per-proposal record: each data point is one of LI's OWN filed proposals that
+ * was handed off and executed, keyed by the domain (scope) it was proposed under.
+ *
+ * `outcomes` is the app's outcome records (from listOutcomes); only records carrying
+ * a resolved `executionOutcome` AND a `scope` contribute. Returns
+ * `{ [scope]: { completed, succeeded, successRate } }` (empty when nothing has been
+ * executed yet). The acceptance signal for #2765: after one proposal in domain X is
+ * executed, only X's bucket moves.
+ */
+export function computeExecutionByDomain(outcomes = []) {
+ const byDomain = {};
+ for (const r of Array.isArray(outcomes) ? outcomes : []) {
+ if (!r || typeof r !== 'object') continue;
+ if (!PROPOSAL_EXECUTION_OUTCOMES.includes(r.executionOutcome)) continue;
+ const scope = typeof r.scope === 'string' && r.scope.trim() ? r.scope.trim() : null;
+ if (!scope) continue;
+ const bucket = byDomain[scope] || (byDomain[scope] = { completed: 0, succeeded: 0 });
+ bucket.completed += 1;
+ if (r.executionOutcome === 'success') bucket.succeeded += 1;
+ }
+ // successRate is derived once here — the sole writer — so the bucket carries no
+ // dead initial value above.
+ for (const bucket of Object.values(byDomain)) {
+ bucket.successRate = Math.round((bucket.succeeded / bucket.completed) * 100);
+ }
+ return byDomain;
+}
+
+/**
+ * Render the per-proposal-DOMAIN execution avoid/prefer split for the reasoning
+ * prompt (#2765) — the real per-proposal signal the #2760 install-wide scope block
+ * could only approximate. Returns '' when no domain clears the sample floor, so
+ * buildPrompt omits the block. Mirrors computeScopeAwareness's 50/75 thresholds and
+ * bounded rendering, but keys on the proposal's own scope and carries NO
+ * "directional context only" caveat: this IS how LI's own proposals in each domain
+ * fared, so the reasoner can steer toward domains it actually executes and away from
+ * domains where its own hand-offs fail even after the proposal was accepted.
+ */
+export function computeProposalExecutionAwareness({ outcomes = [] } = {}) {
+ const byDomain = computeExecutionByDomain(outcomes);
+ const avoid = [];
+ const prefer = [];
+ for (const [scope, bucket] of Object.entries(byDomain)) {
+ if (bucket.completed < PROPOSAL_EXECUTION_MIN_SAMPLE) continue; // not enough executions to judge this domain
+ if (bucket.successRate < SCOPE_AVOID_SUCCESS_THRESHOLD) avoid.push({ scope, rate: bucket.successRate, n: bucket.completed });
+ else if (bucket.successRate >= SCOPE_PREFER_SUCCESS_THRESHOLD) prefer.push({ scope, rate: bucket.successRate, n: bucket.completed });
+ }
+ return renderAvoidPreferSections({
+ avoid,
+ prefer,
+ fmt: ({ scope, rate, n }) => `- ${clampScopeLabel(scope)}: LI implemented ${rate}% of its own ${scope} proposals successfully over ${n} executed`,
+ avoidHeader: `LOW-EXECUTION proposal domains — LI's OWN hand-offs in these domains succeed below ${SCOPE_AVOID_SUCCESS_THRESHOLD}% of the time; a proposal here needs a strong justification or a narrower slice:`,
+ preferHeader: `HIGH-EXECUTION proposal domains — LI reliably implements its own proposals here (at or above ${SCOPE_PREFER_SUCCESS_THRESHOLD}%):`
+ });
}
// Source keys that buildPrompt renders as their OWN dedicated block (with tailored
@@ -1032,9 +1145,11 @@ const BESPOKE_SOURCE_BLOCK_KEYS = new Set(['plannedWork', 'scopeGuidance']);
* block with calibration guidance when non-empty (#2428). `selfEvalReport` (from
* computeSelfEvalSummary) is injected as a `liSelfEval` block the same way (#2700).
* `sources.scopeGuidance` (from computeScopeAwareness) is injected as a
- * `liScopeAwareness` block the same way (#2760).
+ * `liScopeAwareness` block the same way (#2760). `proposalExecutionReport` (from
+ * computeProposalExecutionAwareness) is injected as a `liProposalExecution` block —
+ * the TRUE per-proposal-domain execution record #2760 could only approximate (#2765).
*/
-export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '', selfEvalReport = '' }) {
+export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '', selfEvalReport = '', proposalExecutionReport = '' }) {
const allowed = (config.allowedScopes || []).filter(s =>
isScopeAllowed({ scope: s, allowedScopes: config.allowedScopes, isPortos })
);
@@ -1099,7 +1214,18 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort
// onto a listed type, so treat a low-completion type as a reason for extra scrutiny /
// a narrower scope, not a hard veto.
const scopeGuidanceBlock = (isPortos && typeof sources.scopeGuidance === 'string' && sources.scopeGuidance.trim())
- ? `\n### liScopeAwareness\n${sources.scopeGuidance.trim()}\n\nThese are per-task-type completion rates for THIS install — how reliably each KIND of work tends to get finished, not a per-proposal record (your proposals don't map 1:1 onto these types). Use it as directional context: a proposal whose implementation resembles a low-completion type deserves extra scrutiny or a narrower scope; high-completion kinds are safer bets. A low rate on self-improve:layered-intelligence is LI's OWN reasoning-run rate — a direct signal to propose conservatively.\n`
+ ? `\n### liScopeAwareness\n${sources.scopeGuidance.trim()}\n\nThese are per-task-type completion rates for THIS install — how reliably each KIND of work tends to get finished, not a per-proposal record (your proposals don't map 1:1 onto these types). Use it as directional context: a proposal whose implementation resembles a low-completion type deserves extra scrutiny or a narrower scope; high-completion kinds are safer bets. A low rate on self-improve:layered-intelligence is LI's OWN reasoning-run rate — a direct signal to propose conservatively. Where the liProposalExecution block below covers a domain, prefer it: it is a direct per-proposal record, whereas these buckets are only directional.\n`
+ : '';
+
+ // Per-proposal-domain execution record (#2765): unlike liScopeAwareness above —
+ // which borrows install-wide per-task-TYPE rates a proposal only loosely maps onto —
+ // this keys on how LI's OWN proposals in each domain actually fared once handed off
+ // and executed. It carries NO "directional only" caveat because the mapping is real,
+ // so it is the authoritative avoid/prefer signal wherever it has data. The report is
+ // pre-gated on the outcomes source by the caller (built from the same records), so no
+ // isPortos re-check here — the block simply renders when execution history exists.
+ const proposalExecutionBlock = (typeof proposalExecutionReport === 'string' && proposalExecutionReport.trim())
+ ? `\n### liProposalExecution\n${proposalExecutionReport.trim()}\n\nThis is a DIRECT record of how LI's own proposals in each domain fared once implemented — not directional context. Favor domains LI executes reliably; for a low-execution domain, either narrow the proposal to a slice an agent can finish or justify why it is still the highest-value work despite the track record.\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.
@@ -1115,7 +1241,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}${selfEvalBlock}${scopeGuidanceBlock}
+${plannedWorkBlock}${outcomesBlock}${selfEvalBlock}${scopeGuidanceBlock}${proposalExecutionBlock}
Respond with JSON only (no markdown fences):
{
"analysis": "brief reasoning summary",
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index 3a92a7963d..f261374ff1 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -43,6 +43,9 @@ import {
LI_DEGRADED_SUCCESS_THRESHOLD,
LI_DEGRADED_MIN_SAMPLE,
computeScopeAwareness,
+ computeExecutionByDomain,
+ computeProposalExecutionAwareness,
+ PROPOSAL_EXECUTION_MIN_SAMPLE,
SCOPE_AVOID_SUCCESS_THRESHOLD,
SCOPE_PREFER_SUCCESS_THRESHOLD,
SCOPE_AWARENESS_MIN_SAMPLE,
@@ -417,6 +420,76 @@ describe('buildHandoffTask', () => {
expect(jira).toContain('PROJ-7');
expect(jira).toContain('change X to Y'); // carries the proposal body
});
+
+ it('stamps the proposal identity + domain for per-domain execution tracking (#2765)', () => {
+ const t = buildHandoffTask({ app, proposal: { ...proposal, scope: 'loop-meta' }, issueRef: 42 });
+ expect(t.liProposal).toEqual({ appId: 'app-1', slug: 'fix-typo', scope: 'loop-meta' });
+ });
+});
+
+describe('computeExecutionByDomain (#2765)', () => {
+ it('groups executed proposals by their scope and computes per-domain success rate', () => {
+ const byDomain = computeExecutionByDomain([
+ { scope: 'loop-meta', executionOutcome: 'success' },
+ { scope: 'loop-meta', executionOutcome: 'failure' },
+ { scope: 'app-improvement', executionOutcome: 'success' }
+ ]);
+ expect(byDomain['loop-meta']).toEqual({ completed: 2, succeeded: 1, successRate: 50 });
+ expect(byDomain['app-improvement']).toEqual({ completed: 1, succeeded: 1, successRate: 100 });
+ });
+
+ it('ignores records with no executionOutcome or no scope', () => {
+ const byDomain = computeExecutionByDomain([
+ { scope: 'loop-meta', executionOutcome: null }, // filed but never executed
+ { scope: null, executionOutcome: 'success' }, // executed but domain unknown
+ { executionOutcome: 'success' }, // no scope key
+ 'nonsense',
+ { scope: 'app-data-gap', executionOutcome: 'success' }
+ ]);
+ expect(Object.keys(byDomain)).toEqual(['app-data-gap']);
+ });
+
+ it('returns an empty map for a non-array / empty input', () => {
+ expect(computeExecutionByDomain()).toEqual({});
+ expect(computeExecutionByDomain(null)).toEqual({});
+ expect(computeExecutionByDomain([])).toEqual({});
+ });
+});
+
+describe('computeProposalExecutionAwareness (#2765)', () => {
+ const execRecords = (scope, successes, failures) => [
+ ...Array.from({ length: successes }, () => ({ scope, executionOutcome: 'success' })),
+ ...Array.from({ length: failures }, () => ({ scope, executionOutcome: 'failure' }))
+ ];
+
+ it('returns "" until a domain clears the sample floor', () => {
+ // One execution is below PROPOSAL_EXECUTION_MIN_SAMPLE (2) — no list yet.
+ expect(computeProposalExecutionAwareness({ outcomes: execRecords('loop-meta', 0, 1) })).toBe('');
+ expect(computeProposalExecutionAwareness({ outcomes: [] })).toBe('');
+ expect(computeProposalExecutionAwareness()).toBe('');
+ });
+
+ it('lists a low-execution domain under AVOID and a high one under PREFER', () => {
+ const out = computeProposalExecutionAwareness({
+ outcomes: [
+ ...execRecords('app-improvement', 0, 3), // 0% → avoid
+ ...execRecords('loop-meta', 3, 0) // 100% → prefer
+ ]
+ });
+ expect(out).toContain('LOW-EXECUTION proposal domains');
+ expect(out).toContain('app-improvement');
+ expect(out).toContain('HIGH-EXECUTION proposal domains');
+ expect(out).toContain('loop-meta');
+ // No "directional context only" hedge — this is a true per-proposal record.
+ expect(out).not.toContain('directional');
+ expect(out).not.toMatch(/don't map 1:1|do not map 1:1/);
+ });
+
+ it('leaves a mid-rate domain (>=avoid, <prefer) off both lists', () => {
+ // 2/3 ≈ 67%: above the 50% avoid line, below the 75% prefer line.
+ expect(computeProposalExecutionAwareness({ outcomes: execRecords('loop-meta', 2, 1) })).toBe('');
+ expect(PROPOSAL_EXECUTION_MIN_SAMPLE).toBe(2);
+ });
});
describe('resolveBlockOnIssue', () => {
@@ -607,6 +680,18 @@ describe('buildPrompt', () => {
expect(withGuidance).not.toContain('### scopeGuidance');
});
+ it('injects the per-proposal-domain execution block only when a report is passed (#2765)', () => {
+ const base = { app, isPortos: true, config: { allowedScopes: ['loop-meta'], rules: '' } };
+ expect(buildPrompt(base)).not.toContain('liProposalExecution');
+ const withExec = buildPrompt({
+ ...base,
+ proposalExecutionReport: 'HIGH-EXECUTION proposal domains — LI reliably implements its own proposals here (at or above 75%):\n- loop-meta: LI implemented 100% of its own loop-meta proposals successfully over 3 executed'
+ });
+ expect(withExec).toContain('### liProposalExecution');
+ expect(withExec).toContain('loop-meta');
+ expect(withExec).toContain('DIRECT record'); // framed as authoritative, not directional
+ });
+
it('suppresses the scope-awareness block on a managed (non-PortOS) app (#2760 codex P2)', () => {
// Even if a stray scopeGuidance string reaches a managed app's sources, buildPrompt
// must not render it — the rates are this install's own CoS history, meaningless
diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.js
index 30f61f82e9..8ee4a01d5b 100644
--- a/server/services/layeredIntelligenceOutcomes.js
+++ b/server/services/layeredIntelligenceOutcomes.js
@@ -22,7 +22,7 @@
import { join } from 'path';
import { PATHS } from '../lib/fileUtils.js';
import { createCollectionStore } from '../lib/collectionStore.js';
-import { normalizeSlug, deriveOutcome, PROPOSAL_OUTCOMES, CLOSED_SUPPRESSION_MS } from './layeredIntelligence.js';
+import { normalizeSlug, deriveOutcome, PROPOSAL_OUTCOMES, PROPOSAL_EXECUTION_OUTCOMES, CLOSED_SUPPRESSION_MS } from './layeredIntelligence.js';
import { classifyRejection, REJECTION_REASON_VALUES } from './layeredIntelligenceRejections.js';
// The report/retention window. Reuses the dedup suppression window so a proposal
@@ -72,7 +72,15 @@ export function sanitizeOutcomeRecord(raw) {
outcome,
outcomeAt: outcome && typeof raw.outcomeAt === 'string' ? raw.outcomeAt : null,
outcomeReason: outcome && typeof raw.outcomeReason === 'string' ? raw.outcomeReason : null,
- rejectionReason: rejectable && REJECTION_REASON_VALUES.includes(raw.rejectionReason) ? raw.rejectionReason : null
+ rejectionReason: rejectable && REJECTION_REASON_VALUES.includes(raw.rejectionReason) ? raw.rejectionReason : null,
+ // Per-proposal-domain EXECUTION record (#2765) — orthogonal to `outcome` (the
+ // FILING fate): whether LI's own coding agent implemented the proposal after the
+ // Engine-A hand-off. `null` = never handed off / not yet executed; a token only
+ // when it is a recognized execution outcome, so a hand-edited/future value coerces
+ // to null (re-derivable on the next run) rather than a fake result. `executionAt`
+ // is kept only alongside a real executionOutcome.
+ executionOutcome: PROPOSAL_EXECUTION_OUTCOMES.includes(raw.executionOutcome) ? raw.executionOutcome : null,
+ executionAt: PROPOSAL_EXECUTION_OUTCOMES.includes(raw.executionOutcome) && typeof raw.executionAt === 'string' ? raw.executionAt : null
};
}
@@ -133,7 +141,11 @@ export async function recordFiledProposal({ appId, slug, tracker = null, issueRe
outcomeAt: null,
outcomeReason: null,
// Unresolved: nothing has rejected it yet, so there is nothing to diagnose.
- rejectionReason: null
+ rejectionReason: null,
+ // Not executed yet — set only if this proposal is later handed off and its agent
+ // run completes (recordProposalExecution, #2765).
+ executionOutcome: null,
+ executionAt: null
};
await ensureTypeIndex(store);
const ok = await store.saveOne(outcomeId(appId, normSlug), record).then(() => true, (err) => {
@@ -143,6 +155,53 @@ export async function recordFiledProposal({ appId, slug, tracker = null, issueRe
return ok;
}
+/**
+ * Record the EXECUTION outcome of a handed-off proposal (#2765): once LI's own
+ * coding agent finishes implementing a proposal it filed, stamp whether the run
+ * succeeded, keyed to the proposal's (app, slug) — so computeExecutionByDomain can
+ * later group these by the proposal's domain (scope). Merges over the existing filed
+ * record (preserving its filing outcome, scope, and refs); if the record is gone
+ * (GC'd, or the filing write failed) a minimal record is created from the passed
+ * scope so the execution signal isn't silently lost. `success` must be a strict
+ * boolean — a non-boolean is a caller bug and returns false without writing.
+ * Best-effort: a write failure logs and returns false rather than throwing into the
+ * completion hook. Environmental failures must be filtered by the CALLER (they say
+ * nothing about the domain — same gate as #2618); this helper records whatever it is
+ * given.
+ */
+export async function recordProposalExecution({ appId, slug, scope = null, success, now = Date.now() } = {}, store = outcomesStore()) {
+ const normSlug = normalizeSlug(slug);
+ if (!appId || !normSlug || typeof success !== 'boolean') return false;
+ const id = outcomeId(appId, normSlug);
+ // The domain to adopt when we don't already have one — the load-bearing field for
+ // per-domain aggregation. Normalized once and reused by both the missing-record
+ // fallback and the scope-preservation merge below.
+ const normScope = typeof scope === 'string' && scope.trim() ? scope.trim() : null;
+ const existing = await store.loadOne(id).catch(() => null);
+ const base = existing && typeof existing === 'object'
+ ? existing
+ : {
+ appId, slug: normSlug, tracker: null, issueRef: null,
+ scope: normScope,
+ filedAt: new Date(now).toISOString(),
+ outcome: null, outcomeAt: null, outcomeReason: null, rejectionReason: null
+ };
+ const next = {
+ ...base,
+ // Preserve the filed scope when the record already carries one; otherwise adopt
+ // the domain the completion hook passed (a missing-record fallback).
+ scope: (typeof base.scope === 'string' && base.scope.trim()) ? base.scope : normScope,
+ executionOutcome: success ? 'success' : 'failure',
+ executionAt: new Date(now).toISOString()
+ };
+ await ensureTypeIndex(store);
+ const ok = await store.saveOne(id, next).then(() => true, (err) => {
+ console.error(`❌ Layered Intelligence: failed to record execution outcome for ${appId}/${normSlug}: ${err.message}`);
+ return false;
+ });
+ return ok;
+}
+
/**
* Load this app's outcome records, GC-ing stale ones from disk so the store stays
* bounded. GC mirrors the dedup window (isIssueWithinDedupWindow): an UNRESOLVED
diff --git a/server/services/layeredIntelligenceOutcomes.test.js b/server/services/layeredIntelligenceOutcomes.test.js
index 1f701d7503..10c1af3edc 100644
--- a/server/services/layeredIntelligenceOutcomes.test.js
+++ b/server/services/layeredIntelligenceOutcomes.test.js
@@ -6,12 +6,14 @@ import { createCollectionStore } from '../lib/collectionStore.js';
import {
sanitizeOutcomeRecord,
recordFiledProposal,
+ recordProposalExecution,
listOutcomes,
listOutcomesResult,
reconcileOutcomes,
OUTCOME_RETENTION_MS,
LI_OUTCOMES_SCHEMA_VERSION
} from './layeredIntelligenceOutcomes.js';
+import { computeExecutionByDomain } from './layeredIntelligence.js';
// Build an isolated store over a temp dir so the suite never touches the real
// data/cos/li-outcomes collection. The store functions all take an injectable
@@ -79,6 +81,29 @@ describe('sanitizeOutcomeRecord', () => {
expect(sanitize({ outcome: 'rejected' }).rejectionReason).toBeNull();
});
});
+
+ describe('executionOutcome (#2765)', () => {
+ const sanitize = (over) => sanitizeOutcomeRecord({ appId: 'a', slug: 's', ...over });
+
+ it('keeps a recognized execution outcome + its timestamp', () => {
+ const r = sanitize({ executionOutcome: 'success', executionAt: '2026-01-01T00:00:00.000Z' });
+ expect(r.executionOutcome).toBe('success');
+ expect(r.executionAt).toBe('2026-01-01T00:00:00.000Z');
+ expect(sanitize({ executionOutcome: 'failure', executionAt: 'x' }).executionOutcome).toBe('failure');
+ });
+
+ it('coerces an unrecognized execution outcome to null and drops its timestamp', () => {
+ const r = sanitize({ executionOutcome: 'bogus', executionAt: 'x' });
+ expect(r.executionOutcome).toBeNull();
+ expect(r.executionAt).toBeNull();
+ });
+
+ it('defaults a record with no execution field to null (never executed)', () => {
+ const r = sanitize({ outcome: 'merged' });
+ expect(r.executionOutcome).toBeNull();
+ expect(r.executionAt).toBeNull();
+ });
+ });
});
describe('recordFiledProposal + listOutcomes', () => {
@@ -425,3 +450,62 @@ describe('listOutcomesResult read sentinel (#2700)', () => {
expect(await listOutcomes({ appId: 'app-1' }, broken)).toEqual([]);
});
});
+
+describe('recordProposalExecution (#2765)', () => {
+ it('stamps execution success onto an existing filed record, preserving its scope + filing outcome', async () => {
+ await recordFiledProposal({ appId: 'app-1', slug: 'tidy-thing', tracker: 'github', issueRef: '#7', scope: 'loop-meta' }, store);
+ const ok = await recordProposalExecution({ appId: 'app-1', slug: 'tidy-thing', success: true }, store);
+ expect(ok).toBe(true);
+ const [row] = await listOutcomes({ appId: 'app-1' }, store);
+ expect(row).toMatchObject({ slug: 'tidy-thing', scope: 'loop-meta', executionOutcome: 'success' });
+ expect(row.executionAt).toBeTruthy();
+ // The filed identity is untouched — execution is orthogonal to the filing fate.
+ expect(row.issueRef).toBe('#7');
+ expect(row.outcome).toBeNull();
+ });
+
+ it('records a failure and normalizes the slug', async () => {
+ await recordFiledProposal({ appId: 'app-1', slug: 'flaky-fix', scope: 'app-improvement' }, store);
+ await recordProposalExecution({ appId: 'app-1', slug: 'Flaky Fix', success: false }, store);
+ const [row] = await listOutcomes({ appId: 'app-1' }, store);
+ expect(row.executionOutcome).toBe('failure');
+ });
+
+ it('creates a minimal record (adopting the passed scope) when the filed record is missing', async () => {
+ // GC'd or a filing-write miss — the execution signal must not be silently lost.
+ const ok = await recordProposalExecution({ appId: 'app-2', slug: 'orphan', scope: 'portos-self', success: true }, store);
+ expect(ok).toBe(true);
+ const [row] = await listOutcomes({ appId: 'app-2' }, store);
+ expect(row).toMatchObject({ appId: 'app-2', slug: 'orphan', scope: 'portos-self', executionOutcome: 'success' });
+ });
+
+ it('rejects a non-boolean success / missing identity without writing', async () => {
+ expect(await recordProposalExecution({ appId: 'app-1', slug: 's', success: 'yes' }, store)).toBe(false);
+ expect(await recordProposalExecution({ appId: 'app-1', success: true }, store)).toBe(false);
+ expect(await recordProposalExecution({ slug: 's', success: true }, store)).toBe(false);
+ expect(await listOutcomes({ appId: 'app-1' }, store)).toHaveLength(0);
+ });
+
+ it('acceptance (#2765): filing + executing a proposal moves ONLY that domain’s bucket', async () => {
+ // Two proposals in different domains; execute only the loop-meta one.
+ await recordFiledProposal({ appId: 'app-1', slug: 'meta-one', scope: 'loop-meta' }, store);
+ await recordFiledProposal({ appId: 'app-1', slug: 'improve-one', scope: 'app-improvement' }, store);
+ await recordProposalExecution({ appId: 'app-1', slug: 'meta-one', success: true }, store);
+
+ const byDomain = computeExecutionByDomain(await listOutcomes({ appId: 'app-1' }, store));
+ expect(byDomain['loop-meta']).toEqual({ completed: 1, succeeded: 1, successRate: 100 });
+ // The un-executed proposal's domain never appears — no executionOutcome to count.
+ expect(byDomain['app-improvement']).toBeUndefined();
+ });
+
+ it('aggregates a domain’s success rate across multiple executions', async () => {
+ await recordFiledProposal({ appId: 'app-1', slug: 'a', scope: 'loop-meta' }, store);
+ await recordFiledProposal({ appId: 'app-1', slug: 'b', scope: 'loop-meta' }, store);
+ await recordFiledProposal({ appId: 'app-1', slug: 'c', scope: 'loop-meta' }, store);
+ await recordProposalExecution({ appId: 'app-1', slug: 'a', success: true }, store);
+ await recordProposalExecution({ appId: 'app-1', slug: 'b', success: true }, store);
+ await recordProposalExecution({ appId: 'app-1', slug: 'c', success: false }, store);
+ const byDomain = computeExecutionByDomain(await listOutcomes({ appId: 'app-1' }, store));
+ expect(byDomain['loop-meta']).toEqual({ completed: 3, succeeded: 2, successRate: 67 });
+ });
+});
diff --git a/server/services/taskLearning/metrics.js b/server/services/taskLearning/metrics.js
index 4820933179..c4554fd6d9 100644
--- a/server/services/taskLearning/metrics.js
+++ b/server/services/taskLearning/metrics.js
@@ -290,11 +290,31 @@ export function recordFailureSignature(data, context) {
return data;
}
+/**
+ * Build the per-proposal-domain execution payload (#2765) from a completed task that
+ * took the Layered-Intelligence hand-off path, or null when the task carries no LI
+ * marker. The marker (`metadata.taskLiProposal`) is projected onto the agent by
+ * agentLifecycle and reconstructed onto the task by the completion listener; it names
+ * the proposal's app, slug, and domain (scope). `success` is the validation-authoritative
+ * learning outcome, so it agrees with the byTaskType aggregate for the same run.
+ */
+function deriveLiExecutionPayload(task, success) {
+ const li = task?.metadata?.taskLiProposal;
+ if (!li || typeof li !== 'object' || Array.isArray(li)) return null;
+ if (!li.appId || !li.slug) return null;
+ return { appId: li.appId, slug: li.slug, scope: li.scope ?? null, success: !!success };
+}
+
/**
* Record a completed task for learning
*/
export async function recordTaskCompletion(agent, task) {
- return withLock(async () => {
+ // Per-proposal-domain execution attribution (#2765) — captured inside the lock (it
+ // needs this run's validation-authoritative outcome) but WRITTEN after it, so the LI
+ // outcome store's I/O never runs under the learning lock and the generic learning
+ // store stays statically decoupled from LI (lazy import below).
+ let liExecPayload = null;
+ const result = await withLock(async () => {
const data = await loadLearningData();
// Structured telemetry context (failure signature + execution context +
@@ -328,6 +348,11 @@ export async function recordTaskCompletion(agent, task) {
// signals and pre-marker records (null origin) keep the category-only behavior.
const isEnvironmentalFailure = shouldDivertToEnvironmental(outcomeSuccess, errorCategory, errorOrigin);
+ // Attribute an LI hand-off's outcome to the proposal's DOMAIN (#2765). Only a
+ // non-environmental completion counts: a rate-limit/outage says nothing about the
+ // domain, exactly as it is barred from denting the byTaskType aggregate below.
+ liExecPayload = isEnvironmentalFailure ? null : deriveLiExecutionPayload(task, outcomeSuccess);
+
// Correlation-quality prediction snapshot (issue #2344) — captured HERE, before
// ANY of this run's aggregates (byModelTier, routingAccuracy, failureSignatures)
// are folded in below, so the prediction reflects history strictly BEFORE this
@@ -556,6 +581,17 @@ export async function recordTaskCompletion(agent, task) {
return data;
});
+
+ // Post-lock, best-effort: record the LI hand-off execution outcome keyed to the
+ // proposal's domain (#2765). Lazy import keeps the learning store's static module
+ // graph free of LI; a failure here never disturbs the learning write above.
+ if (liExecPayload) {
+ await import('../layeredIntelligenceOutcomes.js')
+ .then(m => m.recordProposalExecution(liExecPayload))
+ .catch(err => console.error(`❌ 📚 TaskLearning: failed to record LI proposal execution: ${err.message}`));
+ }
+
+ return result;
}
/**