Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
add hard pre-filing exclusion gate for degraded LI execution (#2824)
[._.]/ Adam Eivy800e07ea78a9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d7cdf9aed8..5310e8177b 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,8 @@- **[issue-2748] Rejected LI proposals are now diagnosed as `merge-conflict` / `validation-failed` from the implementing PR** — when a Layered Intelligence proposal is closed unmerged and its implementing pull request had merge conflicts or failing checks, the loop now records that as the rejection reason instead of a generic "declined." It reads the PR handle from GitHub's closing-PR references in the batch it already fetches, then makes one bounded `gh pr view` check only for proposals a label or closing comment didn't already explain — so a mechanical PR fact refines an otherwise-vague close but never overrides a human's stated reason, and nothing runs at boot.+- **[issue-2824] Hard pre-filing exclusion gate — a degraded Layered Intelligence loop stops proposing work it can't finish.** When LI's own execution health (its reasoning-run success rate) is confidently below 75%, a deterministic gate now SUPPRESSES a proposal *before it is filed* — not just advises against it — if the proposal is self-improve-scoped (`loop-meta` / `portos-self`) or maps to a chronically-failing execution domain (the same `isAvoidDomain` classifier the hand-off routing gate already uses). Enforcement runs server-side in `processTaskOutput` regardless of what the reasoning model returns, so the loop can no longer "reason past" the exclusion; the reasoner's prompt gains a matching `liHardExclusions` block + GATE CHECK step and the proposal playbook §4 moves from advisory to mandatory language, both driven from the same execution-health read so prompt guidance and enforcement can never disagree. A degraded loop cannot repair itself, so self-improvement work is deferred to a human rather than re-proposed each run; a cold loop with too few recorded runs is never gated. Suppressed runs record the neutral `hard-gate-excluded` outcome with a plain-English explanation.+## Enterprise GitHub support- [issue-2650] The CoS branch reconciler and issue reconciler now work on self-hosted GitHub Enterprise (`github.*`) repos, not just `github.com`. Both previously gated on the github.com-only `isGithub` origin flag (which drives PortOS's own fork/update flow), so their scans silently skipped enterprise repos even though the sibling PR-watcher already handled them. All three services now share an `isGithubHost(host)` classifier and target `gh` via a host-qualified `HOST/OWNER/REPO` selector, so enterprise repos reconcile correctly and detection stays deterministic on a fork+upstream checkout. Existing github.com behavior is unchanged.diff --git a/client/src/utils/layeredIntelligenceReasons.js b/client/src/utils/layeredIntelligenceReasons.jsindex 486514b146..9658657656 100644--- a/client/src/utils/layeredIntelligenceReasons.js+++ b/client/src/utils/layeredIntelligenceReasons.js@@ -2,8 +2,8 @@//// The reason vocabulary is authored server-side (server/services/autonomousJobs/// layeredIntelligenceHooks.js — `no-provider`, `unparseable-response`,-// `no-proposal`, `scope-suppressed`, `file-failed`, `duplicate`,-// `semantic-duplicate`, `tracker-read-failed`, `blocking-read-failed`,+// `no-proposal`, `scope-suppressed`, `hard-gate-excluded`, `file-failed`,+// `duplicate`, `semantic-duplicate`, `tracker-read-failed`, `blocking-read-failed`,// `jira-not-configured`, `provider-not-agent-capable`, `blocking-open`, plus the// synthesized `llm-error:<msg>`// prefix) and consumed by BOTH the on-demand toast (useOnDemandTaskToast) and the@@ -15,7 +15,7 @@// Reasons that are a normal, non-alarming outcome (a run that simply had nothing// new to file) — rendered in a neutral tone rather than a warning.export const LI_NEUTRAL_REASONS = new Set([- 'no-proposal', 'duplicate', 'semantic-duplicate', 'blocking-open'+ 'no-proposal', 'duplicate', 'semantic-duplicate', 'blocking-open', 'hard-gate-excluded']);const LI_REASON_LABELS = {@@ -23,6 +23,7 @@ const LI_REASON_LABELS = {'unparseable-response': 'the reasoning model returned no usable JSON — try a non-reasoning model or an API provider','no-proposal': 'the loop had nothing to propose','scope-suppressed': "the proposal's scope isn't allowed for this app",+ 'hard-gate-excluded': "excluded before filing — the loop's own execution is degraded and this proposal maps to self-improve scope or a chronically-failing domain",'file-failed': 'filing the tracker issue failed','duplicate': 'the proposal matched an existing open issue','semantic-duplicate': 'the proposal closely matched an existing issue',diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex e27ba04906..38f13558e1 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -57,6 +57,8 @@ import {computeProposalExecutionAwareness,computeCrossReferenceAnalysis,computeHandoffRouting,+ computeHardExclusionGate,+ computeHardExclusionNotice,readLiTaskMetrics,hasPlannedWorkListing} from '../layeredIntelligence.js'@@ -372,16 +374,27 @@ export async function buildTaskInput({ app } = {}) {// will actually do. Do NOT "fix" this by marking a missing PLAN.md as a failed// read: an app with no PLAN.md yet genuinely has nothing filed, and suppressing// its proposals would park the loop on every such app permanently.+ // Read LI's own execution-health stats ONCE and feed BOTH the selfEval Signal-3 line+ // and the hard-exclusion notice (#2824) — they must judge health off the same number.+ const liTaskStats = (config.sources?.selfEval) ? await readLiTaskMetrics() : nulllet selfEvalReport = ''if (config.sources?.selfEval) {selfEvalReport = computeSelfEvalSummary({outcomes,existingIssues: trackerReadFailed ? null : existingIssues,- liTaskStats: await readLiTaskMetrics()+ liTaskStats})}- const prompt = buildPrompt({ app, config, sources, openIssues, isPortos, outcomesReport, selfEvalReport, proposalExecutionReport, crossReferenceReport }) + buildCompletionContract()+ // Hard-exclusion notice (#2824): the reasoner-facing mirror of the deterministic+ // filing gate. '' unless LI's execution health is degraded (gate armed), so a healthy+ // loop's prompt is unchanged. Enforcement runs in processTaskOutput regardless.+ const hardExclusionNotice = computeHardExclusionNotice({+ liTaskStats,+ outcomes: Array.isArray(outcomes) ? outcomes : []+ })++ const prompt = buildPrompt({ app, config, sources, openIssues, isPortos, outcomesReport, selfEvalReport, proposalExecutionReport, crossReferenceReport, hardExclusionNotice }) + 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@@ -530,9 +543,28 @@ export async function processTaskOutput({ appId, success, payload, agentId } = {// finalize timeout on a run whose verdict is already known).const { existingIssues, trackerReadFailed } = await readIssues({ filer, forgeCli, cwd, jira, config })const scopeOk = isScopeAllowed({ scope: proposal.scope, allowedScopes: config.allowedScopes, isPortos })+ // Hard exclusion gate (#2824): deterministic pre-filing suppression, enforced+ // independent of what the reasoner returned. Reads LI's own execution health + this+ // app's outcome records; suppresses when the loop is degraded AND the proposal maps+ // to self-improve scope or a chronically-failing domain. Only computed on the+ // scope-allowed path (an out-of-scope proposal is already suppressed). An unreadable+ // outcome store degrades to [] → the domain rule simply can't fire, never a false+ // exclusion.+ const hardExclusion = scopeOk+ ? computeHardExclusionGate({+ proposal,+ liTaskStats: await readLiTaskMetrics(),+ outcomes: await listOutcomes({ appId: app.id }).catch(() => []),+ now+ })+ : { excluded: false, reason: null }if (!scopeOk) {console.log(`🚫 Layered Intelligence: ${app.name} proposal scope "${proposal.scope}" not allowed — suppressed`)reason = 'scope-suppressed'+ } else if (hardExclusion.excluded) {+ console.log(`🚫 Layered Intelligence: ${app.name} proposal "${proposal.slug}" hard-excluded before filing — ${hardExclusion.reason}`)+ filedAction = 'excluded'+ reason = 'hard-gate-excluded'} else if (trackerReadFailed) {console.warn(`⚠️ Layered Intelligence: ${app.name} tracker read failed — suppressing proposal to avoid a blind duplicate`)filedAction = 'tracker-read-failed'diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.jsindex 0eb6c06ba3..ca01245dbb 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js@@ -73,6 +73,13 @@ vi.mock('../layeredIntelligence.js', () => ({// 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 })),+ // Hard exclusion gate (#2824). Semantics are unit-tested in+ // layeredIntelligence.test.js; here spies so the hook's WIRING (the notice fed to+ // buildPrompt, the gate consulted before filing and suppressing on excluded:true)+ // can be asserted. Default to "not excluded" / "no notice" so the existing filing+ // path is unaffected.+ computeHardExclusionGate: vi.fn(() => ({ excluded: false, reason: null })),+ computeHardExclusionNotice: 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@@ -112,6 +119,11 @@ beforeEach(() => {li.listBlockingIssues.mockResolvedValue({ ok: true, issues: [] });li.listForgeIssues.mockResolvedValue({ ok: true, issues: [] });li.isAppParked.mockReturnValue(false);+ // Hard exclusion gate (#2824): re-establish "disarmed" defaults each test —+ // clearAllMocks resets call history but NOT a mockReturnValue an individual test set,+ // so without this a test that arms the gate would leak into later ones.+ li.computeHardExclusionGate.mockReturnValue({ excluded: false, reason: null });+ li.computeHardExclusionNotice.mockReturnValue('');});describe('buildTaskInput', () => {@@ -321,6 +333,20 @@ describe('buildTaskInput', () => {}));});+ it('folds the hard-exclusion notice into the prompt from the same liTaskStats (#2824)', async () => {+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { selfEval: true } });+ li.computeHardExclusionNotice.mockReturnValue('HARD EXCLUSION GATE ARMED — 30%');+ await buildTaskInput({ app: APP });+ // Health stats are read once and fed to BOTH selfEval and the notice.+ expect(li.readLiTaskMetrics).toHaveBeenCalledTimes(1);+ expect(li.computeHardExclusionNotice).toHaveBeenCalledWith(expect.objectContaining({+ liTaskStats: expect.objectContaining({ read: true })+ }));+ expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({+ hardExclusionNotice: 'HARD EXCLUSION GATE ARMED — 30%'+ }));+ });+it('passes outcomes to selfEval as null (not []) when the outcomes source is off (#2700)', async () => {// The sentinel that keeps "we never gathered outcomes" from reaching the// reasoner as "this app has never had a proposal merged".@@ -483,6 +509,22 @@ describe('processTaskOutput', () => {expect(apps.updateAppLayeredIntelligence).toHaveBeenCalledWith('app-1', expect.objectContaining({ lastRunAction: 'filed', lastRunRef: '#77' }));});+ it('hard-excludes a proposal before filing when the gate fires (#2824)', async () => {+ li.validateReasonerResponse.mockReturnValue({+ proposal: { scope: 'loop-meta', slug: 'fix-loop', title: 'Fix the loop', body: 'do it' },+ pause: null+ });+ li.computeHardExclusionGate.mockReturnValue({ excluded: true, rule: 'self-improve-scope', reason: 'LI execution health 30% (< 75%) — self-improve-scoped proposals (loop-meta) are excluded' });+ const out = await processTaskOutput({ appId: 'app-1', success: true, payload: { proposal: {} } });+ // The gate was consulted with the validated proposal…+ expect(li.computeHardExclusionGate).toHaveBeenCalledWith(expect.objectContaining({+ proposal: expect.objectContaining({ scope: 'loop-meta' })+ }));+ // …and filing was suppressed entirely.+ expect(li.fileProposalToForge).not.toHaveBeenCalled();+ expect(out).toMatchObject({ action: 'excluded', reason: 'hard-gate-excluded' });+ });+it('records the filed proposal for the feedback loop only when outcomes is enabled', async () => {li.validateReasonerResponse.mockReturnValue({proposal: { scope: 'app-improvement', slug: 'add-telemetry', title: 'Add telemetry', body: 'do it' },diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex e038cde3e9..90ff954210 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -180,6 +180,18 @@ export const LI_DEGRADED_SUCCESS_THRESHOLD = 50;// reported as-is but is NOT treated as a confidence signal either way.export const LI_DEGRADED_MIN_SAMPLE = 4;+// LI execution health (%) below which the deterministic HARD PRE-FILING EXCLUSION+// gate (#2824) arms. Distinct from LI_DEGRADED_SUCCESS_THRESHOLD (50 — the "your+// loop is failing, hold a higher bar" ADVISORY line surfaced to the reasoner): the+// hard gate does not advise, it SUPPRESSES filing, so it opens a WIDER, more cautious+// net. Once LI's own runs dip below three-quarters success it stops FILING self-+// directed work it demonstrably cannot see through, rather than merely being warned.+// Reuses the SCOPE_PREFER value (75) intentionally: the same "reliably executes" bar+// that marks a proposal DOMAIN preferable is the bar LI's own execution health must+// clear before it is trusted to file self-improvement work. The gate arms only on a+// CONFIDENT read (>= LI_DEGRADED_MIN_SAMPLE runs) — a cold loop is never locked out.+export const LI_HARD_GATE_EXECUTION_THRESHOLD = 75;+// The resolved outcomes a filed proposal can reach (the feedback loop, #2428).// A record with a null outcome is still open/unresolved. All three are// auto-derived from the tracker's closed state by deriveOutcome: completed →@@ -861,6 +873,33 @@ export function describeSuppressedIssue(issue, reasonBySlug = null) {* @param {number} [args.now] - clock seam for the suppression window.* @returns {string} the liSelfEval block body.*/+/**+ * Resolve LI's own EXECUTION HEALTH — the loop's reasoning-run success rate — into a+ * single structured read, so every consumer (the selfEval Signal 3 line AND the hard+ * exclusion gate, #2824) judges LI's health off the SAME number instead of each+ * re-deriving it and risking drift. Reads the LI-task metrics bucket+ * (readLiTaskMetrics) through the effective (recency-windowed-or-lifetime) success+ * rate, exactly as Signal 3 did inline.+ *+ * @param {{ read: boolean, metrics: Object|null }|null} liTaskStats - from+ * readLiTaskMetrics. `null`/`read:false` = the learning store was unreadable;+ * `read:true, metrics:null` = read fine and LI has simply never run a task.+ * @param {{ now?: number }} [opts] - clock seam forwarded to computeEffectiveSuccessRate.+ * @returns {{ rate: number|null, sample: number, source: string|null, confident: boolean }}+ * `rate` is null when health is UNKNOWN (store unreadable, no runs, or no completed+ * runs). `confident` is true only at >= LI_DEGRADED_MIN_SAMPLE runs — the floor+ * below which a rate (0-of-1 vs 0-of-N) is not yet evidence.+ */+export function computeLiExecutionHealth(liTaskStats = null, { now = Date.now() } = {}) {+ if (!liTaskStats?.read || !liTaskStats.metrics) {+ return { rate: null, sample: 0, source: null, confident: false };+ }+ const { successRate, source, windowedCompleted } = computeEffectiveSuccessRate(liTaskStats.metrics, { now });+ if (successRate === null) return { rate: null, sample: 0, source: null, confident: false };+ const sample = source === 'windowed' ? windowedCompleted : (liTaskStats.metrics.completed || 0);+ return { rate: successRate, sample, source, confident: sample >= LI_DEGRADED_MIN_SAMPLE };+}+export function computeSelfEvalSummary({outcomes = null,existingIssues = null,@@ -951,19 +990,19 @@ export function computeSelfEvalSummary({} else if (!liTaskStats.metrics) {lines.push('- LI execution health: no LI runs recorded yet — this loop has no execution history.');} else {- // Forward the clock seam: computeEffectiveSuccessRate age-filters the recent- // ring, so without `now` this branch would read the real wall clock while the- // suppression-window branch above uses the injected one — the same summary- // reasoning against two different "nows", and a non-pure "pure" function.- const { successRate, source, windowedCompleted } = computeEffectiveSuccessRate(liTaskStats.metrics, { now });- const sample = source === 'windowed' ? windowedCompleted : (liTaskStats.metrics.completed || 0);- if (successRate === null) {+ // Forward the clock seam via the shared helper (computeLiExecutionHealth), which+ // the hard exclusion gate (#2824) reads too — so the DEGRADED line and the gate can+ // never disagree about LI's own success rate. Without `now` computeEffectiveSuccessRate+ // would read the real wall clock while the suppression-window branch above uses the+ // injected one — the same summary reasoning against two different "nows".+ const health = computeLiExecutionHealth(liTaskStats, { now });+ if (health.rate === null) {lines.push('- LI execution health: no completed LI runs recorded yet — success rate unknown.');} else {- taskSignal = sample >= LI_DEGRADED_MIN_SAMPLE;- liDegraded = taskSignal && successRate < LI_DEGRADED_SUCCESS_THRESHOLD;+ taskSignal = health.confident;+ liDegraded = taskSignal && health.rate < LI_DEGRADED_SUCCESS_THRESHOLD;lines.push(- `- LI execution health: ${successRate}% of ${sample} ${source} LI runs succeeded`+ `- LI execution health: ${health.rate}% of ${health.sample} ${health.source} LI runs succeeded`+ `${taskSignal ? '' : ' — too small a sample to judge'}${liDegraded ? ' — DEGRADED' : ''}.`);}@@ -987,7 +1026,7 @@ export function computeSelfEvalSummary({if (liDegraded) {guidance.push('',- `GUIDANCE — your own execution is degraded (LI run success is under ${LI_DEGRADED_SUCCESS_THRESHOLD}%): the problem may be THIS LOOP, not the app. Favor a narrowly-scoped, low-risk proposal that a coding agent can finish, and do not mark anything trivial+safe for hand-off while your runs are failing this often. A loop-meta proposal that fixes the failure mode may be the highest-value item this run.`+ `GUIDANCE — your own execution is degraded (LI run success is under ${LI_DEGRADED_SUCCESS_THRESHOLD}%): the problem may be THIS LOOP, not the app. Favor a narrowly-scoped, low-risk app-improvement / app-data-gap proposal that a coding agent can finish, and do not mark anything trivial+safe for hand-off while your runs are failing this often. Self-improve-scoped work (loop-meta / portos-self) is HARD-EXCLUDED while your execution health is below ${LI_HARD_GATE_EXECUTION_THRESHOLD}% (#2824): a degraded loop cannot repair itself, so that work is deferred to a human — return proposal: null rather than filing it.`);}@@ -1368,6 +1407,115 @@ export function computeHandoffRouting({ proposal, outcomes = [] } = {}) {return { handoff: false, domain, rate: bucket.successRate, n: bucket.completed, cause, reason };}+// The proposal scopes treated as LI "self-improve" work by the hard exclusion gate+// (#2824): the PortOS-only meta/self scopes. These are the proposals that improve LI /+// PortOS itself and execute under self-improve:* task types — the exact execution class+// whose chronic failure motivated the gate. Reuses PORTOS_ONLY_SCOPES as the single+// definition so "self-improve scope" can never drift from "the PortOS-only scopes".+export const SELF_IMPROVE_SCOPES = PORTOS_ONLY_SCOPES;++/**+ * Deterministic HARD PRE-FILING EXCLUSION gate (#2824). Given a validated proposal,+ * LI's own execution-health stats, and the app's outcome records, decides whether the+ * proposal must be SUPPRESSED before it is ever filed — because LI's own execution is+ * degraded and the proposal maps to work LI cannot see through. This is the SYSTEM-side+ * enforcement of the exclusion the reasoner is merely WARNED about in the prompt notice+ * (computeHardExclusionNotice): even when the reasoner "wants" to file, this gate drops+ * the proposal to null.+ *+ * Pure + side-effect-free like the sibling compute* gates. Two independent exclusion+ * rules, both ARMED only when LI's execution health is CONFIDENTLY below+ * LI_HARD_GATE_EXECUTION_THRESHOLD (75%) — unknown or below-sample-floor health leaves+ * the gate DISARMED, so a cold loop with no track record is never locked out:+ * 1. Self-improve scope — any proposal in a SELF_IMPROVE_SCOPES scope (loop-meta /+ * portos-self) is excluded regardless of domain. A degraded loop cannot repair+ * itself; that work is deferred to a human.+ * 2. Chronically-failing domain — a proposal whose OWN scope's hand-offs chronically+ * fail (the SAME isAvoidDomain classifier the hand-off gate + reasoner avoid list+ * use, so all three agree on which domains qualify) is excluded from FILING, not+ * just from auto-hand-off.+ *+ * @param {object} args+ * @param {object} args.proposal - the validated proposal ({ scope, ... }).+ * @param {{ read: boolean, metrics: Object|null }|null} [args.liTaskStats] - readLiTaskMetrics output.+ * @param {Array} [args.outcomes] - the app's li-outcomes records (for rule 2's domain lookup).+ * @param {number} [args.now] - clock seam for the effective-rate window.+ * @returns {{ excluded: boolean, reason: string|null, rule?: 'self-improve-scope'|'failing-domain' }}+ */+export function computeHardExclusionGate({ proposal, liTaskStats = null, outcomes = [], now = Date.now() } = {}) {+ if (!proposal || typeof proposal !== 'object') return { excluded: false, reason: null };++ // The gate is ARMED only on a confident read of degraded execution health. Unknown+ // health (store unreadable / no runs) or a below-floor sample disarms it — the same+ // 0-of-1-vs-0-of-N reasoning as LI_DEGRADED_MIN_SAMPLE. A healthy loop (>= 75%) files+ // exactly as before this gate existed.+ const health = computeLiExecutionHealth(liTaskStats, { now });+ if (!health.confident || health.rate >= LI_HARD_GATE_EXECUTION_THRESHOLD) {+ return { excluded: false, reason: null };+ }++ const scope = typeof proposal.scope === 'string' && proposal.scope.trim() ? proposal.scope.trim() : null;+ const healthClause = `LI execution health ${health.rate}% (< ${LI_HARD_GATE_EXECUTION_THRESHOLD}%)`;++ // Rule 1: self-improve scope — excluded wholesale while armed.+ if (scope && SELF_IMPROVE_SCOPES.includes(scope)) {+ return {+ excluded: true,+ rule: 'self-improve-scope',+ reason: `${healthClause} — self-improve-scoped proposals (${scope}) are excluded while the loop's own runs are failing; a degraded loop cannot repair itself, so this is deferred to a human`+ };+ }++ // Rule 2: chronically-failing execution domain — same isAvoidDomain classifier the+ // hand-off routing gate uses, so a domain on the reasoner's avoid list is the same+ // set the gate blocks. Only reached for non-self-improve scopes with a scope present.+ if (scope) {+ const bucket = computeExecutionByDomain(outcomes)[scope];+ if (isAvoidDomain(bucket)) {+ const cause = formatDominantFailureCause(bucket.failureSummary);+ return {+ excluded: true,+ rule: 'failing-domain',+ reason: `${healthClause} and ${scope} hand-offs succeed only ${bucket.successRate}% over ${bucket.completed} executed — excluded from filing${cause ? ` (${cause})` : ''}`+ };+ }+ }++ return { excluded: false, reason: null };+}++/**+ * Render the reasoner-facing HARD EXCLUSION notice block (#2824). Computed from the+ * SAME health + outcome inputs the enforcement gate (computeHardExclusionGate) reads,+ * so the prompt's stated exclusions and what the gate actually suppresses can never+ * disagree. Returns '' when the gate is DISARMED (health unknown, below sample floor,+ * or at/above the threshold), so buildPrompt omits the block entirely on a healthy loop.+ * Names both the self-improve scopes and any currently chronically-failing domain, and+ * carries the explicit GATE CHECK step the reasoner must run before committing.+ */+export function computeHardExclusionNotice({ liTaskStats = null, outcomes = [], now = Date.now() } = {}) {+ const health = computeLiExecutionHealth(liTaskStats, { now });+ if (!health.confident || health.rate >= LI_HARD_GATE_EXECUTION_THRESHOLD) return '';++ const lines = [+ `HARD EXCLUSION GATE ARMED — your execution health is ${health.rate}% (below ${LI_HARD_GATE_EXECUTION_THRESHOLD}%). The following work is EXCLUDED this run and will be dropped BEFORE filing even if your reasoning leads you to it:`,+ `- Any self-improve-scoped proposal (${SELF_IMPROVE_SCOPES.join(', ')}). A degraded loop cannot repair itself — that work is deferred to a human.`+ ];++ // Surface each currently chronically-failing domain by name so the reasoner can route+ // around it explicitly — the same isAvoidDomain set rule 2 of the gate enforces.+ const byDomain = computeExecutionByDomain(outcomes);+ const failing = Object.entries(byDomain)+ .filter(([, bucket]) => isAvoidDomain(bucket))+ .map(([scope, bucket]) => `${clampScopeLabel(scope)} (${bucket.successRate}% over ${bucket.completed})`);+ if (failing.length) {+ lines.push(`- Any proposal in a chronically-failing execution domain: ${failing.join('; ')}.`);+ }++ lines.push('', 'GATE CHECK: If your proposal maps to an excluded scope or domain above → return proposal: null. Do not reason past this gate.');+ return lines.join('\n');+}+// 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@@ -1388,11 +1536,14 @@ const BESPOKE_SOURCE_BLOCK_KEYS = new Set(['plannedWork', 'scopeGuidance']);* the TRUE per-proposal-domain execution record #2760 could only approximate (#2765).* `crossReferenceReport` (from computeCrossReferenceAnalysis) is injected as a* `liCrossReference` block that names domains LI proposes well but executes poorly (#2764 §3).+ * `hardExclusionNotice` (from computeHardExclusionNotice, #2824) is injected as a+ * prominent `liHardExclusions` block ABOVE the allowed scopes when LI's execution+ * health is degraded — the reasoner-facing mirror of the deterministic filing gate.* Finally, the static `liPlaybook` block (LI_PROPOSAL_PLAYBOOK, #2763) is ALWAYS* appended: the a-priori scope/task-type/goal rule set LI needs from run one, before* any per-app outcome data exists.*/-export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '', selfEvalReport = '', proposalExecutionReport = '', crossReferenceReport = '' }) {+export function buildPrompt({ app, config, sources = {}, openIssues = [], isPortos = false, outcomesReport = '', selfEvalReport = '', proposalExecutionReport = '', crossReferenceReport = '', hardExclusionNotice = '' }) {const allowed = (config.allowedScopes || []).filter(s =>isScopeAllowed({ scope: s, allowedScopes: config.allowedScopes, isPortos }));@@ -1490,8 +1641,17 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort? `\n### liPlaybook\n${LI_PROPOSAL_PLAYBOOK}\n\n${LI_PLAYBOOK_GUIDANCE}\n`: '';+ // Hard exclusion gate (#2824): rendered ABOVE the allowed scopes and sources as a+ // hard constraint so the reasoner sees what is off-limits before it picks a scope.+ // Non-empty only when the deterministic filing gate is armed (execution health+ // degraded), so a healthy loop's prompt is unchanged. Even if the reasoner reasons+ // past this, computeHardExclusionGate drops the proposal before it is filed.+ const hardExclusionBlock = (typeof hardExclusionNotice === 'string' && hardExclusionNotice.trim())+ ? `\n### liHardExclusions\n${hardExclusionNotice.trim()}\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.-${handoffNote}${metricsGuidance}+${handoffNote}${metricsGuidance}${hardExclusionBlock}Rules & guidance from the operator:${config.rules?.trim() || '(none)'}diff --git a/server/services/layeredIntelligence.playbook.md b/server/services/layeredIntelligence.playbook.mdindex 2b5db64e1f..55831c3772 100644--- a/server/services/layeredIntelligence.playbook.md+++ b/server/services/layeredIntelligence.playbook.md@@ -34,7 +34,10 @@ require extra justification for scopes that historically get rejected.- **Prefer `loop-meta`** (PortOS install only). Improvements to the LI loopitself — better dedup, better calibration, clearer prompts, fixing a failuremode you can see in your own reports — merge at a high rate because they are- concrete, verifiable, and self-contained.+ concrete, verifiable, and self-contained. **BUT** when a live `liHardExclusions`+ block appears above (your execution health is degraded), `loop-meta` and+ `portos-self` are HARD-EXCLUDED and will be dropped before filing — a degraded+ loop cannot repair itself, so that work is deferred to a human (see §4).- **Prefer `app-data-gap`.** Adding the telemetry / metrics / instrumentationneeded to reason well (e.g. a missing METRICS.md, an unmeasured KPI) landsreliably: it is unambiguous, low-risk, and unblocks future higher-value work.@@ -85,17 +88,23 @@ not one of these:An LI proposal is later EXECUTED as a coding-agent task. Proposing work that mapsto a task type that reliably FAILS to complete is systematic waste, even when the-idea is good.--- **Avoid your own worst scope.** Self-improvement work that maps to LI's own- reasoning-run task type (`self-improve:layered-intelligence`) has historically- had ~0% completion. Do not propose more of it while your own execution is- degraded — the highest-value loop-meta fix is usually the one that repairs- the failure mode itself, framed so it is genuinely finishable.-- **Avoid chronically-failing types** surfaced in `liScopeAwareness` /- `liProposalExecution` (e.g. types sitting at 0% completion). If the live block- above lists a low-completion type, treat a proposal resembling it as needing a- narrower scope or a different framing.+idea is good. Some of these rules are MANDATORY, not advisory: when a live+`liHardExclusions` block appears above, the named scopes/domains are excluded and+a matching proposal is dropped BEFORE it is filed — reasoning past the block does+not get the proposal through.++- **Do NOT propose self-improve-scoped work while your execution is degraded.**+ When the `liHardExclusions` block is present (your reasoning-run success is below+ the hard-gate threshold), `loop-meta` and `portos-self` proposals are hard-+ excluded — LI's own reasoning-run task type (`self-improve:layered-intelligence`)+ has historically sat near ~0% completion, so a degraded loop cannot see its own+ repair through. If your reasoning leads to self-improve work while degraded,+ return `proposal: null`; loop repair is deferred to a human, not re-proposed.+- **Do NOT propose into a chronically-failing execution domain.** Any domain the+ `liHardExclusions` block names (or that `liScopeAwareness` / `liProposalExecution`+ shows sitting below completion threshold) is off-limits while the gate is armed;+ when the gate is NOT armed, still treat a low-completion domain as needing a+ narrower scope or a different framing rather than a re-file of the same shape.- **Prefer reliably-completed types.** Work that resembles `plan-task`,`test-coverage`, or `performance` tends to complete near-reliably — biasproposals toward shapes an agent actually finishes.diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex c123515239..ae8b9acb73 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -48,6 +48,11 @@ import {computeProposalExecutionAwareness,computeCrossReferenceAnalysis,computeHandoffRouting,+ computeHardExclusionGate,+ computeHardExclusionNotice,+ computeLiExecutionHealth,+ LI_HARD_GATE_EXECUTION_THRESHOLD,+ SELF_IMPROVE_SCOPES,PROPOSAL_EXECUTION_MIN_SAMPLE,SCOPE_AVOID_SUCCESS_THRESHOLD,SCOPE_PREFER_SUCCESS_THRESHOLD,@@ -681,6 +686,129 @@ describe('computeHandoffRouting (#2764 §4)', () => {});});+describe('computeLiExecutionHealth (#2824)', () => {+ const stats = (over = {}) => ({ read: true, metrics: { completed: 10, succeeded: 3, failed: 7, successRate: 30, recentOutcomes: [], ...over } });++ it('reports UNKNOWN (rate null) when the store is unreadable or has no runs', () => {+ expect(computeLiExecutionHealth(null)).toEqual({ rate: null, sample: 0, source: null, confident: false });+ expect(computeLiExecutionHealth({ read: false })).toMatchObject({ rate: null, confident: false });+ expect(computeLiExecutionHealth({ read: true, metrics: null })).toMatchObject({ rate: null, confident: false });+ });++ it('reads the effective lifetime rate + sample and marks it confident above the floor', () => {+ const health = computeLiExecutionHealth(stats());+ expect(health.rate).toBe(30);+ expect(health.sample).toBe(10);+ expect(health.confident).toBe(true);+ });++ it('is NOT confident below LI_DEGRADED_MIN_SAMPLE runs', () => {+ const health = computeLiExecutionHealth(stats({ completed: 2, succeeded: 0, failed: 2, successRate: 0 }));+ expect(health.rate).toBe(0);+ expect(health.sample).toBe(2);+ expect(health.confident).toBe(false);+ });+});++describe('computeHardExclusionGate (#2824)', () => {+ // Degraded (below the 75% gate line) AND confident (>= LI_DEGRADED_MIN_SAMPLE runs).+ const degraded = { read: true, metrics: { completed: 10, succeeded: 3, failed: 7, successRate: 30, recentOutcomes: [] } };+ // Healthy: at/above the gate line.+ const healthy = { read: true, metrics: { completed: 10, succeeded: 9, failed: 1, successRate: 90, recentOutcomes: [] } };+ // Below the sample floor even though 0%.+ const thinSample = { read: true, metrics: { completed: 2, succeeded: 0, failed: 2, successRate: 0, recentOutcomes: [] } };++ it('never excludes a null/invalid proposal', () => {+ expect(computeHardExclusionGate({ proposal: null, liTaskStats: degraded })).toEqual({ excluded: false, reason: null });+ expect(computeHardExclusionGate({ liTaskStats: degraded })).toEqual({ excluded: false, reason: null });+ });++ it('is DISARMED when execution health is unknown, healthy, or below the sample floor', () => {+ const p = { scope: 'loop-meta' };+ expect(computeHardExclusionGate({ proposal: p, liTaskStats: null }).excluded).toBe(false);+ expect(computeHardExclusionGate({ proposal: p, liTaskStats: healthy }).excluded).toBe(false);+ expect(computeHardExclusionGate({ proposal: p, liTaskStats: thinSample }).excluded).toBe(false);+ });++ it('excludes EVERY self-improve scope when armed, regardless of domain history', () => {+ for (const scope of SELF_IMPROVE_SCOPES) {+ const res = computeHardExclusionGate({ proposal: { scope }, liTaskStats: degraded, outcomes: [] });+ expect(res.excluded).toBe(true);+ expect(res.rule).toBe('self-improve-scope');+ expect(res.reason).toContain(scope);+ expect(res.reason).toContain(`< ${LI_HARD_GATE_EXECUTION_THRESHOLD}%`);+ }+ });++ it('excludes a non-self-improve proposal in a chronically-failing domain when armed', () => {+ const outcomes = [+ { scope: 'app-improvement', executionOutcome: 'success' },+ { scope: 'app-improvement', executionOutcome: 'failure', failureCategory: 'planning' },+ { scope: 'app-improvement', executionOutcome: 'failure', failureCategory: 'planning' } // 1/3 = 33% < 50%+ ];+ const res = computeHardExclusionGate({ proposal: { scope: 'app-improvement' }, liTaskStats: degraded, outcomes });+ expect(res.excluded).toBe(true);+ expect(res.rule).toBe('failing-domain');+ expect(res.reason).toContain('app-improvement');+ expect(res.reason).toContain('33%');+ });++ it('does NOT exclude a non-self-improve proposal in a healthy/unknown domain even when armed', () => {+ // app-data-gap has no failing execution history → domain rule can't fire.+ expect(computeHardExclusionGate({ proposal: { scope: 'app-data-gap' }, liTaskStats: degraded, outcomes: [] }).excluded).toBe(false);+ // A domain at/above the avoid line is not chronically failing.+ const okOutcomes = [+ { scope: 'app-improvement', executionOutcome: 'success' },+ { scope: 'app-improvement', executionOutcome: 'success' },+ { scope: 'app-improvement', executionOutcome: 'failure' } // 2/3 = 67% >= 50%+ ];+ expect(computeHardExclusionGate({ proposal: { scope: 'app-improvement' }, liTaskStats: degraded, outcomes: okOutcomes }).excluded).toBe(false);+ });++ it('agrees with computeHandoffRouting on which non-self-improve domains are chronically failing', () => {+ const outcomes = [+ { scope: 'app-improvement', executionOutcome: 'failure' },+ { scope: 'app-improvement', executionOutcome: 'failure' } // 0/2 = 0%+ ];+ // Both the hand-off gate and the filing gate flag the same domain; the filing gate+ // additionally requires degraded overall health to fire.+ expect(computeHandoffRouting({ proposal: { scope: 'app-improvement' }, outcomes }).handoff).toBe(false);+ expect(computeHardExclusionGate({ proposal: { scope: 'app-improvement' }, liTaskStats: degraded, outcomes }).excluded).toBe(true);+ // …but with healthy execution health, the filing gate stays disarmed.+ expect(computeHardExclusionGate({ proposal: { scope: 'app-improvement' }, liTaskStats: healthy, outcomes }).excluded).toBe(false);+ });+});++describe('computeHardExclusionNotice (#2824)', () => {+ const degraded = { read: true, metrics: { completed: 10, succeeded: 3, failed: 7, successRate: 30, recentOutcomes: [] } };+ const healthy = { read: true, metrics: { completed: 10, succeeded: 9, failed: 1, successRate: 90, recentOutcomes: [] } };++ it('is empty when the gate is disarmed (healthy / unknown health)', () => {+ expect(computeHardExclusionNotice({ liTaskStats: healthy })).toBe('');+ expect(computeHardExclusionNotice({ liTaskStats: null })).toBe('');+ });++ it('names the self-improve scopes, the armed health, and the GATE CHECK step', () => {+ const notice = computeHardExclusionNotice({ liTaskStats: degraded, outcomes: [] });+ expect(notice).toContain('HARD EXCLUSION GATE ARMED');+ expect(notice).toContain('30%');+ expect(notice).toContain(`below ${LI_HARD_GATE_EXECUTION_THRESHOLD}%`);+ for (const scope of SELF_IMPROVE_SCOPES) expect(notice).toContain(scope);+ expect(notice).toContain('GATE CHECK');+ expect(notice).toContain('return proposal: null');+ });++ it('names a currently chronically-failing domain when one exists', () => {+ const outcomes = [+ { scope: 'app-improvement', executionOutcome: 'failure' },+ { scope: 'app-improvement', executionOutcome: 'failure' } // 0% over 2+ ];+ const notice = computeHardExclusionNotice({ liTaskStats: degraded, outcomes });+ expect(notice).toContain('chronically-failing execution domain');+ expect(notice).toContain('app-improvement');+ });+});+describe('resolveBlockOnIssue', () => {it('maps "this" to the just-filed issue number', () => {expect(resolveBlockOnIssue({ blockOnIssue: 'this' }, 99)).toBe(99);