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

fix: keep quota-burn sequences, peers, and explicit choices working with the applicability gate

[._.]/ Adam Eivy40afa6c2bb65
diff --git a/client/src/components/apps/AppQuality.jsx b/client/src/components/apps/AppQuality.jsx
index 0250cd0d49..011faa61dd 100644
--- a/client/src/components/apps/AppQuality.jsx
+++ b/client/src/components/apps/AppQuality.jsx
@@ -79,7 +79,7 @@ export default function AppQuality({ app, detail = false }) {
: score == null ? unscoredLabel : `Quality: ${score}/100`;
if (!detail) return (
<Link to={`/apps/${app.id}/quality`} className="text-xs text-port-accent hover:underline" title="View audit scores and coverage">
- {label}{score != null && ` · ${quality.ratedCategories}/${categoryCount} categories`}
+ {label}{score != null && ` · ${quality.ratedCategories} rated`}
</Link>
);
const panelLink = (name, categoryId) => {
diff --git a/client/src/components/apps/AppQualityRunner.jsx b/client/src/components/apps/AppQualityRunner.jsx
index 4ec248b672..22072059a5 100644
--- a/client/src/components/apps/AppQualityRunner.jsx
+++ b/client/src/components/apps/AppQualityRunner.jsx
@@ -13,7 +13,8 @@ import { getMaintenanceRuns, startMaintenanceRun, stopMaintenanceRun } from '../
const isApplicable = category => category.applicable !== false;
const needsCheck = category => {
if (!isApplicable(category)) return false;
- if (category.coverage === 'not-applicable' || (category.coverage === 'unavailable' && category.assessedAt)) return false;
+ // A stale not-applicable ruling has expired (the repo may have gained a UI), so it is re-offered.
+ if ((category.coverage === 'not-applicable' && !category.stale) || (category.coverage === 'unavailable' && category.assessedAt)) return false;
return category.score == null || category.stale || category.coverage !== 'broad' || category.confidence === 'low';
};
diff --git a/client/src/components/apps/AppQualityRunner.test.jsx b/client/src/components/apps/AppQualityRunner.test.jsx
index dca453d1b0..6e0a0265dd 100644
--- a/client/src/components/apps/AppQualityRunner.test.jsx
+++ b/client/src/components/apps/AppQualityRunner.test.jsx
@@ -76,7 +76,7 @@ it('launches alongside pending runners and stops each run independently', async
it('excludes known unavailable and N/A assessments from suggestions while allowing explicit reruns', async () => {
const categories = [
- { id: 'typing', label: 'Typing', score: null, coverage: 'not-applicable', stale: true },
+ { id: 'typing', label: 'Typing', score: null, coverage: 'not-applicable', stale: false },
{ id: 'console-errors', label: 'Console errors', score: null, coverage: 'unavailable', assessedAt: '2026-09-01T00:00:00Z' },
];
startMaintenanceRun.mockResolvedValue({ run: { id: 'run-3', status: 'running', steps: [] } });
@@ -101,6 +101,14 @@ it('excludes known unavailable and N/A assessments from suggestions while allowi
await waitFor(() => expect(startMaintenanceRun).toHaveBeenLastCalledWith(expect.objectContaining({ taskTypes: ['typing', 'console-errors', 'security'] }), { silent: true }));
});
+it('re-offers a category whose not-applicable ruling has expired', async () => {
+ startMaintenanceRun.mockResolvedValue({ run: { id: 'run-5', status: 'running', steps: [] } });
+ const categories = [{ id: 'accessibility', label: 'Accessibility', score: null, coverage: 'not-applicable', stale: true, assessedAt: '2026-07-01T00:00:00Z' }];
+ render(<MemoryRouter><AppQualityRunner app={{ ...app, quality: { categories } }} /></MemoryRouter>);
+ fireEvent.click(await findEnabledByRole('button', { name: 'Run now' }));
+ await waitFor(() => expect(startMaintenanceRun).toHaveBeenLastCalledWith(expect.objectContaining({ taskTypes: ['accessibility'] }), { silent: true }));
+});
+
it('leaves audits that cannot apply to this repository out of batch runs, but runs one on request', async () => {
const categories = [
{ id: 'security', label: 'Security', score: null, applicable: true },
diff --git a/docs/features/app-quality.md b/docs/features/app-quality.md
index 5bebc760c5..8192c6e110 100644
--- a/docs/features/app-quality.md
+++ b/docs/features/app-quality.md
@@ -138,6 +138,15 @@ ordering uses a transient digest of the row, computed when the file is read.
That file is not the peer federation payload. Peers still exchange schema v1
objects. Upgrading the file does not require every peer to upgrade.
+The category catalog can grow without breaking that exchange. A requester sends
+the categories it can parse (`categories=` on `GET /api/apps/quality-federation`),
+and the peer answering returns only those. A request without the parameter, from
+an install that predates it, gets only the 25 categories that existed before the
+service and data-platform lenses (`FEDERATION_LEGACY_CATEGORIES`), because such an
+install rejects a whole payload over one row it cannot parse. On receipt, rows are
+validated one at a time, so a malformed or unknown row costs that row, not the
+peer's other evidence.
+
Readers accept a v1 `.quality.json` and, when that file is absent, the historical
`quality-snapshot.json` name. A read never rewrites the checkout. Future schemas,
unrecognized documents (including TSV, CSV, or NDJSON), malformed snapshots, and
diff --git a/server/lib/auditQuality.js b/server/lib/auditQuality.js
index 652baf1688..f171ce9edf 100644
--- a/server/lib/auditQuality.js
+++ b/server/lib/auditQuality.js
@@ -120,7 +120,10 @@ export function summarizeAppQuality(records = [], now = Date.now(), { inapplicab
const assessedAt = record?.assessedAt;
const stale = valid && !isFreshAssessment(assessedAt, now);
const contributes = valid && !stale && report.data.coverage === 'broad' && report.data.confidence !== 'low' && report.data.score !== null;
- const reportedNotApplicable = valid && !stale && report.data.coverage === 'not-applicable';
+ // Only this install's own ruling, as the dispatch gate reads it: a peer's
+ // or a release snapshot's describes a different checkout of the repository.
+ const local = !record?.sourcePeerId && !record?.sourcePeerName;
+ const reportedNotApplicable = valid && !stale && local && report.data.coverage === 'not-applicable';
const detectedReason = Object.hasOwn(inapplicable, id) ? inapplicable[id] : null;
const applicable = contributes || !(reportedNotApplicable || detectedReason);
const inapplicableReason = applicable ? null
@@ -182,4 +185,8 @@ export function compareQualityRecords(a, b) {
export const appQualityFederationQuerySchema = appQualityHistoryQuerySchema.extend({
repository: z.string().regex(/^[a-f0-9]{64}$/).optional(),
+ // The categories the requesting install can parse, comma-separated. Absent on
+ // a request from an install that predates it — see FEDERATION_LEGACY_CATEGORIES.
+ categories: z.string().max(4000).regex(/^[a-z0-9-]+(,[a-z0-9-]+)*$/).optional()
+ .transform(value => (value ? value.split(',') : undefined)),
});
diff --git a/server/routes/apps/crud.js b/server/routes/apps/crud.js
index edf7f38773..199a42fff5 100644
--- a/server/routes/apps/crud.js
+++ b/server/routes/apps/crud.js
@@ -35,8 +35,8 @@ const router = Router();
// Numeric local evidence only. This endpoint never invokes aggregate reads or forwards peer data.
router.get('/quality-federation', asyncHandler(async (req, res) => {
- const { days, repository } = validateRequest(appQualityFederationQuerySchema, req.query);
- const payload = await exportPortosQuality(req.get('X-PortOS-Instance-Id'), days, {}, repository);
+ const { days, repository, categories } = validateRequest(appQualityFederationQuerySchema, req.query);
+ const payload = await exportPortosQuality(req.get('X-PortOS-Instance-Id'), days, {}, repository, categories);
if (!payload) throw new ServerError('Quality sharing requires a registered enabled sync peer and a known repository', {
status: 403,
code: 'PEER_PULL_FORBIDDEN',
diff --git a/server/routes/apps/crud.test.js b/server/routes/apps/crud.test.js
index 9fae3f95e4..cd36ad2b7a 100644
--- a/server/routes/apps/crud.test.js
+++ b/server/routes/apps/crud.test.js
@@ -67,11 +67,13 @@ describe('Apps CRUD Routes', () => {
exportPortosQuality.mockResolvedValue({ schemaVersion: 1, measurements: [] });
const result = await request(app).get('/api/apps/quality-federation?days=30').set('X-PortOS-Instance-Id', 'peer');
expect(result.status).toBe(200);
- expect(exportPortosQuality).toHaveBeenCalledWith('peer', 30, {}, undefined);
+ expect(exportPortosQuality).toHaveBeenCalledWith('peer', 30, {}, undefined, undefined);
expect(appsService.getAppById).not.toHaveBeenCalled();
const repository = 'a'.repeat(64);
expect((await request(app).get(`/api/apps/quality-federation?repository=${repository}`).set('X-PortOS-Instance-Id', 'peer')).status).toBe(200);
- expect(exportPortosQuality).toHaveBeenLastCalledWith('peer', 90, {}, repository);
+ expect(exportPortosQuality).toHaveBeenLastCalledWith('peer', 90, {}, repository, undefined);
+ await request(app).get('/api/apps/quality-federation?categories=security,privacy').set('X-PortOS-Instance-Id', 'peer');
+ expect(exportPortosQuality).toHaveBeenLastCalledWith('peer', 90, {}, undefined, ['security', 'privacy']);
expect((await request(app).get('/api/apps/quality-federation?repository=invalid')).status).toBe(400);
expect((await request(app).get('/api/apps/quality-federation?days=999')).status).toBe(400);
exportPortosQuality.mockResolvedValue(null);
diff --git a/server/services/appQuality.test.js b/server/services/appQuality.test.js
index a2e65b31d5..56ce7418d6 100644
--- a/server/services/appQuality.test.js
+++ b/server/services/appQuality.test.js
@@ -118,6 +118,17 @@ describe('scheduled audit measurement workflow', () => {
log.mockRestore();
});
+ // The dispatch gate reads only this install's rulings; a peer's describes a
+ // different checkout, so the Quality tab must not hide the category on it.
+ it('does not let a peer\'s not-applicable ruling mark a category inapplicable here', () => {
+ const now = Date.now();
+ const peerRow = { category: 'ux', sourcePeerId: 'peer-a', sourcePeerName: 'Peer A', assessedAt: new Date(now).toISOString(),
+ report: report({ category: 'ux', score: null, coverage: 'not-applicable', confidence: 'low' }) };
+ const localRow = { ...peerRow, sourcePeerId: undefined, sourcePeerName: undefined };
+ expect(summarizeAppQuality([peerRow], now).categories.find(c => c.id === 'ux').applicable).toBe(true);
+ expect(summarizeAppQuality([localRow], now).categories.find(c => c.id === 'ux').applicable).toBe(false);
+ });
+
// The detail read feeds the repository scan into the summary; a failing scan
// must cost only the applicability, never the whole quality read.
it('folds the repository-scan verdicts into the summary, and ignores a scan that fails', async () => {
diff --git a/server/services/appQualityFederation.js b/server/services/appQualityFederation.js
index 11ceb4a882..2770043de2 100644
--- a/server/services/appQualityFederation.js
+++ b/server/services/appQualityFederation.js
@@ -4,7 +4,7 @@ import { createHash } from 'node:crypto';
import { z } from 'zod';
import { query } from '../lib/db.js';
import { PORTOS_APP_ID } from '../lib/appIdentity.js';
-import { normalizeAuditTaskType } from '../lib/auditCatalog.js';
+import { AUDIT_TASK_TYPE_LIST, LEGACY_AUDIT_TASK_TYPE_ALIASES, normalizeAuditTaskType } from '../lib/auditCatalog.js';
import { auditQualityReportSchema, AUDIT_FRESHNESS_MS } from '../lib/auditQuality.js';
import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
import { getOriginInfo } from '../lib/gitRemote.js';
@@ -24,12 +24,36 @@ const measurementSchema = z.object({
assessedAt: z.string().datetime(),
report: numericReportSchema,
}).strict();
+// Rows are validated one by one (below), so a peer on a newer catalog that
+// sends a category this install does not know costs that row, not the peer.
+// Everything this install can parse, sent with each request so a peer on a
+// newer catalog withholds categories this one would reject.
+const READABLE_CATEGORY_PARAM = encodeURIComponent([
+ ...AUDIT_TASK_TYPE_LIST, ...Object.keys(LEGACY_AUDIT_TASK_TYPE_ALIASES),
+].join(','));
+
const payloadSchema = z.object({
schemaVersion: z.literal(PORTOS_SCHEMA_VERSIONS.appQuality),
repository: z.string().regex(/^[a-f0-9]{64}$/),
- measurements: z.array(measurementSchema).max(10000),
+ measurements: z.array(z.unknown()).max(10000),
}).strict();
+/**
+ * The categories every install parsed before the catalog added the service and
+ * data-platform lenses. An install that predates the `categories` request
+ * parameter validates the whole payload strictly, so one row in a category it
+ * does not know would make it drop EVERY measurement from this install. Such a
+ * requester is sent only these. Frozen: a later catalog addition is announced by
+ * the requester's own `categories` list, never by editing this one.
+ */
+export const FEDERATION_LEGACY_CATEGORIES = Object.freeze([
+ 'security', 'code-quality', 'test-coverage', 'performance', 'accessibility', 'documentation',
+ 'ui-bugs', 'mobile-responsive', 'error-handling', 'typing', 'console-errors', 'ux', 'data-safety',
+ 'simplify', 'module-hygiene', 'api-contract', 'ui-lifecycle', 'observability', 'copy',
+ 'better-complexity', 'better-cognitive-load', 'better-structural-drift', 'better-runtime-safety',
+ 'better-dependency-freedom', 'better-test-quality',
+]);
+
// PortOS's own app record always carries a repoPath; the bare `{ id: PORTOS_APP_ID }`
// form used for self-directed calls resolves to this install's checkout.
const appRepoPath = app => app.repoPath || (app.id === PORTOS_APP_ID ? PATHS.root : null);
@@ -70,7 +94,7 @@ export async function readQualityRecords(appId, days, now, deps = {}) {
}
/** New endpoint always enforces peer sharing consent, even without instance-password auth. */
-export async function exportPortosQuality(callerId, days, deps = {}, requestedRepository) {
+export async function exportPortosQuality(callerId, days, deps = {}, requestedRepository, requesterCategories = FEDERATION_LEGACY_CATEGORIES) {
const peers = await eligiblePeers(deps);
if (!callerId || !peers.some(peer => peer.instanceId === callerId)) return null;
let app = { id: PORTOS_APP_ID };
@@ -82,7 +106,10 @@ export async function exportPortosQuality(callerId, days, deps = {}, requestedRe
app = candidates.find(candidate => candidate.repository === requestedRepository)?.app;
if (!app) return null;
}
- return buildQualitySnapshot(app, days, deps);
+ const snapshot = await buildQualitySnapshot(app, days, deps);
+ if (!snapshot) return snapshot;
+ const parseable = new Set(requesterCategories);
+ return { ...snapshot, measurements: snapshot.measurements.filter(row => parseable.has(row.report.category)) };
}
/** Sanitized local evidence, also used by the explicit release snapshot command. */
@@ -111,7 +138,7 @@ export async function collectAppQuality(app, days, deps = {}) {
const now = deps.now ?? Date.now();
const results = await Promise.allSettled(peers.map(async peer => {
const response = await (deps.peerFetch || peerFetch)(
- `${peerBaseUrl(peer)}/api/apps/quality-federation?days=${days}${app.id === PORTOS_APP_ID ? '' : `&repository=${repository}`}`,
+ `${peerBaseUrl(peer)}/api/apps/quality-federation?days=${days}${app.id === PORTOS_APP_ID ? '' : `&repository=${repository}`}&categories=${READABLE_CATEGORY_PARAM}`,
{ signal: AbortSignal.timeout(3000), redirect: 'error', maxBytes: MAX_PAYLOAD_BYTES }, peer);
if (!response.ok) {
await response.body?.cancel?.();
@@ -124,7 +151,11 @@ export async function collectAppQuality(app, days, deps = {}) {
}
const payload = payloadSchema.parse(JSON.parse(body.toString('utf8')));
if (payload.repository !== repository) throw new Error('Different repository');
- return payload.measurements.filter(row => Date.parse(row.assessedAt) <= now).map(row => ({
+ const measurements = payload.measurements.flatMap(row => {
+ const parsed = measurementSchema.safeParse(row);
+ return parsed.success ? [parsed.data] : [];
+ });
+ return measurements.filter(row => Date.parse(row.assessedAt) <= now).map(row => ({
...row, category: row.report.category, sourcePeerId: peer.id, sourcePeerName: peer.name || peer.id,
report: { ...row.report, summary: sharedSummary },
}));
diff --git a/server/services/appQualityFederation.test.js b/server/services/appQualityFederation.test.js
index 4acfcaa8b7..b02f8796b9 100644
--- a/server/services/appQualityFederation.test.js
+++ b/server/services/appQualityFederation.test.js
@@ -1,6 +1,6 @@
import { it, expect, vi } from 'vitest';
import { mockNoPeers } from '../lib/mockPathsDataRoot.js';
-import { exportPortosQuality, collectPortosQuality, collectAppQuality, buildQualitySnapshot, readReleaseQuality } from './appQualityFederation.js';
+import { exportPortosQuality, collectPortosQuality, collectAppQuality, buildQualitySnapshot, readReleaseQuality, FEDERATION_LEGACY_CATEGORIES } from './appQualityFederation.js';
import { enrichAppsWithQuality, getAppQualityHistory } from './appQuality.js';
import { PORTOS_SCHEMA_VERSIONS } from '../lib/schemaVersions.js';
import { qualityFileFromWireSnapshot } from './appQualitySnapshotFormat.js';
@@ -41,7 +41,7 @@ it('combines newest categories in app view and UTC history without changing othe
expect(apps[0].quality).toMatchObject({ score: 70, ratedCategories: 2, federation: { peers: 1, available: 1, unavailable: 0 } });
expect(apps[0].quality.categories.find(c => c.id === 'security')).toMatchObject({ sourcePeerId: 'peer-a', agentId: null });
expect(apps[1].quality.score).toBeNull();
- expect(local.peerFetch.mock.calls[0]).toEqual(['http://192.0.2.1:5555/api/apps/quality-federation?days=30',
+ expect(local.peerFetch.mock.calls[0]).toEqual([expect.stringMatching(/^http:\/\/192\.0\.2\.1:5555\/api\/apps\/quality-federation\?days=30&categories=security%2C/),
expect.objectContaining({ signal: expect.any(AbortSignal), redirect: 'error', maxBytes: 4194304 }), peer]);
const history = await getAppQualityHistory({ id: 'portos-default' }, 30, local);
expect(history.points.find(p => p.date === '2026-09-09').score).toBe(20);
@@ -50,6 +50,26 @@ it('combines newest categories in app view and UTC history without changing othe
expect((await exportPortosQuality(peer.instanceId, 30, local)).measurements.map(m => m.report.score)).toEqual([20]);
});
+// A peer on an older catalog validates the whole payload strictly: one row in a
+// category it does not know would make it drop every measurement from us.
+it('sends a requester only the categories it can parse, and the pre-expansion set to one that does not say', async () => {
+ const source = deps([row('security', 80), row('privacy', 60)]);
+ const legacy = await exportPortosQuality(peer.instanceId, 30, source);
+ expect(legacy.measurements.map(m => m.report.category)).toEqual(['security']);
+ const current = await exportPortosQuality(peer.instanceId, 30, source, undefined, ['security', 'privacy']);
+ expect(current.measurements.map(m => m.report.category).sort()).toEqual(['privacy', 'security']);
+ expect(FEDERATION_LEGACY_CATEGORIES).toHaveLength(25);
+});
+
+it('keeps a newer peer\'s known categories when it also sends one this install cannot parse', async () => {
+ const remote = await exportPortosQuality(peer.instanceId, 30, deps([row('security', 80)]));
+ const withUnknown = { ...remote, measurements: [...remote.measurements,
+ { ...remote.measurements[0], measurementId: 'c'.repeat(64), report: { ...remote.measurements[0].report, category: 'example-future-lens' } }] };
+ const { records, federation } = await collectPortosQuality(30, { ...deps([]), peerFetch: async () => response(withUnknown) });
+ expect(records.map(record => record.category)).toEqual(['security']);
+ expect(federation).toMatchObject({ available: 1, unavailable: 0 });
+});
+
it('reads stored lifecycle measurements under the renamed category', async () => {
const [app] = await enrichAppsWithQuality(
[{ id: 'portos-default' }],
@@ -67,12 +87,15 @@ it('keeps local scores on old, offline, malformed, oversize or mismatched peers
async () => { throw new Error('offline'); },
async () => response({ ...payload, schemaVersion: 2 }),
async () => response({ ...payload, repository: '0'.repeat(64) }),
- async () => response({ ...payload, measurements: [{ ...payload.measurements[0], report: { ...payload.measurements[0].report, score: 101 } }] }),
async () => new Response('too large', { headers: { 'content-length': '4194305' } }),
]) {
const [app] = await enrichAppsWithQuality([{ id: 'portos-default' }], { ...local, peerFetch: fetch });
expect(app.quality).toMatchObject({ score: 20, federation: { available: 0, unavailable: 1 } });
}
+ // A malformed ROW costs that row, not the peer: the rest of its evidence counts.
+ const oneBad = { ...payload, measurements: [{ ...payload.measurements[0], report: { ...payload.measurements[0].report, score: 101 } }] };
+ const [partial] = await enrichAppsWithQuality([{ id: 'portos-default' }], { ...local, peerFetch: async () => response(oneBad) });
+ expect(partial.quality).toMatchObject({ score: 20, federation: { available: 1, unavailable: 0 } });
const future = { ...payload, measurements: [{ ...payload.measurements[0], assessedAt: '2026-09-11T00:00:00Z' }] };
expect((await collectPortosQuality(30, { ...local, peerFetch: async () => response(future) })).records).toEqual([]);
});
diff --git a/server/services/appQualitySchedule.js b/server/services/appQualitySchedule.js
index 088783f195..a0f347e5b0 100644
--- a/server/services/appQualitySchedule.js
+++ b/server/services/appQualitySchedule.js
@@ -134,8 +134,10 @@ export async function detectRepoCapabilities(app) {
// share one repoPath — so it is OR'd in AFTER the (path-keyed) cache read.
// A compiled or templated front end leaves no .jsx behind, but a served UI
// port is direct evidence there is an interface to audit.
+ // It proves the UI capability, never the completeness of a shallow listing:
+ // only a full inventory licenses "this repo has no tests / no deploy config".
const capabilities = { ...scan.capabilities, ui: scan.capabilities.ui || Boolean(app.uiPort) };
- return { capabilities, scanned: scan.scanned, complete: scan.complete || Boolean(app.uiPort) };
+ return { capabilities, scanned: scan.scanned, complete: scan.complete };
}
/** The file-derived half of the verdict — cacheable because it is per-checkout. */
@@ -273,7 +275,10 @@ export async function inapplicableAuditReasons(app) {
export async function inapplicableAuditReason(appId, taskType) {
if (!appId || !Object.hasOwn(AUDIT_DEFINITIONS, normalizeAuditTaskType(taskType))) return null;
const verdict = await getAppById(appId)
- .then(app => (app ? resolveAuditApplicability(app, taskType) : null))
+ // The schedule form's recorded override is the user's choice for this app,
+ // whichever lane dispatches the audit.
+ .then(app => (app && app.taskTypeOverrides?.[taskType]?.taskMetadata?.runInapplicableAudit !== true
+ ? resolveAuditApplicability(app, taskType) : null))
.catch(() => null);
return verdict && !verdict.applicable ? verdict.reason || 'not applicable to this repository' : null;
}
diff --git a/server/services/appQualitySchedule.test.js b/server/services/appQualitySchedule.test.js
index 4b28e81939..5044094180 100644
--- a/server/services/appQualitySchedule.test.js
+++ b/server/services/appQualitySchedule.test.js
@@ -71,6 +71,12 @@ describe('audit applicability gate', () => {
expect(execGit).not.toHaveBeenCalled();
});
+ it('honors the schedule form\'s per-app override on the sequencing lanes too', async () => {
+ const app = appWith(NODE_SERVICE, { taskTypeOverrides: { accessibility: { taskMetadata: { runInapplicableAudit: true } } } });
+ getAppById.mockResolvedValueOnce(app);
+ expect(await inapplicableAuditReason(app.id, 'accessibility')).toBeNull();
+ });
+
it('answers by app id for the sequencing lanes, and fails open when the app is unreadable', async () => {
const app = appWith(NODE_SERVICE);
getAppById.mockResolvedValueOnce(app);
@@ -146,6 +152,11 @@ describe('resolveQualityChecks', () => {
const { checks, complete } = await resolveQualityChecks({ id: 'skim', name: 'Skim', repoPath: '/repos/skim' });
expect(complete).toBe(false);
expect(checks.every(check => check.applicable)).toBe(true);
+ // A served UI port proves there is a UI, not that the skim saw everything:
+ // it must not turn the misses into "no tests / no deploy config".
+ const served = await resolveQualityChecks({ id: 'skim-ui', name: 'Skim UI', repoPath: '/repos/skim-ui', uiPort: 5555 });
+ expect(served.complete).toBe(false);
+ expect(served.checks.every(check => check.applicable)).toBe(true);
});
it('does not let one app’s uiPort decide a sibling app sharing the checkout', async () => {
diff --git a/server/services/maintenanceRun.js b/server/services/maintenanceRun.js
index 43dcee5a2e..e1661427a1 100644
--- a/server/services/maintenanceRun.js
+++ b/server/services/maintenanceRun.js
@@ -320,20 +320,22 @@ async function evaluate(id, { ignoreTaskId }) {
const catalog = await getQuotaBurnTaskCatalog({ manual: true });
const completed = { ...run.completed };
- // Step id → why it did not apply. Persisted with every hold, not only on
- // dispatch, so a later hold does not throw away skips this pass decided.
+ // Step id → why it did not apply. Persisted with a hold too, so a later hold
+ // does not throw away skips this pass decided — but only when the pass moved
+ // the ledger, so an unchanged hold still costs no write or broadcast.
const skipped = { ...run.skipped };
+ const ledger = () => (Object.keys(completed).length !== Object.keys(run.completed || {}).length ? { completed, skipped } : null);
for (const step of run.steps) {
if (completed[step.id]) continue;
const shape = sequenceStepShapeReason(step);
- if (shape) return hold(shape, { completed, skipped });
+ if (shape) return hold(shape, ledger());
if (step.drain) {
const probe = await probeSequenceDrain(step, { catalog, ignoreTaskId });
if (probe.drained) {
completed[step.id] = new Date().toISOString();
continue;
}
- if (!probe.job) return hold(probe.reason, { completed, skipped });
+ if (!probe.job) return hold(probe.reason, ledger());
}
const result = await invokeQuotaBurnStep({ step, family: stepBurnFamily(step, run), catalog, maintenanceRunId: id });
// An audit this repository cannot have findings for is COMPLETED as
diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.js
index 87a0eb0606..b437654b56 100644
--- a/server/services/quotaBurnInvoke.js
+++ b/server/services/quotaBurnInvoke.js
@@ -186,7 +186,7 @@ export function isBurnEligibleCustomJob(job) {
* An unset override inherits; nothing here writes back to the schedule or the
* job record.
*/
-export async function resolveQuotaBurnStep(step, catalog = null) {
+export async function resolveQuotaBurnStep(step, catalog = null, { explicit = false } = {}) {
const resolvedCatalog = catalog || await getQuotaBurnTaskCatalog();
const unavailable = resolveQuotaBurnStepAvailability(step, resolvedCatalog);
if (unavailable) return { unavailable };
@@ -212,7 +212,7 @@ export async function resolveQuotaBurnStep(step, catalog = null) {
// Here rather than at invoke, so the status page's probe and the runner agree
// that an audit which cannot apply to its app is not ready work, and so a
// maintenance run can complete it as skipped from the same verdict.
- const notApplicable = await notApplicableReason(ref, effective.params);
+ const notApplicable = explicit ? null : await notApplicableReason(ref, effective.params);
if (notApplicable) return { unavailable: { code: QUOTA_BURN_UNAVAILABLE.NOT_APPLICABLE, reason: notApplicable } };
return {
kind: isProgrammaticScheduledTaskType(ref.taskType) ? 'programmatic' : 'builtin',
@@ -418,7 +418,9 @@ async function queuedOnDemandReason(queued, taskType, appId) {
* spends a subscription while the user has CoS improvement switched off.
*/
export async function invokeQuotaBurnStep({ step, family, candidate, context, force = false, catalog = null, maintenanceRunId = null } = {}) {
- const resolved = await resolveQuotaBurnStep(step, catalog);
+ // A forced run is the user clicking this one step: like a manual Run, it is an
+ // explicit choice and is not refused as not-applicable.
+ const resolved = await resolveQuotaBurnStep(step, catalog, { explicit: force });
// The code rides along so a caller can tell "does not apply" (a maintenance
// run completes that step as skipped) from a refusal it must hold on.
if (resolved.unavailable) return { ...declined(resolved.unavailable.reason), code: resolved.unavailable.code };
diff --git a/server/services/quotaBurnInvoke.test.js b/server/services/quotaBurnInvoke.test.js
index e6e618c48c..6067232417 100644
--- a/server/services/quotaBurnInvoke.test.js
+++ b/server/services/quotaBurnInvoke.test.js
@@ -418,7 +418,10 @@ describe('built-in agent task invocation', () => {
const refused = await invokeQuotaBurnStep({ step: auditStep({ fileIssues: true }), family: grok, candidate });
expect(refused).toEqual({ dispatched: false, reason: expect.stringMatching(/does not apply to this app: no user interface/), code: 'not-applicable' });
expect(state.triggered).toHaveLength(0);
- const forced = await invokeQuotaBurnStep({ step: auditStep({ fileIssues: true, runInapplicableAudit: true }), family: grok, candidate });
+ const overridden = await invokeQuotaBurnStep({ step: auditStep({ fileIssues: true, runInapplicableAudit: true }), family: grok, candidate });
+ expect(overridden.dispatched).toBe(true);
+ // A forced ▶ on the step is the user choosing it, like a manual Run.
+ const forced = await invokeQuotaBurnStep({ step: auditStep({ fileIssues: true }), family: grok, candidate, force: true });
expect(forced.dispatched).toBe(true);
inapplicable.byType = {};
});
diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.js
index baa65076bb..71c9036637 100644
--- a/server/services/quotaBurnRunner.test.js
+++ b/server/services/quotaBurnRunner.test.js
@@ -72,6 +72,9 @@ vi.mock('./quotaBurnAcceptance.js', () => ({
// copy of the invocation logic (`quotaBurnInvoke.test.js` owns that).
vi.mock('./quotaBurnInvoke.js', () => ({
getQuotaBurnTaskCatalog: vi.fn(async () => { state.catalogReads += 1; return state.catalog; }),
+ // The sequence walker asks it whether a step still applies to its app.
+ resolveQuotaBurnStep: vi.fn(async (job) => (state.notApplicable?.includes(job.id)
+ ? { unavailable: { code: 'not-applicable', reason: 'does not apply' } } : {})),
countQuotaBurnStepPending: vi.fn(async ({ step }) => state.invokePending[step.id] ?? { count: 0, detail: 'nothing' }),
invokeQuotaBurnStep: vi.fn(async ({ step, family, candidate, context, force }) => {
state.invoked.push({ stepId: step.id, familyId: family.id, charge: candidate.charge, force });
diff --git a/server/services/quotaBurnSequence.js b/server/services/quotaBurnSequence.js
index e07f99bf0a..e31b0c7c27 100644
--- a/server/services/quotaBurnSequence.js
+++ b/server/services/quotaBurnSequence.js
@@ -1,4 +1,5 @@
/** Strict sequence barriers; ordinary burn rotations keep their existing semantics. */
+import { QUOTA_BURN_UNAVAILABLE } from '../lib/quotaBurnTaskRef.js';
import { requiresInstallWideTarget } from '../lib/taskTargetScope.js';
import { burnPlanOwnsAgent, burnPlanOwnsTask, quotaBurnProvenance } from '../lib/quotaBurnOrigin.js';
import { MAINTENANCE_DRAIN_TASK } from '../lib/maintenanceSequence.js';
@@ -58,6 +59,12 @@ export async function probeSequenceDrain(job, { catalog, ignoreTaskId = null })
return { drained: true };
}
+async function sequenceStepNotApplicable(job, catalog) {
+ const { resolveQuotaBurnStep } = await import('./quotaBurnInvoke.js');
+ const resolved = await resolveQuotaBurnStep(job, catalog);
+ return resolved.unavailable?.code === QUOTA_BURN_UNAVAILABLE.NOT_APPLICABLE;
+}
+
export async function nextQuotaBurnSequenceJob(family, { completions, reservations, catalog, ignoreTaskId = null }) {
const { getAllTasks } = await import('./cosTaskStore.js');
const { user, cos } = await getAllTasks();
@@ -74,7 +81,17 @@ export async function nextQuotaBurnSequenceJob(family, { completions, reservatio
if (job.enabled === false) return { reason: 'sequence step is disabled' };
const shape = sequenceStepShapeReason(job);
if (shape) return { reason: shape };
- if (!job.drain) return { job };
+ if (!job.drain) {
+ // An audit this app's repository cannot have findings for will never
+ // become ready, so as a barrier it would stop the whole sequence for good.
+ // Record it done, as a maintenance run does, and move on.
+ if (!await sequenceStepNotApplicable(job, catalog)) return { job };
+ const written = await recordQuotaBurnJobCompletion(family.id, job.id);
+ if (!written) return { reason: 'could not record skipped sequence step' };
+ completions[quotaBurnJobKey(family.id, job.id)] = written[quotaBurnJobKey(family.id, job.id)];
+ console.log(`⏭️ Quota-burn sequence ${family.id}: skipped ${job.taskRef?.taskType} (${job.id}) — not applicable`);
+ continue;
+ }
const probe = await probeSequenceDrain(job, { catalog, ignoreTaskId });
if (!probe.drained) return probe;
const written = await recordQuotaBurnJobCompletion(family.id, job.id);
diff --git a/server/services/quotaBurnSequence.test.js b/server/services/quotaBurnSequence.test.js
index f9c1a200fc..4051101599 100644
--- a/server/services/quotaBurnSequence.test.js
+++ b/server/services/quotaBurnSequence.test.js
@@ -27,6 +27,18 @@ beforeEach(() => {
recordQuotaBurnJobCompletion.mockImplementation(async (f, j) => ({ [`${f}:${j}`]: 'done' }));
});
describe('maintenance sequence workflow', () => {
+ // Before, an audit that could never apply was a permanent barrier: every
+ // later step in the family stopped running for good.
+ it('passes an audit that does not apply to its app instead of stalling the family on it', async () => {
+ const onlyAudits = { id: 'codex', sequence: true, jobs: [audit, docs] };
+ resolveQuotaBurnStep.mockImplementation(async (job) => (job.id === 'audit'
+ ? { unavailable: { code: 'not-applicable', reason: 'does not apply' } } : {}));
+ const ctx = { completions: {}, reservations: {}, catalog: {} };
+ expect(await nextQuotaBurnSequenceJob(onlyAudits, ctx)).toEqual({ job: docs });
+ expect(recordQuotaBurnJobCompletion).toHaveBeenCalledWith('codex', 'audit');
+ expect(ctx.completions['codex:audit']).toBe('done');
+ });
+
it('repeats claims with saved app filters, then advances only after the backlog drains', async () => {
const ctx = context();
expect(await nextQuotaBurnSequenceJob(family, ctx)).toEqual({ job: drain });