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 LI rejections from closing-comment text (#2748)

[._.]/ Adam Eivyce3991bca6a3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3a4be9ff1e..8fb86d0d2c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -26,6 +26,8 @@
- [issue-2689] **Layered Intelligence now tells its reasoner *why* each recently-rejected proposal was turned down, so it stops re-filing known failure patterns.** The loop's self-check already listed the proposals it filed recently that are still suppressed and warned "do NOT re-propose these" — but it named only their dedup slugs, so the reasoner could avoid an exact duplicate yet re-file the very same idea, worded differently, that had already been declined for being out of scope or missing context. Each named proposal now carries the reason it was closed ("— previously closed: outside the app's scope"), read straight from the rejection diagnosis the loop already records, so the reasoner sees the specific failure pattern and can route around it rather than repeating it. Costs no extra AI calls and no extra tracker reads; a proposal that was closed with no recorded reason is simply left unannotated rather than guessed at.
+- [issue-2748] **Layered Intelligence now reads the closing comment to work out why a proposal was declined, not just the label.** When a proposal is closed with no diagnostic label and no machine-readable close reason — a human just typed "this is out of scope" or "can't reproduce, too vague" and closed it (the common case on GitLab/Jira, and often on GitHub too) — the loop now scans that closing comment with a deterministic keyword pass and maps it onto the same taxonomy (out of scope / missing context / quality), so the rationale reaches the feedback loop instead of being recorded as an undiagnosed "no recorded reason". It stays a last-resort signal: an explicit label or close reason still wins, because free text is noisier than something a human deliberately applied. Costs no extra AI calls and no extra tracker reads — the comment text rides along in the issue list the loop already fetches — and nothing about how records are stored changes, so older installs pick this up on the next run with no migration.
+
- [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". Rejections the loop hasn't classified yet are reported as their own separate count rather than being folded in with the ones it examined and couldn't explain, because the two have different remedies. 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.
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index f88344a44c..ebffd08bb0 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -1524,7 +1524,7 @@ export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state =
// gh takes the state explicitly.
const args = cli === 'glab'
? ['issue', 'list', '--label', label, ...(state === 'all' ? ['--all'] : []), '-P', '100', '-F', 'json']
- : ['issue', 'list', '--label', label, '--state', state, '--limit', '100', '--json', 'number,title,body,state,stateReason,closedAt,url,labels'];
+ : ['issue', 'list', '--label', label, '--state', state, '--limit', '100', '--json', 'number,title,body,state,stateReason,closedAt,url,labels,comments'];
const { code, stdout } = await exec(cli, args, { cwd, env });
if (code !== 0) return { ok: false, issues: [] };
if (!stdout.trim()) return { ok: true, issues: [] };
@@ -1546,11 +1546,32 @@ export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state =
// dead href.
url: i.url || i.web_url || null,
labels: normalizeIssueLabels(i.labels),
+ // The rejection classifier's last-resort signal (#2748): the prose a human
+ // left when declining, for a close with no matching label/close-reason. gh
+ // returns `comments` in the same batched list call (no extra fetch); glab's
+ // `-F json` omits them, so its rows carry null and fall through to label/
+ // stateReason only (tracked in the issue's Remaining).
+ closingComment: extractClosingComment(i.comments),
slug: extractSlugFromBody(i.body || i.description || '') || extractSlugFromBody(i.title || '')
}))
};
}
+/**
+ * The rationale a human left when closing a proposal, for the rejection classifier
+ * (#2748). gh returns issue comments oldest-first; the LAST non-empty one sits
+ * closest to the close, so it carries the decline reason in the common case.
+ * Returns null for an issue closed with no comment — there is nothing to classify.
+ */
+export function extractClosingComment(comments) {
+ if (!Array.isArray(comments)) return null;
+ for (let i = comments.length - 1; i >= 0; i -= 1) {
+ const body = comments[i]?.body;
+ if (typeof body === 'string' && body.trim()) return body;
+ }
+ return null;
+}
+
/**
* List OPEN blocking-labeled issues for the app (park check). Returns
* `{ ok, issues }` with the same failed-vs-empty distinction as listForgeIssues.
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index 34adec7f54..ed34b11337 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -52,6 +52,7 @@ import {
getTrustShellSources,
normalizeIssueState,
listForgeIssues,
+ extractClosingComment,
listBlockingIssues,
fileProposalToForge,
ensureForgeLabels,
@@ -1376,6 +1377,48 @@ describe('forge I/O (injected exec)', () => {
expect(issues[1].closedAt).toBe('2026-07-01T00:00:00Z');
});
+ it('listForgeIssues requests comments and threads the closing comment on gh rows (#2748)', async () => {
+ const exec = vi.fn().mockResolvedValue({
+ code: 0,
+ stdout: JSON.stringify([
+ {
+ number: 3,
+ title: 'C',
+ body: `x ${slugMarker('slug-c')}`,
+ state: 'CLOSED',
+ closedAt: '2026-07-02T00:00:00Z',
+ comments: [
+ { body: 'Interesting idea.' },
+ { body: 'Closing — this is out of scope for the app.' }
+ ]
+ }
+ ])
+ });
+ const { ok, issues } = await listForgeIssues({ cli: 'gh', cwd: '/x', exec });
+ expect(ok).toBe(true);
+ // The batched list call must ask gh for `comments` so no extra fetch is needed.
+ expect(exec.mock.calls[0][1]).toContain('number,title,body,state,stateReason,closedAt,url,labels,comments');
+ // The LAST comment (closest to the close) becomes the classifier's signal.
+ expect(issues[0].closingComment).toBe('Closing — this is out of scope for the app.');
+ });
+
+ it('listForgeIssues leaves closingComment null when gh returns no comments', async () => {
+ const exec = vi.fn().mockResolvedValue({
+ code: 0,
+ stdout: JSON.stringify([{ number: 4, title: 'D', body: `x ${slugMarker('slug-d')}`, state: 'CLOSED', comments: [] }])
+ });
+ const { issues } = await listForgeIssues({ cli: 'gh', cwd: '/x', exec });
+ expect(issues[0].closingComment).toBeNull();
+ });
+
+ it('extractClosingComment returns the last non-empty comment body, else null', () => {
+ expect(extractClosingComment([{ body: 'first' }, { body: ' ' }, { body: 'last real' }])).toBe('last real');
+ expect(extractClosingComment([{ body: 'only' }])).toBe('only');
+ expect(extractClosingComment([])).toBeNull();
+ expect(extractClosingComment(null)).toBeNull();
+ expect(extractClosingComment([{ body: ' ' }, { body: null }])).toBeNull();
+ });
+
it('listForgeIssues normalizes GitLab "opened" state to open', async () => {
const exec = vi.fn().mockResolvedValue({
code: 0,
diff --git a/server/services/layeredIntelligenceOutcomes.js b/server/services/layeredIntelligenceOutcomes.js
index c2f34fe620..30f61f82e9 100644
--- a/server/services/layeredIntelligenceOutcomes.js
+++ b/server/services/layeredIntelligenceOutcomes.js
@@ -224,11 +224,14 @@ export async function reconcileOutcomes({ appId, existingIssues = [], now = Date
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.
+ // tracker call. Merged/unresolved → null. `closingComment` (#2748) is the
+ // deterministic last-resort signal for a close stated only in prose; forges
+ // that don't surface comments simply pass null.
const rejectionReason = classifyRejection({
outcome,
stateReason: issue.stateReason,
- labels: issue.labels
+ labels: issue.labels,
+ closingComment: issue.closingComment
});
// A same-outcome record is only rewritten when the tracker reports a NEWER
// close time (closed → reopened → re-closed): outcomeAt drives retention/GC,
diff --git a/server/services/layeredIntelligenceOutcomes.test.js b/server/services/layeredIntelligenceOutcomes.test.js
index 92e3d9c1ac..bcc8b7f1e8 100644
--- a/server/services/layeredIntelligenceOutcomes.test.js
+++ b/server/services/layeredIntelligenceOutcomes.test.js
@@ -287,6 +287,42 @@ describe('reconcileOutcomes', () => {
expect((await rowsBySlug())['mystery'].rejectionReason).toBe('duplicate');
});
+ it('lets a real close reason outrank a conflicting closing comment (#2748)', async () => {
+ // The comment scan is the WEAKEST signal: an explicit not_planned close reason
+ // must still win over prose that would otherwise say scope-mismatch.
+ await recordFiledProposal({ appId: 'app-1', slug: 'prose-scope' }, store);
+ const updated = await reconcileOutcomes({
+ appId: 'app-1',
+ existingIssues: [{
+ slug: 'prose-scope',
+ state: 'closed',
+ stateReason: 'not_planned',
+ closingComment: 'Appreciate it, but this is out of scope for the app.',
+ closedAt: '2026-07-01T00:00:00Z'
+ }]
+ }, store);
+ expect(updated).toBe(1);
+ expect((await rowsBySlug())['prose-scope'].rejectionReason).toBe('user-rejected');
+ });
+
+ it('lets the closing comment diagnose a close that carries no other signal (#2748)', async () => {
+ await recordFiledProposal({ appId: 'app-1', slug: 'prose-only' }, store);
+ const updated = await reconcileOutcomes({
+ appId: 'app-1',
+ existingIssues: [{
+ slug: 'prose-only',
+ state: 'closed',
+ // reopened ⇒ deriveOutcome abandons it; no stateReason/label the classifier
+ // recognizes, so the comment is the sole diagnostic signal.
+ stateReason: 'reopened',
+ closingComment: "Closing — can't reproduce and the report is too vague.",
+ closedAt: '2026-07-01T00:00:00Z'
+ }]
+ }, store);
+ expect(updated).toBe(1);
+ expect((await rowsBySlug())['prose-only'].rejectionReason).toBe('missing-context');
+ });
+
it('leaves a label-only closure on a reason-less tracker unclassified (known limitation)', async () => {
// glab/jira never report a stateReason, so deriveOutcome reads a bare close as
// `merged` and classification never runs — the `wontfix` signal is wasted.
diff --git a/server/services/layeredIntelligenceRejections.js b/server/services/layeredIntelligenceRejections.js
index a567d2fa86..967bca2d80 100644
--- a/server/services/layeredIntelligenceRejections.js
+++ b/server/services/layeredIntelligenceRejections.js
@@ -43,22 +43,23 @@
// 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.
+// Only the tokens marked (live) are reachable from the 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 the implementing PR's checks can then persist them
+// WITHOUT a record-shape migration.
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.
+ // (live) An explicit tracker label, OR the deterministic closing-comment keyword
+ // pass (#2748) — a human who declined in prose without applying a matching label.
'scope-mismatch',
'missing-context',
'quality-issue',
+ // Label-only today.
'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.
@@ -159,6 +160,81 @@ const STATE_REASON_REASONS = new Map(Object.entries({
'duplicate': 'duplicate'
}));
+// Closing-comment keyword pass (#2748). Some closures state their rationale only in
+// prose — a human declines in a comment without applying a matching label or (on
+// glab/jira) any close reason at all. This is a DETERMINISTIC keyword/heuristic
+// scan of that prose, NOT an LLM call: it adds no provider round-trip (the
+// "no cold-bootstrap LLM" policy) and no tracker fetch beyond the comment text the
+// reconciler already read.
+//
+// It is deliberately a LAST-RESORT signal, weaker than a label or a close reason:
+// classifyRejection consults it only when both of those miss. Free text is noisier
+// than a label a human deliberately applied, so it must never override one. Groups
+// are ordered and the FIRST group with any match wins, so the order below is the
+// tiebreak when one comment trips more than one bucket — most-specific intent
+// (scope) before the vaguer quality catch-all. Patterns are conservative: a miss
+// (→ null → the honest `unknown-reason`) is the correct failure, better than a
+// confident wrong diagnosis feeding the reasoner a fabricated pattern.
+const CLOSING_COMMENT_PATTERNS = [
+ {
+ reason: 'scope-mismatch',
+ patterns: [
+ /\bout[\s-]?of[\s-]?scope\b/,
+ /\b(?:outside|beyond|not in|not within) (?:the |our |its )?scope\b/,
+ /\bnot (?:in|within) scope\b/,
+ /\bdoes ?n[o']?t (?:fit|belong)\b/,
+ /\bwo ?n[o']?t fit\b/,
+ /\bnot (?:aligned|a (?:good )?fit)\b/,
+ /\bnot something (?:we|this app|the app)\b/
+ ]
+ },
+ {
+ reason: 'missing-context',
+ patterns: [
+ /\b(?:need|needs|needing|require[sd]?) (?:more|additional|further) (?:info|information|context|detail|details|clarification)\b/,
+ /\b(?:not enough|insufficient|lack(?:s|ing)? (?:of )?) (?:info|information|context|detail|details)\b/,
+ /\b(?:cannot|can'?t|could ?n'?t|couldn'?t|unable to) reproduce\b/,
+ /\bunder[\s-]?specified\b/,
+ /\bplease clarify\b/,
+ /\bmore (?:details|information|context) (?:needed|required)\b/,
+ /\btoo vague\b/,
+ /\bunclear\b/
+ ]
+ },
+ {
+ reason: 'quality-issue',
+ patterns: [
+ /\blow[\s-]?quality\b/,
+ /\bpoorly (?:written|specified|thought|scoped)\b/,
+ /\bmalformed\b/,
+ /\bdoes ?n[o']?t make sense\b/,
+ /\bnot actionable\b/,
+ /\bhallucinat/,
+ /\b(?:nonsense|incoherent|gibberish)\b/,
+ /\bspam\b/
+ ]
+ }
+];
+
+/**
+ * Classify a rejection rationale from the closing comment's TEXT. Pure, total,
+ * deterministic: same string always yields the same token. Returns a
+ * REJECTION_REASONS token, or null when no keyword matched (a nullish/blank comment
+ * included) so the caller can fall through to the honest `unknown-reason`.
+ */
+export function classifyClosingComment(text) {
+ if (typeof text !== 'string' || !text.trim()) return null;
+ // Lowercase + collapse whitespace so a rationale split across newlines still
+ // matches multi-word patterns.
+ const normalized = text.toLowerCase().replace(/\s+/g, ' ');
+ for (const { reason, patterns } of CLOSING_COMMENT_PATTERNS) {
+ for (const re of patterns) {
+ if (re.test(normalized)) return reason;
+ }
+ }
+ return null;
+}
+
/**
* Classify WHY a filed proposal ended up not merged.
*
@@ -173,9 +249,14 @@ const STATE_REASON_REASONS = new Map(Object.entries({
* asks for — "how much of our rejection history is undiagnosed" — so it must
* never be silently dressed up as a real reason.
*
+ * Signal precedence (most authoritative first): a human-applied label, then the
+ * tracker's close reason, then the deterministic closing-comment keyword pass
+ * (#2748). Explicit signals a human/agent deliberately set outrank a prose
+ * heuristic, so the comment scan only decides an otherwise-undiagnosed close.
+ *
* Deterministic and total: same inputs always yield the same token.
*/
-export function classifyRejection({ outcome = null, stateReason = null, labels = [] } = {}) {
+export function classifyRejection({ outcome = null, stateReason = null, labels = [], closingComment = null } = {}) {
// Only a resolved, non-merged proposal has a rejection to explain.
if (outcome !== 'rejected' && outcome !== 'abandoned') return null;
@@ -186,7 +267,16 @@ export function classifyRejection({ outcome = null, stateReason = null, labels =
if (hit) return hit;
}
- return STATE_REASON_REASONS.get(normalizeToken(stateReason)) || UNKNOWN_REJECTION_REASON;
+ // The tracker's own close reason (GitHub only) outranks free-text prose.
+ const stateHit = STATE_REASON_REASONS.get(normalizeToken(stateReason));
+ if (stateHit) return stateHit;
+
+ // Last resort before the honest unknown: scan the closing-comment prose for a
+ // rationale a human stated without a matching label/close reason.
+ const commentHit = classifyClosingComment(closingComment);
+ if (commentHit) return commentHit;
+
+ return UNKNOWN_REJECTION_REASON;
}
/**
diff --git a/server/services/layeredIntelligenceRejections.test.js b/server/services/layeredIntelligenceRejections.test.js
index ea0e882628..b35faa745d 100644
--- a/server/services/layeredIntelligenceRejections.test.js
+++ b/server/services/layeredIntelligenceRejections.test.js
@@ -4,6 +4,7 @@ import {
REJECTION_REASON_VALUES,
UNKNOWN_REJECTION_REASON,
classifyRejection,
+ classifyClosingComment,
formatRejectionReason,
formatRejectionReasons,
summarizeRejectionReasons
@@ -118,9 +119,116 @@ describe('classifyRejection', () => {
expect(classifyRejection({ outcome: 'rejected', stateReason: 'duplicate', labels: null })).toBe('duplicate');
});
+ it('classifies from the closing comment when no label or close reason fires (#2748)', () => {
+ // The glab/jira gap: a human declines in prose with no matching label and no
+ // close reason at all. The comment scan is what makes the token reachable.
+ expect(classifyRejection({
+ outcome: 'rejected',
+ stateReason: null,
+ labels: [],
+ closingComment: 'Thanks, but this is out of scope for this app.'
+ })).toBe('scope-mismatch');
+ expect(classifyRejection({
+ outcome: 'rejected',
+ closingComment: "Closing — can't reproduce and the report is too vague."
+ })).toBe('missing-context');
+ });
+
+ it('lets a label and a close reason both outrank a conflicting closing comment', () => {
+ // Free text is noisier than a deliberately-applied signal, so it must never
+ // override one — it only decides an otherwise-undiagnosed close.
+ expect(classifyRejection({
+ outcome: 'rejected',
+ labels: ['duplicate'],
+ closingComment: 'this is out of scope'
+ })).toBe('duplicate');
+ expect(classifyRejection({
+ outcome: 'rejected',
+ stateReason: 'not_planned',
+ closingComment: 'low quality proposal'
+ })).toBe('user-rejected');
+ });
+
+ it('falls through to the unknown sentinel when the closing comment states no rationale', () => {
+ expect(classifyRejection({
+ outcome: 'rejected',
+ closingComment: 'Closing this one out. Thanks!'
+ })).toBe(UNKNOWN_REJECTION_REASON);
+ });
+
it('only ever yields a storable token', () => {
const got = classifyRejection({ outcome: 'rejected', stateReason: 'not_planned' });
expect(REJECTION_REASON_VALUES).toContain(got);
+ const fromComment = classifyRejection({ outcome: 'rejected', closingComment: 'out of scope' });
+ expect(REJECTION_REASON_VALUES).toContain(fromComment);
+ });
+});
+
+describe('classifyClosingComment', () => {
+ it('returns null for a nullish, non-string, or blank comment', () => {
+ expect(classifyClosingComment(null)).toBeNull();
+ expect(classifyClosingComment(undefined)).toBeNull();
+ expect(classifyClosingComment('')).toBeNull();
+ expect(classifyClosingComment(' \n ')).toBeNull();
+ expect(classifyClosingComment(42)).toBeNull();
+ });
+
+ it('detects scope-mismatch rationales', () => {
+ for (const text of [
+ 'This is out of scope.',
+ 'Sorry, this is outside the scope of the project.',
+ "This does n't belong in this app",
+ 'Not aligned with where we are taking things.'
+ ]) {
+ expect(classifyClosingComment(text)).toBe('scope-mismatch');
+ }
+ });
+
+ it('detects missing-context rationales', () => {
+ for (const text of [
+ 'We need more information before we can act on this.',
+ 'Not enough detail to proceed.',
+ "Can't reproduce from what's here.",
+ 'This is under-specified — please clarify.',
+ 'The description is too vague.'
+ ]) {
+ expect(classifyClosingComment(text)).toBe('missing-context');
+ }
+ });
+
+ it('detects quality-issue rationales', () => {
+ for (const text of [
+ 'This is a low-quality proposal.',
+ 'The suggestion is malformed and does not make sense.',
+ 'Reads like a hallucinated feature.',
+ 'Not actionable as written.'
+ ]) {
+ expect(classifyClosingComment(text)).toBe('quality-issue');
+ }
+ });
+
+ it('matches across newlines and mixed case', () => {
+ expect(classifyClosingComment('Thanks for the idea!\n\nHowever this is\nOUT OF SCOPE here.'))
+ .toBe('scope-mismatch');
+ });
+
+ it('is deterministic and resolves multi-bucket text by fixed group order', () => {
+ // Trips both scope and quality; scope is the earlier, more-specific group.
+ const text = 'out of scope and honestly low-quality too';
+ expect(classifyClosingComment(text)).toBe('scope-mismatch');
+ expect(classifyClosingComment(text)).toBe('scope-mismatch');
+ });
+
+ it('returns null when no keyword matches, never a fabricated reason', () => {
+ expect(classifyClosingComment('Closing this out, thanks everyone.')).toBeNull();
+ expect(classifyClosingComment('Merged in a follow-up, all good.')).toBeNull();
+ });
+
+ it('only ever yields a storable token or null', () => {
+ for (const text of ['out of scope', 'need more info', 'malformed', 'nothing here']) {
+ const got = classifyClosingComment(text);
+ expect(got === null || REJECTION_REASONS.includes(got)).toBe(true);
+ }
});
});