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: classify why LI proposals are closed unmerged, not just that they were (#2689)

[._.]/ Adam Eivyd43f237621c2
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c6ba36ffbb..17ec5427ac 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -18,6 +18,8 @@
- [issue-2702] **The Creative Director now shows you what it made.** Project cards on `/creative-director` lead with a preview of the produced media — the final video's poster with a play badge (click the artwork to open the project, the badge to play it inline), a rendered scene, or a produced image from a directive plan — falling back to a tidy "no render yet" placeholder instead of a wall of text. The Overview tab renders the final cut inline instead of showing only a job id, keeping the Media History link alongside it; plans that emit images show the image. Previews respect each project's aspect ratio (16:9 / 9:16 / 1:1), and the grid never downloads a video until you actually press play.
+- [issue-2689] **Layered Intelligence now diagnoses *why* its proposals were turned down, instead of parroting the tracker back at itself.** When a filed proposal is closed unmerged, it's classified against a fixed vocabulary — duplicate, declined, out of scope, missing context, quality, environment blocker, and more — read from the issue's close reason and its labels, and stored alongside the outcome. The loop's feedback block used to tell it "common rejection reasons: not_planned", which restates the outcome rather than explaining it; it now reads "already tracked elsewhere (2); the user declined it (1)". A proposal closed with nothing to explain it is recorded as an explicit unknown and counted, so "3 of 4 closed with no recorded reason" is reported to the loop as the blind spot it is — never dressed up as a real diagnosis, and never allowed to read as "nothing was ever rejected". Merged proposals never acquire a rejection reason, which matters for Jira- and PLAN.md-backed apps whose trackers report no close reason at all and whose ordinary close *is* a merge. Costs no extra AI calls and no extra tracker reads — every reason is derived from issue data the loop already fetches — and rejection history recorded before this upgrade is re-diagnosed on the next run rather than needing a reset.
+
- Daily log entries now re-embed into the Chief-of-Staff memory index once you settle (coalesced per day, ~30s after your last edit) instead of on every single save. Autosave means a day's entry is now written every couple of seconds while you type; re-embedding per save would have meant an embedding call per typing pause — and, once a day's log grows past the embedding size budget, an unrequested AI summarization call each time too. Search results are unchanged; the index simply updates when you pause rather than mid-sentence, which also produces a better vector than embedding a half-typed sentence a hundred times. Journals now use the same debounced, coalesced re-embed path every other Brain record type already used.
## Internal
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index b1f3c36786..5e21c86e19 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -30,6 +30,7 @@ import { validateCommand } from '../lib/commandSecurity.js';
import { getSettings } from './settings.js';
import { createTicket, searchIssues, addLabels, escapeJql } from './jira.js';
import { computeWindowedStats, computeEffectiveSuccessRate, extractTaskType } from './taskLearning/store.js';
+import { formatRejectionReasons } from './layeredIntelligenceRejections.js';
// Tracker labels + slug marker. The slug is the stable dedup key the reasoner
// chooses; it is embedded in each filed issue body so a later run (or the
@@ -604,9 +605,11 @@ export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false }
.map(([s, v]) => `- ${s}: ${v.filed} filed, ${v.merged} merged (${v.filed ? Math.round((v.merged / v.filed) * 100) : 0}%)`)
.join('\n');
- const reasons = [...new Set(filed
- .filter(o => o.outcome === 'rejected' && o.outcomeReason)
- .map(o => o.outcomeReason))].slice(0, 5);
+ // Structured diagnosis of every non-merged proposal (#2689), replacing the raw
+ // tracker string this used to echo ('not_planned' merely restated the outcome).
+ // '' when nothing has been closed unmerged — distinct from "closed, reason
+ // unknown", which the line reports explicitly.
+ const rejectionReasons = formatRejectionReasons(filed, 5);
// Low-merge-rate alarm (#2698). `rawMergeRate` is measured over RESOLVED
// proposals only and is null when none have resolved — see summarizeOutcomeStats
@@ -641,7 +644,7 @@ export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false }
'By scope:',
scopeLines || '- (none)',
'',
- `Common rejection reasons: ${reasons.length ? reasons.join('; ') : 'none'}`,
+ `Why non-merged proposals were closed: ${rejectionReasons || 'nothing has been closed unmerged yet'}`,
...lowMergeWarning
].join('\n');
}
@@ -717,20 +720,22 @@ export function computeSelfEvalSummary({
if (!Array.isArray(outcomes)) {
lines.push('- Proposal merge rate: UNAVAILABLE — no outcome history was gathered this run (the outcomes source is off, or this tracker cannot report outcomes). You cannot see how your past proposals fared; do not assume they went well.');
} else {
- const { total, merged, rejected, resolved, rawMergeRate, filed } = summarizeOutcomeStats(outcomes);
+ const { total, merged, resolved, rawMergeRate, filed } = summarizeOutcomeStats(outcomes);
if (total === 0) {
lines.push('- Proposal merge rate: no proposals filed yet for this app — you have no track record here to calibrate against.');
} else if (rawMergeRate === null) {
lines.push(`- Proposal merge rate: ${total} filed, none resolved yet — rate unknown. Awaiting triage is NOT rejection; do not read this as failure.`);
} else {
mergeSignal = resolved >= LOW_MERGE_RATE_MIN_SAMPLE;
- const reasons = [...new Set(filed
- .filter(o => o.outcome === 'rejected' && o.outcomeReason)
- .map(o => o.outcomeReason))].slice(0, 3);
+ // Same structured diagnosis as computeOutcomesReport (#2689) — one helper, so
+ // the two blocks can never disagree about why proposals were closed. Gated on
+ // the formatted string, not on `rejected`, because an `abandoned` proposal is
+ // also a non-merge worth explaining.
+ const reasons = formatRejectionReasons(filed, 3);
lines.push(
`- Proposal merge rate: ${merged} of ${resolved} resolved proposals merged (${Math.round(rawMergeRate)}%)`
+ `${resolved < LOW_MERGE_RATE_MIN_SAMPLE ? ' — too small a sample to read a rate from yet' : ''}.`
- + (rejected > 0 && reasons.length ? ` Recurring rejection reasons: ${reasons.join('; ')}.` : '')
+ + (reasons ? ` Why the rest were closed: ${reasons}.` : '')
);
}
}
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index 55f6e05c36..19c7099186 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -589,11 +589,11 @@ describe('computeOutcomesReport', () => {
expect(computeOutcomesReport({})).toBe('');
});
- it('summarizes totals, per-scope merge rates, and rejection reasons', () => {
+ it('summarizes totals, per-scope merge rates, and classified rejection reasons', () => {
const outcomes = [
{ scope: 'app-data-gap', outcome: 'merged' },
{ scope: 'app-data-gap', outcome: 'merged' },
- { scope: 'app-improvement', outcome: 'rejected', outcomeReason: 'too complex' },
+ { scope: 'app-improvement', outcome: 'rejected', rejectionReason: 'duplicate' },
{ scope: 'app-improvement', outcome: null }
];
const report = computeOutcomesReport({ outcomes });
@@ -603,7 +603,23 @@ describe('computeOutcomesReport', () => {
expect(report).toContain('Still open: 1 (25%)');
expect(report).toContain('app-data-gap: 2 filed, 2 merged (100%)');
expect(report).toContain('app-improvement: 2 filed, 0 merged (0%)');
- expect(report).toContain('Common rejection reasons: too complex');
+ // The taxonomy gloss (#2689), not the raw tracker string this used to echo.
+ expect(report).toContain('Why non-merged proposals were closed: already tracked elsewhere (duplicate) (1)');
+ });
+
+ it('reports an undiagnosed rejection history as the data gap it is (#2689)', () => {
+ const report = computeOutcomesReport({
+ outcomes: [
+ { scope: 'app-improvement', outcome: 'merged' },
+ { scope: 'app-improvement', outcome: 'rejected', rejectionReason: 'unknown-reason' }
+ ]
+ });
+ expect(report).toContain('Why non-merged proposals were closed: 1 of 1 closed with no recorded reason');
+ });
+
+ it('says nothing has been closed unmerged rather than implying no reasons exist (#2689)', () => {
+ const report = computeOutcomesReport({ outcomes: [{ scope: 'app-improvement', outcome: 'merged' }] });
+ expect(report).toContain('Why non-merged proposals were closed: nothing has been closed unmerged yet');
});
it('reports abandoned distinctly and excludes it from the merged numerator (#2620)', () => {
@@ -682,17 +698,26 @@ describe('computeSelfEvalSummary (#2700)', () => {
expect(report).not.toContain('0%');
});
- it('reports a real merge rate with its recurring rejection reasons', () => {
+ it('reports a real merge rate with its classified rejection reasons', () => {
const outcomes = [
{ outcome: 'merged' },
- { outcome: 'rejected', outcomeReason: 'NOT_PLANNED' },
- { outcome: 'rejected', outcomeReason: 'NOT_PLANNED' },
- { outcome: 'rejected', outcomeReason: 'too vague' }
+ { outcome: 'rejected', rejectionReason: 'user-rejected' },
+ { outcome: 'rejected', rejectionReason: 'user-rejected' },
+ { outcome: 'abandoned', rejectionReason: 'duplicate' }
];
const report = computeSelfEvalSummary({ outcomes });
expect(report).toContain('1 of 4 resolved proposals merged (25%)');
- // De-duplicated reasons.
- expect(report).toContain('Recurring rejection reasons: NOT_PLANNED; too vague');
+ // Tallied by taxonomy token and glossed, commonest first — and an `abandoned`
+ // proposal is explained too, not just a `rejected` one (#2689).
+ expect(report).toContain(
+ 'Why the rest were closed: the user declined it (closed as not planned) (2); already tracked elsewhere (duplicate) (1)'
+ );
+ });
+
+ it('omits the rejection clause when every resolved proposal merged (#2689)', () => {
+ const report = computeSelfEvalSummary({ outcomes: [{ outcome: 'merged' }, { outcome: 'merged' }] });
+ expect(report).toContain('2 of 2 resolved proposals merged (100%)');
+ expect(report).not.toContain('Why the rest were closed');
});
it('flags a below-floor sample as unreadable rather than as evidence', () => {
diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.js
index a62f82db42..c2f34fe620 100644
--- a/server/services/layeredIntelligenceOutcomes.js
+++ b/server/services/layeredIntelligenceOutcomes.js
@@ -23,6 +23,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 { classifyRejection, REJECTION_REASON_VALUES } from './layeredIntelligenceRejections.js';
// The report/retention window. Reuses the dedup suppression window so a proposal
// stays in the outcome report exactly as long as it still suppresses re-proposal —
@@ -38,6 +39,19 @@ export const LI_OUTCOMES_SCHEMA_VERSION = 1;
* appId+slug (the identity), coerces the outcome to a known value or null, and
* defaults the timestamps. Returning null makes collectionStore treat the row as
* invalid (loadOne → null), so a hand-corrupted file can't poison the report.
+ *
+ * `rejectionReason` (#2689) carries the structured diagnosis and is deliberately
+ * three-valued — the sentinel rule, which matters here because the whole point of
+ * the field is to MEASURE how much history is undiagnosed:
+ * - `null` — not classified (a merged record, an unresolved one, or
+ * a record written before this field existed). Reconcile
+ * treats it as work to do.
+ * - `'unknown-reason'` — classified, and no signal explained the rejection. A
+ * real, deliberate answer; NOT re-derived every run.
+ * - a taxonomy token — classified with a supporting signal.
+ * An unrecognized token coerces to `null` rather than `'unknown-reason'`, so a
+ * hand-edited or future-version value re-classifies on the next reconcile instead
+ * of being laundered into a fake "we looked and found nothing".
*/
export function sanitizeOutcomeRecord(raw) {
if (!raw || typeof raw !== 'object') return null;
@@ -45,6 +59,9 @@ export function sanitizeOutcomeRecord(raw) {
const slug = normalizeSlug(raw.slug);
if (!appId || !slug) return null;
const outcome = PROPOSAL_OUTCOMES.includes(raw.outcome) ? raw.outcome : null;
+ // A merged proposal has no rejection to explain, so its slot stays null however
+ // the file reads — a stray token there would inflate the rejection tally.
+ const rejectable = outcome === 'rejected' || outcome === 'abandoned';
return {
appId,
slug,
@@ -54,7 +71,8 @@ export function sanitizeOutcomeRecord(raw) {
filedAt: typeof raw.filedAt === 'string' ? raw.filedAt : null,
outcome,
outcomeAt: outcome && typeof raw.outcomeAt === 'string' ? raw.outcomeAt : null,
- outcomeReason: outcome && typeof raw.outcomeReason === 'string' ? raw.outcomeReason : null
+ outcomeReason: outcome && typeof raw.outcomeReason === 'string' ? raw.outcomeReason : null,
+ rejectionReason: rejectable && REJECTION_REASON_VALUES.includes(raw.rejectionReason) ? raw.rejectionReason : null
};
}
@@ -113,7 +131,9 @@ export async function recordFiledProposal({ appId, slug, tracker = null, issueRe
filedAt: new Date(now).toISOString(),
outcome: null,
outcomeAt: null,
- outcomeReason: null
+ outcomeReason: null,
+ // Unresolved: nothing has rejected it yet, so there is nothing to diagnose.
+ rejectionReason: null
};
await ensureTypeIndex(store);
const ok = await store.saveOne(outcomeId(appId, normSlug), record).then(() => true, (err) => {
@@ -202,6 +222,14 @@ export async function reconcileOutcomes({ appId, existingIssues = [], now = Date
if (!issue) continue;
const outcome = deriveOutcome(issue);
if (!outcome) continue;
+ // Diagnose WHY a non-merged proposal ended that way (#2689). Derived from the
+ // issue rows the reconciler already has, so classification costs no extra
+ // tracker call. Merged/unresolved → null.
+ const rejectionReason = classifyRejection({
+ outcome,
+ stateReason: issue.stateReason,
+ labels: issue.labels
+ });
// A same-outcome record is only rewritten when the tracker reports a NEWER
// close time (closed → reopened → re-closed): outcomeAt drives retention/GC,
// so it must track the latest closure. Timestampless trackers (plan) and an
@@ -209,12 +237,19 @@ export async function reconcileOutcomes({ appId, existingIssues = [], now = Date
const closedMs = Date.parse(issue.closedAt);
const storedMs = Date.parse(r.outcomeAt);
const newerClose = Number.isFinite(closedMs) && (!Number.isFinite(storedMs) || closedMs > storedMs);
- if (outcome === r.outcome && !newerClose) continue;
+ // A changed classification is its own reason to rewrite — same self-heal as
+ // the outcome reclassification above (#2620). It BACKFILLS records written
+ // before the taxonomy existed (stored null, now a token) and re-diagnoses an
+ // `unknown-reason` record once someone finally labels the issue. Comparing the
+ // derived token to the stored one (rather than writing unconditionally) keeps
+ // a settled record from churning on every reconcile.
+ if (outcome === r.outcome && rejectionReason === r.rejectionReason && !newerClose) continue;
const next = {
...r,
outcome,
outcomeAt: issue.closedAt || r.outcomeAt || new Date(now).toISOString(),
- outcomeReason: issue.stateReason || 'auto-derived from tracker state'
+ outcomeReason: issue.stateReason || 'auto-derived from tracker state',
+ rejectionReason
};
const ok = await store.saveOne(outcomeId(appId, r.slug), next).then(() => true, () => false);
if (ok) updated += 1;
diff --git a/server/services/layeredIntelligenceOutcomes.test.js b/server/services/layeredIntelligenceOutcomes.test.js
index a03f8ebe1e..0c3c9d7d8e 100644
--- a/server/services/layeredIntelligenceOutcomes.test.js
+++ b/server/services/layeredIntelligenceOutcomes.test.js
@@ -52,6 +52,33 @@ describe('sanitizeOutcomeRecord', () => {
expect(unresolved.outcomeAt).toBeNull();
expect(unresolved.outcomeReason).toBeNull();
});
+
+ describe('rejectionReason (#2689)', () => {
+ const sanitize = (over) => sanitizeOutcomeRecord({ appId: 'a', slug: 's', ...over });
+
+ it('keeps a valid taxonomy token on a non-merged record', () => {
+ expect(sanitize({ outcome: 'rejected', rejectionReason: 'duplicate' }).rejectionReason).toBe('duplicate');
+ expect(sanitize({ outcome: 'abandoned', rejectionReason: 'unknown-reason' }).rejectionReason).toBe('unknown-reason');
+ });
+
+ it('strips a rejection reason from a merged or unresolved record', () => {
+ // A merged proposal has no rejection to explain; a stray token would inflate
+ // the rejection tally.
+ expect(sanitize({ outcome: 'merged', rejectionReason: 'duplicate' }).rejectionReason).toBeNull();
+ expect(sanitize({ outcome: null, rejectionReason: 'duplicate' }).rejectionReason).toBeNull();
+ });
+
+ it('coerces an unrecognized token to null (unclassified), NOT to unknown-reason', () => {
+ // null re-classifies on the next reconcile; laundering it into the sentinel
+ // would freeze a bogus "we looked and found nothing" in place.
+ expect(sanitize({ outcome: 'rejected', rejectionReason: 'bogus' }).rejectionReason).toBeNull();
+ expect(sanitize({ outcome: 'rejected', rejectionReason: 42 }).rejectionReason).toBeNull();
+ });
+
+ it('defaults a pre-taxonomy record to null rather than inventing a reason', () => {
+ expect(sanitize({ outcome: 'rejected' }).rejectionReason).toBeNull();
+ });
+ });
});
describe('recordFiledProposal + listOutcomes', () => {
@@ -188,6 +215,85 @@ describe('reconcileOutcomes', () => {
await recordFiledProposal({ appId: 'app-1', slug: 's', scope: 'app-improvement' }, store);
expect(await reconcileOutcomes({ appId: 'app-1', existingIssues: [] }, store)).toBe(0);
});
+
+ describe('rejection classification (#2689)', () => {
+ const rowsBySlug = async () =>
+ Object.fromEntries((await listOutcomes({ appId: 'app-1' }, store)).map(r => [r.slug, r]));
+
+ it('classifies each non-merged proposal from the tracker state it already has', async () => {
+ await recordFiledProposal({ appId: 'app-1', slug: 'merged-one' }, store);
+ await recordFiledProposal({ appId: 'app-1', slug: 'declined' }, store);
+ await recordFiledProposal({ appId: 'app-1', slug: 'dupe' }, store);
+ await recordFiledProposal({ appId: 'app-1', slug: 'labelled' }, store);
+ await recordFiledProposal({ appId: 'app-1', slug: 'mystery' }, store);
+
+ await reconcileOutcomes({
+ appId: 'app-1',
+ existingIssues: [
+ { slug: 'merged-one', state: 'closed', stateReason: 'completed' },
+ { slug: 'declined', state: 'closed', stateReason: 'not_planned' },
+ { slug: 'dupe', state: 'closed', stateReason: 'duplicate' },
+ { slug: 'labelled', state: 'closed', stateReason: 'not_planned', labels: ['out-of-scope'] },
+ { slug: 'mystery', state: 'closed', stateReason: 'reopened' }
+ ]
+ }, store);
+
+ const rows = await rowsBySlug();
+ // A merged proposal is never given a rejection reason — the load-bearing case
+ // for jira/plan, whose trackers report no stateReason at all.
+ expect(rows['merged-one'].rejectionReason).toBeNull();
+ expect(rows['declined'].rejectionReason).toBe('user-rejected');
+ expect(rows['dupe'].rejectionReason).toBe('duplicate');
+ // A label outranks the generic not_planned.
+ expect(rows['labelled'].rejectionReason).toBe('scope-mismatch');
+ // No signal ⇒ the explicit sentinel, never a fabricated diagnosis.
+ expect(rows['mystery'].rejectionReason).toBe('unknown-reason');
+ });
+
+ it('backfills a record resolved before the taxonomy existed', async () => {
+ // Pre-#2689 installs hold resolved records with no rejectionReason. The
+ // outcome is unchanged, so only the classification diff can trigger the
+ // rewrite that fills them in.
+ await recordFiledProposal({ appId: 'app-1', slug: 'legacy' }, store);
+ const legacy = (await listOutcomes({ appId: 'app-1' }, store))[0];
+ await store.saveOne('app-1--legacy', {
+ ...legacy, outcome: 'rejected', outcomeAt: '2026-07-01T00:00:00Z', outcomeReason: 'not_planned'
+ });
+ expect((await rowsBySlug())['legacy'].rejectionReason).toBeNull();
+
+ const updated = await reconcileOutcomes({
+ appId: 'app-1',
+ existingIssues: [{ slug: 'legacy', state: 'closed', stateReason: 'not_planned', closedAt: '2026-07-01T00:00:00Z' }]
+ }, store);
+ expect(updated).toBe(1);
+ const row = (await rowsBySlug())['legacy'];
+ expect(row.rejectionReason).toBe('user-rejected');
+ expect(row.outcome).toBe('rejected');
+ // Backfilling the diagnosis must not disturb the retention clock.
+ expect(row.outcomeAt).toBe('2026-07-01T00:00:00Z');
+ });
+
+ it('re-diagnoses an unknown-reason record once the issue is finally labelled', async () => {
+ await recordFiledProposal({ appId: 'app-1', slug: 'mystery' }, store);
+ const closed = { slug: 'mystery', state: 'closed', stateReason: 'reopened', closedAt: '2026-07-01T00:00:00Z' };
+ await reconcileOutcomes({ appId: 'app-1', existingIssues: [closed] }, store);
+ expect((await rowsBySlug())['mystery'].rejectionReason).toBe('unknown-reason');
+
+ const updated = await reconcileOutcomes({
+ appId: 'app-1',
+ existingIssues: [{ ...closed, labels: ['duplicate'] }]
+ }, store);
+ expect(updated).toBe(1);
+ expect((await rowsBySlug())['mystery'].rejectionReason).toBe('duplicate');
+ });
+
+ it('does not churn a settled record whose classification is unchanged', async () => {
+ await recordFiledProposal({ appId: 'app-1', slug: 's' }, store);
+ const issue = { slug: 's', state: 'closed', stateReason: 'not_planned', closedAt: '2026-07-01T00:00:00Z' };
+ expect(await reconcileOutcomes({ appId: 'app-1', existingIssues: [issue] }, store)).toBe(1);
+ expect(await reconcileOutcomes({ appId: 'app-1', existingIssues: [issue] }, store)).toBe(0);
+ });
+ });
});
describe('listOutcomesResult read sentinel (#2700)', () => {
diff --git a/server/services/layeredIntelligenceRejections.js b/server/services/layeredIntelligenceRejections.js
new file mode 100644
index 0000000000..ec67596daf
--- /dev/null
+++ b/server/services/layeredIntelligenceRejections.js
@@ -0,0 +1,208 @@
+/**
+ * Layered Intelligence rejection taxonomy + classifier (#2689).
+ *
+ * `deriveOutcome` (layeredIntelligence.js) answers *whether* a filed proposal was
+ * merged, rejected, or abandoned. It does not answer *why* — the store's
+ * `outcomeReason` slot held whatever raw string the tracker happened to report
+ * (GitHub's `not_planned`, or the literal filler `auto-derived from tracker state`
+ * on trackers that report nothing). That is unusable as a feedback signal: the
+ * reasoner was told "common rejection reasons: not_planned", which restates the
+ * outcome rather than diagnosing it.
+ *
+ * This module owns the structured vocabulary and the deterministic mapping onto
+ * it. Pure, no I/O, no LLM call — every token is derived from data the reconciler
+ * already holds, so classification never adds a provider round-trip (the
+ * "no cold-bootstrap LLM calls" policy) and never adds a tracker fetch.
+ *
+ * A LEAF module by design: it imports nothing from the LI graph, so both
+ * `layeredIntelligence.js` (which formats the reports) and
+ * `layeredIntelligenceOutcomes.js` (which persists the classification) can use it
+ * without an import cycle.
+ */
+
+// The rejection-reason vocabulary. Stored on the outcome record and rendered into
+// the reasoner's prompt, so these tokens are a persisted contract: rename one and
+// old records fail the sanitizer's membership check and re-classify (which is the
+// designed self-heal, but it discards history — prefer adding over renaming).
+//
+// Only the tokens marked (live) are reachable from the tracker-state signals the
+// reconciler has today. The rest are declared now because they are the vocabulary
+// this taxonomy is meant to express, and because the sanitizer must already accept
+// them: a later PR that classifies from closing comments or from the implementing
+// PR's checks can then persist them WITHOUT a record-shape migration. Every
+// unreachable token is populated today only by an explicit tracker label.
+export const REJECTION_REASONS = [
+ // (live) stateReason `duplicate`, or a duplicate/dupe label.
+ 'duplicate',
+ // (live) GitHub's "closed as not planned", or a wontfix/declined label — a human
+ // looked at it and said no.
+ 'user-rejected',
+ // Label-only today. Needs closing-comment analysis to fire on its own.
+ 'scope-mismatch',
+ 'missing-context',
+ 'quality-issue',
+ 'environment-blocker',
+ // Label-only today. These are properties of the PR that IMPLEMENTS a proposal,
+ // and LI tracks proposals as issues — it has no PR handle to read checks from.
+ 'merge-conflict',
+ 'validation-failed'
+];
+
+/**
+ * The explicit "we classified this and found no signal" sentinel. NOT a member of
+ * REJECTION_REASONS: it is the absence of a diagnosis, not a diagnosis. Kept
+ * distinct from a `null` rejectionReason, which means "not classified yet" —
+ * conflating the two would either hide the data gap this issue exists to measure
+ * or re-classify the same record forever. See sanitizeOutcomeRecord.
+ */
+export const UNKNOWN_REJECTION_REASON = 'unknown-reason';
+
+// Every value the store may legitimately hold in `rejectionReason` for a
+// non-merged proposal.
+export const REJECTION_REASON_VALUES = [...REJECTION_REASONS, UNKNOWN_REJECTION_REASON];
+
+// Human-readable gloss, used to render the prompt blocks. A token with no gloss
+// degrades to the raw token rather than being dropped.
+const REJECTION_REASON_LABELS = {
+ 'duplicate': 'already tracked elsewhere (duplicate)',
+ 'user-rejected': 'the user declined it (closed as not planned)',
+ 'scope-mismatch': "outside the app's scope",
+ 'missing-context': 'missing context the proposal should have supplied',
+ 'quality-issue': 'the proposal itself was low quality or malformed',
+ 'environment-blocker': 'blocked on the environment or a dependency',
+ 'merge-conflict': 'the implementing change could not be merged',
+ 'validation-failed': 'the implementing change failed lint/validation',
+ [UNKNOWN_REJECTION_REASON]: 'closed with no recorded reason'
+};
+
+/** Render one token as prose for the reasoner. Unknown tokens pass through. */
+export function formatRejectionReason(reason) {
+ return REJECTION_REASON_LABELS[reason] || reason || UNKNOWN_REJECTION_REASON;
+}
+
+// Normalize a tracker token (label name or stateReason) for matching: lowercased,
+// with separators collapsed so `not_planned`, `not-planned` and `Not Planned` all
+// land on the same key.
+function normalizeToken(value) {
+ return typeof value === 'string' ? value.trim().toLowerCase().replace(/[\s_-]+/g, '-') : '';
+}
+
+// Label → reason. Labels are a deliberate human act, so they outrank the generic
+// stateReason: `not_planned` + a `duplicate` label is a duplicate, not a bare
+// user rejection. Keys are normalizeToken'd; add conventions here rather than
+// teaching callers to pre-map.
+const LABEL_REASONS = new Map(Object.entries({
+ 'duplicate': 'duplicate',
+ 'dupe': 'duplicate',
+ 'wontfix': 'user-rejected',
+ 'declined': 'user-rejected',
+ 'not-planned': 'user-rejected',
+ 'out-of-scope': 'scope-mismatch',
+ 'scope-mismatch': 'scope-mismatch',
+ 'needs-input': 'missing-context',
+ 'needs-info': 'missing-context',
+ 'incomplete': 'missing-context',
+ 'invalid': 'quality-issue',
+ 'quality-issue': 'quality-issue',
+ 'blocked': 'environment-blocker',
+ 'layered-intelligence:blocking': 'environment-blocker',
+ 'environment-blocker': 'environment-blocker',
+ 'merge-conflict': 'merge-conflict',
+ 'conflict': 'merge-conflict',
+ 'validation-failed': 'validation-failed',
+ 'ci-failure': 'validation-failed'
+}));
+
+// stateReason → reason. Only GitHub reports one; `completed`/absent never reach
+// here because the caller classifies non-merged outcomes only.
+const STATE_REASON_REASONS = new Map(Object.entries({
+ 'not-planned': 'user-rejected',
+ 'duplicate': 'duplicate'
+}));
+
+/**
+ * Classify WHY a filed proposal ended up not merged.
+ *
+ * Returns:
+ * - `null` for a merged or still-unresolved proposal — there is no rejection to
+ * diagnose. Never invent one: a merged jira/plan proposal (whose tracker
+ * reports no stateReason at all) must not acquire a rejection reason just
+ * because the signals are empty.
+ * - a REJECTION_REASONS token when a tracker signal supports it.
+ * - UNKNOWN_REJECTION_REASON when the proposal was demonstrably not merged but
+ * no signal explains it. This is the honest answer and the metric the issue
+ * asks for — "how much of our rejection history is undiagnosed" — so it must
+ * never be silently dressed up as a real reason.
+ *
+ * Deterministic and total: same inputs always yield the same token.
+ */
+export function classifyRejection({ outcome = null, stateReason = null, labels = [] } = {}) {
+ // Only a resolved, non-merged proposal has a rejection to explain.
+ if (outcome !== 'rejected' && outcome !== 'abandoned') return null;
+
+ // A human-applied label is the most specific signal available; first match wins
+ // in the tracker's own label order.
+ for (const label of Array.isArray(labels) ? labels : []) {
+ const hit = LABEL_REASONS.get(normalizeToken(label));
+ if (hit) return hit;
+ }
+
+ return STATE_REASON_REASONS.get(normalizeToken(stateReason)) || UNKNOWN_REJECTION_REASON;
+}
+
+/**
+ * Tally rejection reasons across an outcome list.
+ *
+ * Counts only non-merged RESOLVED records: a pending proposal is awaiting triage,
+ * not rejected. Records with no stored classification (`null` — merged, or written
+ * before the taxonomy existed) are counted in neither bucket; they are unclassified
+ * data, not a measured gap, and folding them into `unknown` would overstate the gap
+ * this metric exists to track.
+ *
+ * Returns `{ entries, unknown, diagnosed, total }`:
+ * - `entries` — `[{ reason, count }]` of REAL diagnoses only, commonest first.
+ * - `unknown` — records classified as `unknown-reason` (the data gap).
+ * - `diagnosed`— records carrying a real diagnosis (sum of `entries`).
+ * - `total` — `diagnosed + unknown`, i.e. every classified record.
+ * `unknown` is kept OUT of `entries` so it can't crowd real diagnoses out of a
+ * caller's top-N list — it is the measure of missing data, not a finding.
+ */
+export function summarizeRejectionReasons(outcomes = []) {
+ const counts = new Map();
+ let unknown = 0;
+ for (const o of Array.isArray(outcomes) ? outcomes : []) {
+ if (!o || (o.outcome !== 'rejected' && o.outcome !== 'abandoned')) continue;
+ const reason = o.rejectionReason;
+ if (reason === UNKNOWN_REJECTION_REASON) { unknown += 1; continue; }
+ if (!REJECTION_REASONS.includes(reason)) continue;
+ counts.set(reason, (counts.get(reason) || 0) + 1);
+ }
+ const entries = [...counts.entries()]
+ // Commonest first; ties broken by taxonomy order so the output is stable
+ // rather than dependent on Map insertion (i.e. on record ordering).
+ .sort((a, b) => b[1] - a[1] || REJECTION_REASONS.indexOf(a[0]) - REJECTION_REASONS.indexOf(b[0]))
+ .map(([reason, count]) => ({ reason, count }));
+ const diagnosed = entries.reduce((n, e) => n + e.count, 0);
+ return { entries, unknown, diagnosed, total: diagnosed + unknown };
+}
+
+/**
+ * Render a tally as one prompt line: the commonest `limit` diagnoses, glossed,
+ * plus the undiagnosed share when there is one.
+ *
+ * Returns '' when NOTHING is classified, so the caller omits the line rather than
+ * emitting "rejection reasons: none" — which reads as "nothing was ever rejected"
+ * when the truth may be "we don't know why anything was".
+ */
+export function formatRejectionReasons(outcomes = [], limit = 3) {
+ const { entries, unknown, total } = summarizeRejectionReasons(outcomes);
+ if (total === 0) return '';
+ const listed = entries
+ .slice(0, limit)
+ .map(({ reason, count }) => `${formatRejectionReason(reason)} (${count})`)
+ .join('; ');
+ // Always name the gap: a run that can only say "3 of 3 closed with no recorded
+ // reason" is reporting a real, actionable fact about its own blind spot.
+ const gap = unknown ? `${unknown} of ${total} closed with no recorded reason` : '';
+ return [listed, gap].filter(Boolean).join(' — ');
+}
diff --git a/server/services/layeredIntelligenceRejections.test.js b/server/services/layeredIntelligenceRejections.test.js
new file mode 100644
index 0000000000..a34dbb104b
--- /dev/null
+++ b/server/services/layeredIntelligenceRejections.test.js
@@ -0,0 +1,212 @@
+import { describe, it, expect } from 'vitest';
+import {
+ REJECTION_REASONS,
+ REJECTION_REASON_VALUES,
+ UNKNOWN_REJECTION_REASON,
+ classifyRejection,
+ formatRejectionReason,
+ formatRejectionReasons,
+ summarizeRejectionReasons
+} from './layeredIntelligenceRejections.js';
+
+const rejected = (rejectionReason) => ({ outcome: 'rejected', rejectionReason });
+
+describe('rejection taxonomy', () => {
+ it('keeps the unknown sentinel OUT of the diagnosis vocabulary but inside the storable values', () => {
+ // The sentinel is the ABSENCE of a diagnosis; letting it into REJECTION_REASONS
+ // would make "we don't know" tally as a finding.
+ expect(REJECTION_REASONS).not.toContain(UNKNOWN_REJECTION_REASON);
+ expect(REJECTION_REASON_VALUES).toContain(UNKNOWN_REJECTION_REASON);
+ expect(REJECTION_REASON_VALUES).toEqual([...REJECTION_REASONS, UNKNOWN_REJECTION_REASON]);
+ });
+
+ it('has no duplicate tokens', () => {
+ expect(new Set(REJECTION_REASON_VALUES).size).toBe(REJECTION_REASON_VALUES.length);
+ });
+
+ it('glosses every storable token, and passes an unglossed token through', () => {
+ for (const token of REJECTION_REASON_VALUES) {
+ expect(formatRejectionReason(token)).toBeTruthy();
+ expect(typeof formatRejectionReason(token)).toBe('string');
+ }
+ expect(formatRejectionReason('some-future-token')).toBe('some-future-token');
+ });
+});
+
+describe('classifyRejection', () => {
+ it('never invents a reason for a merged or unresolved proposal', () => {
+ // The load-bearing case: jira/plan report no stateReason at all, and their
+ // common close path IS a merge. Empty signals must not read as a rejection.
+ expect(classifyRejection({ outcome: 'merged', stateReason: null, labels: [] })).toBeNull();
+ expect(classifyRejection({ outcome: null, stateReason: null, labels: [] })).toBeNull();
+ expect(classifyRejection({})).toBeNull();
+ });
+
+ it('maps GitHub not_planned to a user rejection', () => {
+ expect(classifyRejection({ outcome: 'rejected', stateReason: 'not_planned' })).toBe('user-rejected');
+ });
+
+ it('maps a duplicate close to duplicate', () => {
+ expect(classifyRejection({ outcome: 'abandoned', stateReason: 'duplicate' })).toBe('duplicate');
+ });
+
+ it('classifies an abandoned proposal, not just a rejected one', () => {
+ // `abandoned` is also a non-merge and is worth diagnosing.
+ expect(classifyRejection({ outcome: 'abandoned', labels: ['wontfix'] })).toBe('user-rejected');
+ });
+
+ it('lets a specific label outrank the generic not_planned stateReason', () => {
+ expect(classifyRejection({
+ outcome: 'rejected',
+ stateReason: 'not_planned',
+ labels: ['duplicate']
+ })).toBe('duplicate');
+ });
+
+ it('normalizes label and stateReason spelling (case, spaces, separators)', () => {
+ expect(classifyRejection({ outcome: 'rejected', stateReason: 'Not Planned' })).toBe('user-rejected');
+ expect(classifyRejection({ outcome: 'rejected', stateReason: 'not-planned' })).toBe('user-rejected');
+ expect(classifyRejection({ outcome: 'rejected', labels: ['Out Of Scope'] })).toBe('scope-mismatch');
+ expect(classifyRejection({ outcome: 'rejected', labels: ['NEEDS_INPUT'] })).toBe('missing-context');
+ });
+
+ it('maps the LI blocking label to an environment blocker', () => {
+ expect(classifyRejection({
+ outcome: 'rejected',
+ labels: ['layered-intelligence:blocking']
+ })).toBe('environment-blocker');
+ });
+
+ it('ignores labels it has no mapping for and falls through to the stateReason', () => {
+ expect(classifyRejection({
+ outcome: 'rejected',
+ stateReason: 'not_planned',
+ labels: ['layered-intelligence', 'p2', 'backend']
+ })).toBe('user-rejected');
+ });
+
+ it('returns the unknown sentinel — never a fake reason — when nothing explains the close', () => {
+ expect(classifyRejection({ outcome: 'rejected', stateReason: null, labels: [] }))
+ .toBe(UNKNOWN_REJECTION_REASON);
+ expect(classifyRejection({ outcome: 'abandoned', stateReason: 'reopened', labels: ['chore'] }))
+ .toBe(UNKNOWN_REJECTION_REASON);
+ });
+
+ it('tolerates a non-array labels value', () => {
+ expect(classifyRejection({ outcome: 'rejected', stateReason: 'duplicate', labels: null })).toBe('duplicate');
+ });
+
+ it('only ever yields a storable token', () => {
+ const got = classifyRejection({ outcome: 'rejected', stateReason: 'not_planned' });
+ expect(REJECTION_REASON_VALUES).toContain(got);
+ });
+});
+
+describe('summarizeRejectionReasons', () => {
+ it('counts diagnoses and the unknown gap separately', () => {
+ const { entries, unknown, diagnosed, total } = summarizeRejectionReasons([
+ rejected('duplicate'),
+ rejected('duplicate'),
+ rejected('user-rejected'),
+ rejected(UNKNOWN_REJECTION_REASON)
+ ]);
+ expect(entries).toEqual([
+ { reason: 'duplicate', count: 2 },
+ { reason: 'user-rejected', count: 1 }
+ ]);
+ expect(unknown).toBe(1);
+ expect(diagnosed).toBe(3);
+ expect(total).toBe(4);
+ });
+
+ it('keeps the unknown sentinel out of entries so it cannot crowd out real diagnoses', () => {
+ const { entries, unknown } = summarizeRejectionReasons([
+ rejected(UNKNOWN_REJECTION_REASON),
+ rejected(UNKNOWN_REJECTION_REASON),
+ rejected(UNKNOWN_REJECTION_REASON),
+ rejected('duplicate')
+ ]);
+ expect(entries).toEqual([{ reason: 'duplicate', count: 1 }]);
+ expect(unknown).toBe(3);
+ });
+
+ it('ignores merged and pending proposals', () => {
+ const { total, unknown } = summarizeRejectionReasons([
+ { outcome: 'merged', rejectionReason: null },
+ { outcome: null, rejectionReason: null }
+ ]);
+ expect(total).toBe(0);
+ expect(unknown).toBe(0);
+ });
+
+ it('counts an unclassified (pre-taxonomy) record in NEITHER bucket', () => {
+ // Reading a null as `unknown` would overstate the very data gap this measures.
+ const { total, unknown, diagnosed } = summarizeRejectionReasons([
+ { outcome: 'rejected', rejectionReason: null },
+ { outcome: 'rejected', rejectionReason: 'duplicate' }
+ ]);
+ expect(diagnosed).toBe(1);
+ expect(unknown).toBe(0);
+ expect(total).toBe(1);
+ });
+
+ it('drops an unrecognized stored token rather than counting it', () => {
+ const { total } = summarizeRejectionReasons([rejected('not-a-real-token')]);
+ expect(total).toBe(0);
+ });
+
+ it('orders ties by taxonomy order so output does not depend on record order', () => {
+ const forward = summarizeRejectionReasons([rejected('duplicate'), rejected('user-rejected')]);
+ const reverse = summarizeRejectionReasons([rejected('user-rejected'), rejected('duplicate')]);
+ expect(forward.entries).toEqual(reverse.entries);
+ expect(forward.entries.map(e => e.reason)).toEqual(['duplicate', 'user-rejected']);
+ });
+
+ it('tolerates junk input', () => {
+ expect(summarizeRejectionReasons(null).total).toBe(0);
+ expect(summarizeRejectionReasons([null, undefined, 'x']).total).toBe(0);
+ });
+});
+
+describe('formatRejectionReasons', () => {
+ it('returns empty when nothing is classified, so the caller omits the line', () => {
+ // '' must not become "reasons: none", which reads as "nothing was rejected".
+ expect(formatRejectionReasons([])).toBe('');
+ expect(formatRejectionReasons([{ outcome: 'merged', rejectionReason: null }])).toBe('');
+ });
+
+ it('renders glossed diagnoses with counts, commonest first', () => {
+ const out = formatRejectionReasons([
+ rejected('duplicate'),
+ rejected('duplicate'),
+ rejected('user-rejected')
+ ]);
+ expect(out).toBe('already tracked elsewhere (duplicate) (2); the user declined it (closed as not planned) (1)');
+ expect(out).not.toContain('no recorded reason');
+ });
+
+ it('names the undiagnosed share alongside the diagnoses', () => {
+ const out = formatRejectionReasons([rejected('duplicate'), rejected(UNKNOWN_REJECTION_REASON)]);
+ expect(out).toBe('already tracked elsewhere (duplicate) (1) — 1 of 2 closed with no recorded reason');
+ });
+
+ it('reports a fully undiagnosed history as exactly that', () => {
+ // The 0%-diagnosed case is the one the issue exists to surface; it must still
+ // produce a line rather than falling back to silence.
+ expect(formatRejectionReasons([rejected(UNKNOWN_REJECTION_REASON), rejected(UNKNOWN_REJECTION_REASON)]))
+ .toBe('2 of 2 closed with no recorded reason');
+ });
+
+ it('caps the listed diagnoses at the limit but still counts the gap over everything', () => {
+ const out = formatRejectionReasons([
+ rejected('duplicate'),
+ rejected('user-rejected'),
+ rejected('scope-mismatch'),
+ rejected('quality-issue'),
+ rejected(UNKNOWN_REJECTION_REASON)
+ ], 2);
+ expect(out).toContain('already tracked elsewhere (duplicate) (1)');
+ expect(out).toContain('1 of 5 closed with no recorded reason');
+ expect(out).not.toContain('quality');
+ });
+});