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: organize scheduled audits with labels and run guidance

[._.]/ Adam Eivy54dc8650c117
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsx
index bc2673fdcf..4a42b3d204 100644
--- a/client/src/components/cos/tabs/ScheduleTab.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.jsx
@@ -45,6 +45,14 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePr
const [schedule, setSchedule] = useState(null);
const [loading, setLoading] = useState(true);
+ const label = searchParams.get('label') || '';
+ const setLabel = next => {
+ const params = new URLSearchParams(searchParams);
+ if (next) params.set('label', next);
+ else params.delete('label');
+ setSearchParams(params, { replace: true });
+ };
+
const filterParam = searchParams.get('filter');
const filter = TASK_FILTERS.some(f => f.id === filterParam) ? filterParam : DEFAULT_FILTER_ID;
const setFilter = useCallback((next) => {
@@ -206,6 +214,8 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePr
onSelectTask={setSelectedTask}
improvementDisabled={improvementDisabled}
filter={filter}
+ label={label}
+ onLabelChange={setLabel}
onFilterChange={setFilter}
/>
diff --git a/client/src/components/cos/tabs/ScheduleTab.test.jsx b/client/src/components/cos/tabs/ScheduleTab.test.jsx
index 987935ea60..0e14d6dc33 100644
--- a/client/src/components/cos/tabs/ScheduleTab.test.jsx
+++ b/client/src/components/cos/tabs/ScheduleTab.test.jsx
@@ -8,6 +8,9 @@ const api = vi.hoisted(() => ({
getCodeReviewDefaults: vi.fn(),
getCosSchedule: vi.fn(),
triggerCosOnDemandTask: vi.fn(),
+ updateCosTaskInterval: vi.fn(),
+ getLocalLlmStatus: vi.fn().mockResolvedValue(null),
+ getProviders: vi.fn().mockResolvedValue({ providers: [] }),
}));
vi.mock('../../ui/Toast', () => ({ default: toast }));
@@ -153,3 +156,29 @@ describe('ScheduleTab on-demand feedback', () => {
expect(await screen.findByText(/CoS daemon is stopped/)).toBeVisible();
});
});
+
+
+describe('Schedule labels', () => {
+ it('filters by a linked label, searches legacy names, and saves custom labels through the drawer', async () => {
+ const user = userEvent.setup();
+ api.getCodeReviewDefaults.mockResolvedValue({});
+ api.getCosSchedule.mockResolvedValue({ tasks: {
+ security: { type: 'on-demand', enabled: false, displayName: 'better-security', defaultLabels: ['slashdo'], labels: [], description: 'Security audit' },
+ 'claim-issue': { type: 'on-demand', enabled: false, description: 'Claim work' },
+ } });
+ api.updateCosTaskInterval.mockResolvedValue({ success: true, interval: { labels: ['backend'] } });
+ render(<MemoryRouter initialEntries={['/cos/schedule?label=slashdo']}><ScheduleTab apps={[]} providers={[]} providersLoaded /></MemoryRouter>);
+ expect(await screen.findByText('better-security')).toBeTruthy();
+ expect(screen.queryByText('claim-issue')).toBeNull();
+ await user.click(screen.getByRole('button', { name: 'Clear label' }));
+ expect(screen.getByText('claim-issue')).toBeTruthy();
+ await user.type(screen.getByRole('textbox', { name: 'Filter tasks by name' }), 'security');
+ expect(screen.queryByText('claim-issue')).toBeNull();
+ await user.click(screen.getByText('better-security'));
+ const labels = await screen.findByRole('textbox', { name: 'Custom labels' });
+ await user.type(labels, 'backend');
+ await user.tab();
+ await waitFor(() => expect(api.updateCosTaskInterval).toHaveBeenCalledWith('security', { labels: ['backend'] }, { silent: true }));
+ expect(await screen.findByRole('option', { name: 'backend (1)' })).toBeTruthy();
+ });
+});
diff --git a/client/src/components/cos/tabs/schedule/AppTaskTypeSection.jsx b/client/src/components/cos/tabs/schedule/AppTaskTypeSection.jsx
index ec58e2b597..32bcd3e86d 100644
--- a/client/src/components/cos/tabs/schedule/AppTaskTypeSection.jsx
+++ b/client/src/components/cos/tabs/schedule/AppTaskTypeSection.jsx
@@ -1,19 +1,21 @@
import { useState } from 'react';
import { Search, X } from 'lucide-react';
import AppTaskCard from './AppTaskCard';
-import { TASK_FILTERS, DEFAULT_FILTER_ID, taskSortKey } from './scheduleConstants';
+import { TASK_FILTERS, DEFAULT_FILTER_ID, taskSortKey, taskLabels } from './scheduleConstants';
-export default function AppTaskTypeSection({ tasks, apps, providers, providersLoaded, activeProviderId, onTrigger, onUpdate, onSelectTask, improvementDisabled, filter, onFilterChange }) {
+export default function AppTaskTypeSection({ tasks, apps, providers, providersLoaded, activeProviderId, onTrigger, onUpdate, onSelectTask, improvementDisabled, filter, onFilterChange, label = '', onLabelChange }) {
const [search, setSearch] = useState('');
const taskEntries = Object.entries(tasks || {});
const activeFilter = TASK_FILTERS.find(f => f.id === filter) || TASK_FILTERS[0];
const counts = Object.fromEntries(TASK_FILTERS.map(f => [f.id, taskEntries.filter(f.match).length]));
+ const labels = [...new Set(taskEntries.flatMap(([, config]) => taskLabels(config)))].sort();
const query = search.trim().toLowerCase();
const visibleEntries = taskEntries
.filter(activeFilter.match)
- .filter(([taskType]) => !query || taskType.toLowerCase().includes(query))
+ .filter(([, config]) => !label || taskLabels(config).includes(label))
+ .filter(([taskType, config]) => !query || [taskType, config.displayName, config.description, ...taskLabels(config)].filter(Boolean).join(' ').toLowerCase().includes(query))
.sort(([aType, aConfig], [bType, bConfig]) => {
const a = taskSortKey(aType, aConfig);
const b = taskSortKey(bType, bConfig);
@@ -50,13 +52,23 @@ export default function AppTaskTypeSection({ tasks, apps, providers, providersLo
Tasks that analyze and improve PortOS and managed apps. Click a card to configure its schedule and to turn it on or off per app.
</p>
+ <div className="flex flex-wrap items-center gap-2">
+ <label htmlFor="schedule-label-filter" className="text-sm text-gray-400">Label</label>
+ <select id="schedule-label-filter" value={label} onChange={event => onLabelChange(event.target.value)}
+ className="max-w-full bg-port-card border border-port-border rounded px-3 py-2 text-sm text-white">
+ <option value="">All labels</option>
+ {label && !labels.includes(label) && <option value={label}>{label} (unavailable)</option>}
+ {labels.map(value => <option key={value} value={value}>{value} ({taskEntries.filter(([, config]) => taskLabels(config).includes(value)).length})</option>)}
+ </select>
+ {label && <button onClick={() => onLabelChange('')} className="text-sm text-port-accent">Clear label</button>}
+ </div>
<div className="relative max-w-sm">
<Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none" />
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
- placeholder="Filter tasks by name…"
+ placeholder="Search names, descriptions, labels…"
aria-label="Filter tasks by name"
className="w-full bg-port-card border border-port-border rounded-lg pl-9 pr-9 py-2 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-port-accent/50"
/>
@@ -74,7 +86,7 @@ export default function AppTaskTypeSection({ tasks, apps, providers, providersLo
{visibleEntries.length === 0 ? (
<div className="text-center py-8 text-gray-500 border border-dashed border-port-border rounded-lg">
- {query
+ {label ? <>No tasks match this label and the current filters. <button onClick={() => onLabelChange('')} className="text-port-accent">Clear label</button></> : query
? <>No tasks match “{search.trim()}”. <button onClick={() => setSearch('')} className="text-port-accent hover:underline">Clear filter</button></>
: <>{activeFilter.emptyMessage}{' '}
{activeFilter.id !== DEFAULT_FILTER_ID && (
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
index 8c0c05c63f..8447bd2d2a 100644
--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
@@ -50,6 +50,11 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
const [selectedType, setSelectedType] = useState(config.type);
const [editingPrompt, setEditingPrompt] = useState(false);
const [promptValue, setPromptValue] = useState(config.prompt || '');
+ const labelsDraft = useFieldDraft((config.labels || []).join(', '), async next => {
+ setUpdating(true);
+ await onUpdate(taskType, { labels: next.split(',').map(label => label.trim()).filter(Boolean) })
+ .finally(() => setUpdating(false));
+ });
const descriptionDraft = useFieldDraft(
config.description || '',
async (next) => {
@@ -258,6 +263,13 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
</Banner>
)}
+ <FormField label="Custom labels" labelClassName="text-sm text-gray-400 block mb-2">
+ <input id={`schedule-labels-${taskType}`} value={labelsDraft.value}
+ onChange={labelsDraft.onChange} onBlur={labelsDraft.onBlur} disabled={updating}
+ placeholder="maintenance, frontend" className="w-full bg-port-card border border-port-border rounded px-3 py-2 text-white text-sm" />
+ <p className="text-xs text-gray-500 mt-1">Comma-separated; up to 20 labels, 40 characters each. Shipped labels remain available. Saves on blur.</p>
+ </FormField>
+
<FormField label="Summary / byline" labelClassName="text-sm text-gray-400 block mb-2">
<input
id={`schedule-description-${taskType}`}
diff --git a/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx b/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx
index 9626905092..3ce26232d8 100644
--- a/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx
+++ b/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx
@@ -60,7 +60,7 @@ export default function TaskConfigDrawer({
<Drawer
open={open && !!config}
onClose={onClose}
- title={taskType || 'Task'}
+ title={config?.displayName || taskType || 'Task'}
size="md"
tabs={tabs}
activeTab={activeTab}
@@ -86,6 +86,7 @@ export default function TaskConfigDrawer({
{activeTab === 'global' && (
<GlobalConfigControls
+ key={taskType}
taskType={taskType}
config={config}
onUpdate={onUpdate}
diff --git a/client/src/components/cos/tabs/schedule/TaskHeader.jsx b/client/src/components/cos/tabs/schedule/TaskHeader.jsx
index 37d8652bf0..5a786d6b1c 100644
--- a/client/src/components/cos/tabs/schedule/TaskHeader.jsx
+++ b/client/src/components/cos/tabs/schedule/TaskHeader.jsx
@@ -1,5 +1,5 @@
import { GitBranch, GitMerge, Users } from 'lucide-react';
-import { badge, statusDot, getTaskStatusGroup, pipelineStages } from './scheduleConstants';
+import { taskLabels, badge, statusDot, getTaskStatusGroup, pipelineStages } from './scheduleConstants';
import IntervalBadge from './IntervalBadge';
// Shared task identity row — status dot, monospace name, pipeline + swarm
@@ -22,7 +22,7 @@ export default function TaskHeader({ taskType, config }) {
<div className="flex items-center justify-between gap-2 min-w-0">
<div className="flex items-center gap-2 min-w-0 flex-1">
<span className={`w-2 h-2 rounded-full shrink-0 ${statusDot(group)}`} title={group} aria-hidden="true" />
- <span className="font-mono text-sm text-white truncate leading-tight" title={taskType}>{taskType}</span>
+ <span className="font-mono text-sm text-white truncate leading-tight" title={taskType}>{config.displayName || taskType}</span>
</div>
<div className="flex items-center gap-1.5 shrink-0 flex-wrap justify-end">
{automationOnly && (
@@ -57,6 +57,12 @@ export default function TaskHeader({ taskType, config }) {
{config.description && (
<p className="text-xs text-gray-400 line-clamp-2" title={config.description}>{config.description}</p>
)}
+ {config.runGuidance && <p className="text-xs text-gray-400">Suggested order: {config.runGuidance}</p>}
+ {taskLabels(config).length > 0 && (
+ <div className="flex flex-wrap gap-1">
+ {taskLabels(config).map(label => <span key={label} className={badge('gray')}>{label}</span>)}
+ </div>
+ )}
{automationOnly && invocation.description && (
<p className="text-xs text-port-warning/80">{invocation.description}</p>
)}
diff --git a/client/src/components/cos/tabs/schedule/scheduleConstants.js b/client/src/components/cos/tabs/schedule/scheduleConstants.js
index 7feef45f79..4a066cb5cf 100644
--- a/client/src/components/cos/tabs/schedule/scheduleConstants.js
+++ b/client/src/components/cos/tabs/schedule/scheduleConstants.js
@@ -295,3 +295,6 @@ export function toggleMetadataField(metadata, field) {
}
return newMeta;
}
+
+// Shipped clusters remain discoverable alongside the operator's own labels.
+export const taskLabels = config => [...new Set([...(config.defaultLabels || []), ...(config.labels || [])])];
diff --git a/docs/features/scheduled-audit-organization.md b/docs/features/scheduled-audit-organization.md
new file mode 100644
index 0000000000..c8b1a85e97
--- /dev/null
+++ b/docs/features/scheduled-audit-organization.md
@@ -0,0 +1,67 @@
+# Scheduled audit names, labels, and order
+
+All tasks in `AUDIT_DEFINITIONS` belong to the `better-*` display-name family.
+On install/update, schedule responses derive these names from the catalog.
+Existing task IDs remain stable: saved prompts, provider pins, cadence, execution
+history, run-after references, app overrides, API calls, and bookmarked task IDs
+continue to work. No task is newly enabled or automatically run.
+
+The newly prefixed display names are: better-security, better-code-quality,
+better-test-coverage, better-performance, better-accessibility,
+better-documentation, better-ui-bugs, better-mobile-responsive,
+better-error-handling, better-typing, better-console-errors, better-ux,
+better-data-safety, better-simplify, better-module-hygiene, better-api-contract,
+better-react-lifecycle, better-observability, and better-copy. The six existing
+better-* names remain unchanged.
+
+Operational tasks (claims, review pipelines, reconciliation, releases, repo sync),
+planning/ideation, private security assessment, JIRA, and media generation retain
+their names: they have distinct execution or security contracts and are not
+members of the configurable audit catalog. Independent code-reviewer A/B tasks
+also retain their identities; they are general review workflows.
+
+Shipped labels include codebase-improvement, slashdo, and the audit's mapped
+slashdo lenses. The slashdo label means alignment with that library's audit
+family, not that dispatch necessarily invokes a slash command. Custom labels
+are optional schedule metadata, saved in the existing task config; absent means
+empty, and clearing uses an empty array. This additive field requires no layout
+conversion or seed rewrite. Shipped labels and names are derived in memory, so
+older schedules gain them without overwriting any customization. Labels do not
+change dispatch, issue labels, eligibility, or failure backoff.
+
+The label filter is linkable with `?label=slashdo`. It intersects the status
+filter and text search; search accepts old IDs, display names, descriptions,
+and both shipped and custom labels. Shipped labels remain available even when
+custom labels are cleared.
+
+## Recommended order for one code area
+
+The bundled `lib/slashdo/lib/better-audit.md` runs the test audit after the other
+selected audit scopes so it can consume their findings; those other audit
+scopes are independent. Follow that for an issues-only audit batch. The sequence
+below concerns **implementing changes in the same area**: tests still need to
+protect behavior before a refactor begins.
+
+This is engineering guidance, not a dependency graph or a claim that every repo
+needs every pass. Existing evidence and urgent defects take priority.
+
+1. Broad code-quality triage if needed; ensure tests detect behavior and add
+ missing boundary coverage. Fix security, data-loss, and runtime defects first.
+2. **Structural drift**: consolidate sources of truth before polishing code
+ that may disappear. **Simplify**: remove dead and duplicate code next.
+3. **Module hygiene**: establish ownership, reuse, and boundaries. Remove
+ unnecessary dependencies once the surviving owners are clear.
+4. **Complexity**: remeasure branching in surviving functions and simplify the
+ costly ones. **Cognitive load**: review readability of the final shape.
+5. Revalidate runtime behavior and meaningful tests; measure performance where
+ there is a demonstrated bottleneck. Refresh documentation after changes land.
+
+Thus module hygiene generally precedes function-level cyclomatic complexity,
+and structural drift generally precedes both. A localized hot function can be
+improved independently when it has no ownership or source-of-truth problem.
+API, React, accessibility, UI, copy, and observability passes follow the needs of
+the changed area rather than a universal rank. Work on disjoint areas may run
+independently; serialize overlapping edits, merge, and reassess before the next
+pass. A completed audit that only files issues has not completed remediation.
+The page repeats the relevant recommendation alongside each audit description;
+custom bylines remain intact and existing run-after settings are unchanged.
diff --git a/server/lib/README.md b/server/lib/README.md
index 861a16b60b..4325798daa 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -73,7 +73,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `quotaBurnLegacyConversion.js` | The ONE rule turning a LEGACY quota-burn step (copied prompt + quota-only `jobType`) into a scheduled-task reference, shared by migration 359 and the live compat path so the two cannot drift. `planQuotaBurnStepConversion` decides between three outcomes — a recognized unmodified shipped preset onto its scheduled audit counterpart with issues-only pinned explicitly (`AUDIT_TASK_TYPE_BY_PRESET_ID`, inverted from `auditCatalog.js`), the two programmatic types onto their scheduled handlers, and anything customized or targetless onto a `buildQuotaBurnCustomJob` on-demand custom task addressed by the deterministic `quotaBurnCustomJobId` (which is what makes a repeated or resumed conversion create no duplicate). `legacyAgentTaskMetadata` reproduces the retired executor's dispatch posture; `applyQuotaBurnStepConversion` rewrites the step, preserving id, label, enabled and run-once state. Recognition is `matchStoredAuditPreset`, never a label or a partial match. |
| `quotaBurnOrigin.js` | Quota-burn PROVENANCE on an on-demand scheduled-task request and on the task it produces. `normalizeQuotaBurnProvenance` reads the request block (family + burn-step id required, plus the limiting-window reset and the provider/model/effort overrides); `QUOTA_BURN_PROVENANCE_FIELDS` is the ONE block definition every persistence and projection hop derives from, spread by `quotaBurnTaskMetadata` (flat task-metadata keys), `quotaBurnAgentMetadata` (the agent projection) and read back by `quotaBurnProvenance` / `hasQuotaBurnProvenance`, which accept both the flat keys and a nested `quotaBurn` block. `onDemandRequestMetadata` is the single spread both on-demand engines apply. Import-light on purpose — `taskScheduleConstants.js` declares the origin string and must not drag the quota-burn config graph. |
| `quotaBurnPresets.js` | FROZEN compatibility-and-migration input (#6381). `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`; `matchStoredAuditPreset` is migration 305's recognition rule (match the MISSION half, gated on the shipped contract anchors + headings) and `upgradeStoredAuditPrompt` is the refresh built on it. |
-| `auditCatalog.js` | Shared catalog of scheduled AUDIT task types (`AUDIT_DEFINITIONS` / `AUDIT_TASK_TYPES`) that can either implement a fix or file tracker issues. `isFileIssuesMode`, `isExplicitFileIssuesRequest`, `FILE_ISSUES_DELIVERY_SETTINGS` (the one delivery posture every file-issues lane stamps), `auditDoWorkRequiresWorktree`, `getAuditFilingPreset`, `modeContractFor`, `applyAuditModeWrapper`. Each quota-burn audit preset maps to a scheduled type here (guarded by `auditCatalog.test.js`). Pure — no I/O. |
+| `auditCatalog.js` | `getAuditScheduleMetadata` derives upgrade-safe display names and cluster labels; `AUDIT_RUN_GUIDANCE` supplies advisory sequencing. Shared catalog of scheduled AUDIT task types (`AUDIT_DEFINITIONS` / `AUDIT_TASK_TYPES`) that can either implement a fix or file tracker issues. `isFileIssuesMode`, `isExplicitFileIssuesRequest`, `FILE_ISSUES_DELIVERY_SETTINGS` (the one delivery posture every file-issues lane stamps), `auditDoWorkRequiresWorktree`, `getAuditFilingPreset`, `modeContractFor`, `applyAuditModeWrapper`. Each quota-burn audit preset maps to a scheduled type here (guarded by `auditCatalog.test.js`). Pure — no I/O. |
| `quotaBurnTaskRef.js` | The quota-burn STEP model: a discriminated scheduled-task reference (`builtin` task type + validated target app, or `custom` app-job id whose own scope is authoritative) plus the per-invocation `overrides` bag (provider/model/effort/params — unset inherits the task's saved settings, and nothing written here edits the schedule). `normalizeQuotaBurnTaskRef` / `normalizeQuotaBurnOverrides` / `normalizeQuotaBurnParams`, the `QUOTA_BURN_UNAVAILABLE` reason codes, `resolveQuotaBurnStepAvailability` (catalog passed IN, so this stays pure) / `applyQuotaBurnAvailability`, `quotaBurnStepIsDispatchable`, and `evaluateOnDemandEligibility` — the ONE on-demand gate ladder (`enabled` / instance feature / invocation eligibility / target scope / per-app switch / master Improve) shared with `taskSchedule.triggerOnDemandTask`, with `enabledAppIdsByTaskType` deriving its per-app input. |
| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, `run once` re-arm body). |
| `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets; `parseObservedReset` pulls the reset a provider stated in its own refusal text, and `isObservedBlockActive` is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses. |
diff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.js
index 45e06ea757..da0c24acb3 100644
--- a/server/lib/auditCatalog.js
+++ b/server/lib/auditCatalog.js
@@ -576,8 +576,8 @@ export function applyAuditModeWrapper(promptTemplate, modeInstructions) {
* per-definition field could not answer the question the map exists for: did
* upstream add a lens that NOTHING here owns?
*
- * It is a parity record, not runtime wiring — nothing dereferences it at
- * dispatch. auditCatalog.test.js is its consumer, and checks it two ways: every
+ * It drives schedule discovery labels, never dispatch or execution ordering.
+ * auditCatalog.test.js checks it two ways: every
* listed type is a real audit type, and (when the submodule is checked out)
* every lens slashdo declares has an entry here, so a lens added upstream
* cannot silently go unschedulable.
@@ -595,3 +595,34 @@ export const DO_BETTER_LENS_COVERAGE = Object.freeze({
structural: ['module-hygiene', 'better-structural-drift', 'simplify'],
'cognitive-load': ['better-cognitive-load', 'better-complexity'],
});
+
+/** Display metadata is derived, so upgrades never rewrite durable task IDs. */
+export function getAuditScheduleMetadata(taskType) {
+ if (!isAuditTaskType(taskType)) return { displayName: taskType, defaultLabels: [] };
+ const lenses = Object.entries(DO_BETTER_LENS_COVERAGE)
+ .filter(([, types]) => types.includes(taskType)).map(([lens]) => lens);
+ return {
+ displayName: taskType.startsWith('better-') ? taskType : `better-${taskType}`,
+ defaultLabels: ['codebase-improvement', 'slashdo', ...lenses],
+ };
+}
+
+// Advisory phases for the SAME slice, not scheduler dependencies. Urgent bugs
+// outrank this sequence; re-measure after each merged change to avoid stale work.
+export const AUDIT_RUN_GUIDANCE = Object.freeze({
+ 'better-test-quality': 'For an audit batch, run after other findings to assess their coverage. Before implementing refactors, ensure tests detect regressions; recheck afterward.',
+ 'test-coverage': 'Audit after other findings to identify missing boundary coverage. Add needed regression tests before implementing refactors; avoid duplicate assertions.',
+ security: 'Prioritize exploitable defects before cleanup, regardless of the suggested sequence.',
+ 'data-safety': 'Fix data-loss and upgrade hazards before structural or complexity refactoring.',
+ 'better-runtime-safety': 'Fix reachable runtime defects before refactoring; rerun after structural changes.',
+ 'error-handling': 'Establish safe failure behavior before restructuring the same code.',
+ 'better-structural-drift': 'Before module hygiene or complexity, consolidate sources of truth so later refactors target the surviving implementation.',
+ simplify: 'After structural drift, remove dead and duplicate code before reorganizing modules or reducing branches.',
+ 'module-hygiene': 'After structural drift and dead-code cleanup, establish ownership and module boundaries before function-level complexity work.',
+ 'better-dependency-freedom': 'After ownership is clear, remove unnecessary dependencies before polishing functions that may be replaced.',
+ 'better-complexity': 'After structural drift, simplify, and module hygiene, remeasure surviving functions and reduce costly branching.',
+ 'better-cognitive-load': 'After complexity work, review names, abstraction levels, and readability of the final shape.',
+ 'code-quality': 'Use for broad triage first, then choose a focused audit; avoid overlapping fixes in the same slice.',
+ documentation: 'Refresh documentation after behavior and structure settle so it describes the final result.',
+ performance: 'Measure a real bottleneck before optimizing; remeasure after structural and complexity changes.',
+});
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index e3075e2ada..4d862305ae 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -21,9 +21,12 @@ const templateTaskSchema = z.object({
metadata: z.record(z.unknown()).optional(),
});
+const scheduleLabelsSchema = z.array(z.string().trim().min(1).max(40)).max(20)
+ .transform(labels => [...new Set(labels.map(label => label.toLowerCase()))]);
+
const router = Router();
-const SCHEDULE_FIELDS = ['type', 'perpetual', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'effort', 'prompt', 'description', 'dataInputs', 'taskMetadata', 'runAfter',
+const SCHEDULE_FIELDS = ['type', 'perpetual', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'effort', 'prompt', 'description', 'labels', 'dataInputs', 'taskMetadata', 'runAfter',
// Perpetual (drain-until-done) recheck cadence: after a perpetual task drains
// its backlog and parks, it re-probes its work-detector on this cadence.
// `recheckCron` (5-field) takes precedence over `recheckIntervalMs`.
@@ -66,6 +69,13 @@ function pickScheduleSettings(body) {
if (settings.cronExpression !== undefined && settings.cronExpression !== null && !isCronExpression(settings.cronExpression)) {
throw new ServerError('cronExpression must be a 5-field cron expression (minute hour dayOfMonth month dayOfWeek) or null', { status: 400, code: 'VALIDATION_ERROR' });
}
+ if (settings.labels !== undefined) {
+ const parsed = scheduleLabelsSchema.safeParse(settings.labels);
+ if (!parsed.success) {
+ throw new ServerError('labels must be at most 20 non-empty strings of at most 40 characters', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ settings.labels = parsed.data;
+ }
if (settings.description !== undefined) {
if (settings.description !== null && typeof settings.description !== 'string') {
throw new ServerError('description must be a string or null', { status: 400, code: 'VALIDATION_ERROR' });
diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.js
index 1056a63d07..83786f2bfb 100644
--- a/server/routes/cosScheduleRoutes.test.js
+++ b/server/routes/cosScheduleRoutes.test.js
@@ -474,4 +474,17 @@ describe('CoS Schedule Routes', () => {
});
});
+ it('normalizes labels, supports clearing, and rejects invalid labels before writing', async () => {
+ taskSchedule.updateTaskInterval.mockResolvedValue({ labels: ['backend'] });
+ const response = await request(app).put('/api/cos/schedule/task/security').send({ labels: [' Backend ', 'backend'] });
+ expect(response.status).toBe(200);
+ expect(taskSchedule.updateTaskInterval).toHaveBeenLastCalledWith('security', { labels: ['backend'] });
+ expect((await request(app).put('/api/cos/schedule/task/security').send({ labels: [] })).status).toBe(200);
+ taskSchedule.updateTaskInterval.mockClear();
+ for (const labels of [null, 'backend', [''], ['x'.repeat(41)], Array(21).fill('x')]) {
+ expect((await request(app).put('/api/cos/schedule/task/security').send({ labels })).status).toBe(400);
+ }
+ expect(taskSchedule.updateTaskInterval).not.toHaveBeenCalled();
+ });
+
});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 1f9a639bf9..c21f23c037 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -26,7 +26,7 @@ import { loadState, isImprovementEnabled } from './cosState.js';
import { getLocalParts } from '../lib/timezone.js';
import { getUserTimezone } from './userTimezone.js';
import { parseCronToNextRun, parseCronToPrevRun } from './eventScheduler.js';
-import { isAuditTaskType, defaultFileIssuesFor, auditDoWorkRequiresWorktree } from '../lib/auditCatalog.js';
+import { isAuditTaskType, defaultFileIssuesFor, auditDoWorkRequiresWorktree, getAuditScheduleMetadata, AUDIT_RUN_GUIDANCE } from '../lib/auditCatalog.js';
import { DEFAULT_TASK_PROMPTS } from './taskPromptDefaults.js';
import {
DEFAULT_PERPETUAL_RECHECK_MS,
@@ -235,7 +235,9 @@ export async function updateTaskInterval(taskType, settings) {
// actually parked so their stale notifications can be pruned after the save.
const topExec = schedule.executions[`task:${taskType}`];
const unparkedScopes = [];
- if (topExec) {
+ // Labels organize the page; they do not signal that a failed task is repaired.
+ const labelsOnly = Object.keys(settings).every(key => key === 'labels');
+ if (topExec && !labelsOnly) {
if (topExec.failureParkedAt) unparkedScopes.push(null);
clearFailureLedgerFields(topExec);
for (const [id, rec] of Object.entries(topExec.perApp || {})) {
@@ -1298,6 +1300,9 @@ export async function getScheduleStatus() {
const taskStatus = {
...interval,
+ ...getAuditScheduleMetadata(taskType),
+ labels: interval.labels || [],
+ runGuidance: AUDIT_RUN_GUIDANCE[taskType] || (isAuditTaskType(taskType) ? 'Run when this area has a concrete need; coordinate overlapping fixes and validate after each merge.' : null),
lastRun: execution.lastRun,
runCount: execution.count,
globalLastRun: execution.lastRun,
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index ba5cf2d713..8e4501076c 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -2347,6 +2347,17 @@ describe('taskSchedule', () => {
expect(status.improvementEnabled).toBe(false)
})
+ it('upgrades audit presentation without renaming stored schedule identities', async () => {
+ mockSchedule({ tasks: { security: { type: 'on-demand', enabled: false, labels: ['backend'], description: 'Custom summary' } } })
+ const status = await getScheduleStatus()
+ expect(status.tasks.security).toMatchObject({ displayName: 'better-security', labels: ['backend'], description: 'Custom summary', enabled: false })
+ expect(status.tasks.security.defaultLabels).toEqual(expect.arrayContaining(['slashdo', 'codebase-improvement', 'security']))
+ expect(status.tasks['better-security']).toBeUndefined()
+ expect(status.tasks['module-hygiene'].runGuidance).toContain('before function-level complexity')
+ expect(status.tasks['better-complexity'].runGuidance).toContain('After structural drift')
+ expect(status.tasks['claim-issue']).toMatchObject({ displayName: 'claim-issue', defaultLabels: [] })
+ })
+
it('projects task summaries and explains hook-owned prompts', async () => {
mockSchedule()
diff --git a/server/services/taskScheduleStore.test.js b/server/services/taskScheduleStore.test.js
index b439995392..0e1cd4e2a3 100644
--- a/server/services/taskScheduleStore.test.js
+++ b/server/services/taskScheduleStore.test.js
@@ -82,6 +82,16 @@ describe('taskScheduleStore', () => {
state.writes = [];
});
+ it('round trips custom labels without resetting execution failures or task settings', async () => {
+ state.persisted.executions['task:security'] = { count: 4, consecutiveFailures: 3, failureParkedAt: '2026-09-01T00:00:00.000Z', perApp: {} };
+ await updateTaskInterval('security', { labels: ['backend'] });
+ const reloaded = await loadSchedule();
+ expect(reloaded.tasks.security).toMatchObject({ labels: ['backend'], enabled: false });
+ expect(reloaded.executions['task:security']).toMatchObject({ count: 4, consecutiveFailures: 3, failureParkedAt: '2026-09-01T00:00:00.000Z' });
+ await updateTaskInterval('security', { labels: [] });
+ expect((await loadSchedule()).tasks.security.labels).toEqual([]);
+ });
+
it('preserves concurrent task settings and execution backoff updates', async () => {
const settingsUpdate = updateSchedule(async (schedule) => {
schedule.tasks.security.enabled = true;