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
fix: tighten plannedWork's Jira scope and the merge-rate alarm's firing conditions (#2698)
[._.]/ Adam Eivy72c0904f10e8
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex 29ca1f2ef1..0181067dc4 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -314,7 +314,13 @@ export async function buildTaskInput({ app } = {}) {if (config.sources?.outcomes && outcomesTrackerSupported(filer)) {if (!trackerReadFailed) await reconcileOutcomes({ appId: app.id, existingIssues })const outcomes = await listOutcomes({ appId: app.id })- outcomesReport = computeOutcomesReport({ outcomes })+ // The low-merge-rate warning cites the plannedWork block by name — only let it+ // do that when one was actually gathered (the source is per-app-toggleable and+ // yields nothing on an unresolvable tracker).+ outcomesReport = computeOutcomesReport({+ outcomes,+ hasPlannedWork: typeof sources.plannedWork === 'string' && !!sources.plannedWork.trim()+ })}const prompt = buildPrompt({ app, config, sources, openIssues, isPortos, outcomesReport }) + buildCompletionContract()diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.jsindex 3cb3ced5b8..85d8f0e2a4 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js@@ -244,6 +244,20 @@ describe('buildTaskInput', () => {}));});+ it('tells computeOutcomesReport whether a plannedWork block exists to cite (#2698)', async () => {+ li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: { outcomes: true } });+ li.gatherSources.mockResolvedValue({ goals: 'g', plannedWork: '1 item(s):\n- #3 Ship X' });+ await buildTaskInput({ app: APP });+ expect(li.computeOutcomesReport).toHaveBeenCalledWith(expect.objectContaining({ hasPlannedWork: true }));++ // Source off / unresolvable tracker → the warning must not cite a block the+ // prompt doesn't contain.+ li.computeOutcomesReport.mockClear();+ li.gatherSources.mockResolvedValue({ goals: 'g' });+ await buildTaskInput({ app: APP });+ expect(li.computeOutcomesReport).toHaveBeenCalledWith(expect.objectContaining({ hasPlannedWork: false }));+ });+it('skips the outcomes feedback loop when the source toggle is off', async () => {li.getEffectiveConfig.mockReturnValue({ providerId: 'ollama', model: 'qwen', allowedScopes: ['app-improvement'], sources: {} });await buildTaskInput({ app: APP });diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.jsindex 9bb14db35b..632ab883ca 100644--- a/server/services/layeredIntelligence.js+++ b/server/services/layeredIntelligence.js@@ -113,6 +113,13 @@ export const HANDOFF_COMPLEXITY = 'trivial';// Measured over RESOLVED proposals only — see computeOutcomesReport.export const LOW_MERGE_RATE_THRESHOLD = 20;+// Minimum RESOLVED proposals before the low-merge-rate alarm is allowed to fire.+// 0-of-1 and 0-of-50 are both "0%", but only the second is evidence: telling the+// loop its rate is "critically low" after a single early rejection biases it+// toward filing nothing, which is self-reinforcing — it can never earn a merge if+// it stops proposing. A rate needs a sample before it means anything.+export const LOW_MERGE_RATE_MIN_SAMPLE = 4;+// 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 →@@ -500,7 +507,7 @@ export function deriveOutcome(issue) {* Returns '' when there's nothing to report (no filed history) so the caller omits* the block entirely rather than injecting an empty section.*/-export function computeOutcomesReport({ outcomes = [] } = {}) {+export function computeOutcomesReport({ outcomes = [], hasPlannedWork = false } = {}) {const filed = (Array.isArray(outcomes) ? outcomes : []).filter(o => o && typeof o === 'object');if (filed.length === 0) return '';const total = filed.length;@@ -535,15 +542,24 @@ export function computeOutcomesReport({ outcomes = [] } = {}) {// "filed yesterday, nobody has triaged it" read exactly like "the user threw it// out" — the sentinel rule (pending ≠ rejected). `null` means "no resolved// sample yet", which is distinct from a genuine 0% and stays silent rather than- // alarming an app whose first proposal is simply still in flight.+ // alarming an app whose first proposal is simply still in flight. The sample+ // floor is the same idea one step further out: 0-of-1 is not evidence of a rate.const resolved = merged + rejected + abandoned;const resolvedMergeRate = resolved > 0 ? Math.round((merged / resolved) * 100) : null;- const lowMergeWarning = (resolvedMergeRate !== null && resolvedMergeRate < LOW_MERGE_RATE_THRESHOLD)+ const lowMergeWarning = (+ resolvedMergeRate !== null+ && resolved >= LOW_MERGE_RATE_MIN_SAMPLE+ && resolvedMergeRate < LOW_MERGE_RATE_THRESHOLD+ )? ['',`WARNING: your merge rate is critically low — only ${merged} of ${resolved} resolved proposals (${resolvedMergeRate}%) were merged.`,- 'Review the "plannedWork" source above: your proposals may be overlapping with work the user has already committed to.',- 'Propose only work that is clearly outside that committed backlog — and if you cannot find any, return proposal: null rather than filing something marginal.'+ // Only point at the plannedWork block when one was actually gathered — the+ // source is per-app-toggleable and yields nothing on an unresolvable+ // tracker, and citing a section that isn't in the prompt is just noise.+ hasPlannedWork+ ? 'Review the "plannedWork" source above: your proposals may be overlapping with work the user has already committed to. Propose only work that is clearly outside that committed backlog — and if you cannot find any, return proposal: null rather than filing something marginal.'+ : 'Your proposals may be overlapping with work the user has already committed to, or missing what they actually value. Hold a higher bar: return proposal: null rather than filing something marginal.']: [];@@ -630,7 +646,7 @@ Already-open tracked issues (DO NOT duplicate these — reuse their slug only if${openList}Gathered sources:-${sourceBlocks || '(no sources available — you may propose an app-data-gap to add telemetry)'}+${sourceBlocks || (plannedWorkBlock ? '(no other sources available — you may propose an app-data-gap to add telemetry)' : '(no sources available — you may propose an app-data-gap to add telemetry)')}${plannedWorkBlock}${outcomesBlock}Respond with JSON only (no markdown fences):{@@ -681,9 +697,11 @@ export function plannedWorkUnavailable(why) {/*** Render a planned-work item list into the prompt block. Pure.*- * Reports the FULL count even when the list is truncated to `maxItems`, so the- * reasoner knows it is seeing the top of a larger backlog rather than all of it —- * "15 items shown" out of 200 must not read as "there are only 15".+ * Reports the count of everything it was HANDED even when the rendered list is+ * truncated to `maxItems`, so the reasoner knows it is seeing the top of a larger+ * backlog rather than all of it — 15 shown out of 100 must not read as "there are+ * only 15". Note the caller's own read is capped too (the tracker lists cap at+ * 100), so on a very large backlog this count is itself a floor, not a census.*/export function formatPlannedWork(items, { maxItems = PLANNED_WORK_MAX_ITEMS, maxChars = PLANNED_WORK_MAX_CHARS } = {}) {const list = (Array.isArray(items) ? items : []).filter(i => i && typeof i === 'object' && (i.title || i.number != null));@@ -728,11 +746,12 @@ export function extractPlannedPlanItems(planContent) {* NO LLM call (the no-cold-bootstrap rule).** Returns a prompt-ready string, or `null` when the source does not apply at all- * (unresolvable tracker, or a plan-tracked app with no PLAN.md) — three distinct- * states, never collapsed:+ * (an unresolvable tracker: no forge CLI, no Jira coords, no repo path) — three+ * distinct states, never collapsed:* - `null` → nothing to say; buildPrompt omits the block* - `plannedWorkUnavailable()` → the read FAILED; be conservative* - a listing / PLANNED_WORK_NONE → the read SUCCEEDED and is trustworthy+ * (a plan-tracked app with no PLAN.md at all is a real PLANNED_WORK_NONE)** Deps are injectable so tests drive every branch without a live tracker.*/@@ -1285,18 +1304,28 @@ export async function listJiraIssues({ instanceId, projectKey, jql, searchOption}/**- * The JQL for a Jira project's committed backlog (#2698): everything not Done,- * highest priority first.+ * The JQL for a Jira project's committed backlog (#2698): `plan`-labeled tickets+ * that aren't Done, highest priority first.+ *+ * The label filter is NOT optional — it is what makes this source mean the same+ * thing on Jira as on a forge. Without it the query returns every open ticket,+ * i.e. the untriaged backlog nobody has committed to (plus LI's own past+ * proposals), which would then render under a header asserting the user+ * "already committed to" them and instruct the reasoner to suppress against+ * essentially the whole tracker — and duplicate the `openIssues` source besides.+ * A project that doesn't use the label reports a truthful "nothing planned"+ * rather than a backlog-shaped lie.** Deliberately NOT `sprint in openSprints()` — the Sprint field only exists on- * boards backed by a Scrum board, and JQL referencing an absent field is a hard- * 400 rather than an empty result. That would make gatherPlannedWork report- * "unavailable" forever on every Kanban/basic project. Priority ordering + the- * item cap is the portable equivalent: it works on every project shape and still- * surfaces the top of the backlog.+ * Scrum-board-backed projects, and JQL referencing an absent field is a hard 400+ * rather than an empty result, which would make gatherPlannedWork report+ * "unavailable" forever on every Kanban/basic project. `labels` exists on every+ * project shape. Priority is an ORDER BY rather than a filter for the same+ * reason: priority NAMES are scheme-specific (a project can rename or drop+ * "Highest"), so filtering on them risks the same permanent-400.*/export function plannedWorkJql(projectKey) {- return `project = "${escapeJql(projectKey)}" AND statusCategory != Done ORDER BY priority DESC, updated DESC`;+ return `project = "${escapeJql(projectKey)}" AND labels = "${PLANNED_WORK_LABEL}" AND statusCategory != Done ORDER BY priority DESC, updated DESC`;}/**diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.jsindex 5da2a9052a..5357c02ee2 100644--- a/server/services/layeredIntelligence.test.js+++ b/server/services/layeredIntelligence.test.js@@ -66,7 +66,8 @@ import {PLANNED_WORK_MAX_ITEMS,PLANNED_WORK_NONE,PLANNED_WORK_GUIDANCE,- LOW_MERGE_RATE_THRESHOLD+ LOW_MERGE_RATE_THRESHOLD,+ LOW_MERGE_RATE_MIN_SAMPLE} from './layeredIntelligence.js';describe('defaultLayeredIntelligenceConfig', () => {@@ -1441,15 +1442,24 @@ describe('plannedWorkUnavailable', () => {});describe('plannedWorkJql', () => {- it('filters to not-Done and orders by priority', () => {+ it('filters to not-Done plan-labeled tickets and orders by priority', () => {const jql = plannedWorkJql('PROJ');expect(jql).toContain('project = "PROJ"');expect(jql).toContain('statusCategory != Done');expect(jql).toContain('ORDER BY priority DESC');});- it('does NOT reference openSprints (a hard JQL error on non-Scrum projects)', () => {- expect(plannedWorkJql('PROJ')).not.toContain('openSprints');+ it('filters on the plan label — parity with the forge, not "every open ticket"', () => {+ // Without this the source would return the whole untriaged backlog under a+ // header claiming the user committed to it, and tell the reasoner to suppress+ // against essentially the entire tracker.+ expect(plannedWorkJql('PROJ')).toContain(`labels = "${PLANNED_WORK_LABEL}"`);+ });++ it('does NOT reference openSprints or filter on priority NAMES (both hard-400 on some projects)', () => {+ const jql = plannedWorkJql('PROJ');+ expect(jql).not.toContain('openSprints');+ expect(jql).not.toContain('priority in');});it('escapes the project key', () => {@@ -1644,30 +1654,41 @@ describe('buildPrompt plannedWork block (#2698)', () => {expect(buildPrompt({ app, config, sources: { goals: 'g' } })).not.toContain('### plannedWork');expect(buildPrompt({ app, config, sources: { plannedWork: ' ' } })).not.toContain('### plannedWork');});++ it('does not claim "no sources available" while rendering a populated plannedWork block', () => {+ // plannedWork is excluded from sourceBlocks so its guidance stays anchored —+ // the empty-sources fallback must not therefore contradict the block below it.+ const p = buildPrompt({ app, config, sources: { plannedWork: '1 item(s):\n- #3 Ship X' } });+ expect(p).toContain('- #3 Ship X');+ expect(p).toContain('(no other sources available');+ // Still says the plain thing when there is genuinely nothing at all.+ expect(buildPrompt({ app, config, sources: {} })).toContain('(no sources available');+ });});describe('computeOutcomesReport low-merge-rate warning (#2698)', () => {const filed = (outcome) => ({ scope: 'app-improvement', outcome });+ const rejected = (n) => Array.from({ length: n }, () => filed('rejected'));it('warns and points at plannedWork when the resolved merge rate is below the threshold', () => {- // 0 of 3 resolved merged → 0% < 20%.- const report = computeOutcomesReport({ outcomes: [filed('rejected'), filed('rejected'), filed('abandoned')] });+ // 0 of 4 resolved merged → 0% < 20%, and 4 clears the sample floor.+ const report = computeOutcomesReport({ outcomes: [...rejected(3), filed('abandoned')], hasPlannedWork: true });expect(report).toContain('WARNING');expect(report).toContain('merge rate is critically low');expect(report).toContain('plannedWork');- expect(report).toContain('0 of 3 resolved proposals (0%)');+ expect(report).toContain('0 of 4 resolved proposals (0%)');});it('stays silent when the merge rate is healthy', () => {- const report = computeOutcomesReport({ outcomes: [filed('merged'), filed('merged'), filed('rejected')] });+ const report = computeOutcomesReport({ outcomes: [filed('merged'), filed('merged'), filed('rejected'), filed('merged')] });expect(report).not.toContain('WARNING');});it('stays silent when NOTHING is resolved yet (pending ≠ rejected)', () => {- // Three filed, all still open: 0 merged of 0 resolved. Dividing by `total`- // would render 0% and alarm — but nothing has actually failed.- const report = computeOutcomesReport({ outcomes: [filed(null), filed(null), filed(null)] });- expect(report).toContain('Total filed: 3');+ // Filed, all still open: 0 merged of 0 resolved. Dividing by `total` would+ // render 0% and alarm — but nothing has actually failed.+ const report = computeOutcomesReport({ outcomes: [filed(null), filed(null), filed(null), filed(null), filed(null)] });+ expect(report).toContain('Total filed: 5');expect(report).not.toContain('WARNING');});@@ -1677,16 +1698,35 @@ describe('computeOutcomesReport low-merge-rate warning (#2698)', () => {expect(report).not.toContain('WARNING');});+ it('stays silent below the sample floor — 0-of-1 is not evidence of a rate', () => {+ // A single early rejection must not tell the loop to stop proposing: it can+ // never earn a merge if it stops filing.+ for (let n = 1; n < LOW_MERGE_RATE_MIN_SAMPLE; n += 1) {+ expect(computeOutcomesReport({ outcomes: rejected(n), hasPlannedWork: true })).not.toContain('WARNING');+ }+ expect(computeOutcomesReport({ outcomes: rejected(LOW_MERGE_RATE_MIN_SAMPLE), hasPlannedWork: true })).toContain('WARNING');+ expect(LOW_MERGE_RATE_MIN_SAMPLE).toBe(4);+ });+it('fires exactly below the documented threshold', () => {// 1 merged of 5 resolved = 20% → NOT below 20 → silent.- const at = computeOutcomesReport({ outcomes: [filed('merged'), filed('rejected'), filed('rejected'), filed('rejected'), filed('rejected')] });+ const at = computeOutcomesReport({ outcomes: [filed('merged'), ...rejected(4)] });expect(at).not.toContain('WARNING');// 1 merged of 6 resolved = 17% → below → warns.- const below = computeOutcomesReport({ outcomes: [filed('merged'), ...Array.from({ length: 5 }, () => filed('rejected'))] });+ const below = computeOutcomesReport({ outcomes: [filed('merged'), ...rejected(5)] });expect(below).toContain('WARNING');expect(LOW_MERGE_RATE_THRESHOLD).toBe(20);});+ it('does NOT cite a plannedWork block that is not in the prompt', () => {+ // The source is per-app-toggleable and yields nothing on an unresolvable+ // tracker — citing a section that isn't there is just noise.+ const report = computeOutcomesReport({ outcomes: rejected(5), hasPlannedWork: false });+ expect(report).toContain('WARNING');+ expect(report).not.toContain('plannedWork');+ expect(report).toContain('return proposal: null');+ });+it('still returns "" with no filed history (nothing to calibrate on)', () => {expect(computeOutcomesReport({ outcomes: [] })).toBe('');});