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: add plannedWork LI source to cross-reference proposals against committed work (#2698)

[._.]/ Adam Eivy7150008bdc72
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c15fedb9c9..f51b99f8a5 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,8 @@
- [issue-2701] **Cerebras is now available as an AI provider.** Add your API key on the AI Providers page and PortOS can route AI-backed work through Cerebras's OpenAI-compatible endpoint (very high tokens/sec). Ships disabled with no key, so nothing calls it until you opt in; hit "Refresh models" after adding your key to pull the live model list. Existing installs pick the provider up automatically on restart. Cost estimates on /devtools/usage are also now accurate for `gpt-oss-120b` — it was previously billed at OpenAI GPT-5.4's rates, roughly 10x its real price.
+- [issue-2698] **Layered Intelligence now sees the work you've already committed to, and won't propose against it.** A new **Planned work** source feeds the loop your `plan`-labeled tracker issues (or your prioritized Jira backlog, or PLAN.md's unchecked items) alongside the flat open-issue list it used to get, with the instruction to cross-reference its proposal and file nothing when it overlaps something already in scope. It also gets told when its own merge rate falls below 20% and pointed at that backlog as the likely reason — LI's most common rejection was "not planned", which is what filing into work you'd already scheduled looks like from the tracker's side. A tracker that can't be read says so explicitly rather than reading as "nothing is planned", so a transient `gh` blip can't hand the loop a blank cheque. On by default for every app; toggle it off per-app under the app's Intelligence tab.
+
## Changed
- 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/client/src/components/apps/LayeredIntelligenceTab.jsx b/client/src/components/apps/LayeredIntelligenceTab.jsx
index 9a018733dc..47804b9a07 100644
--- a/client/src/components/apps/LayeredIntelligenceTab.jsx
+++ b/client/src/components/apps/LayeredIntelligenceTab.jsx
@@ -19,6 +19,7 @@ export const LI_SOURCE_FIELDS = [
{ key: 'healthReport', label: 'Health report', hint: 'Latest health / lint / test summary' },
{ key: 'planMd', label: 'PLAN.md', hint: 'The app\'s open work-plan items' },
{ key: 'openIssues', label: 'Open issues', hint: 'Currently open tracker issues' },
+ { key: 'plannedWork', label: 'Planned work', hint: 'The backlog you\'ve already committed to (plan-labeled issues / prioritized Jira backlog / unchecked PLAN.md items), so the loop won\'t propose work that\'s already in scope' },
{ key: 'outcomes', label: 'Proposal outcomes', hint: 'Past LI proposals + how they fared (merge rate), fed back so the loop calibrates on its own results' }
];
diff --git a/server/lib/validation.js b/server/lib/validation.js
index d04664c178..2ef08c293f 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -129,6 +129,10 @@ export const layeredIntelligenceConfigSchema = z.object({
healthReport: z.boolean().optional(),
planMd: z.boolean().optional(),
openIssues: z.boolean().optional(),
+ // The committed backlog (#2698): `plan`-labeled tracker issues / the
+ // prioritized Jira backlog / PLAN.md's unchecked items, fed in so the reasoner
+ // can suppress a proposal that overlaps work already in scope. Default on.
+ plannedWork: z.boolean().optional(),
// Feedback loop (#2428): feed past LI proposals + their tracker outcomes back
// into the reasoning prompt. Default on for PortOS, off for managed apps.
outcomes: z.boolean().optional(),
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.js
index 96244c6397..29ca1f2ef1 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js
@@ -295,8 +295,11 @@ export async function buildTaskInput({ app } = {}) {
// Independent reads (app source set vs the tracker's open-issue list) — overlap
// them so the non-parked path pays one round-trip, not two.
+ // The resolved tracker coords flow into gatherSources so the plannedWork source
+ // (#2698) can read the app's committed backlog off the SAME tracker the loop
+ // files to — gatherSources has no other way to know where work lives.
const [sources, issuesRead] = await Promise.all([
- gatherSources(app, config),
+ gatherSources(app, config, { tracker: { filer, forgeCli, cwd, jira } }),
readIssues({ filer, forgeCli, cwd, jira, config })
])
const { openIssues, existingIssues, trackerReadFailed } = issuesRead
diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
index ff54ceee6d..3cb3ced5b8 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.test.js
@@ -213,6 +213,37 @@ describe('buildTaskInput', () => {
expect(res.model).toBe('qwen');
});
+ it('threads the resolved tracker coords into gatherSources so plannedWork can read the backlog (#2698)', async () => {
+ // gatherSources has no way to know WHERE the app's work lives — the hook is
+ // the only place the tracker is resolved, so it must hand it over or the
+ // plannedWork source silently no-ops.
+ await buildTaskInput({ app: APP });
+ expect(li.gatherSources).toHaveBeenCalledWith(
+ APP,
+ expect.anything(),
+ { tracker: { filer: 'forge', forgeCli: 'gh', cwd: '/repo', jira: null } }
+ );
+ });
+
+ it('threads jira coords into gatherSources for a jira-tracked app (#2698)', async () => {
+ resolveAppWorkTracker.mockResolvedValue({ resolved: 'jira', forge: null });
+ const jiraApp = { ...APP, jira: { enabled: true, instanceId: 'i1', projectKey: 'PROJ' } };
+ await buildTaskInput({ app: jiraApp });
+ expect(li.gatherSources).toHaveBeenCalledWith(
+ jiraApp,
+ expect.anything(),
+ { tracker: expect.objectContaining({ filer: 'jira', jira: expect.objectContaining({ instanceId: 'i1', projectKey: 'PROJ' }) }) }
+ );
+ });
+
+ it('passes the gathered plannedWork source through to buildPrompt (#2698)', async () => {
+ li.gatherSources.mockResolvedValue({ goals: 'be great', plannedWork: '2 item(s):\n- #3 Ship X' });
+ await buildTaskInput({ app: APP });
+ expect(li.buildPrompt).toHaveBeenCalledWith(expect.objectContaining({
+ sources: expect.objectContaining({ plannedWork: expect.stringContaining('#3 Ship X') })
+ }));
+ });
+
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/jira.js b/server/services/jira.js
index 9c673c5551..8f14550f80 100644
--- a/server/services/jira.js
+++ b/server/services/jira.js
@@ -296,6 +296,9 @@ export async function searchIssues(instanceId, jql, { fields = 'summary,status,l
description: issue.fields.description || '',
status: issue.fields.status?.name || null,
statusCategory: issue.fields.status?.statusCategory?.name || null,
+ // Only populated when the caller asked for the `priority` field (it is not in
+ // the default `fields` set) — null otherwise, never a fabricated default.
+ priority: issue.fields.priority?.name || null,
labels: issue.fields.labels || [],
updated: issue.fields.updated || null,
resolutiondate: issue.fields.resolutiondate || null,
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index c1a6ca498c..9bb14db35b 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -37,6 +37,32 @@ import { computeWindowedStats } from './taskLearning/store.js';
export const LI_LABEL = 'layered-intelligence';
export const LI_BLOCKING_LABEL = 'layered-intelligence:blocking';
+// The tracker label marking an issue as work the user has COMMITTED to — the
+// `plannedWork` source's filter (#2698). PortOS's own roadmap "lives entirely in
+// the GitHub issue tracker" as `plan`-labeled issues, and that convention is the
+// default for managed apps too.
+export const PLANNED_WORK_LABEL = 'plan';
+
+// How many planned-work items are surfaced to the reasoner. The point is to give
+// it enough of the committed backlog to spot an overlap, not to reproduce the
+// tracker — the count of the FULL set is always reported alongside, so a
+// truncated list never reads as the whole picture.
+export const PLANNED_WORK_MAX_ITEMS = 15;
+
+// Character bound for the rendered plannedWork block, matching the other
+// file-backed sources' 8000-char ceiling.
+export const PLANNED_WORK_MAX_CHARS = 8000;
+
+// The instruction buildPrompt attaches directly beneath the plannedWork block —
+// the whole point of the source: turn "here is the backlog" into "so do not file
+// against it".
+export const PLANNED_WORK_GUIDANCE = 'Cross-reference your proposal against the user\'s actively-planned work above. If your proposal duplicates or conflicts with an active item, DO NOT file — return proposal: null. Only propose genuinely new work that does NOT overlap with what is already in scope.';
+
+// Rendered when the tracker read SUCCEEDED and the app genuinely has no committed
+// backlog. Says so explicitly rather than omitting the block, so "nothing planned"
+// is legible to the reasoner as a real answer rather than a missing source.
+export const PLANNED_WORK_NONE = 'No actively-planned work is currently tracked for this app. (The tracker was read successfully — this is a real "nothing is planned", not a failed read.)';
+
// Jira labels can't contain spaces, and a ':' is unsafe on some Jira versions,
// so the Jira pause label swaps the ':' for a '-'. The base LI_LABEL is already
// Jira-safe (kebab, no colon) and is reused verbatim across all trackers.
@@ -82,6 +108,11 @@ export const PROPOSAL_COMPLEXITIES = ['trivial', 'moderate', 'complex'];
// lets the loop enqueue a coding agent instead of only filing the issue.
export const HANDOFF_COMPLEXITY = 'trivial';
+// Merge rate (as a %) below which computeOutcomesReport tells the reasoner its
+// proposals are landing badly and points it at the plannedWork source (#2698).
+// Measured over RESOLVED proposals only — see computeOutcomesReport.
+export const LOW_MERGE_RATE_THRESHOLD = 20;
+
// 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 →
@@ -120,6 +151,14 @@ export function defaultLayeredIntelligenceConfig(isPortos = false) {
healthReport: true,
planMd: true,
openIssues: true,
+ // The backlog the user has ALREADY committed to (#2698): `plan`-labeled
+ // tracker issues / the app's prioritized Jira backlog / PLAN.md's unchecked
+ // items. Open issues alone read as a flat list with no priority context, so
+ // the reasoner had no way to tell "nobody has looked at this" from "the user
+ // already scheduled this" — the top NOT_PLANNED rejection cause. On by
+ // default for every app: cross-referencing against committed work is only
+ // useful if it is there by default.
+ plannedWork: true,
// The self-feedback signal (#2428): past LI proposals + their tracker
// outcomes, fed back so the reasoner calibrates on its own merge rate.
// Default ON for the PortOS install (it improves itself), OFF for managed
@@ -490,6 +529,24 @@ export function computeOutcomesReport({ outcomes = [] } = {}) {
.filter(o => o.outcome === 'rejected' && o.outcomeReason)
.map(o => o.outcomeReason))].slice(0, 5);
+ // Low-merge-rate alarm (#2698). Measured over RESOLVED proposals only
+ // (merged + rejected + abandoned), NOT over `total`: a still-open proposal has
+ // not failed, it just hasn't been judged yet, and dividing by `total` would let
+ // "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.
+ const resolved = merged + rejected + abandoned;
+ const resolvedMergeRate = resolved > 0 ? Math.round((merged / resolved) * 100) : null;
+ const lowMergeWarning = (resolvedMergeRate !== null && 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.'
+ ]
+ : [];
+
return [
'Recent LI proposals (all still-open, plus outcomes resolved within ~30 days):',
`- Total filed: ${total}`,
@@ -501,7 +558,8 @@ export function computeOutcomesReport({ outcomes = [] } = {}) {
'By scope:',
scopeLines || '- (none)',
'',
- `Common rejection reasons: ${reasons.length ? reasons.join('; ') : 'none'}`
+ `Common rejection reasons: ${reasons.length ? reasons.join('; ') : 'none'}`,
+ ...lowMergeWarning
].join('\n');
}
@@ -517,7 +575,12 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort
isScopeAllowed({ scope: s, allowedScopes: config.allowedScopes, isPortos })
);
const scopeLines = allowed.map(s => ` - ${s}`).join('\n');
+ // plannedWork renders as its OWN block (below) rather than inside the generic
+ // source list, so the cross-reference guidance is guaranteed to sit directly
+ // under the committed backlog it refers to instead of drifting to wherever
+ // object key order happens to put it.
const sourceBlocks = Object.entries(sources)
+ .filter(([k]) => k !== 'plannedWork')
.filter(([, v]) => typeof v === 'string' && v.trim())
.map(([k, v]) => `### ${k}\n${v.trim()}`)
.join('\n\n');
@@ -540,6 +603,15 @@ export function buildPrompt({ app, config, sources = {}, openIssues = [], isPort
? '\nHand-off: a proposal you mark BOTH "complexity":"trivial" AND "safe":true may be handed directly to a coding agent to implement now (not just filed). Only mark a proposal trivial+safe when it is small, self-contained, and carries no regression or data-loss risk — when in doubt, use a higher complexity or "safe":false so a human triages it first.\n'
: '';
+ // The committed backlog (#2698) + the instruction to check against it. Emitted
+ // whenever gatherPlannedWork produced ANY string — including its explicit
+ // "could not be read" marker, which must still reach the reasoner: silently
+ // dropping an unavailable read would look identical to "this app has nothing
+ // planned" and license a proposal straight into committed work.
+ const plannedWorkBlock = (typeof sources.plannedWork === 'string' && sources.plannedWork.trim())
+ ? `\n### plannedWork\n${sources.plannedWork.trim()}\n\n${PLANNED_WORK_GUIDANCE}\n`
+ : '';
+
// Feedback loop (#2428): show the reasoner how its own past proposals fared so
// it can calibrate scope/merge-rate instead of proposing in a vacuum.
const outcomesBlock = (typeof outcomesReport === 'string' && outcomesReport.trim())
@@ -559,7 +631,7 @@ ${openList}
Gathered sources:
${sourceBlocks || '(no sources available — you may propose an app-data-gap to add telemetry)'}
-${outcomesBlock}
+${plannedWorkBlock}${outcomesBlock}
Respond with JSON only (no markdown fences):
{
"analysis": "brief reasoning summary",
@@ -595,13 +667,141 @@ function runCli(cmd, args, options = {}) {
});
}
+/**
+ * Why a planned-work read came back empty-handed. Rendered INSTEAD of a listing so
+ * a failed tracker read can never be mistaken for "this app has nothing planned" —
+ * the two are opposite instructions to the reasoner (be conservative vs. the field
+ * is wide open), and collapsing them is exactly the failure the sentinel rule in
+ * CLAUDE.md exists to prevent.
+ */
+export function plannedWorkUnavailable(why) {
+ return `Planned work could NOT be read (${why}). Do NOT treat this as "nothing is planned" — this app may well have a committed backlog that simply could not be listed this run. Be conservative: prefer proposal: null over filing work that might already be in scope.`;
+}
+
+/**
+ * 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".
+ */
+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));
+ if (list.length === 0) return PLANNED_WORK_NONE;
+ const top = list.slice(0, maxItems);
+ const lines = top.map(i => {
+ const ref = i.number != null ? `#${i.number} ` : '';
+ const meta = [
+ i.priority ? `priority: ${i.priority}` : null,
+ Array.isArray(i.labels) && i.labels.length ? `labels: ${i.labels.join(', ')}` : null
+ ].filter(Boolean).join('; ');
+ return `- ${ref}${(i.title || '').trim()}${meta ? ` (${meta})` : ''}`;
+ });
+ const header = list.length > top.length
+ ? `${list.length} items of actively-planned work the user has already committed to (showing the top ${top.length}):`
+ : `${list.length} item(s) of actively-planned work the user has already committed to:`;
+ return [header, ...lines].join('\n').slice(0, maxChars);
+}
+
+/**
+ * Extract a PLAN.md's UNCHECKED (`- [ ]`) items — the plan tracker's equivalent of
+ * a `plan`-labeled issue. A `- [x]` item is finished work, not committed-and-
+ * pending, so it is excluded: proposing something already done is a different
+ * (and already-handled) problem than proposing something already scheduled.
+ */
+export function extractPlannedPlanItems(planContent) {
+ if (typeof planContent !== 'string') return [];
+ const items = [];
+ const re = /^[ \t]*[-*][ \t]+\[ \][ \t]*(\S.*)$/gm;
+ let m;
+ while ((m = re.exec(planContent))) {
+ const title = m[1].replace(/\s+/g, ' ').trim();
+ if (title) items.push({ number: null, title: title.slice(0, 200), labels: [], priority: null });
+ }
+ return items;
+}
+
+/**
+ * Gather the app's actively-planned work — the backlog the user has ALREADY
+ * committed to — so the reasoner can cross-reference a proposal against it before
+ * filing (#2698). A deterministic tracker read: files + `gh`/`glab`/Jira REST, and
+ * 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:
+ * - `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
+ *
+ * Deps are injectable so tests drive every branch without a live tracker.
+ */
+export async function gatherPlannedWork({
+ filer,
+ forgeCli,
+ cwd,
+ jira,
+ listForge = listForgeIssues,
+ listJira = listJiraIssues,
+ readFileFn = tryReadFile
+} = {}) {
+ if (filer === 'forge' && forgeCli && cwd) {
+ const { ok, issues } = await listForge({ cli: forgeCli, cwd, label: PLANNED_WORK_LABEL, state: 'open' });
+ if (!ok) return plannedWorkUnavailable(`the ${forgeCli} issue list failed`);
+ // gh honors --state open, but glab's label list can still surface a closed
+ // issue depending on version — re-filter so a done item never reads as pending.
+ const open = issues.filter(i => i.state === 'open');
+ return formatPlannedWork(open.map(i => ({
+ number: i.number,
+ title: i.title,
+ labels: i.labels || [],
+ priority: extractIssuePriority(i.labels)
+ })));
+ }
+
+ if (filer === 'jira' && jira?.instanceId && jira?.projectKey) {
+ const { ok, issues } = await listJira({
+ instanceId: jira.instanceId,
+ projectKey: jira.projectKey,
+ jql: plannedWorkJql(jira.projectKey),
+ // Jira's priority field is not in searchIssues' default `fields` set — ask
+ // for it explicitly, or every item would report a null priority.
+ searchOptions: { fields: 'summary,status,labels,updated,description,resolutiondate,priority' }
+ });
+ if (!ok) return plannedWorkUnavailable('the Jira search failed');
+ const open = issues.filter(i => i.state === 'open');
+ return formatPlannedWork(open.map(i => ({
+ number: i.number,
+ title: i.title,
+ labels: i.labels || [],
+ // Prefer Jira's real priority field; fall back to a priority-ish label.
+ priority: i.priority || extractIssuePriority(i.labels)
+ })));
+ }
+
+ if (filer === 'plan' && cwd) {
+ const planPath = join(cwd, 'PLAN.md');
+ // No PLAN.md at all is a real "nothing is planned" for a plan-tracked app —
+ // distinguish it from a PLAN.md that EXISTS but could not be read (a genuine
+ // failure), which tryReadFile's null would otherwise conflate.
+ if (!existsSync(planPath)) return PLANNED_WORK_NONE;
+ const content = await readFileFn(planPath);
+ if (typeof content !== 'string') return plannedWorkUnavailable('PLAN.md exists but could not be read');
+ return formatPlannedWork(extractPlannedPlanItems(content));
+ }
+
+ return null;
+}
+
/**
* Gather the enabled Layer-1 sources for one app into a `{ key: string }` map.
- * Deterministic reads only (files + CoS metric JSON); NO LLM calls. Missing
- * files degrade to omitted keys, never throws. `openIssues` is gathered
- * separately by the handler (it shells out to the forge).
+ * Deterministic reads only (files + CoS metric JSON + tracker lists); NO LLM calls.
+ * Missing files degrade to omitted keys, never throws. `openIssues` is gathered
+ * separately by the handler (it shells out to the forge). `tracker`
+ * (`{ filer, forgeCli, cwd, jira }`, resolved by the caller) enables the
+ * plannedWork source — absent, that source is simply skipped.
*/
-export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShellSources } = {}) {
+export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShellSources, tracker = null } = {}) {
const out = {};
const src = config.sources || {};
const repo = app.repoPath;
@@ -634,6 +834,13 @@ export async function gatherSources(app, config, { cosPath = PATHS.cos, trustShe
const health = await tryReadFile(join(repo, 'HEALTH_REPORT.md'));
if (health) out.healthReport = health.slice(0, 8000);
}
+ if (src.plannedWork && tracker) {
+ // The committed backlog (#2698). Unlike the file sources above, an EMPTY or
+ // FAILED result still emits a key — each renders a distinct sentence, and
+ // both are meaningful instructions to the reasoner (see gatherPlannedWork).
+ const planned = await gatherPlannedWork(tracker);
+ if (planned) out.plannedWork = planned.slice(0, PLANNED_WORK_MAX_CHARS);
+ }
if (src.cosMetrics) {
// This install's own autonomous-agent run stats (per task type), NOT scoped to
// the app being analyzed — see the default-config note for the PortOS-vs-managed
@@ -879,18 +1086,56 @@ export function normalizeIssueState(state) {
}
/**
- * List existing layered-intelligence issues on a forge (open + recently closed)
- * so the handler can feed them to the reasoner and run the dedup guard.
+ * Normalize a forge issue's labels to a plain `string[]`. gh reports objects
+ * (`[{ name, color, … }]`); glab reports bare strings. Anything unrecognized
+ * drops out rather than rendering `[object Object]` into the reasoner's prompt.
+ */
+export function normalizeIssueLabels(raw) {
+ if (!Array.isArray(raw)) return [];
+ return raw
+ .map(l => (typeof l === 'string' ? l : l?.name))
+ .filter(l => typeof l === 'string' && l.trim())
+ .map(l => l.trim());
+}
+
+/**
+ * Best-effort priority read from an issue's labels — there is no cross-forge
+ * priority field, so the common label conventions are matched instead:
+ * `priority: high` / `priority/high`, `P0`–`P4`, and a bare
+ * `critical|urgent|high|medium|low` (optionally suffixed `-priority`).
+ *
+ * Returns null when no label looks like a priority. Null means "this issue
+ * carries no priority label", NOT "priority zero" — the renderer omits the field
+ * entirely rather than inventing a default the tracker never asserted.
+ */
+export function extractIssuePriority(labels = []) {
+ const re = /^(?:priority[:/\s-]+(.+)|p([0-4])|(critical|urgent|high|medium|low)(?:[\s-]priority)?)$/i;
+ for (const label of normalizeIssueLabels(labels)) {
+ const m = label.match(re);
+ if (!m) continue;
+ const value = m[1] ?? (m[2] != null ? `p${m[2]}` : m[3]);
+ if (typeof value === 'string' && value.trim()) return value.trim().toLowerCase();
+ }
+ return null;
+}
+
+/**
+ * List issues on a forge. Defaults to the layered-intelligence set (open +
+ * recently closed) for the reasoner + dedup guard; `label`/`state` are
+ * parameterized so the plannedWork source (#2698) can reuse the exact same
+ * parse/normalize path for the `plan`-labeled committed backlog.
*
* Returns `{ ok, issues }` — `ok:false` means the tracker read FAILED (CLI error
* or unparseable output), which is NOT the same as "no existing issues" (`ok:true,
* issues:[]`). The handler must NOT file when the read failed, or a transient
* `gh` blip would defeat dedup and file a duplicate (CLAUDE.md sentinel rule).
*/
-export async function listForgeIssues({ cli, cwd, env, exec = runCli } = {}) {
+export async function listForgeIssues({ cli, cwd, env, label = LI_LABEL, state = 'all', exec = runCli } = {}) {
+ // glab lists open issues by default and needs `--all` to widen to every state;
+ // gh takes the state explicitly.
const args = cli === 'glab'
- ? ['issue', 'list', '--label', LI_LABEL, '--all', '-P', '100', '-F', 'json']
- : ['issue', 'list', '--label', LI_LABEL, '--state', 'all', '--limit', '100', '--json', 'number,title,body,state,stateReason,closedAt,url'];
+ ? ['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'];
const { code, stdout } = await exec(cli, args, { cwd, env });
if (code !== 0) return { ok: false, issues: [] };
if (!stdout.trim()) return { ok: true, issues: [] };
@@ -911,6 +1156,7 @@ export async function listForgeIssues({ cli, cwd, env, exec = runCli } = {}) {
// the overview's proposal links degrade to a plain count rather than a
// dead href.
url: i.url || i.web_url || null,
+ labels: normalizeIssueLabels(i.labels),
slug: extractSlugFromBody(i.body || i.description || '') || extractSlugFromBody(i.title || '')
}))
};
@@ -1011,10 +1257,14 @@ export function normalizeJiraState(statusCategory) {
* failed-vs-empty contract: a thrown search is `ok:false` (do NOT file — a blind
* dedup would duplicate); an empty result is `ok:true, issues:[]`.
*/
-export async function listJiraIssues({ instanceId, projectKey, search = searchIssues } = {}) {
+export async function listJiraIssues({ instanceId, projectKey, jql, searchOptions, search = searchIssues } = {}) {
if (!instanceId || !projectKey) return { ok: false, issues: [] };
- const jql = `project = "${escapeJql(projectKey)}" AND labels = "${LI_LABEL}" ORDER BY updated DESC`;
- const rows = await search(instanceId, jql).then(r => r, () => null);
+ // `jql` lets the plannedWork source (#2698) reuse this parse path for the
+ // prioritized backlog; absent, it's the layered-intelligence label set.
+ const query = jql || `project = "${escapeJql(projectKey)}" AND labels = "${LI_LABEL}" ORDER BY updated DESC`;
+ const rows = searchOptions
+ ? await search(instanceId, query, searchOptions).then(r => r, () => null)
+ : await search(instanceId, query).then(r => r, () => null);
if (!Array.isArray(rows)) return { ok: false, issues: [] };
return {
ok: true,
@@ -1024,11 +1274,31 @@ export async function listJiraIssues({ instanceId, projectKey, search = searchIs
body: i.description || '',
state: normalizeJiraState(i.statusCategory),
closedAt: i.resolutiondate || null,
+ labels: normalizeIssueLabels(i.labels),
+ // Jira DOES have a real priority field (unlike the forges) — but only when
+ // the caller asked searchIssues for it. Absent → null → the renderer omits
+ // it, rather than a fabricated default.
+ priority: typeof i.priority === 'string' && i.priority.trim() ? i.priority.trim() : null,
slug: extractSlugFromBody(i.description || '') || extractSlugFromBody(i.summary || '')
}))
};
}
+/**
+ * The JQL for a Jira project's committed backlog (#2698): everything not Done,
+ * highest priority first.
+ *
+ * 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.
+ */
+export function plannedWorkJql(projectKey) {
+ return `project = "${escapeJql(projectKey)}" AND statusCategory != Done ORDER BY priority DESC, updated DESC`;
+}
+
/**
* List OPEN blocking-labeled Jira tickets for the app (park check). `{ ok, issues }`
* with the same failed-vs-empty distinction. JQL filters out Done so a resolved
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index 49c7b59453..5da2a9052a 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -54,7 +54,19 @@ import {
LI_LABEL,
LI_BLOCKING_LABEL,
LI_JIRA_BLOCKING_LABEL,
- LI_JOB_ID
+ LI_JOB_ID,
+ normalizeIssueLabels,
+ extractIssuePriority,
+ extractPlannedPlanItems,
+ formatPlannedWork,
+ gatherPlannedWork,
+ plannedWorkUnavailable,
+ plannedWorkJql,
+ PLANNED_WORK_LABEL,
+ PLANNED_WORK_MAX_ITEMS,
+ PLANNED_WORK_NONE,
+ PLANNED_WORK_GUIDANCE,
+ LOW_MERGE_RATE_THRESHOLD
} from './layeredIntelligence.js';
describe('defaultLayeredIntelligenceConfig', () => {
@@ -1315,3 +1327,439 @@ describe('gatherSources cosMetrics windowed rate (issue #2460)', () => {
expect(out.cosMetrics).toBeUndefined();
});
});
+
+// ---------------------------------------------------------------------------
+// plannedWork source (#2698) — the committed backlog fed to the reasoner so it
+// can suppress a proposal that overlaps work already in scope.
+// ---------------------------------------------------------------------------
+
+describe('normalizeIssueLabels', () => {
+ it('reads gh label objects and glab label strings alike', () => {
+ expect(normalizeIssueLabels([{ name: 'plan' }, { name: 'p1' }])).toEqual(['plan', 'p1']);
+ expect(normalizeIssueLabels(['plan', 'p1'])).toEqual(['plan', 'p1']);
+ });
+
+ it('drops junk rather than rendering [object Object] into the prompt', () => {
+ expect(normalizeIssueLabels([{ color: 'red' }, null, '', ' ', 42, { name: ' ok ' }])).toEqual(['ok']);
+ });
+
+ it('returns [] for a non-array (never throws)', () => {
+ expect(normalizeIssueLabels(undefined)).toEqual([]);
+ expect(normalizeIssueLabels('plan')).toEqual([]);
+ });
+});
+
+describe('extractIssuePriority', () => {
+ it('reads the common priority label conventions', () => {
+ expect(extractIssuePriority(['bug', 'priority: high'])).toBe('high');
+ expect(extractIssuePriority(['priority/critical'])).toBe('critical');
+ expect(extractIssuePriority(['P0'])).toBe('p0');
+ expect(extractIssuePriority(['high-priority'])).toBe('high');
+ expect(extractIssuePriority([{ name: 'low' }])).toBe('low');
+ });
+
+ it('returns null when no label looks like a priority (absent ≠ p0)', () => {
+ expect(extractIssuePriority(['plan', 'enhancement'])).toBeNull();
+ expect(extractIssuePriority([])).toBeNull();
+ expect(extractIssuePriority(undefined)).toBeNull();
+ // A near-miss must not be coerced into a priority.
+ expect(extractIssuePriority(['p9', 'priority'])).toBeNull();
+ });
+});
+
+describe('extractPlannedPlanItems', () => {
+ it('extracts unchecked items only — a done item is not pending work', () => {
+ const plan = [
+ '# Plan',
+ '## Next Up',
+ '- [ ] Add a widget',
+ '- [x] Already shipped',
+ '* [ ] Star bullet item',
+ 'not a list item'
+ ].join('\n');
+ expect(extractPlannedPlanItems(plan).map(i => i.title)).toEqual(['Add a widget', 'Star bullet item']);
+ });
+
+ it('collapses whitespace and yields the planned-item shape', () => {
+ expect(extractPlannedPlanItems('- [ ] Do the thing ')[0]).toEqual({
+ number: null, title: 'Do the thing', labels: [], priority: null
+ });
+ });
+
+ it('returns [] for a non-string or an empty/checkbox-less plan', () => {
+ expect(extractPlannedPlanItems(null)).toEqual([]);
+ expect(extractPlannedPlanItems('# Plan\n\nJust prose.')).toEqual([]);
+ // A checkbox with no text is not an item.
+ expect(extractPlannedPlanItems('- [ ] ')).toEqual([]);
+ });
+});
+
+describe('formatPlannedWork', () => {
+ it('renders number, title, priority and labels', () => {
+ const out = formatPlannedWork([{ number: 12, title: 'Ship X', labels: ['plan', 'p1'], priority: 'p1' }]);
+ expect(out).toContain('- #12 Ship X');
+ expect(out).toContain('priority: p1');
+ expect(out).toContain('labels: plan, p1');
+ });
+
+ it('omits the priority/labels parens when there is nothing to say', () => {
+ const out = formatPlannedWork([{ number: null, title: 'Bare item', labels: [], priority: null }]);
+ const itemLine = out.split('\n').find(l => l.startsWith('- '));
+ expect(itemLine).toBe('- Bare item');
+ });
+
+ it('reports the FULL count when truncating so a partial list never reads as the whole backlog', () => {
+ const many = Array.from({ length: 40 }, (_, n) => ({ number: n + 1, title: `Item ${n + 1}`, labels: [], priority: null }));
+ const out = formatPlannedWork(many);
+ expect(out).toContain('40 items');
+ expect(out).toContain(`showing the top ${PLANNED_WORK_MAX_ITEMS}`);
+ expect(out).toContain('- #15 Item 15');
+ expect(out).not.toContain('Item 16');
+ });
+
+ it('bounds the rendered block', () => {
+ const many = Array.from({ length: 15 }, (_, n) => ({ number: n, title: 'x'.repeat(2000), labels: [], priority: null }));
+ expect(formatPlannedWork(many).length).toBeLessThanOrEqual(8000);
+ });
+
+ it('says "nothing planned" EXPLICITLY for a real empty result (not an omitted block)', () => {
+ expect(formatPlannedWork([])).toBe(PLANNED_WORK_NONE);
+ expect(formatPlannedWork(undefined)).toBe(PLANNED_WORK_NONE);
+ expect(PLANNED_WORK_NONE).toContain('read successfully');
+ });
+});
+
+describe('plannedWorkUnavailable', () => {
+ it('tells the reasoner NOT to read a failed read as "nothing planned"', () => {
+ const msg = plannedWorkUnavailable('the gh issue list failed');
+ expect(msg).toContain('could NOT be read');
+ expect(msg).toContain('the gh issue list failed');
+ // The whole point of the sentinel: it must be distinguishable from the
+ // legitimately-empty rendering.
+ expect(msg).not.toBe(PLANNED_WORK_NONE);
+ });
+});
+
+describe('plannedWorkJql', () => {
+ it('filters to not-Done 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('escapes the project key', () => {
+ expect(plannedWorkJql('A"B')).toContain('A\\"B');
+ });
+});
+
+describe('gatherPlannedWork', () => {
+ it('forge: queries the plan label + open state and summarizes with derived priority', async () => {
+ const listForge = vi.fn().mockResolvedValue({
+ ok: true,
+ issues: [
+ { number: 3, title: 'Planned A', state: 'open', labels: ['plan', 'priority: high'] },
+ { number: 4, title: 'Planned B', state: 'open', labels: ['plan'] }
+ ]
+ });
+ const out = await gatherPlannedWork({ filer: 'forge', forgeCli: 'gh', cwd: '/repo', listForge });
+ expect(listForge).toHaveBeenCalledWith({ cli: 'gh', cwd: '/repo', label: PLANNED_WORK_LABEL, state: 'open' });
+ expect(out).toContain('- #3 Planned A');
+ expect(out).toContain('priority: high');
+ expect(out).toContain('- #4 Planned B');
+ });
+
+ it('forge: filters out a closed issue the tracker still returned', async () => {
+ const listForge = vi.fn().mockResolvedValue({
+ ok: true,
+ issues: [
+ { number: 3, title: 'Open one', state: 'open', labels: [] },
+ { number: 5, title: 'Done one', state: 'closed', labels: [] }
+ ]
+ });
+ const out = await gatherPlannedWork({ filer: 'forge', forgeCli: 'glab', cwd: '/repo', listForge });
+ expect(out).toContain('Open one');
+ expect(out).not.toContain('Done one');
+ expect(out).toContain('1 item(s)');
+ });
+
+ it('forge: a FAILED read renders the unavailable sentinel, NOT "nothing planned"', async () => {
+ const listForge = vi.fn().mockResolvedValue({ ok: false, issues: [] });
+ const out = await gatherPlannedWork({ filer: 'forge', forgeCli: 'gh', cwd: '/repo', listForge });
+ expect(out).toContain('could NOT be read');
+ expect(out).not.toBe(PLANNED_WORK_NONE);
+ });
+
+ it('forge: a SUCCESSFUL empty read renders "nothing planned" (distinct from a failure)', async () => {
+ const listForge = vi.fn().mockResolvedValue({ ok: true, issues: [] });
+ expect(await gatherPlannedWork({ filer: 'forge', forgeCli: 'gh', cwd: '/repo', listForge })).toBe(PLANNED_WORK_NONE);
+ });
+
+ it('jira: uses the planned-work JQL, requests the priority field, and prefers it over labels', async () => {
+ const listJira = vi.fn().mockResolvedValue({
+ ok: true,
+ issues: [{ number: 'PROJ-9', title: 'Jira item', state: 'open', labels: ['low'], priority: 'Highest' }]
+ });
+ const out = await gatherPlannedWork({
+ filer: 'jira', jira: { instanceId: 'i1', projectKey: 'PROJ' }, listJira
+ });
+ const arg = listJira.mock.calls[0][0];
+ expect(arg.jql).toBe(plannedWorkJql('PROJ'));
+ expect(arg.searchOptions.fields).toContain('priority');
+ // Jira's real priority field wins over the label-derived fallback.
+ expect(out).toContain('priority: Highest');
+ expect(out).toContain('- #PROJ-9 Jira item');
+ });
+
+ it('jira: falls back to a label-derived priority when the field is absent', async () => {
+ const listJira = vi.fn().mockResolvedValue({
+ ok: true,
+ issues: [{ number: 'PROJ-9', title: 'J', state: 'open', labels: ['p2'], priority: null }]
+ });
+ const out = await gatherPlannedWork({ filer: 'jira', jira: { instanceId: 'i1', projectKey: 'PROJ' }, listJira });
+ expect(out).toContain('priority: p2');
+ });
+
+ it('jira: a FAILED search renders the unavailable sentinel', async () => {
+ const listJira = vi.fn().mockResolvedValue({ ok: false, issues: [] });
+ const out = await gatherPlannedWork({ filer: 'jira', jira: { instanceId: 'i1', projectKey: 'PROJ' }, listJira });
+ expect(out).toContain('could NOT be read');
+ });
+
+ it('returns null when the tracker coords are unusable (source simply does not apply)', async () => {
+ expect(await gatherPlannedWork({ filer: 'forge', forgeCli: null, cwd: '/repo' })).toBeNull();
+ expect(await gatherPlannedWork({ filer: 'jira', jira: null })).toBeNull();
+ expect(await gatherPlannedWork({ filer: 'plan', cwd: null })).toBeNull();
+ expect(await gatherPlannedWork({})).toBeNull();
+ });
+
+ describe('plan tracker', () => {
+ let dir;
+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'lil-planned-')); });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ it('summarizes PLAN.md unchecked items', async () => {
+ await writeFile(join(dir, 'PLAN.md'), '# P\n- [ ] Committed thing\n- [x] Done thing\n');
+ const out = await gatherPlannedWork({ filer: 'plan', cwd: dir });
+ expect(out).toContain('- Committed thing');
+ expect(out).not.toContain('Done thing');
+ });
+
+ it('an ABSENT PLAN.md is a real "nothing planned"', async () => {
+ expect(await gatherPlannedWork({ filer: 'plan', cwd: dir })).toBe(PLANNED_WORK_NONE);
+ });
+
+ it('a PRESENT-but-unreadable PLAN.md is a FAILURE, not "nothing planned"', async () => {
+ await writeFile(join(dir, 'PLAN.md'), '- [ ] x');
+ // tryReadFile collapses every failure to null; the existsSync probe is what
+ // keeps "unreadable" from masquerading as "no plan at all".
+ const out = await gatherPlannedWork({ filer: 'plan', cwd: dir, readFileFn: async () => null });
+ expect(out).toContain('could NOT be read');
+ expect(out).not.toBe(PLANNED_WORK_NONE);
+ });
+ });
+});
+
+describe('gatherSources plannedWork wiring (#2698)', () => {
+ let dir;
+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'lil-pw-src-')); });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ it('gathers plannedWork when the source is on and a tracker is supplied', async () => {
+ await writeFile(join(dir, 'PLAN.md'), '- [ ] Committed thing\n');
+ const out = await gatherSources(
+ { repoPath: dir },
+ { sources: { plannedWork: true } },
+ { tracker: { filer: 'plan', cwd: dir } }
+ );
+ expect(out.plannedWork).toContain('Committed thing');
+ });
+
+ it('skips plannedWork when the source is off', async () => {
+ await writeFile(join(dir, 'PLAN.md'), '- [ ] Committed thing\n');
+ const out = await gatherSources(
+ { repoPath: dir },
+ { sources: { plannedWork: false } },
+ { tracker: { filer: 'plan', cwd: dir } }
+ );
+ expect(out.plannedWork).toBeUndefined();
+ });
+
+ it('skips plannedWork when no tracker context was resolved', async () => {
+ await writeFile(join(dir, 'PLAN.md'), '- [ ] Committed thing\n');
+ const out = await gatherSources({ repoPath: dir }, { sources: { plannedWork: true } });
+ expect(out.plannedWork).toBeUndefined();
+ });
+
+ it('is on by default for every app', () => {
+ expect(defaultLayeredIntelligenceConfig(false).sources.plannedWork).toBe(true);
+ expect(defaultLayeredIntelligenceConfig(true).sources.plannedWork).toBe(true);
+ });
+
+ it('reaches an existing install that stored sources before the key existed', () => {
+ // getEffectiveConfig spreads defaults under stored sources, so no migration
+ // is needed for the new key — but an explicit opt-out must still survive.
+ const stored = { layeredIntelligence: { sources: { goals: false } } };
+ expect(getEffectiveConfig(stored).sources.plannedWork).toBe(true);
+ const optedOut = { layeredIntelligence: { sources: { plannedWork: false } } };
+ expect(getEffectiveConfig(optedOut).sources.plannedWork).toBe(false);
+ });
+});
+
+describe('buildPrompt plannedWork block (#2698)', () => {
+ const app = { name: 'App' };
+ const config = { allowedScopes: ['app-improvement'], sources: {} };
+
+ it('renders the block with the cross-reference guidance attached', () => {
+ const p = buildPrompt({ app, config, sources: { plannedWork: '1 item(s):\n- #3 Ship X' } });
+ expect(p).toContain('### plannedWork');
+ expect(p).toContain('- #3 Ship X');
+ expect(p).toContain(PLANNED_WORK_GUIDANCE);
+ expect(p).toContain('DO NOT file — return proposal: null');
+ });
+
+ it('renders plannedWork ONCE — not also inside the generic source list', () => {
+ const p = buildPrompt({ app, config, sources: { goals: 'be great', plannedWork: 'PLANNED BACKLOG' } });
+ expect(p.match(/### plannedWork/g)).toHaveLength(1);
+ expect(p).toContain('### goals');
+ });
+
+ it('puts the guidance AFTER the backlog it refers to', () => {
+ const p = buildPrompt({ app, config, sources: { plannedWork: 'PLANNED BACKLOG' } });
+ expect(p.indexOf('PLANNED BACKLOG')).toBeLessThan(p.indexOf(PLANNED_WORK_GUIDANCE));
+ });
+
+ it('still surfaces the "could not be read" sentinel to the reasoner', () => {
+ const p = buildPrompt({ app, config, sources: { plannedWork: plannedWorkUnavailable('the gh issue list failed') } });
+ expect(p).toContain('### plannedWork');
+ expect(p).toContain('could NOT be read');
+ expect(p).toContain(PLANNED_WORK_GUIDANCE);
+ });
+
+ it('omits the block entirely when the source produced nothing', () => {
+ expect(buildPrompt({ app, config, sources: { goals: 'g' } })).not.toContain('### plannedWork');
+ expect(buildPrompt({ app, config, sources: { plannedWork: ' ' } })).not.toContain('### plannedWork');
+ });
+});
+
+describe('computeOutcomesReport low-merge-rate warning (#2698)', () => {
+ const filed = (outcome) => ({ scope: 'app-improvement', outcome });
+
+ 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')] });
+ 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%)');
+ });
+
+ it('stays silent when the merge rate is healthy', () => {
+ const report = computeOutcomesReport({ outcomes: [filed('merged'), filed('merged'), filed('rejected')] });
+ 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');
+ expect(report).not.toContain('WARNING');
+ });
+
+ it('measures over resolved proposals, not total (a pending backlog cannot trip it)', () => {
+ // 1 merged of 1 resolved = 100% → healthy, despite 1/5 = 20% of total.
+ const report = computeOutcomesReport({ outcomes: [filed('merged'), filed(null), filed(null), filed(null), filed(null)] });
+ expect(report).not.toContain('WARNING');
+ });
+
+ 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')] });
+ 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'))] });
+ expect(below).toContain('WARNING');
+ expect(LOW_MERGE_RATE_THRESHOLD).toBe(20);
+ });
+
+ it('still returns "" with no filed history (nothing to calibrate on)', () => {
+ expect(computeOutcomesReport({ outcomes: [] })).toBe('');
+ });
+});
+
+describe('listForgeIssues label/state parameterization (#2698)', () => {
+ it('defaults to the LI label across all states', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: '[]' });
+ await listForgeIssues({ cli: 'gh', cwd: '/x', exec });
+ const args = exec.mock.calls[0][1];
+ expect(args).toContain(LI_LABEL);
+ expect(args).toContain('--state');
+ expect(args[args.indexOf('--state') + 1]).toBe('all');
+ });
+
+ it('queries the requested label + state (gh)', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: '[]' });
+ await listForgeIssues({ cli: 'gh', cwd: '/x', label: 'plan', state: 'open', exec });
+ const args = exec.mock.calls[0][1];
+ expect(args).toContain('plan');
+ expect(args).not.toContain(LI_LABEL);
+ expect(args[args.indexOf('--state') + 1]).toBe('open');
+ expect(args[args.indexOf('--json') + 1]).toContain('labels');
+ });
+
+ it('drops --all for an open-only glab query (glab lists open by default)', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: '[]' });
+ await listForgeIssues({ cli: 'glab', cwd: '/x', label: 'plan', state: 'open', exec });
+ expect(exec.mock.calls[0][1]).not.toContain('--all');
+ await listForgeIssues({ cli: 'glab', cwd: '/x', exec });
+ expect(exec.mock.calls[1][1]).toContain('--all');
+ });
+
+ it('normalizes labels from both forges', async () => {
+ const exec = vi.fn().mockResolvedValue({
+ code: 0,
+ stdout: JSON.stringify([{ number: 1, title: 'A', state: 'open', labels: [{ name: 'plan' }] }])
+ });
+ const { issues } = await listForgeIssues({ cli: 'gh', cwd: '/x', exec });
+ expect(issues[0].labels).toEqual(['plan']);
+ });
+
+ it('reports [] labels when the forge omits the field (never undefined)', async () => {
+ const exec = vi.fn().mockResolvedValue({ code: 0, stdout: JSON.stringify([{ number: 1, title: 'A', state: 'open' }]) });
+ const { issues } = await listForgeIssues({ cli: 'gh', cwd: '/x', exec });
+ expect(issues[0].labels).toEqual([]);
+ });
+});
+
+describe('listJiraIssues jql override (#2698)', () => {
+ it('defaults to the LI-label JQL and passes no search options', async () => {
+ const search = vi.fn().mockResolvedValue([]);
+ await listJiraIssues({ instanceId: 'i1', projectKey: 'PROJ', search });
+ expect(search).toHaveBeenCalledWith('i1', expect.stringContaining(`labels = "${LI_LABEL}"`));
+ });
+
+ it('uses an explicit jql + search options when given', async () => {
+ const search = vi.fn().mockResolvedValue([]);
+ await listJiraIssues({
+ instanceId: 'i1', projectKey: 'PROJ', jql: 'CUSTOM JQL', searchOptions: { fields: 'summary,priority' }, search
+ });
+ expect(search).toHaveBeenCalledWith('i1', 'CUSTOM JQL', { fields: 'summary,priority' });
+ });
+
+ it('maps priority + labels, and keeps an absent priority null', async () => {
+ const search = vi.fn().mockResolvedValue([
+ { key: 'PROJ-1', summary: 'A', statusCategory: 'To Do', priority: 'High', labels: ['plan'] },
+ { key: 'PROJ-2', summary: 'B', statusCategory: 'To Do' }
+ ]);
+ const { issues } = await listJiraIssues({ instanceId: 'i1', projectKey: 'PROJ', search });
+ expect(issues[0].priority).toBe('High');
+ expect(issues[0].labels).toEqual(['plan']);
+ expect(issues[1].priority).toBeNull();
+ expect(issues[1].labels).toEqual([]);
+ });
+});