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-2799]): gate LI auto-hand-off on the domain's own execution track record

[._.]/ Adam Eivyca7cf496a9da
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a189a95805..cdb3002b8c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -141,3 +141,5 @@
- [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.
- [issue-2798] **Layered Intelligence now pairs *why* a domain's hand-offs fail with the domain's own record — and flags where it proposes well but executes poorly.** Two refinements join the signals above. First, when the loop reports a low execution rate for a domain (e.g. "loop-meta 0% executed"), it now names the dominant cause right on that line ("failing mostly on planning") instead of leaving the failure taxonomy tallied only install-wide — so the loop can tell an under-scoped domain apart from one that keeps breaking tests. Second, a new cross-reference summary correlates each domain's *merge* rate against its *execution-failure* mode and surfaces the revealing mismatch — "your loop-meta proposals merge at 50% but your hand-offs there fail on planning 3 of 4 times" — so a domain you pick well but can't finish as handed off is called out as a blind spot to narrow or split, rather than abandoned. Both are derived purely from the outcome records the loop already keeps: no extra AI calls, no extra tracker reads, and only diagnosed non-environmental failures are named (an outage or an undiagnosed failure is never dressed up as a cause).
+
+- [issue-2799] **Layered Intelligence now files a proposal for you instead of auto-handing it to an agent when its own past hand-offs in that area chronically fail.** The reasoner is already warned about domains where its hand-offs stall (above), but a warning it can ignore isn't enforcement — so even a proposal it marked trivial-and-safe could still be auto-dispatched to a coding agent in an area with a proven track record of failing. Now a deterministic gate runs at hand-off time: when a domain has enough executed hand-offs to be evidence and its success rate sits below the coin-flip line, the loop declines the automatic dispatch and files the proposal for human review instead, logging exactly why ("app-improvement hand-offs succeed 33% over 3 executed — filing for human review instead of auto-hand-off"). Filing-for-a-human is treated as the intended good outcome, not a failure — the issue is still filed and nothing is lost; only the unattended agent dispatch is withheld. Healthy domains are unaffected and still hand off automatically. The gate is derived purely from the outcome records the loop already keeps (no extra AI calls, no extra tracker reads), a freshly-filed proposal can't skew its own routing, and an unreadable history degrades safely to "hand off as before" rather than silently suppressing the dispatch.
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index e26c89f43f..cb9f60b57e 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -56,10 +56,11 @@ import {
computeSelfEvalSummary,
computeProposalExecutionAwareness,
computeCrossReferenceAnalysis,
+ computeHandoffRouting,
readLiTaskMetrics,
hasPlannedWorkListing
} from '../layeredIntelligence.js'
-import { recordFiledProposal, listOutcomesResult, reconcileOutcomes } from '../layeredIntelligenceOutcomes.js'
+import { recordFiledProposal, listOutcomesResult, reconcileOutcomes, listOutcomes } from '../layeredIntelligenceOutcomes.js'
// The outcome feedback loop (#2428) can only reconcile a proposal's fate on a
// tracker that reports closed-state. All three now qualify: a forge (gh/glab
@@ -512,6 +513,10 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {
let filedAction = 'no-op'
let reason = envelope == null || proposalAttemptedButInvalid ? 'unparseable-response' : 'no-proposal'
let handedOff = false
+ // §4 (#2764): when the deterministic routing gate files-for-human instead of
+ // auto-handing-off a trivial+safe proposal, surface WHY on the returned result.
+ let handoffRouted = false
+ let handoffRoutingReason = null
if (proposal) {
// Re-read issues NOW (not at gather time) so dedup sees the freshest tracker
@@ -569,14 +574,32 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {
}
const issueRef = filedKey || filedNumber
if (isHandoffEligible({ proposal, config, filed: issueRef })) {
- // Only mark the hand-off for per-domain execution recording (#2765) when the
- // proposal itself was recorded above — same gate — so execution-tracking never
- // creates an outcome row for a proposal the `outcomes` toggle says isn't tracked.
- const task = await enqueueHandoff(buildHandoffTask({ app, proposal, issueRef, recordExecution: outcomesRecordable }))
- .catch((err) => { console.error(`❌ Layered Intelligence: ${app.name} hand-off enqueue failed: ${err.message}`); return null })
- if (task && !task.duplicate) {
- handedOff = true
- console.log(`🤝 Layered Intelligence: ${app.name} handed off ${ref} to a coding agent (task ${task.id})`)
+ // §4 (#2764): the reasoner-signal gate (isHandoffEligible) passed, but the
+ // SYSTEM still refuses to auto-hand-off a trivial+safe proposal in a domain
+ // where LI's OWN prior hand-offs chronically fail — it stays filed for a human
+ // instead. Load the app's historical outcomes lazily (only on the hand-off-
+ // eligible path) for computeHandoffRouting. An unreadable history degrades to
+ // "allow hand-off as before" (no-signal → handoff:true) — a store hiccup must
+ // never silently SUPPRESS a hand-off.
+ const outcomes = await listOutcomes({ appId: app.id }).catch(() => [])
+ const routing = computeHandoffRouting({ proposal, outcomes })
+ if (routing.handoff === false) {
+ // Filing-for-human IS the intended good outcome here, not a failure — the
+ // proposal WAS filed successfully, so `reason` stays null. Record the routing
+ // on the returned result for observability.
+ handoffRouted = true
+ handoffRoutingReason = routing.reason
+ console.log(`🧭 Layered Intelligence: ${app.name} routed ${ref} to human review instead of auto-hand-off — ${routing.reason}`)
+ } else {
+ // Only mark the hand-off for per-domain execution recording (#2765) when the
+ // proposal itself was recorded above — same gate — so execution-tracking never
+ // creates an outcome row for a proposal the `outcomes` toggle says isn't tracked.
+ const task = await enqueueHandoff(buildHandoffTask({ app, proposal, issueRef, recordExecution: outcomesRecordable }))
+ .catch((err) => { console.error(`❌ Layered Intelligence: ${app.name} hand-off enqueue failed: ${err.message}`); return null })
+ if (task && !task.duplicate) {
+ handedOff = true
+ console.log(`🤝 Layered Intelligence: ${app.name} handed off ${ref} to a coding agent (task ${task.id})`)
+ }
}
}
} else {
@@ -604,5 +627,5 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {
}
}
- return settle({ action: filedAction, reason, filedNumber, filedKey, paused, handedOff })
+ return settle({ action: filedAction, reason, filedNumber, filedKey, paused, handedOff, handoffRouted, handoffRoutingReason })
}
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
index a78e650f46..0eb6c06ba3 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
@@ -68,6 +68,11 @@ vi.mock('../layeredIntelligence.js', () => ({
// layeredIntelligence.test.js; a spy here so the hook's WIRING (computed from the
// loaded outcomes and passed to buildPrompt) can be asserted.
computeCrossReferenceAnalysis: vi.fn(() => ''),
+ // Hand-off routing gate (#2764 §4). Semantics are unit-tested in
+ // layeredIntelligence.test.js; here it's a spy so the hook's WIRING (consulted
+ // before enqueuing, suppressing on handoff:false) can be asserted. Defaults to
+ // "allow the hand-off" so the existing hand-off path is unaffected.
+ computeHandoffRouting: vi.fn(() => ({ handoff: true, reason: null })),
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
@@ -80,12 +85,14 @@ vi.mock('../layeredIntelligence.js', () => ({
vi.mock('../layeredIntelligenceOutcomes.js', () => ({
recordFiledProposal: vi.fn().mockResolvedValue(true),
listOutcomesResult: vi.fn().mockResolvedValue({ read: true, outcomes: [] }),
- reconcileOutcomes: vi.fn().mockResolvedValue(0)
+ reconcileOutcomes: vi.fn().mockResolvedValue(0),
+ // The routing gate (#2764 §4) reads the app's history lazily on the hand-off path.
+ listOutcomes: vi.fn().mockResolvedValue([])
}));
import { buildTaskInput, processTaskOutput } from './layeredIntelligenceHooks.js';
import * as li from '../layeredIntelligence.js';
-import { recordFiledProposal, listOutcomesResult, reconcileOutcomes } from '../layeredIntelligenceOutcomes.js';
+import { recordFiledProposal, listOutcomesResult, reconcileOutcomes, listOutcomes } from '../layeredIntelligenceOutcomes.js';
import * as apps from '../apps.js';
import { resolveAppWorkTracker } from '../../lib/workTracker.js';
import { tryReadFile } from '../../lib/fileUtils.js';
@@ -514,6 +521,56 @@ describe('processTaskOutput', () => {
}));
});
+ it('hands off a trivial+safe proposal in a healthy domain (routing allows) (#2764 §4)', async () => {
+ li.validateReasonerResponse.mockReturnValue({
+ proposal: { scope: 'app-improvement', slug: 'quick-fix', title: 'Quick fix', body: 'x', complexity: 'trivial', safe: true },
+ pause: null
+ });
+ li.fileProposalToForge.mockResolvedValue({ success: true, number: 88 });
+ li.isHandoffEligible.mockReturnValue(true);
+ li.computeHandoffRouting.mockReturnValue({ handoff: true, reason: null });
+ li.getEffectiveConfig.mockReturnValue({ allowedScopes: ['app-improvement'], sources: { outcomes: true }, handoff: { enabled: true } });
+ const enqueueHandoff = vi.fn().mockResolvedValue({ id: 't-1', duplicate: false });
+ const out = await processTaskOutput({ appId: 'app-1', success: true, payload: { proposal: {} } }, { enqueueHandoff });
+ // The routing gate was consulted with the loaded history, then allowed the enqueue.
+ expect(listOutcomes).toHaveBeenCalledWith(expect.objectContaining({ appId: 'app-1' }));
+ expect(li.computeHandoffRouting).toHaveBeenCalled();
+ expect(enqueueHandoff).toHaveBeenCalled();
+ expect(out).toMatchObject({ action: 'filed', reason: null, handedOff: true, handoffRouted: false });
+ });
+
+ it('files but does NOT auto-hand-off a trivial+safe proposal in a chronically-failing domain (#2764 §4)', async () => {
+ li.validateReasonerResponse.mockReturnValue({
+ proposal: { scope: 'app-improvement', slug: 'risky-here', title: 'Risky here', body: 'x', complexity: 'trivial', safe: true },
+ pause: null
+ });
+ li.fileProposalToForge.mockResolvedValue({ success: true, number: 89 });
+ li.isHandoffEligible.mockReturnValue(true);
+ // The domain's own hand-offs chronically fail → route to a human instead.
+ li.computeHandoffRouting.mockReturnValue({
+ handoff: false,
+ domain: 'app-improvement',
+ rate: 33,
+ n: 3,
+ cause: 'failing mostly on planning (2)',
+ reason: 'app-improvement hand-offs succeed 33% over 3 executed — filing for human review instead of auto-hand-off (failing mostly on planning (2))'
+ });
+ li.getEffectiveConfig.mockReturnValue({ allowedScopes: ['app-improvement'], sources: { outcomes: true }, handoff: { enabled: true } });
+ const enqueueHandoff = vi.fn().mockResolvedValue({ id: 't-2', duplicate: false });
+ const out = await processTaskOutput({ appId: 'app-1', success: true, payload: { proposal: {} } }, { enqueueHandoff });
+ // Filed for a human, but the coding agent was NOT enqueued.
+ expect(li.fileProposalToForge).toHaveBeenCalled();
+ expect(enqueueHandoff).not.toHaveBeenCalled();
+ // The proposal WAS filed successfully — filing-for-human is the good outcome, not a failure.
+ expect(out).toMatchObject({
+ action: 'filed',
+ reason: null,
+ handedOff: false,
+ handoffRouted: true,
+ handoffRoutingReason: expect.stringContaining('filing for human review instead of auto-hand-off')
+ });
+ });
+
it('reports a re-proposed already-tracked PLAN slug as duplicate without resetting its outcome (#2435)', async () => {
// Since #2620 a checked `- [x]` item stays within the dedup window, so this
// path normally never reaches the append. Belt-and-suspenders: should the
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index c1f4a74261..8063f8f6ab 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -1179,6 +1179,23 @@ function formatDominantFailureCause(failureSummary, limit = 2) {
return `failing mostly on ${listed}`;
}
+/**
+ * Is this a proposal DOMAIN whose OWN hand-offs chronically fail — enough executed
+ * hand-offs to be evidence (PROPOSAL_EXECUTION_MIN_SAMPLE) AND a success rate below
+ * the coin-flip avoid line (SCOPE_AVOID_SUCCESS_THRESHOLD)? The single load-bearing
+ * definition of "on the avoid list", shared so the reasoner-facing prompt
+ * (computeProposalExecutionAwareness) and the deterministic hand-off gate
+ * (computeHandoffRouting) can NEVER disagree about which domains qualify — the
+ * design requires the prompt's avoid list and the gate to name the same set. Takes
+ * a per-domain bucket from computeExecutionByDomain (or undefined when the domain
+ * has no execution history → false).
+ */
+function isAvoidDomain(bucket) {
+ return !!bucket
+ && bucket.completed >= PROPOSAL_EXECUTION_MIN_SAMPLE
+ && bucket.successRate < SCOPE_AVOID_SUCCESS_THRESHOLD;
+}
+
/**
* 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
@@ -1201,7 +1218,7 @@ export function computeProposalExecutionAwareness({ outcomes = [] } = {}) {
// we do not also emit a one-sample per-domain cause here (it would read as a trend
// off n=1).
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, cause: formatDominantFailureCause(bucket.failureSummary) });
+ if (isAvoidDomain(bucket)) avoid.push({ scope, rate: bucket.successRate, n: bucket.completed, cause: formatDominantFailureCause(bucket.failureSummary) });
else if (bucket.successRate >= SCOPE_PREFER_SUCCESS_THRESHOLD) prefer.push({ scope, rate: bucket.successRate, n: bucket.completed });
}
return renderAvoidPreferSections({
@@ -1290,6 +1307,63 @@ export function computeCrossReferenceAnalysis({ outcomes = [] } = {}) {
return `${CROSS_REFERENCE_HEADER}\n${lines.join('\n')}`;
}
+/**
+ * Deterministic hand-off routing gate (#2764 §4). Given a proposal and the app's
+ * historical outcome records, decides whether a trivial+safe proposal may be
+ * auto-handed-off to a coding agent NOW, or must instead be filed for a human —
+ * because LI's OWN prior hand-offs in that domain chronically fail. This is the
+ * SYSTEM-side enforcement of the same signal the reasoner is merely WARNED about
+ * in the liProposalExecution / liCrossReference prompt blocks: even when the
+ * reasoner marks a proposal trivial+safe, the gate suppresses the auto-hand-off
+ * for a domain whose track record says the hand-off will just fail again.
+ *
+ * Pure + side-effect-free, like the sibling compute* report functions — derives
+ * only from the `li-outcomes` records already loaded (no new AI/tracker/store
+ * call). The just-filed proposal cannot skew this: computeExecutionByDomain only
+ * counts records carrying a resolved `executionOutcome`, which a freshly-filed
+ * proposal has not got yet.
+ *
+ * Shares the isAvoidDomain classifier with computeProposalExecutionAwareness so the
+ * gate and the reasoner-facing prompt can NEVER disagree about which domains are
+ * "chronically failing": a domain qualifies only when it has at least
+ * PROPOSAL_EXECUTION_MIN_SAMPLE executed hand-offs AND its success rate is below
+ * SCOPE_AVOID_SUCCESS_THRESHOLD — the SAME floor + threshold that puts a domain on
+ * the reasoner's avoid list.
+ *
+ * Returns:
+ * - `{ handoff: true, reason: null }` — allow the auto-hand-off, when the
+ * proposal has no scope (can't judge), the domain is below the sample floor,
+ * the domain has no execution history, or its rate is at/above the threshold.
+ * - `{ handoff: false, domain, rate, n, cause, reason }` — SUPPRESS: file for a
+ * human instead. `reason` names the domain, rate, sample size, and (when a
+ * dominant failure cause is diagnosed) the cause — reusing formatDominantFailureCause,
+ * which returns '' for a purely unknown/unclassified domain so the cause clause
+ * is simply omitted there.
+ *
+ * @param {object} args
+ * @param {object} args.proposal - the reasoner's proposal ({ scope, ... }).
+ * @param {Array} [args.outcomes] - the app's li-outcomes records.
+ * @returns {{ handoff: boolean, reason: string|null, domain?: string, rate?: number, n?: number, cause?: string }}
+ */
+export function computeHandoffRouting({ proposal, outcomes = [] } = {}) {
+ // No scope → we can't map the proposal to a domain's track record, so we can't
+ // justify suppressing the hand-off. Allow, as before §4 existed.
+ const domain = typeof proposal?.scope === 'string' && proposal.scope.trim() ? proposal.scope.trim() : null;
+ if (!domain) return { handoff: true, reason: null };
+
+ const byDomain = computeExecutionByDomain(outcomes);
+ const bucket = byDomain[domain];
+ // Below the floor, no bucket, or at/above the threshold → no signal to suppress on,
+ // so allow the hand-off exactly as today. isAvoidDomain is the SAME predicate
+ // computeProposalExecutionAwareness uses for its avoid list, so the gate and the
+ // reasoner-facing prompt agree on which domains are "chronically failing".
+ if (!isAvoidDomain(bucket)) return { handoff: true, reason: null };
+
+ const cause = formatDominantFailureCause(bucket.failureSummary);
+ const reason = `${domain} hand-offs succeed ${bucket.successRate}% over ${bucket.completed} executed — filing for human review instead of auto-hand-off${cause ? ` (${cause})` : ''}`;
+ return { handoff: false, domain, rate: bucket.successRate, n: bucket.completed, cause, reason };
+}
+
// Source keys that buildPrompt renders as their OWN dedicated block (with tailored
// guidance) instead of dumping into the generic "### <key>\n<value>" source list.
// Keeping them in one named set — rather than accreting `&& k !== 'x'` clauses on the
@@ -1344,7 +1418,7 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort
: '';
const handoffNote = config.handoff?.enabled
- ? '\nHand-off: a proposal you mark BOTH "complexity":"trivial" AND "safe":true may be handed directly to a coding agent to implement now (not just filed). Only mark a proposal trivial+safe when it is small, self-contained, and carries no regression or data-loss risk — when in doubt, use a higher complexity or "safe":false so a human triages it first.\n'
+ ? '\nHand-off: a proposal you mark BOTH "complexity":"trivial" AND "safe":true may be handed directly to a coding agent to implement now (not just filed). Only mark a proposal trivial+safe when it is small, self-contained, and carries no regression or data-loss risk — when in doubt, use a higher complexity or "safe":false so a human triages it first. Note: even a trivial+safe proposal is filed for a human (not auto-handed-off) when it falls in a domain where LI\'s own past hand-offs chronically fail, so prefer to narrow such a proposal to a slice an agent can actually finish.\n'
: '';
// The committed backlog (#2698) + the instruction to check against it. Emitted
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index a4b35a0d4f..9afa84c63f 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -47,6 +47,7 @@ import {
computeExecutionByDomain,
computeProposalExecutionAwareness,
computeCrossReferenceAnalysis,
+ computeHandoffRouting,
PROPOSAL_EXECUTION_MIN_SAMPLE,
SCOPE_AVOID_SUCCESS_THRESHOLD,
SCOPE_PREFER_SUCCESS_THRESHOLD,
@@ -594,6 +595,79 @@ describe('computeCrossReferenceAnalysis (#2764 §3)', () => {
});
});
+describe('computeHandoffRouting (#2764 §4)', () => {
+ const execRecords = (scope, successes, failures, extraFail = {}) => [
+ ...Array.from({ length: successes }, () => ({ scope, executionOutcome: 'success' })),
+ ...Array.from({ length: failures }, () => ({ scope, executionOutcome: 'failure', ...extraFail }))
+ ];
+
+ it('allows the hand-off when the proposal has no scope (cannot judge)', () => {
+ expect(computeHandoffRouting({ proposal: {}, outcomes: [] })).toEqual({ handoff: true, reason: null });
+ expect(computeHandoffRouting({ proposal: { scope: ' ' }, outcomes: [] })).toEqual({ handoff: true, reason: null });
+ expect(computeHandoffRouting()).toEqual({ handoff: true, reason: null });
+ });
+
+ it('allows the hand-off for an unknown domain (no execution history)', () => {
+ expect(computeHandoffRouting({ proposal: { scope: 'loop-meta' }, outcomes: [] }))
+ .toEqual({ handoff: true, reason: null });
+ });
+
+ it('allows the hand-off below the sample floor even at 0%', () => {
+ // One failed execution is below PROPOSAL_EXECUTION_MIN_SAMPLE (2) — not evidence.
+ expect(computeHandoffRouting({ proposal: { scope: 'loop-meta' }, outcomes: execRecords('loop-meta', 0, 1) }))
+ .toEqual({ handoff: true, reason: null });
+ });
+
+ it('allows the hand-off when the rate is at/above the avoid threshold', () => {
+ // 2/3 ≈ 67% is at/above the 50% avoid line → not chronically failing.
+ expect(computeHandoffRouting({ proposal: { scope: 'loop-meta' }, outcomes: execRecords('loop-meta', 2, 1) }))
+ .toEqual({ handoff: true, reason: null });
+ });
+
+ it('suppresses the hand-off for a chronically-failing domain and names domain+rate+cause', () => {
+ const routing = computeHandoffRouting({
+ proposal: { scope: 'loop-meta' },
+ outcomes: [
+ { scope: 'loop-meta', executionOutcome: 'success' }, // 1 success
+ { scope: 'loop-meta', executionOutcome: 'failure', failureCategory: 'planning' },
+ { scope: 'loop-meta', executionOutcome: 'failure', failureCategory: 'planning' } // 2 failures → 33%
+ ]
+ });
+ expect(routing.handoff).toBe(false);
+ expect(routing.domain).toBe('loop-meta');
+ expect(routing.rate).toBe(33);
+ expect(routing.n).toBe(3);
+ expect(routing.reason).toContain('loop-meta');
+ expect(routing.reason).toContain('33%');
+ expect(routing.reason).toContain('over 3 executed');
+ expect(routing.reason).toContain('filing for human review instead of auto-hand-off');
+ // Dominant cause is glossed and appended in parentheses.
+ expect(routing.reason).toContain('failing mostly on');
+ expect(routing.reason).toContain('the task was under-defined or already done (no correct change to make) (2)');
+ // Agrees with the reasoner-facing avoid list on WHICH domains are chronically failing.
+ expect(computeProposalExecutionAwareness({ outcomes: [
+ { scope: 'loop-meta', executionOutcome: 'success' },
+ { scope: 'loop-meta', executionOutcome: 'failure', failureCategory: 'planning' },
+ { scope: 'loop-meta', executionOutcome: 'failure', failureCategory: 'planning' }
+ ] })).toContain('loop-meta');
+ });
+
+ it('suppresses with NO trailing cause clause when failures are purely undiagnosed', () => {
+ const routing = computeHandoffRouting({
+ proposal: { scope: 'app-improvement' },
+ outcomes: execRecords('app-improvement', 0, 3) // 0%, all unclassified
+ });
+ expect(routing.handoff).toBe(false);
+ expect(routing.domain).toBe('app-improvement');
+ expect(routing.rate).toBe(0);
+ expect(routing.n).toBe(3);
+ expect(routing.cause).toBe('');
+ expect(routing.reason).toContain('app-improvement');
+ expect(routing.reason).not.toContain('failing mostly on');
+ expect(routing.reason).not.toContain('(');
+ });
+});
+
describe('resolveBlockOnIssue', () => {
it('maps "this" to the just-filed issue number', () => {
expect(resolveBlockOnIssue({ blockOnIssue: 'this' }, 99)).toBe(99);