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: feed each audit lane what became of its filed issues (#12187)

[._.]/519a2120b6be
diff --git a/client/src/components/apps/AppLaneHealth.jsx b/client/src/components/apps/AppLaneHealth.jsx
new file mode 100644
index 0000000000..2d922d5722
--- /dev/null
+++ b/client/src/components/apps/AppLaneHealth.jsx
@@ -0,0 +1,92 @@
+import { useEffect, useState } from 'react';
+import { RefreshCw } from 'lucide-react';
+import { getAppLaneHealth } from '../../services/apiApps';
+import { formatCount, formatDateShort } from '../../utils/formatters';
+import InfoTooltip from '../ui/InfoTooltip';
+
+const UNAVAILABLE = {
+ 'forge-unavailable': 'This app has no GitHub or GitLab tracker, so there is no issue record to read.',
+ issues: 'The tracker could not be read.',
+};
+
+// A lane's noise is what it got wrong or repeated; filed breaks ties so the
+// busiest noisy lane sits first.
+const noise = (lane) => lane.notPlanned + lane.reverted + lane.refiled;
+const describeFlag = (reason) => {
+ if (reason.kind === 'not-planned') return reason.stateReason === 'duplicate' ? 'duplicate' : 'not planned';
+ if (reason.kind === 'reverted') return reason.pullRequest != null ? `reverted (PR #${reason.pullRequest})` : 'reverted';
+ if (reason.kind === 're-filed') return reason.of != null ? `re-filed after #${reason.of}` : 're-filed';
+ return 'flagged';
+};
+
+/** Per-lane outcome of the issues each audit lane filed (#12088): a read on request, never polled. */
+export default function AppLaneHealth({ appId }) {
+ const [state, setState] = useState({ loading: true });
+ const [refresh, setRefresh] = useState(0);
+ useEffect(() => {
+ let active = true;
+ setState({ loading: true });
+ getAppLaneHealth(appId).then((data) => {
+ if (active) setState({ data });
+ }).catch(() => {
+ if (active) setState({ error: true });
+ });
+ return () => { active = false; };
+ }, [appId, refresh]);
+ const data = state.data;
+ const lanes = (data?.lanes || []).filter((lane) => lane.filed > 0)
+ .sort((a, b) => noise(b) - noise(a) || b.filed - a.filed || a.label.localeCompare(b.label));
+ return (
+ <section aria-label="Lane health" className="bg-port-card border border-port-border rounded-lg p-4 space-y-3 min-w-0">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h4 className="flex items-center gap-1.5 text-sm font-medium">
+ Lane health
+ <InfoTooltip label="About lane health" placement="below" align="start" width={300}>
+ What became of the issues each audit lane filed in the last {data?.windowDays ?? 60} days, read from the tracker. Not planned counts issues closed as not planned or duplicate; reverted counts fixes a later <code>Revert</code> commit undid; re-filed counts issues citing a file a closed finding of the same lane cited within {data?.refileDays ?? 30} days. Each lane sees its own row before it runs, so it does not repeat a rejected finding.
+ </InfoTooltip>
+ </h4>
+ <button type="button" aria-label="Refresh lane health" title="Refresh lane health" className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center text-gray-400 hover:text-port-accent" onClick={() => setRefresh((n) => n + 1)}>
+ <RefreshCw size={14} aria-hidden="true" />
+ </button>
+ </div>
+ {state.loading ? <p role="status">Loading lane health…</p>
+ : state.error ? <p role="alert">Lane health could not be loaded. Use Refresh lane health to retry.</p>
+ : data?.available === false ? <p className="text-sm text-gray-400">{UNAVAILABLE[data.reason] || 'Lane health is unavailable.'}{data.error ? ` ${data.error}` : ''}</p>
+ : !lanes.length ? <p className="text-sm text-gray-400">No audit lane filed an issue in the last {data.windowDays} days.</p>
+ : <>
+ {(data.truncated || data.partial?.length > 0) && <p className="text-xs text-port-warning">
+ {data.truncated ? `The tracker read was truncated; counts cover issues filed since ${formatDateShort(data.from)}. ` : ''}
+ {data.partial?.length > 0 ? `${data.partial.join(' and ')} could not be read, so reverted counts are incomplete.` : ''}
+ </p>}
+ <div className="overflow-x-auto"><table className="w-full text-left text-sm" aria-label="Audit lane outcomes">
+ <thead className="text-xs text-gray-400"><tr>
+ <th scope="col" className="py-1.5 px-2">Lane</th>
+ <th scope="col" className="py-1.5 px-2 text-right">Filed</th>
+ <th scope="col" className="py-1.5 px-2 text-right">Completed</th>
+ <th scope="col" className="py-1.5 px-2 text-right">Not planned</th>
+ <th scope="col" className="py-1.5 px-2 text-right">Reverted</th>
+ <th scope="col" className="py-1.5 px-2 text-right">Re-filed</th>
+ </tr></thead>
+ <tbody>{lanes.map((lane) => <tr key={lane.id} className={`border-t border-port-border${noise(lane) > 0 ? ' bg-port-warning/10' : ''}`}>
+ <th scope="row" className="py-1.5 px-2 font-medium">
+ <span className="inline-flex items-center gap-1.5">
+ {lane.label}
+ {lane.flagged?.length > 0 && <InfoTooltip label={`${lane.label} findings that were rejected, reverted or repeated`} placement="below" align="start" width={320} panelClassName="font-normal">
+ <ul className="space-y-1">{lane.flagged.map((item) => <li key={item.number} className="break-words">
+ {item.url ? <a href={item.url} target="_blank" rel="noreferrer" className="text-port-accent hover:underline">#{item.number}</a> : `#${item.number}`} {item.title} · {item.reasons.map(describeFlag).join('; ')}
+ </li>)}</ul>
+ {lane.flaggedTotal > lane.flagged.length && <p className="mt-1 text-gray-400">{formatCount(lane.flaggedTotal - lane.flagged.length)} more not shown</p>}
+ </InfoTooltip>}
+ </span>
+ </th>
+ <td className="py-1.5 px-2 text-right tabular-nums">{formatCount(lane.filed)}</td>
+ <td className="py-1.5 px-2 text-right tabular-nums">{formatCount(lane.completed)}</td>
+ <td className="py-1.5 px-2 text-right tabular-nums">{formatCount(lane.notPlanned)}</td>
+ <td className="py-1.5 px-2 text-right tabular-nums">{formatCount(lane.reverted)}</td>
+ <td className="py-1.5 px-2 text-right tabular-nums">{formatCount(lane.refiled)}</td>
+ </tr>)}</tbody>
+ </table></div>
+ </>}
+ </section>
+ );
+}
diff --git a/client/src/components/apps/AppLaneHealth.test.jsx b/client/src/components/apps/AppLaneHealth.test.jsx
new file mode 100644
index 0000000000..b57e2dbc9b
--- /dev/null
+++ b/client/src/components/apps/AppLaneHealth.test.jsx
@@ -0,0 +1,47 @@
+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { it, expect, vi } from 'vitest';
+import AppLaneHealth from './AppLaneHealth';
+import { getAppLaneHealth } from '../../services/apiApps';
+vi.mock('../../services/apiApps', () => ({ getAppLaneHealth: vi.fn() }));
+
+const lane = (overrides) => ({ id: 'x', label: 'X', metricLabel: 'x', filed: 0, completed: 0, notPlanned: 0, open: 0, reverted: 0, refiled: 0, flagged: [], flaggedTotal: 0, ...overrides });
+
+it('lists lanes with filed issues noisiest first, names the flagged findings, and warns about a shortened or partial read', async () => {
+ getAppLaneHealth.mockResolvedValueOnce({
+ available: true, windowDays: 60, refileDays: 30, from: '2026-09-20T00:00:00.000Z', to: '2026-10-17T00:00:00.000Z', truncated: true, partial: ['commits'],
+ lanes: [
+ lane({ id: 'security', label: 'Security', filed: 3, completed: 3 }),
+ lane({ id: 'better-complexity', label: 'Cyclomatic complexity', filed: 12, completed: 9, notPlanned: 2, reverted: 1, refiled: 1, flaggedTotal: 11, flagged: [
+ { number: 31, title: 'Dispatcher branches on every provider', url: 'https://example.com/31', reasons: [{ kind: 're-filed', of: 20, path: 'server/x.js' }] },
+ { number: 28, title: 'Hotspot', url: null, reasons: [{ kind: 'reverted', pullRequest: 90 }, { kind: 'not-planned', stateReason: 'duplicate' }] },
+ ] }),
+ lane({ id: 'ux', label: 'UX' }),
+ ],
+ });
+ render(<AppLaneHealth appId="portos-default" />);
+ const table = await screen.findByRole('table', { name: 'Audit lane outcomes' });
+ expect(getAppLaneHealth).toHaveBeenCalledWith('portos-default');
+ const rows = within(table).getAllByRole('row').slice(1);
+ expect(rows.map((row) => within(row).getByRole('rowheader').textContent)).toEqual(['Cyclomatic complexity', 'Security']);
+ expect(within(rows[0]).getAllByRole('cell').map((cell) => cell.textContent)).toEqual(['12', '9', '2', '1', '1']);
+ expect(screen.getByText(/counts cover issues filed since/)).toHaveTextContent(/commits could not be read/);
+ fireEvent.click(screen.getByRole('button', { name: 'Cyclomatic complexity findings that were rejected, reverted or repeated' }));
+ const tooltip = screen.getByRole('tooltip');
+ expect(tooltip).toHaveTextContent('#31 Dispatcher branches on every provider · re-filed after #20');
+ expect(tooltip).toHaveTextContent('#28 Hotspot · reverted (PR #90); duplicate');
+ expect(tooltip).toHaveTextContent('9 more not shown');
+ expect(within(tooltip).getByRole('link', { name: '#31' })).toHaveAttribute('href', 'https://example.com/31');
+});
+
+it('explains an app without a tracker, reports a failed load, and retries on refresh', async () => {
+ getAppLaneHealth.mockResolvedValueOnce({ available: false, reason: 'forge-unavailable' });
+ render(<AppLaneHealth appId="app-2" />);
+ expect(await screen.findByText(/no GitHub or GitLab tracker/)).toBeInTheDocument();
+ getAppLaneHealth.mockRejectedValueOnce(new Error('offline'));
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh lane health' }));
+ expect(await screen.findByRole('alert')).toHaveTextContent('could not be loaded');
+ getAppLaneHealth.mockResolvedValueOnce({ available: true, windowDays: 60, refileDays: 30, truncated: false, partial: [], lanes: [lane({ id: 'ux', label: 'UX' })] });
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh lane health' }));
+ await waitFor(() => expect(screen.getByText(/No audit lane filed an issue in the last 60 days/)).toBeInTheDocument());
+ expect(getAppLaneHealth).toHaveBeenCalledTimes(3);
+});
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsx
index 60532c003d..abda9e8b7d 100644
--- a/client/src/components/apps/AppQuality.jsx
+++ b/client/src/components/apps/AppQuality.jsx
@@ -1,5 +1,6 @@
import AppQualityRunner from './AppQualityRunner';
import AppQualityHistory from './AppQualityHistory';
+import AppLaneHealth from './AppLaneHealth';
import AppQualityScheduleForm from './AppQualityScheduleForm';
import { useId, useState } from 'react';
import { CalendarClock, Play } from 'lucide-react';
@@ -181,6 +182,7 @@ export default function AppQuality({ app, detail = false }) {
</section>
)}
</div>
+ <AppLaneHealth appId={app.id} />
<Drawer open={!!panel} onClose={() => setPanel(null)} title={PANELS[panel]} size="md" closeLabel="Close"
// The schedule form holds an unapplied plan; a stray Esc/backdrop click would discard it.
closeOnEsc={panel !== 'schedule'} closeOnBackdrop={panel !== 'schedule'}>
diff --git a/client/src/components/apps/AppQuality.test.jsx b/client/src/components/apps/AppQuality.test.jsx
index bb1db83573..7315833351 100644
--- a/client/src/components/apps/AppQuality.test.jsx
+++ b/client/src/components/apps/AppQuality.test.jsx
@@ -5,6 +5,8 @@ import AppQuality from './AppQuality';
vi.mock('./AppQualityRunner', () => ({ default: ({ children }) => children(<div>Runner</div>) }));
// The schedule form owns its own async load and is covered by its own suite.
vi.mock('./AppQualityScheduleForm', () => ({ default: () => <div>Schedule form</div> }));
+// The lane-health table owns its own read and is covered by its own suite.
+vi.mock('./AppLaneHealth', () => ({ default: () => <div>Lane health table</div> }));
vi.mock('../../services/apiApps', () => ({
getAppQualityHistory: vi.fn().mockResolvedValue({ points: [], totalCategories: 25 }),
publishAppQualitySnapshot: vi.fn(),
diff --git a/client/src/components/apps/AppQualityRunner.test.jsx b/client/src/components/apps/AppQualityRunner.test.jsx
index 54df1d342b..0f22ab650a 100644
--- a/client/src/components/apps/AppQualityRunner.test.jsx
+++ b/client/src/components/apps/AppQualityRunner.test.jsx
@@ -21,6 +21,7 @@ import AppQualityRunner from './AppQualityRunner';
import AppQuality from './AppQuality';
import { awaitEnabled, findEnabledByLabelText, findEnabledByRole } from '../../test/enabledBarrier.js';
vi.mock('./AppQualityHistory', () => ({ default: () => null }));
+vi.mock('./AppLaneHealth', () => ({ default: () => null }));
import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun, setMaintenanceRunArchived } from '../../services/apiAgents';
import useProviderModels from '../../hooks/useProviderModels';
vi.mock('../../services/apiAgents', () => ({ getMaintenanceRuns: vi.fn(), startMaintenanceRun: vi.fn(), stopMaintenanceRun: vi.fn(), setMaintenanceRunArchived: vi.fn() }));
diff --git a/client/src/services/apiApps.js b/client/src/services/apiApps.js
index ffca0dd687..b97deebe82 100644
--- a/client/src/services/apiApps.js
+++ b/client/src/services/apiApps.js
@@ -20,6 +20,9 @@ export const getApps = ({ includeQuality = false, view, ...options } = {}) => {
};
export const getApp = (id, { includeQuality = false, ...options } = {}) => request(includeQuality ? `/apps/${id}?includeQuality=true` : `/apps/${id}`, options);
export const getAppQualityHistory = (id, days, options) => request(`/apps/${id}/quality-history?days=${days}`, { silent: true, ...options });
+// Per-lane outcome of filed audit issues (#12088); the table renders its own
+// unavailable state, so the wrapper is silent.
+export const getAppLaneHealth = (id, options) => request(`/apps/${id}/lane-health`, { silent: true, ...options });
// Land the app's numeric quality scores as `.quality.json` through an
// immediately-merged pull request, so other PortOS installs running this app start
// with the latest scores. Opt-in per app (`publishQualitySnapshot`) and
diff --git a/docs/API.md b/docs/API.md
index 4f0ed2d799..2aabf5d864 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -127,6 +127,7 @@ legacy list for local Apps/Dashboard views.
| GET | `/apps/:id/status` | Get PM2 status |
| GET | `/apps/:id/logs` | Get recent logs |
| POST | `/apps/:id/refresh-config` | Re-parse ecosystem config; the record's `apiPort`/`uiPort`/`devUiPort` are set to match it, and a port the config no longer declares is cleared |
+| GET | `/apps/:id/lane-health` | What became of the issues each audit lane filed in the last 60 days (#12088), read from the app's GitHub/GitLab tracker on request: `{ available, windowDays, refileDays, from, to, truncated, partial, lanes }`, one row per audit lane with `filed`, `completed`, `notPlanned` (not planned or duplicate), `open`, `reverted` (a later `Revert` commit names the closing PR or one of its SHAs), `refiled` (a new issue citing a file a closed finding of the same lane cited within 30 days) and up to ten `flagged` issues. `truncated` means the issue read hit its limit and `from` moved to the oldest issue covered; `partial` names the pull-request or commit read that failed, so a reverted count of 0 is not evidence. `{ available: false, reason }` for an app without a forge tracker (`forge-unavailable`) or a failed issue read (`issues`, with the remedy in `error`). |
| POST | `/apps/:id/quality-snapshot` | Rebuild the app's numeric quality snapshot and land canonical schema v2 `.quality.json` through an immediately-merged pull request on `portos/quality-snapshot` (scoped to that one path; the live checkout is not committed). The file is not the peer wire payload (`PORTOS_SCHEMA_VERSIONS.appQuality` stays 1). A v1 file is rewritten when current evidence exists. Answers `{ success, published, path }` plus the commit `hash`, `prUrl`, and `prNumber`, or a `reason` of `no-repo-path` / `not-a-repo` / `no-evidence` / `no-changes` / `no-remote` / `no-default-branch` / `pr-failed` / `unsupported-format` / `invalid-evidence` when nothing was written. `unsupported-format` means a future, unrecognized, malformed, or oversize file was left in place. Not gated on the app's `publishQualitySnapshot` toggle — that toggle only automates the same publish after each audit. Any app's committed `.quality.json` (or a historical `quality-snapshot.json` when `.quality.json` is absent) is read back as a "Release snapshot" quality source, PortOS's own checkout included (`npm run quality:snapshot` is the same publish, run from the release step; `npm run quality:snapshot -- --migrate` converts an old file without reading the database). |
| GET | `/apps/:id/quality-schedule` | The Quality tab's weekly-schedule form: every audit check with its applicability verdict and reason, the repository shapes that verdict came from, the cron expressions already occupied on this app, and the plan the shipped defaults produce. Read-only — no LLM call, no write. |
| POST | `/apps/:id/quality-schedule/preview` | Re-plan for an edited form (selection, per-check delivery mode, checks per day, hour window, claim-drain task and offset). Still read-only; a POST only because the option bag carries a per-check map. |
diff --git a/docs/features/app-quality.md b/docs/features/app-quality.md
index 2ea95ee4d8..0274d88990 100644
--- a/docs/features/app-quality.md
+++ b/docs/features/app-quality.md
@@ -85,6 +85,27 @@ route and slice choice. Peers and the `.quality.json` snapshot
receive the numeric v1 wire shape with a v2 run's `sliceScore` in `score`, so
an older install keeps reading it; the slice text never leaves the machine.
+### Lane health
+
+Every audit lane also preloads what became of the issues it filed, through the
+`lane-health` task data input ("Lane health", #12088). `server/lib/laneHealth.js`
+computes, per lane (the audit's metric label; the shared `code-quality` label
+yields to the more specific lane label beside it), the issues filed in the last
+60 days and how they ended: completed, not planned (or duplicate), open, fixes
+reverted (a later commit whose subject starts with `Revert` and names the
+closing PR or one of its SHAs), and re-filed (a new issue citing a
+`path/to/file.ext` that a closed finding of the same lane cited within 30
+days). The block lists up to ten of the lane's not-planned, reverted or re-filed
+titles under "Findings this lane got wrong or repeated", and the discovery
+contract tells the lane not to re-file one of them without new evidence.
+`services/appLaneHealth.js` reads the forge (`gh`/`glab`) and the checkout's
+revert commits on request; nothing is cached or scheduled. The Quality page
+shows the same numbers for every lane in a "Lane health" table
+(`GET /api/apps/:id/lane-health`), noisiest lane first, so the operator can see
+which lanes to retune. A truncated issue read shortens the window and says so;
+a failed pull-request or commit read is named rather than read as "nothing
+reverted".
+
## Coverage review
The existing catalog already separates conventional quality, cyclomatic
diff --git a/server/lib/README.md b/server/lib/README.md
index 321119b3a8..89e58ac9a0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -812,6 +812,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `voiceEngines.js` | Shared TTS engine IDs, display metadata, supported-engine set, persisted configuration keys, and retired TTS config migration. |
| `voiceModelAssets.js` | Completion contract for downloaded voice model assets (Whisper `.bin`, Piper `.onnx` + `.onnx.json`). `inspectVoiceAsset(kind, path)` is the read-only readiness check (`verified` / `unverified` / `incomplete` / `missing` — stat plus one small JSON read, no hashing or network); `verifyVoiceAssetHashes` and `writeVoiceAssetReceipt` are the script-side halves that re-hash and record the `.portos-complete.json` receipt after promotion. `isManagedVoiceAsset` separates setup-script-owned files from user-supplied ones. Shared by `voice/bootstrap.js`, `voice/health.js` and `scripts/voice-asset.js`. |
+| `laneHealth.js` | Lane-health metrics (#12088): `computeLaneHealth` counts, per audit lane (metric label, `auditLanes`), the issues filed in a window and how they ended — completed, not planned/duplicate, fix reverted (a `Revert` commit naming the PR or a SHA of it), re-filed (a new issue citing a `path/to/file.ext` a closed one cited within 30 days); `laneHealthFor` picks one lane, `describeLaneFlag` words a flag. Pure; `services/appLaneHealth.js` supplies the forge and git reads. |
| `auditQuality.js` | Category discovery strategies, slice-scored assessment prompt and v1/v2 report schema, sentinel parsing, and freshness-aware app quality aggregation: per-category rolling window of recent run scores over daily winners across peers. |
| `mindToolRecipes.js` | Closed recipe schemas, current semantic-contract validation, and safe JSON field binding resolution. |
diff --git a/server/lib/auditQuality.js b/server/lib/auditQuality.js
index ffd1712cd2..4b5115f473 100644
--- a/server/lib/auditQuality.js
+++ b/server/lib/auditQuality.js
@@ -48,7 +48,7 @@ export function auditQualityInstructions(taskType) {
if (!Object.hasOwn(AUDIT_DEFINITIONS, category)) return '';
return `## Repository-wide discovery, worst offender first, and quality assessment
-This contract overrides narrower slice-selection or ranking advice in the mission, including customized prompts. Preserve the selected file-issues/fix mode and documented non-issues.
+This contract overrides narrower slice-selection or ranking advice in the mission, including customized prompts. Preserve the selected file-issues/fix mode and documented non-issues. Read the lane-health block: do not re-file a finding it lists as reverted or not-planned without new evidence.
1. Inventory all first-party source roots with git ls-files or rg --files, excluding vendored/generated/build/dependency output. Do a cheap repository-wide signal scan BEFORE choosing where to investigate. Do not deep-read the entire repository.
2. Category search: ${AUDIT_DISCOVERY[category]}
3. Rank at least the top five candidates (or all if fewer), with paths, measured signals, impact, reach, confidence and why higher candidates win. Validate the top candidates through callers, tests and relevant history before filing or fixing. Severity and user impact outrank ease, small scope and recency. Churn and fan-in break ties; inactivity alone never dismisses a severe offender. If the raw worst is exempt, already filed or not actionable, report why and continue down the ranking. Existing unresolved issues still count against quality. Never pick a nit while a verified major problem remains actionable.
diff --git a/server/lib/index.js b/server/lib/index.js
index e56d5b09f4..495af59e3e 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -788,6 +788,7 @@ export * from './kilo.js';
export * from './openchamber.js';
export * from './layaMlx.js';
+export * from './laneHealth.js';
export * from './layeredIntelligenceSources.js';
export * from './layeredIntelligenceSourceKeys.js';
diff --git a/server/lib/laneHealth.js b/server/lib/laneHealth.js
new file mode 100644
index 0000000000..d18e83b167
--- /dev/null
+++ b/server/lib/laneHealth.js
@@ -0,0 +1,205 @@
+/**
+ * Lane-health metrics (#12088): what happened to the issues each audit lane
+ * filed. Pure — the forge and git reads live in `services/appLaneHealth.js`;
+ * this module only counts and matches, so revert and re-file detection can be
+ * pinned with fixtures.
+ *
+ * A lane is an audit definition's metric label (`auditCatalog.js`). An issue
+ * belongs to every lane whose metric label it carries, except that a shared
+ * category label (`code-quality`) yields to the more specific lane label an
+ * issue also carries (`simplify`, `complexity`, …), so a simplify finding is
+ * never double-counted as a code-quality one.
+ */
+
+import { AUDIT_DEFINITIONS } from './auditCatalog.js';
+
+export const LANE_HEALTH_WINDOW_DAYS = 60;
+export const LANE_REFILE_WINDOW_DAYS = 30;
+export const LANE_HEALTH_FLAGGED_LIMIT = 10;
+const DAY_MS = 86_400_000;
+const MIN_SHA_PREFIX = 7;
+
+/** The audit lanes as `{ id, label, metricLabel, issueLabel }`, catalog order. */
+export function auditLanes(definitions = AUDIT_DEFINITIONS) {
+ return Object.entries(definitions)
+ .filter(([, definition]) => definition?.filing?.metricLabel)
+ .map(([id, { label, filing }]) => ({ id, label, metricLabel: filing.metricLabel, issueLabel: filing.issueLabel }));
+}
+
+function labelNames(labels) {
+ if (!Array.isArray(labels)) return [];
+ return labels
+ .map((label) => (typeof label === 'string' ? label : label?.name))
+ .filter((name) => typeof name === 'string')
+ .map((name) => name.trim().toLowerCase())
+ .filter(Boolean);
+}
+
+/** Lane ids an issue's labels attribute it to; the shared category label yields to a specific lane label. */
+function attributeIssueLanes(issue, lanes = auditLanes()) {
+ const labels = new Set(labelNames(issue?.labels));
+ const carried = lanes.filter((lane) => labels.has(lane.metricLabel));
+ return carried
+ .filter((lane) => !carried.some((other) => other !== lane && other.issueLabel === lane.metricLabel && other.metricLabel !== lane.metricLabel))
+ .map((lane) => lane.id);
+}
+
+// A repository-relative source path with at least one directory and an
+// extension, as the audit filing contract's `path/to/file.js:LINE` writes it.
+// Must follow a boundary character so URL path segments never match.
+const FILE_REFERENCE = /(?:^|[\s`'"(\[<,;])\.?\/?((?:[\w.-]+\/)+[\w.-]+\.[A-Za-z0-9]+)(?::\d+(?::\d+)?)?(?=$|[\s`'"),\]>:;.!?])/g;
+
+/** Sorted unique `path/to/file.ext` references cited in an issue body or title. */
+function extractFileReferences(text) {
+ if (typeof text !== 'string' || !text) return [];
+ const paths = new Set();
+ for (const match of text.matchAll(FILE_REFERENCE)) paths.add(match[1]);
+ return [...paths].sort();
+}
+
+const shaTokens = (text) => [...String(text || '').matchAll(/\b[0-9a-f]{7,40}\b/g)].map((match) => match[0]);
+
+/**
+ * Does this commit revert the pull request? Its subject starts with `Revert`
+ * and its message names the PR (`#N`) or a prefix of at least seven hex digits
+ * of the merge SHA or one of the PR's own commits — a rebase-merged PR has no
+ * merge commit of its own, so the revert body's "This reverts commit <sha>"
+ * names one of the PR's commits instead.
+ */
+function isRevertOf(commit, pullRequest) {
+ if (!/^\s*revert\b/i.test(String(commit?.subject || ''))) return false;
+ const text = `${commit.subject || ''}\n${commit.body || ''}`;
+ if (pullRequest?.number != null && new RegExp(`(?<![\\w#])#${pullRequest.number}(?!\\d)`).test(text)) return true;
+ const shas = [pullRequest?.mergeCommit, ...(pullRequest?.commitShas || [])]
+ .filter((sha) => typeof sha === 'string' && sha.length >= MIN_SHA_PREFIX)
+ .map((sha) => sha.toLowerCase());
+ if (!shas.length) return false;
+ return shaTokens(text.toLowerCase()).some((token) => shas.some((sha) => sha.startsWith(token) || token.startsWith(sha)));
+}
+
+const parseTime = (value) => {
+ const ms = Date.parse(value);
+ return Number.isFinite(ms) ? ms : null;
+};
+
+const closeReason = (issue) => {
+ const reason = String(issue?.stateReason || '').toLowerCase().replace(/[\s-]+/g, '_');
+ if (reason === 'not_planned') return 'not-planned';
+ if (reason === 'duplicate') return 'duplicate';
+ if (reason === 'completed' || reason === '') return 'completed';
+ return null;
+};
+
+const isClosed = (issue) => {
+ const state = String(issue?.state || '').toLowerCase();
+ return state === 'closed' || (state === '' && parseTime(issue?.closedAt) !== null);
+};
+
+function revertsFor(issue, pullRequestsByNumber, commits) {
+ const reverts = [];
+ for (const number of issue.linkedPullRequests || []) {
+ const pullRequest = pullRequestsByNumber.get(number) || { number };
+ const revert = commits.find((commit) => isRevertOf(commit, pullRequest));
+ if (revert) reverts.push({ pullRequest: number, commit: revert.sha || null });
+ }
+ return reverts;
+}
+
+/**
+ * @param {object} input
+ * @param {object[]} input.issues - `{ number, title, labels, createdAt, closedAt, state, stateReason, body, url, linkedPullRequests: number[] }`;
+ * include issues closed up to `refileDays` before the window so a re-file of one is seen.
+ * @param {object[]} input.pullRequests - `{ number, mergeCommit, commitShas }` merged in the window.
+ * @param {object[]} input.commits - `{ sha, subject, body }` on the default branch in the window.
+ * @param {number} [input.from] - epoch ms; defaults to `now - windowDays`. A caller whose
+ * issue read was truncated passes the oldest created time it covered so counts stay honest.
+ * @returns {{ windowDays, refileDays, from, to, lanes: object[] }} one row per lane, catalog order.
+ */
+export function computeLaneHealth({
+ issues = [],
+ pullRequests = [],
+ commits = [],
+ lanes = auditLanes(),
+ now = Date.now(),
+ windowDays = LANE_HEALTH_WINDOW_DAYS,
+ refileDays = LANE_REFILE_WINDOW_DAYS,
+ from = now - windowDays * DAY_MS,
+ flaggedLimit = LANE_HEALTH_FLAGGED_LIMIT,
+} = {}) {
+ const pullRequestsByNumber = new Map(pullRequests.filter((pr) => pr?.number != null).map((pr) => [pr.number, pr]));
+ const refileMs = refileDays * DAY_MS;
+ const byLane = new Map(lanes.map((lane) => [lane.id, []]));
+ for (const issue of issues) {
+ for (const laneId of attributeIssueLanes(issue, lanes)) byLane.get(laneId).push(issue);
+ }
+
+ const rows = lanes.map((lane) => {
+ const laneIssues = byLane.get(lane.id)
+ .filter((issue) => parseTime(issue.createdAt) !== null)
+ .sort((a, b) => parseTime(a.createdAt) - parseTime(b.createdAt) || (a.number ?? 0) - (b.number ?? 0));
+ const closedRefs = laneIssues
+ .filter((issue) => isClosed(issue) && parseTime(issue.closedAt) !== null)
+ .map((issue) => ({ issue, closedAt: parseTime(issue.closedAt), paths: extractFileReferences(`${issue.title || ''}\n${issue.body || ''}`) }))
+ .filter((entry) => entry.paths.length);
+ const inWindow = laneIssues.filter((issue) => {
+ const created = parseTime(issue.createdAt);
+ return created >= from && created <= now;
+ });
+
+ const counts = { filed: inWindow.length, completed: 0, notPlanned: 0, open: 0, reverted: 0, refiled: 0 };
+ const flagged = [];
+ for (const issue of inWindow) {
+ const reasons = [];
+ if (isClosed(issue)) {
+ const reason = closeReason(issue);
+ // A duplicate close is the forge's own "already filed" verdict; it
+ // counts beside not-planned because the lane repeated itself either way.
+ if (reason === 'not-planned' || reason === 'duplicate') {
+ counts.notPlanned += 1;
+ reasons.push({ kind: 'not-planned', stateReason: reason });
+ } else if (reason === 'completed') {
+ counts.completed += 1;
+ }
+ const reverts = revertsFor(issue, pullRequestsByNumber, commits);
+ if (reverts.length) {
+ counts.reverted += 1;
+ reasons.push({ kind: 'reverted', pullRequest: reverts[0].pullRequest, commit: reverts[0].commit });
+ }
+ } else {
+ counts.open += 1;
+ }
+ const created = parseTime(issue.createdAt);
+ const paths = extractFileReferences(`${issue.title || ''}\n${issue.body || ''}`);
+ const earlier = paths.length
+ ? closedRefs.find((entry) => entry.issue !== issue && entry.issue.number !== issue.number
+ && entry.closedAt <= created && created - entry.closedAt <= refileMs
+ && entry.paths.some((path) => paths.includes(path)))
+ : null;
+ if (earlier) {
+ counts.refiled += 1;
+ reasons.push({ kind: 're-filed', of: earlier.issue.number, path: earlier.paths.find((path) => paths.includes(path)) });
+ }
+ if (reasons.length) {
+ flagged.push({ number: issue.number, title: String(issue.title || '').trim(), url: issue.url || null, reasons });
+ }
+ }
+ // Newest first, so the agent sees what it most recently got wrong.
+ flagged.reverse();
+ return { id: lane.id, label: lane.label, metricLabel: lane.metricLabel, ...counts, flagged: flagged.slice(0, flaggedLimit), flaggedTotal: flagged.length };
+ });
+
+ return { windowDays, refileDays, from: new Date(from).toISOString(), to: new Date(now).toISOString(), lanes: rows };
+}
+
+/** One lane's row, by task type, from a computed report. */
+export function laneHealthFor(report, taskType) {
+ return report?.lanes?.find((lane) => lane.id === taskType) || null;
+}
+
+/** Plain-prose reason for a flagged issue, the same in the prompt block and the UI. */
+export function describeLaneFlag(reason) {
+ if (reason?.kind === 'not-planned') return reason.stateReason === 'duplicate' ? 'closed as duplicate' : 'closed as not planned';
+ if (reason?.kind === 'reverted') return `fix reverted${reason.pullRequest != null ? ` (PR #${reason.pullRequest})` : ''}`;
+ if (reason?.kind === 're-filed') return `re-filed${reason.of != null ? ` after #${reason.of}` : ''}${reason.path ? ` on ${reason.path}` : ''}`;
+ return 'flagged';
+}
diff --git a/server/lib/laneHealth.test.js b/server/lib/laneHealth.test.js
new file mode 100644
index 0000000000..5980890538
--- /dev/null
+++ b/server/lib/laneHealth.test.js
@@ -0,0 +1,137 @@
+import { describe, expect, it } from 'vitest';
+import {
+ auditLanes,
+ computeLaneHealth,
+ describeLaneFlag,
+ laneHealthFor,
+} from './laneHealth.js';
+import { AUDIT_DEFINITIONS } from './auditCatalog.js';
+
+const NOW = Date.parse('2026-10-17T12:00:00.000Z');
+const daysAgo = (days) => new Date(NOW - days * 86_400_000).toISOString();
+
+const issue = (number, overrides = {}) => ({
+ number,
+ title: `Finding ${number}`,
+ labels: ['plan', 'code-quality', 'complexity'],
+ createdAt: daysAgo(10),
+ closedAt: daysAgo(8),
+ state: 'closed',
+ stateReason: 'COMPLETED',
+ body: `Problem at server/lib/example.js:42. Fix: server/lib/example.js`,
+ url: `https://example.com/issues/${number}`,
+ linkedPullRequests: [],
+ ...overrides,
+});
+
+describe('laneHealth', () => {
+ it('derives one lane per audit definition and attributes an issue to its most specific lane', () => {
+ const lanes = auditLanes();
+ expect(lanes.map(({ id }) => id)).toEqual(Object.keys(AUDIT_DEFINITIONS));
+ expect(lanes.find(({ id }) => id === 'better-complexity')).toEqual({ id: 'better-complexity', label: 'Cyclomatic complexity', metricLabel: 'complexity', issueLabel: 'code-quality' });
+ // The shared category label yields to the lane label beside it.
+ const report = computeLaneHealth({ now: NOW, issues: [
+ issue(1, { labels: [{ name: 'code-quality' }, { name: 'Simplify' }] }),
+ issue(2, { labels: ['code-quality'] }),
+ issue(3, { labels: ['ux', 'copy'] }),
+ issue(4, { labels: ['bug', 'model:heavy'] }),
+ ] });
+ const filed = Object.fromEntries(report.lanes.filter(({ filed }) => filed).map(({ id, filed }) => [id, filed]));
+ expect(filed).toEqual({ simplify: 1, 'code-quality': 1, copy: 1 });
+ });
+
+ it('matches re-filed findings on file:line citations and ignores URLs and bare words', () => {
+ const closed = (number, body) => issue(number, { createdAt: daysAgo(20), closedAt: daysAgo(15), body });
+ const report = computeLaneHealth({ now: NOW, issues: [
+ closed(1, 'Problem in `server/lib/foo.js:12`'),
+ closed(2, 'see (client/src/App.jsx:3:4)'),
+ closed(3, 'see ./scripts/run.sh.'),
+ closed(4, 'Not https://example.com/x/y.js'),
+ closed(5, 'nor README.md or 1.2.3'),
+ issue(10, { createdAt: daysAgo(5), body: 'Again server/lib/foo.js, client/src/App.jsx:9 and scripts/run.sh:1' }),
+ issue(11, { createdAt: daysAgo(5), body: 'https://example.com/x/y.js README.md 1.2.3 x/y.js' }),
+ ] });
+ const lane = laneHealthFor(report, 'better-complexity');
+ expect(lane.refiled).toBe(1);
+ expect(lane.flagged).toEqual([expect.objectContaining({ number: 10, reasons: [{ kind: 're-filed', of: 1, path: 'server/lib/foo.js' }] })]);
+ });
+
+ it('matches a revert by PR number, merge SHA prefix, or one of the PR\'s own commits', () => {
+ const pr = { number: 120, mergeCommit: 'abcdef1234567890abcdef1234567890abcdef12', commitShas: ['0123456789abcdef0123456789abcdef01234567'] };
+ const reverted = (commit, pullRequest = pr) => laneHealthFor(computeLaneHealth({
+ now: NOW, issues: [issue(1, { linkedPullRequests: [pullRequest.number] })], pullRequests: [pullRequest], commits: [{ sha: 'f00', ...commit }],
+ }), 'better-complexity').reverted === 1;
+ expect(reverted({ subject: 'Revert "feat: thing (#120)"', body: '' })).toBe(true);
+ expect(reverted({ subject: 'Revert "feat: thing"', body: 'This reverts commit abcdef1234567890abcdef1234567890abcdef12.' })).toBe(true);
+ expect(reverted({ subject: 'revert: feat thing', body: 'This reverts commit 0123456789abcdef.' })).toBe(true);
+ // Not a revert, a different PR, a different SHA, or a prefix too short to trust.
+ expect(reverted({ subject: 'feat: re-land #120', body: 'This reverts commit abcdef1234567890' })).toBe(false);
+ expect(reverted({ subject: 'Revert "feat: other (#1200)"', body: '' })).toBe(false);
+ expect(reverted({ subject: 'Revert "feat: other"', body: 'This reverts commit ffffff1234567.' })).toBe(false);
+ expect(reverted({ subject: 'Revert "feat: other"', body: 'This reverts commit abcdef.' })).toBe(false);
+ // An issue whose PR record is missing still matches by number alone.
+ expect(laneHealthFor(computeLaneHealth({ now: NOW, issues: [issue(1, { linkedPullRequests: [77] })], commits: [{ sha: 'f00', subject: 'Revert "fix (#77)"', body: '' }] }), 'better-complexity').reverted).toBe(1);
+ });
+
+ it('counts filed, completed, not-planned, open, reverted and re-filed per lane over the window', () => {
+ const issues = [
+ issue(1),
+ issue(2, { stateReason: 'NOT_PLANNED', body: 'Nothing to cite' }),
+ issue(3, { stateReason: 'DUPLICATE', body: 'Nothing to cite' }),
+ issue(4, { state: 'open', closedAt: null, stateReason: null, createdAt: daysAgo(2), body: 'Still open' }),
+ // Fixed by PR 120, which a later commit reverted.
+ issue(5, { linkedPullRequests: [120], body: 'server/services/jobs.js:10' }),
+ // Closed 20 days ago; #6 re-files its path 5 days later.
+ issue(8, { createdAt: daysAgo(25), closedAt: daysAgo(20), body: 'Hotspot in server/routes/api.js:5' }),
+ issue(6, { createdAt: daysAgo(15), closedAt: daysAgo(14), body: 'Again server/routes/api.js:9' }),
+ // Cites a path last closed 70 days ago: outside the re-file window, so not a repeat.
+ issue(7, { createdAt: daysAgo(1), state: 'open', closedAt: null, body: 'server/lib/old.js:3 once more', labels: ['code-quality', 'complexity'] }),
+ // Outside the window: still an earlier closed reference, never a filed count.
+ issue(9, { createdAt: daysAgo(80), closedAt: daysAgo(70), body: 'server/lib/old.js:1' }),
+ // Another lane; the shared category label does not pull it into complexity.
+ issue(10, { labels: ['code-quality', 'simplify'], stateReason: 'NOT_PLANNED' }),
+ ];
+ const pullRequests = [{ number: 120, mergeCommit: 'abcdef1234567890abcdef1234567890abcdef12', commitShas: [] }];
+ const commits = [
+ { sha: '1111111111111111111111111111111111111111', subject: 'feat: unrelated', body: '' },
+ { sha: '2222222222222222222222222222222222222222', subject: 'Revert "fix: jobs (#120)"', body: 'This reverts commit abcdef1234567890abcdef1234567890abcdef12.' },
+ ];
+ const report = computeLaneHealth({ issues, pullRequests, commits, now: NOW });
+ expect(report).toMatchObject({ windowDays: 60, refileDays: 30, from: daysAgo(60), to: new Date(NOW).toISOString() });
+ expect(report.lanes.map(({ id }) => id)).toEqual(Object.keys(AUDIT_DEFINITIONS));
+
+ const complexity = laneHealthFor(report, 'better-complexity');
+ expect(complexity).toMatchObject({ metricLabel: 'complexity', filed: 8, completed: 4, notPlanned: 2, open: 2, reverted: 1, refiled: 1, flaggedTotal: 4 });
+ expect(complexity.flagged.map(({ number }) => number)).toEqual([5, 3, 2, 6]);
+ expect(complexity.flagged.find(({ number }) => number === 5).reasons).toEqual([{ kind: 'reverted', pullRequest: 120, commit: '2222222222222222222222222222222222222222' }]);
+ expect(complexity.flagged.find(({ number }) => number === 6).reasons).toEqual([{ kind: 're-filed', of: 8, path: 'server/routes/api.js' }]);
+ expect(complexity.flagged.find(({ number }) => number === 3).reasons).toEqual([{ kind: 'not-planned', stateReason: 'duplicate' }]);
+ expect(complexity.flagged[3]).toMatchObject({ number: 6, title: 'Finding 6', url: 'https://example.com/issues/6' });
+
+ const simplify = laneHealthFor(report, 'simplify');
+ expect(simplify).toMatchObject({ filed: 1, notPlanned: 1, completed: 0, reverted: 0, refiled: 0 });
+ expect(laneHealthFor(report, 'code-quality')).toMatchObject({ filed: 0, flagged: [] });
+ expect(laneHealthFor(report, 'missing-lane')).toBeNull();
+ });
+
+ it('honors an explicit window start, the flagged cap, and reads GitLab-shaped issues without a state reason as completed', () => {
+ const issues = Array.from({ length: 12 }, (_, index) => issue(index + 1, {
+ createdAt: daysAgo(index + 1), closedAt: daysAgo(index + 0.5), stateReason: 'NOT_PLANNED', body: 'none',
+ }));
+ const report = computeLaneHealth({ issues, now: NOW, from: NOW - 5 * 86_400_000, flaggedLimit: 3 });
+ const lane = laneHealthFor(report, 'better-complexity');
+ expect(report.from).toBe(daysAgo(5));
+ expect(lane).toMatchObject({ filed: 5, notPlanned: 5, flaggedTotal: 5 });
+ expect(lane.flagged.map(({ number }) => number)).toEqual([1, 2, 3]);
+
+ const gitlab = computeLaneHealth({ issues: [issue(1, { state: 'closed', stateReason: undefined }), issue(2, { state: 'opened', closedAt: null, stateReason: undefined })], now: NOW });
+ expect(laneHealthFor(gitlab, 'better-complexity')).toMatchObject({ filed: 2, completed: 1, open: 1, notPlanned: 0 });
+ });
+
+ it('describes each flag the same way for the prompt block and the UI', () => {
+ expect(describeLaneFlag({ kind: 'not-planned' })).toBe('closed as not planned');
+ expect(describeLaneFlag({ kind: 'not-planned', stateReason: 'duplicate' })).toBe('closed as duplicate');
+ expect(describeLaneFlag({ kind: 'reverted', pullRequest: 9 })).toBe('fix reverted (PR #9)');
+ expect(describeLaneFlag({ kind: 're-filed', of: 4, path: 'a/b.js' })).toBe('re-filed after #4 on a/b.js');
+ });
+});
diff --git a/server/lib/taskDataInputCatalog.js b/server/lib/taskDataInputCatalog.js
index 7cfe9d7240..a8362c798c 100644
--- a/server/lib/taskDataInputCatalog.js
+++ b/server/lib/taskDataInputCatalog.js
@@ -13,6 +13,7 @@ export const TASK_DATA_INPUT_DEFINITIONS = Object.freeze([
Object.freeze({ id: 'open-pull-requests', label: 'Open pull requests', description: 'Include the target repository\'s current open pull or merge requests.', requiresApp: true }),
Object.freeze({ id: 'closed-unmerged-pull-requests', label: 'Closed unmerged pull requests', description: 'Include recently closed pull or merge requests that were not merged.', requiresApp: true }),
Object.freeze({ id: 'audit-slice-history', label: 'Recent audit slices', description: 'Include the areas this audit lane deep-reviewed in its last eight runs for the app, so the run rotates to other areas.', requiresApp: true }),
+ Object.freeze({ id: 'lane-health', label: 'Lane health', description: 'Include what became of the issues this audit lane filed in the last 60 days (completed, not planned, reverted, re-filed) so the run does not repeat a rejected finding.', requiresApp: true }),
]);
export const TASK_DATA_INPUT_IDS = Object.freeze(TASK_DATA_INPUT_DEFINITIONS.map(({ id }) => id));
diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.js
index 0eec6c416f..6daae88017 100644
--- a/server/routes/apps/crud.js
+++ b/server/routes/apps/crud.js
@@ -1,6 +1,7 @@
import { appListQuerySchema, appQualityQuerySchema, appQualityHistoryQuerySchema, appQualityFederationQuerySchema } from '../../lib/auditQuality.js';
import { exportPortosQuality } from '../../services/appQualityFederation.js';
import { enrichAppsWithQuality, getAppQualityHistory } from '../../services/appQuality.js';
+import { getAppLaneHealth } from '../../services/appLaneHealth.js';
import { publishAppQualitySnapshot } from '../../services/appQualitySnapshotFile.js';
/**
* App CRUD + status enrichment + archive lifecycle.
@@ -84,6 +85,12 @@ router.get('/:id/quality-history', loadApp, asyncHandler(async (req, res) => {
res.json(await getAppQualityHistory(req.loadedApp, days));
}));
+// GET /api/apps/:id/lane-health - What became of each audit lane's filed issues
+// (#12088): a forge read on request, never cached into the app record.
+router.get('/:id/lane-health', loadApp, asyncHandler(async (req, res) => {
+ res.json(await getAppLaneHealth(req.loadedApp));
+}));
+
// POST /api/apps/:id/quality-snapshot - Land this app's numeric snapshot as
// `.quality.json` through an immediately-merged PR. Deliberately NOT gated on
// publishQualitySnapshot: the toggle automates the audit hook, a manual call
diff --git a/server/routes/apps/crud.test.js b/server/routes/apps/crud.test.js
index cd9214222e..bd8605d8fb 100644
--- a/server/routes/apps/crud.test.js
+++ b/server/routes/apps/crud.test.js
@@ -2,6 +2,7 @@ vi.mock('../../services/appQualityFederation.js', () => ({ exportPortosQuality:
import { exportPortosQuality } from '../../services/appQualityFederation.js';
vi.mock('../../services/appQuality.js', () => ({ getAppQualityHistory: vi.fn(async () => ({ points: [], days: 90 })), enrichAppsWithQuality: vi.fn(async apps => apps.map(app => ({ ...app, quality: { score: 75 } }))) }));
vi.mock('../../services/appQualitySnapshotFile.js', () => ({ publishAppQualitySnapshot: vi.fn(async () => ({ published: true, hash: 'abc1234', path: '.quality.json' })) }));
+vi.mock('../../services/appLaneHealth.js', () => ({ getAppLaneHealth: vi.fn(async () => ({ available: true, windowDays: 60, lanes: [] })) }));
import { describe, it, expect, vi, beforeEach } from 'vitest';
import express from 'express';
import { execFileSync } from 'child_process';
@@ -13,6 +14,7 @@ import { errorEvents } from '../../lib/errorHandler.js';
import crudRoutes from './crud.js';
import { enrichAppsWithQuality, getAppQualityHistory } from '../../services/appQuality.js';
import { publishAppQualitySnapshot } from '../../services/appQualitySnapshotFile.js';
+import { getAppLaneHealth } from '../../services/appLaneHealth.js';
// Mock the services this router (and its port-config service) touch.
vi.mock('../../services/apps.js', () => ({
@@ -221,6 +223,13 @@ describe('Apps CRUD Routes', () => {
expect(history.status).toBe(200);
expect(getAppQualityHistory).toHaveBeenCalledWith({ id: 'portos-default', name: 'PortOS', type: 'ios-native' }, 90);
expect((await request(app).get('/api/apps/portos-default/quality-history?days=9999')).status).toBe(400);
+ // Lane health (#12088) is a forge read on request for the loaded app, never cached on the record.
+ const laneHealth = await request(app).get('/api/apps/portos-default/lane-health');
+ expect(laneHealth.status).toBe(200);
+ expect(laneHealth.body).toEqual({ available: true, windowDays: 60, lanes: [] });
+ expect(getAppLaneHealth).toHaveBeenCalledWith({ id: 'portos-default', name: 'PortOS', type: 'ios-native' });
+ appsService.getAppById.mockResolvedValueOnce(null);
+ expect((await request(app).get('/api/apps/missing/lane-health')).status).toBe(404);
});
it('should handle apps with no PM2 processes', async () => {
diff --git a/server/services/appLaneHealth.js b/server/services/appLaneHealth.js
new file mode 100644
index 0000000000..7c89488767
--- /dev/null
+++ b/server/services/appLaneHealth.js
@@ -0,0 +1,184 @@
+/**
+ * Lane health for an app's audit lanes (#12088): the forge and git reads behind
+ * `lib/laneHealth.js`. One read per source; the `lane-health` task data input
+ * narrows the issue read to the running lane's metric label, the Quality page
+ * reads every lane at once.
+ */
+
+import { execGit } from '../lib/execGit.js';
+import { safeJSONParse } from '../lib/fileUtils.js';
+import { normalizeAuditTaskType } from '../lib/auditCatalog.js';
+import { auditLanes, computeLaneHealth, LANE_HEALTH_WINDOW_DAYS, LANE_REFILE_WINDOW_DAYS } from '../lib/laneHealth.js';
+import { resolveAppWorkTracker } from '../lib/workTracker.js';
+import { resolveForgeTokenEnv } from './forgeAuth.js';
+import { describeForgeReadFailure, resolveForgeContext, runForgeCli } from './taskDataInputs.js';
+
+const DAY_MS = 86_400_000;
+// Every lane of a busy install files thousands of issues in a window; the page
+// read stops here and reports the window it actually covered.
+const ALL_LANES_ISSUE_LIMIT = 1000;
+const ONE_LANE_ISSUE_LIMIT = 500;
+const PULL_REQUEST_LIMIT = 300;
+const GIT_TIMEOUT_MS = 15_000;
+const CLOSING_KEYWORD = /\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\s*:?\s+#(\d+)/gi;
+
+const dateOnly = (ms) => new Date(ms).toISOString().slice(0, 10);
+const labelNames = (labels) => (Array.isArray(labels) ? labels : [])
+ .map((label) => (typeof label === 'string' ? label : label?.name)).filter(Boolean);
+const closingIssueNumbers = (text) => [...String(text || '').matchAll(CLOSING_KEYWORD)].map((match) => Number(match[1]));
+
+function normalizeIssue(cli, item) {
+ if (cli === 'glab') {
+ return {
+ number: item.iid, title: item.title || '', labels: labelNames(item.labels),
+ createdAt: item.created_at || null, closedAt: item.closed_at || null,
+ state: String(item.state || '').toLowerCase() === 'opened' ? 'open' : String(item.state || '').toLowerCase(),
+ // GitLab has no close reason; a closed issue reads as completed.
+ stateReason: null, body: item.description || '', url: item.web_url || null, linkedPullRequests: [],
+ };
+ }
+ return {
+ number: item.number, title: item.title || '', labels: labelNames(item.labels),
+ createdAt: item.createdAt || null, closedAt: item.closedAt || null,
+ state: String(item.state || '').toLowerCase(), stateReason: item.stateReason || null,
+ body: item.body || '', url: item.url || null,
+ linkedPullRequests: (item.closedByPullRequestsReferences || []).map((ref) => ref?.number).filter((n) => n != null),
+ };
+}
+
+function normalizePullRequest(cli, item) {
+ if (cli === 'glab') {
+ return {
+ number: item.iid, mergeCommit: item.merge_commit_sha || null,
+ commitShas: [item.sha].filter(Boolean), closesIssues: closingIssueNumbers(item.description),
+ };
+ }
+ return {
+ number: item.number, mergeCommit: item.mergeCommit?.oid || null,
+ // Only the oids: the commits payload also carries author identities.
+ commitShas: (item.commits || []).map((commit) => commit?.oid).filter(Boolean),
+ closesIssues: [
+ ...(item.closingIssuesReferences || []).map((ref) => ref?.number).filter((n) => n != null),
+ ...closingIssueNumbers(item.body),
+ ],
+ };
+}
+
+function parseRows(cli, result) {
+ if (result.code !== 0 || !result.stdout.trim()) return { ok: false, error: result.code !== 0 ? (result.stderr || '') : `${cli} returned no parseable list` };
+ const parsed = safeJSONParse(result.stdout, null, { logError: false });
+ return Array.isArray(parsed) ? { ok: true, rows: parsed } : { ok: false, error: `${cli} returned no parseable list` };
+}
+
+/** Issues created since `since` (epoch ms), newest first; `label` narrows to one lane. */
+async function listForgeIssuesSince({ cli, cwd, env, since, label = null, limit = ALL_LANES_ISSUE_LIMIT, exec = runForgeCli } = {}) {
+ if (!cwd || (cli !== 'gh' && cli !== 'glab')) return { ok: false, issues: [], truncated: false };
+ const args = cli === 'glab'
+ ? ['issue', 'list', '--all', '-P', String(limit), ...(label ? ['--label', label] : [])]
+ : [
+ 'issue', 'list', '--state', 'all', '--limit', String(limit),
+ '--search', `created:>=${dateOnly(since)} sort:created-desc`,
+ ...(label ? ['--label', label] : []),
+ '--json', 'number,title,labels,createdAt,closedAt,state,stateReason,body,url,closedByPullRequestsReferences',
+ ];
+ const parsed = parseRows(cli, await exec(cli, args, { cwd, env }));
+ if (!parsed.ok) return { ok: false, issues: [], truncated: false, error: parsed.error };
+ const issues = parsed.rows.map((item) => normalizeIssue(cli, item))
+ .filter((issue) => !Number.isFinite(Date.parse(issue.createdAt)) || Date.parse(issue.createdAt) >= since);
+ return { ok: true, issues, truncated: parsed.rows.length >= limit };
+}
+
+/** Pull/merge requests merged since `since`, with the SHAs a revert could name. */
+async function listForgeMergedPullRequestsSince({ cli, cwd, env, since, limit = PULL_REQUEST_LIMIT, exec = runForgeCli } = {}) {
+ if (!cwd || (cli !== 'gh' && cli !== 'glab')) return { ok: false, items: [] };
+ const args = cli === 'glab'
+ ? ['mr', 'list', '--merged', '-P', String(limit)]
+ : [
+ 'pr', 'list', '--state', 'merged', '--limit', String(limit),
+ '--search', `merged:>=${dateOnly(since)} sort:updated-desc`,
+ '--json', 'number,mergeCommit,commits,closingIssuesReferences,body',
+ ];
+ const parsed = parseRows(cli, await exec(cli, args, { cwd, env }));
+ if (!parsed.ok) return { ok: false, items: [], error: parsed.error };
+ return { ok: true, items: parsed.rows.map((item) => normalizePullRequest(cli, item)) };
+}
+
+/**
+ * Commits since `since` whose message has a line starting with "Revert" — a
+ * cheap prefilter; `computeLaneHealth` re-checks the subject. `null` when git fails,
+ * so a broken checkout is not read as "nothing was reverted".
+ */
+async function listRevertCommitsSince(repoPath, since, { runGit = execGit } = {}) {
+ if (!repoPath) return null;
+ const result = await runGit(
+ ['log', `--since=${new Date(since).toISOString()}`, '-i', '--grep=^revert', '--format=%H%x1f%s%x1f%b%x1e', 'HEAD'],
+ repoPath,
+ { ignoreExitCode: true, timeout: GIT_TIMEOUT_MS },
+ ).catch(() => null);
+ if (!result || result.exitCode !== 0) return null;
+ return result.stdout.split('\x1e').map((record) => record.trim()).filter(Boolean).map((record) => {
+ const [sha, subject = '', body = ''] = record.split('\x1f');
+ return { sha: sha.trim(), subject: subject.trim(), body: body.trim() };
+ });
+}
+
+/**
+ * @param {object} app - managed app (`repoPath`)
+ * @param {object} options
+ * @param {object|null} options.forge - resolved `{ cli, env, host }` (see `resolveForgeContext`)
+ * @param {string|null} [options.taskType] - one audit lane; omitted reads every lane
+ * @returns {Promise<object>} `{ ok: false, reason, error? }` or the `computeLaneHealth` report
+ * plus `ok: true`, `truncated` and `partial` (sources whose read failed).
+ */
+export async function collectLaneHealth(app, { forge, taskType = null, now = Date.now(), deps = {} } = {}) {
+ if (!forge || !app?.repoPath) return { ok: false, reason: 'forge-unavailable' };
+ const lanes = auditLanes();
+ const lane = taskType ? lanes.find((candidate) => candidate.id === normalizeAuditTaskType(taskType)) : null;
+ if (taskType && !lane) return { ok: false, reason: 'not-an-audit-lane' };
+ const windowDays = LANE_HEALTH_WINDOW_DAYS;
+ const refileDays = LANE_REFILE_WINDOW_DAYS;
+ const from = now - windowDays * DAY_MS;
+ const forgeOptions = { cli: forge.cli, cwd: app.repoPath, env: forge.env };
+ // `deps.exec` / `deps.runGit` replace the forge CLI and git spawns.
+ const exec = deps.exec || runForgeCli;
+ const [issues, pullRequests, commits] = await Promise.all([
+ listForgeIssuesSince({ ...forgeOptions, since: from - refileDays * DAY_MS, label: lane?.metricLabel ?? null, limit: lane ? ONE_LANE_ISSUE_LIMIT : ALL_LANES_ISSUE_LIMIT, exec }),
+ listForgeMergedPullRequestsSince({ ...forgeOptions, since: from, exec }),
+ listRevertCommitsSince(app.repoPath, from, { runGit: deps.runGit || execGit }),
+ ]);
+ if (!issues.ok) return { ok: false, reason: 'issues', error: issues.error };
+
+ const partial = [...(pullRequests.ok ? [] : ['pull-requests']), ...(commits === null ? ['commits'] : [])];
+ // A closing reference recorded on the PR side links the issue the same way
+ // the forge's own issue-side reference does.
+ const linkedByIssue = new Map();
+ for (const pullRequest of pullRequests.ok ? pullRequests.items : []) {
+ for (const number of pullRequest.closesIssues) linkedByIssue.set(number, [...(linkedByIssue.get(number) || []), pullRequest.number]);
+ }
+ const linkedIssues = issues.issues.map((issue) => ({
+ ...issue, linkedPullRequests: [...new Set([...issue.linkedPullRequests, ...(linkedByIssue.get(issue.number) || [])])],
+ }));
+ // A truncated read covers only the newest issues; count from the oldest one seen.
+ const createdTimes = linkedIssues.map((issue) => Date.parse(issue.createdAt)).filter(Number.isFinite);
+ const oldestCreated = issues.truncated && createdTimes.length ? Math.max(from, Math.min(...createdTimes)) : from;
+ const report = computeLaneHealth({
+ issues: linkedIssues, pullRequests: pullRequests.ok ? pullRequests.items : [], commits: commits || [],
+ lanes: lane ? [lane] : lanes, now, windowDays, refileDays, from: oldestCreated,
+ });
+ return { ok: true, ...report, truncated: issues.truncated, partial };
+}
+
+/** The Quality page read: every lane, with the forge resolved from the app's tracker. */
+export async function getAppLaneHealth(app, deps = {}) {
+ const forge = await resolveForgeContext(app, {
+ resolveTracker: resolveAppWorkTracker, resolveTokenEnv: resolveForgeTokenEnv, environment: process.env, ...deps,
+ }).catch(() => null);
+ const result = await collectLaneHealth(app, { forge, now: deps.now, deps });
+ if (!result.ok) {
+ const error = result.error != null ? describeForgeReadFailure({ cli: forge?.cli, stderr: result.error, host: forge?.host }) : null;
+ if (error) console.warn(`⚠️ Lane health unavailable for ${app?.id}: ${error}`);
+ return { available: false, reason: result.reason, ...(error ? { error } : {}) };
+ }
+ const { ok, ...health } = result;
+ return { available: true, ...health };
+}
diff --git a/server/services/appLaneHealth.test.js b/server/services/appLaneHealth.test.js
new file mode 100644
index 0000000000..a3a86d3f12
--- /dev/null
+++ b/server/services/appLaneHealth.test.js
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi } from 'vitest';
+import { collectLaneHealth, getAppLaneHealth } from './appLaneHealth.js';
+
+const NOW = Date.parse('2026-10-17T12:00:00.000Z');
+const DAY = 86_400_000;
+const APP = { id: 'app-1', name: 'Example App', repoPath: '/repo' };
+const GH = { cli: 'gh', env: { PATH: '/bin' }, host: 'github.com' };
+const GLAB = { cli: 'glab', env: {}, host: 'gitlab.example.com' };
+const iso = (daysAgo) => new Date(NOW - daysAgo * DAY).toISOString();
+
+// One fake per spawn: the forge CLI answers by subcommand, git by its log call.
+const forgeExec = ({ issues = [], pullRequests = [] } = {}) => vi.fn(async (_cli, args) => {
+ const rows = args[0] === 'issue' ? issues : pullRequests;
+ return rows instanceof Error ? { code: -1, stdout: '', stderr: rows.message } : { code: 0, stdout: JSON.stringify(rows) };
+});
+const gitLog = (records) => vi.fn(async () => ({ exitCode: 0, stdout: records.map(({ sha, subject, body = '' }) => `${sha}\x1f${subject}\x1f${body}\x1e\n`).join('') }));
+
+describe('appLaneHealth', () => {
+ it('reads one GitHub lane through gh and git, linking PRs either way and matching a rebase-merged revert', async () => {
+ const exec = forgeExec({
+ issues: [
+ { number: 5, title: 'Hotspot', labels: [{ name: 'code-quality' }, { name: 'complexity' }], createdAt: iso(10), closedAt: iso(9), state: 'CLOSED', stateReason: 'COMPLETED', body: 'server/a.js:1', url: 'https://example.com/5', closedByPullRequestsReferences: [{ number: 50 }] },
+ { number: 6, title: 'Linked from the PR side', labels: ['complexity'], createdAt: iso(8), closedAt: iso(7), state: 'CLOSED', stateReason: 'COMPLETED', body: '', closedByPullRequestsReferences: [] },
+ { number: 4, title: 'Older than the re-file lookback', labels: ['complexity'], createdAt: iso(200), state: 'CLOSED' },
+ ],
+ pullRequests: [
+ { number: 50, mergeCommit: null, commits: [{ oid: 'def1234567890', authors: [{ email: '[email protected]' }] }], closingIssuesReferences: [], body: '' },
+ { number: 51, mergeCommit: { oid: 'abc9876543210' }, commits: [], closingIssuesReferences: [], body: 'Fixes #6' },
+ ],
+ });
+ const runGit = gitLog([
+ { sha: 'aaaa111', subject: 'Revert "fix: hotspot"', body: 'This reverts commit def1234567890.' },
+ { sha: 'bbbb222', subject: 'Revert "fix: path (#51)"' },
+ ]);
+ const result = await collectLaneHealth(APP, { forge: GH, taskType: 'better-complexity', now: NOW, deps: { exec, runGit } });
+
+ expect(exec).toHaveBeenCalledWith('gh', [
+ 'issue', 'list', '--state', 'all', '--limit', '500', '--search', 'created:>=2026-07-19 sort:created-desc', '--label', 'complexity',
+ '--json', 'number,title,labels,createdAt,closedAt,state,stateReason,body,url,closedByPullRequestsReferences',
+ ], { cwd: '/repo', env: GH.env });
+ expect(exec).toHaveBeenCalledWith('gh', expect.arrayContaining(['pr', 'list', '--state', 'merged', '--search', 'merged:>=2026-08-18 sort:updated-desc']), { cwd: '/repo', env: GH.env });
+ expect(runGit).toHaveBeenCalledWith(['log', '--since=2026-08-18T12:00:00.000Z', '-i', '--grep=^revert', '--format=%H%x1f%s%x1f%b%x1e', 'HEAD'], '/repo', expect.objectContaining({ ignoreExitCode: true }));
+ expect(result).toMatchObject({ ok: true, truncated: false, partial: [], windowDays: 60, refileDays: 30 });
+ expect(result.lanes).toHaveLength(1);
+ expect(result.lanes[0]).toMatchObject({ id: 'better-complexity', filed: 2, completed: 2, reverted: 2 });
+ expect(result.lanes[0].flagged.map(({ number, reasons }) => [number, reasons])).toEqual([
+ [6, [{ kind: 'reverted', pullRequest: 51, commit: 'bbbb222' }]],
+ [5, [{ kind: 'reverted', pullRequest: 50, commit: 'aaaa111' }]],
+ ]);
+ // The commit payload's author identities never leave the adapter.
+ expect(JSON.stringify(result)).not.toContain('alice');
+ });
+
+ it('reads every lane through glab, treating closed GitLab issues as completed and closing keywords as links', async () => {
+ const exec = forgeExec({
+ issues: [
+ { iid: 7, title: 'Drift', labels: ['simplify'], created_at: iso(10), closed_at: iso(9), state: 'closed', description: 'lib/x.js:3', web_url: 'https://gitlab.example.com/7' },
+ { iid: 8, title: 'Open', labels: ['complexity'], created_at: iso(5), state: 'opened', description: '' },
+ ],
+ pullRequests: [{ iid: 70, merge_commit_sha: 'abc1234567', sha: 'def1234567', description: 'Closes #7' }],
+ });
+ const runGit = gitLog([{ sha: 'cccc333', subject: 'Revert "drift"', body: 'This reverts commit abc1234567.' }]);
+ const result = await collectLaneHealth(APP, { forge: GLAB, now: NOW, deps: { exec, runGit } });
+ expect(exec).toHaveBeenCalledWith('glab', ['issue', 'list', '--all', '-P', '1000'], expect.any(Object));
+ expect(exec).toHaveBeenCalledWith('glab', ['mr', 'list', '--merged', '-P', '300'], expect.any(Object));
+ expect(result.lanes.length).toBeGreaterThan(20);
+ expect(result.lanes.find(({ id }) => id === 'simplify')).toMatchObject({ filed: 1, completed: 1, reverted: 1 });
+ expect(result.lanes.find(({ id }) => id === 'better-complexity')).toMatchObject({ filed: 1, open: 1 });
+ });
+
+ it('shortens a truncated window and names failed PR and commit reads instead of reading them as no reverts', async () => {
+ const issues = [
+ { number: 9, title: 'Newest', labels: ['complexity'], createdAt: iso(3), state: 'OPEN' },
+ { number: 8, title: 'Oldest seen', labels: ['complexity'], createdAt: iso(20), state: 'OPEN' },
+ ];
+ const exec = forgeExec({ issues, pullRequests: new Error('gh: HTTP 500') });
+ const result = await collectLaneHealth(APP, { forge: GH, taskType: 'better-complexity', now: NOW, deps: { exec, runGit: vi.fn().mockResolvedValue({ exitCode: 128, stdout: '' }) } });
+ expect(result).toMatchObject({ ok: true, truncated: false, partial: ['pull-requests', 'commits'] });
+
+ const full = Array.from({ length: 500 }, (_, index) => ({ ...issues[0], number: 1000 + index, createdAt: iso(3 + index / 100) }));
+ const truncated = await collectLaneHealth(APP, { forge: GH, taskType: 'better-complexity', now: NOW, deps: { exec: forgeExec({ issues: full }), runGit: vi.fn().mockRejectedValue(new Error('timeout')) } });
+ expect(truncated).toMatchObject({ ok: true, truncated: true, partial: ['commits'], from: iso(3 + 499 / 100) });
+ expect(truncated.lanes[0].filed).toBe(500);
+ });
+
+ it('separates a failed or unusable forge from an empty one', async () => {
+ const empty = await collectLaneHealth(APP, { forge: GH, taskType: 'better-complexity', now: NOW, deps: { exec: forgeExec(), runGit: gitLog([]) } });
+ expect(empty.lanes[0]).toMatchObject({ filed: 0, flagged: [] });
+ const blank = vi.fn().mockResolvedValue({ code: 0, stdout: ' ' });
+ expect(await collectLaneHealth(APP, { forge: GH, now: NOW, deps: { exec: blank, runGit: gitLog([]) } })).toEqual({ ok: false, reason: 'issues', error: 'gh returned no parseable list' });
+ const failed = forgeExec({ issues: new Error('gh: HTTP 502') });
+ expect(await collectLaneHealth(APP, { forge: GH, now: NOW, deps: { exec: failed, runGit: gitLog([]) } })).toEqual({ ok: false, reason: 'issues', error: 'gh: HTTP 502' });
+ expect(await collectLaneHealth(APP, { forge: null, now: NOW })).toEqual({ ok: false, reason: 'forge-unavailable' });
+ expect(await collectLaneHealth(APP, { forge: GH, taskType: 'plan-feature', now: NOW })).toEqual({ ok: false, reason: 'not-an-audit-lane' });
+ });
+
+ it('resolves the forge for the page read and answers unavailable with the remedy instead of throwing', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const exec = forgeExec();
+ const deps = {
+ now: NOW,
+ resolveTracker: vi.fn().mockResolvedValue({ forge: 'gh', host: 'github.com' }),
+ resolveTokenEnv: vi.fn().mockResolvedValue({ GH_TOKEN: 'test-token' }),
+ environment: { PATH: '/bin' },
+ exec,
+ runGit: gitLog([]),
+ };
+ const available = await getAppLaneHealth(APP, deps);
+ expect(available).toMatchObject({ available: true, truncated: false, partial: [], windowDays: 60 });
+ expect(available.ok).toBeUndefined();
+ expect(exec).toHaveBeenCalledWith('gh', expect.any(Array), { cwd: '/repo', env: { PATH: '/bin', GH_TOKEN: 'test-token' } });
+
+ deps.exec = forgeExec({ issues: new Error('To get started with GitHub CLI, please run: gh auth login') });
+ expect(await getAppLaneHealth(APP, deps)).toMatchObject({ available: false, reason: 'issues', error: expect.stringContaining('gh auth login') });
+ expect(warn).toHaveBeenCalledTimes(1);
+
+ deps.resolveTracker.mockResolvedValueOnce({ forge: 'jira' });
+ expect(await getAppLaneHealth(APP, deps)).toEqual({ available: false, reason: 'forge-unavailable' });
+ warn.mockRestore();
+ });
+});
diff --git a/server/services/taskDataInputs.js b/server/services/taskDataInputs.js
index c8b9df08ef..3dbb4d3d71 100644
--- a/server/services/taskDataInputs.js
+++ b/server/services/taskDataInputs.js
@@ -15,7 +15,8 @@ import { DISPATCH_HINT_READING_GUIDANCE } from '../lib/dispatchLabels.js';
import { TASK_DATA_INPUT_DEFINITIONS } from '../lib/taskDataInputCatalog.js';
import { githubApiHost, resolveAppWorkTracker } from '../lib/workTracker.js';
import { PORTOS_APP_ID } from '../lib/appIdentity.js';
-import { isAuditTaskType } from '../lib/auditCatalog.js';
+import { isAuditTaskType, normalizeAuditTaskType } from '../lib/auditCatalog.js';
+import { describeLaneFlag, laneHealthFor } from '../lib/laneHealth.js';
import { resolveForgeTokenEnv } from './forgeAuth.js';
import { classifyGhProbe, execGh, ghRemedy } from './github.js';
import { execGlabJson } from './gitlab.js';
@@ -128,7 +129,7 @@ export function renderForgeItems(items, { emptyMessage }) {
return truncateWithNotice(lines.join('\n'), MAX_INPUT_CHARS);
}
-async function runForgeCli(cli, args, { cwd, env } = {}) {
+export async function runForgeCli(cli, args, { cwd, env } = {}) {
if (cli === 'gh') {
let stderr = '';
const stdout = await execGh(args, FORGE_TIMEOUT_MS, { cwd, env }).catch((err) => {
@@ -223,7 +224,7 @@ function forgeUnavailable(label, forge, result) {
return unavailableMessage(label, reason);
}
-async function resolveForgeContext(app, deps) {
+export async function resolveForgeContext(app, deps) {
if (!app?.repoPath) return null;
const tracker = await deps.resolveTracker(app);
if (tracker?.forge !== 'gh' && tracker?.forge !== 'glab') return null;
@@ -246,6 +247,31 @@ async function resolveForgeContext(app, deps) {
return { cli: tracker.forge, env, host: tracker.host };
}
+/**
+ * The lane-health block (#12088): this lane's window numbers and the findings
+ * it got wrong or repeated, so the prompt can refuse to re-file them.
+ */
+function renderLaneHealth(report, taskType) {
+ const lane = laneHealthFor(report, normalizeAuditTaskType(taskType));
+ if (!lane) return unavailableMessage('Lane health', 'no lane matches this task');
+ const scope = report.truncated ? ` (the issue read was truncated; the window starts ${report.from.slice(0, 10)})` : '';
+ const lines = [
+ `This lane (\`${lane.metricLabel}\` issues) over the last ${report.windowDays} days${scope}: filed ${lane.filed}, completed ${lane.completed}, not planned ${lane.notPlanned}, open ${lane.open}, fixes reverted ${lane.reverted}, re-filed within ${report.refileDays} days of a closed finding on the same file ${lane.refiled}.`,
+ ];
+ if (report.partial?.length) lines.push(`Revert detection is incomplete this run (${report.partial.join(' and ')} could not be read); a reverted count of 0 is not evidence.`);
+ if (!lane.flagged.length) {
+ lines.push('No finding of this lane was closed as not planned, reverted, or re-filed in the window.');
+ } else {
+ const shown = lane.flaggedTotal > lane.flagged.length ? ` (newest ${lane.flagged.length} of ${lane.flaggedTotal})` : '';
+ lines.push(`Findings this lane got wrong or repeated${shown}:`);
+ for (const { number, title, reasons } of lane.flagged) {
+ const safeTitle = redactPii(scrubSecretTokens(title)).slice(0, 160);
+ lines.push(`- #${number} ${safeTitle} — ${reasons.map(describeLaneFlag).join('; ')}`);
+ }
+ }
+ return truncateWithNotice(lines.join('\n'), MAX_INPUT_CHARS);
+}
+
const INPUT_LOADERS = {
'product-requirements': async ({ app, deps }) => renderRepositoryDocuments(
'PRD.md', await deps.findFiles(app?.repoPath, 'PRD.md')
@@ -302,6 +328,12 @@ const INPUT_LOADERS = {
const lines = runs.map(({ assessedAt, slice }) => `- ${assessedAt.slice(0, 10)}: ${redactPii(scrubSecretTokens(slice)).slice(0, 300)}`);
return truncateWithNotice(`Recently audited by this lane (prefer other areas unless evidence points here):\n${lines.join('\n')}`, MAX_INPUT_CHARS);
},
+ 'lane-health': async ({ app, deps, forge, taskType }) => {
+ if (!isAuditTaskType(taskType)) return 'This input applies to audit lanes only; no lane health applies to this task.';
+ if (!forge) return unavailableMessage('Lane health', 'repository forge is unavailable');
+ const result = await deps.collectLaneHealth(app, { forge, taskType });
+ return result.ok ? renderLaneHealth(result, taskType) : forgeUnavailable('Lane health', forge, result);
+ },
'closed-unmerged-pull-requests': async ({ app, deps, forge }) => {
if (!forge) return unavailableMessage('Closed unmerged pull requests', 'repository forge is unavailable');
const result = await deps.listPullRequests({ cli: forge.cli, cwd: app.repoPath, env: forge.env, state: 'closed-unmerged' });
@@ -330,10 +362,14 @@ export async function resolveTaskDataInputs(inputIds, { app, taskMetadata = {},
const { readRecentAuditSlices } = await import('./appQuality.js');
return readRecentAuditSlices(...args);
},
+ collectLaneHealth: async (...args) => {
+ const { collectLaneHealth } = await import('./appLaneHealth.js');
+ return collectLaneHealth(...args);
+ },
environment: process.env,
...dependencies,
};
- const needsForge = selected.some((id) => id.includes('issues') || (id.includes('pull-requests')
+ const needsForge = selected.some((id) => id.includes('issues') || id === 'lane-health' || (id.includes('pull-requests')
&& !(taskType === 'pr-watcher' && id === 'open-pull-requests')));
const forge = needsForge
? await resolveForgeContext(app, deps).catch(() => null)
diff --git a/server/services/taskDataInputs.test.js b/server/services/taskDataInputs.test.js
index 0cf6554e71..e4d4bdf366 100644
--- a/server/services/taskDataInputs.test.js
+++ b/server/services/taskDataInputs.test.js
@@ -20,9 +20,52 @@ describe('taskDataInputs', () => {
'open-pull-requests',
'closed-unmerged-pull-requests',
'audit-slice-history',
+ 'lane-health',
]);
});
+ // #12088: the lane reads what became of its own findings before it files more.
+ it('renders the lane-health block for an audit lane through the resolved forge, and names a failed read', async () => {
+ const resolveTracker = vi.fn().mockResolvedValue({ forge: 'gh', host: 'github.com' });
+ const resolveTokenEnv = vi.fn().mockResolvedValue({ GH_TOKEN: 'test-token' });
+ const collectLaneHealth = vi.fn().mockResolvedValue({
+ ok: true, windowDays: 60, refileDays: 30, from: '2026-08-18T12:00:00.000Z', to: '2026-10-17T12:00:00.000Z', truncated: false, partial: [],
+ lanes: [{ id: 'better-complexity', label: 'Cyclomatic complexity', metricLabel: 'complexity', filed: 12, completed: 9, notPlanned: 2, open: 1, reverted: 1, refiled: 1, flaggedTotal: 3, flagged: [
+ { number: 31, title: 'Dispatcher branches on every provider', url: null, reasons: [{ kind: 're-filed', of: 20, path: 'server/services/dispatch.js' }] },
+ { number: 28, title: 'Contact [email protected] about the hotspot', url: null, reasons: [{ kind: 'reverted', pullRequest: 90 }] },
+ { number: 25, title: 'Nested ternary', url: null, reasons: [{ kind: 'not-planned' }] },
+ ] }],
+ });
+ const options = { app: APP, taskType: 'better-complexity', dependencies: { resolveTracker, resolveTokenEnv, collectLaneHealth } };
+ const [section] = await resolveTaskDataInputs(['lane-health'], options);
+ expect(section.label).toBe('Lane health');
+ expect(collectLaneHealth).toHaveBeenCalledWith(APP, { forge: expect.objectContaining({ cli: 'gh', env: expect.objectContaining({ GH_TOKEN: 'test-token' }) }), taskType: 'better-complexity' });
+ expect(section.content).toContain('This lane (`complexity` issues) over the last 60 days: filed 12, completed 9, not planned 2, open 1, fixes reverted 1, re-filed within 30 days of a closed finding on the same file 1.');
+ expect(section.content).toContain('Findings this lane got wrong or repeated:');
+ expect(section.content).toContain('- #31 Dispatcher branches on every provider — re-filed after #20 on server/services/dispatch.js');
+ expect(section.content).toContain('- #28 Contact <email> about the hotspot — fix reverted (PR #90)');
+ expect(section.content).toContain('- #25 Nested ternary — closed as not planned');
+ expect(appendTaskDataInputs('Audit.', [section])).toContain('### Lane health');
+
+ collectLaneHealth.mockResolvedValueOnce({ ok: true, windowDays: 60, refileDays: 30, from: '2026-09-20T00:00:00.000Z', to: '2026-10-17T12:00:00.000Z', truncated: true, partial: ['commits'],
+ lanes: [{ id: 'better-complexity', metricLabel: 'complexity', filed: 0, completed: 0, notPlanned: 0, open: 0, reverted: 0, refiled: 0, flaggedTotal: 0, flagged: [] }] });
+ const [clean] = await resolveTaskDataInputs(['lane-health'], options);
+ expect(clean.content).toContain('the issue read was truncated; the window starts 2026-09-20');
+ expect(clean.content).toContain('Revert detection is incomplete this run (commits could not be read)');
+ expect(clean.content).toContain('No finding of this lane was closed as not planned, reverted, or re-filed in the window.');
+
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ collectLaneHealth.mockResolvedValueOnce({ ok: false, reason: 'issues', error: 'gh: HTTP 502' });
+ const [failed] = await resolveTaskDataInputs(['lane-health'], options);
+ expect(failed.content).toContain('Lane health could not be preloaded (gh failed: gh: HTTP 502)');
+ expect(failed.content).toContain('Do not interpret this as an empty source');
+ warn.mockRestore();
+
+ expect((await resolveTaskDataInputs(['lane-health'], { ...options, taskType: 'plan-feature' }))[0].content).toContain('applies to audit lanes only');
+ resolveTracker.mockResolvedValueOnce({ forge: 'jira' });
+ expect((await resolveTaskDataInputs(['lane-health'], options))[0].content).toContain('repository forge is unavailable');
+ });
+
// #12090: the lane's recent slices are preloaded so it rotates coverage; an
// empty history and an unreadable store each say so instead of reading as empty.
it('renders the lane\'s recent audit slices, an empty history, and an unreadable store without a forge call', async () => {
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 0880f9536f..37880d1500 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -1973,9 +1973,10 @@ describe('taskSchedule', () => {
// asserting it in two places 20 lines apart just means a future flag gets
// added to one of them. Every audit includes open issues; some also preload
// PRs to dedup against work in flight without spending forge calls. Every
- // audit also preloads its recent slices so runs rotate coverage (#12090).
- const OPEN_ISSUES_ONLY = ['open-issues', 'audit-slice-history']
- const DEDUP_PRELOAD = ['open-issues', 'open-pull-requests', 'audit-slice-history']
+ // audit also preloads its recent slices so runs rotate coverage (#12090)
+ // and its lane health so it does not re-file a rejected finding (#12088).
+ const OPEN_ISSUES_ONLY = ['open-issues', 'audit-slice-history', 'lane-health']
+ const DEDUP_PRELOAD = ['open-issues', 'open-pull-requests', 'audit-slice-history', 'lane-health']
const FILE_ISSUES_LANES = [
['data-safety', OPEN_ISSUES_ONLY],
['simplify', OPEN_ISSUES_ONLY],
@@ -2000,10 +2001,11 @@ describe('taskSchedule', () => {
])
})
- it('ships open issues and the slice rotation record for every scheduled quality audit', () => {
+ it('ships open issues, the slice rotation record and lane health for every scheduled quality audit', () => {
for (const taskType of AUDIT_TASK_TYPES) {
expect(DEFAULT_TASK_INTERVALS[taskType]?.dataInputs, taskType).toContain('open-issues')
expect(DEFAULT_TASK_INTERVALS[taskType]?.dataInputs, taskType).toContain('audit-slice-history')
+ expect(DEFAULT_TASK_INTERVALS[taskType]?.dataInputs, taskType).toContain('lane-health')
}
})
diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.js
index c5aff9e462..aefc4b706f 100644
--- a/server/services/taskScheduleRegistry.js
+++ b/server/services/taskScheduleRegistry.js
@@ -449,13 +449,14 @@ const TASK_INTERVAL_DEFAULTS = {
// Every catalog audit is displayed as a `better-*` quality task. Give all of
// them the current issue inventory by default so they can avoid filing work
-// that is already tracked, and the lane's recent slices so runs rotate
-// coverage (#12090). Preserve other configured inputs such as PRs.
+// that is already tracked, the lane's recent slices so runs rotate coverage
+// (#12090), and the lane's health record so a rejected or reverted finding is
+// not re-filed (#12088). Preserve other configured inputs such as PRs.
export const DEFAULT_TASK_INTERVALS = Object.fromEntries(
Object.entries(TASK_INTERVAL_DEFAULTS).map(([taskType, interval]) => [
taskType,
isAuditTaskType(taskType)
- ? { ...interval, dataInputs: [...new Set([...(interval.dataInputs || []), 'open-issues', 'audit-slice-history'])] }
+ ? { ...interval, dataInputs: [...new Set([...(interval.dataInputs || []), 'open-issues', 'audit-slice-history', 'lane-health'])] }
: interval
])
);