Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
name scheduled-task run order by task type instead of describing it in prose
[._.]/ Adam Eivy88d7d52fb797
diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxindex e217795117..f1aa36606b 100644--- a/client/src/components/cos/tabs/ScheduleTab.jsx+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -9,7 +9,7 @@ import { CodeReviewDefaultsProvider } from '../../../hooks/useCodeReviewDefaultsimport { useAppOverrideActions } from '../../../hooks/useAppOverrideActions';import AppTaskTypeSection from './schedule/AppTaskTypeSection';import TaskConfigDrawer from './schedule/TaskConfigDrawer';-import { TASK_FILTERS, DEFAULT_FILTER_ID } from './schedule/scheduleConstants';+import { TASK_FILTERS, DEFAULT_FILTER_ID, TASK_SORTS, DEFAULT_SORT_ID, suggestedOrderSteps } from './schedule/scheduleConstants';export function mergeUpdatedTaskInterval(schedule, taskType, interval) {if (!schedule) return schedule;@@ -62,6 +62,17 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePrsetSearchParams(params, { replace: true });}, [searchParams, setSearchParams]);+ // Card ordering rides the URL like its neighbours in the same control row, so+ // a link to "the schedule in run order" survives a reload and can be shared.+ const sortParam = searchParams.get('sort');+ const sort = TASK_SORTS.some(option => option.id === sortParam) ? sortParam : DEFAULT_SORT_ID;+ const setSort = useCallback((next) => {+ const params = new URLSearchParams(searchParams);+ if (next === DEFAULT_SORT_ID) params.delete('sort');+ else params.set('sort', next);+ setSearchParams(params, { replace: true });+ }, [searchParams, setSearchParams]);+// The open config drawer is deep-linkable via ?task= per the URL-param convention.const selectedTask = searchParams.get('task');const setSelectedTask = useCallback((next) => {@@ -152,6 +163,9 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePrconst tasks = schedule.tasks || schedule.appImprovement || schedule.selfImprovement || {};const allTaskTypes = Object.keys(tasks);const selectedConfig = selectedTask ? tasks[selectedTask] : null;+ // The drawer's header shows the same advisory step the card does, so it is+ // ranked from the same graph rather than from the one open task.+ const selectedOrderStep = selectedTask ? suggestedOrderSteps(tasks)[selectedTask] : undefined;return (<CodeReviewDefaultsProvider>@@ -215,6 +229,8 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePrlabel={label}onLabelChange={setLabel}onFilterChange={setFilter}+ sort={sort}+ onSortChange={setSort}/>{schedule.lastUpdated && (@@ -237,6 +253,7 @@ export default function ScheduleTab({ apps, providers, providersLoaded, activePronUpdateOverride={handleUpdateOverride}onBulkToggleOverride={handleBulkToggleOverride}allTaskTypes={allTaskTypes}+ orderStep={selectedOrderStep}improvementDisabled={improvementDisabled}dataInputCatalog={schedule.dataInputCatalog || []}/>diff --git a/client/src/components/cos/tabs/schedule/AppTaskCard.jsx b/client/src/components/cos/tabs/schedule/AppTaskCard.jsxindex 338e841021..8d6be20225 100644--- a/client/src/components/cos/tabs/schedule/AppTaskCard.jsx+++ b/client/src/components/cos/tabs/schedule/AppTaskCard.jsx@@ -9,7 +9,7 @@ import TaskModelQuickControls from './TaskModelQuickControls';// One scheduled task rendered as a status-rich card. Browsing plus the common// "retarget the model and run it" loop happen here; the rest of the// configuration lives in the slide-over drawer (opened via Configure).-export default function AppTaskCard({ taskType, config, apps, onTrigger, onConfigure, onUpdate, providers, providersLoaded = true, activeProviderId, improvementDisabled }) {+export default function AppTaskCard({ taskType, config, apps, onTrigger, onConfigure, onUpdate, providers, providersLoaded = true, activeProviderId, improvementDisabled, orderStep }) {// Owned here, not in the controls, so Run can gate on the same `saving` flag —// it reads the server-side config, so a run fired mid-write uses the old pins.const pins = useTaskModelPins({ taskType, config, providers, activeProviderId, onUpdate });@@ -35,7 +35,7 @@ export default function AppTaskCard({ taskType, config, apps, onTrigger, onConfionClick={() => onConfigure(taskType)}className="flex-1 flex flex-col items-stretch gap-3 text-left p-4 rounded-t-lg hover:bg-port-card/60 transition-colors">- <TaskHeader taskType={taskType} config={config} />+ <TaskHeader taskType={taskType} config={config} orderStep={orderStep} />{/* Next run */}<div className="flex items-center gap-1.5 text-xs min-w-0">@@ -66,8 +66,11 @@ export default function AppTaskCard({ taskType, config, apps, onTrigger, onConfi? `Last run ${timeAgo(config.globalLastRun)} · ${config.globalRunCount || 0}×`: 'Never run'}</div>+ {/* "waits for" is the ENFORCED gate; the advisory order renders as+ "Run first:" chips in TaskHeader above. Spelling out the+ difference here keeps the two lines from reading as one. */}{config.runAfter?.length > 0 && (- <div className="truncate">after: {config.runAfter.join(', ')}</div>+ <div className="truncate" title={`Blocked until these run: ${config.runAfter.join(', ')}`}>waits for: {config.runAfter.join(', ')}</div>)}</div></button>diff --git a/client/src/components/cos/tabs/schedule/AppTaskTypeSection.jsx b/client/src/components/cos/tabs/schedule/AppTaskTypeSection.jsxindex d292a23a30..2f110bc75c 100644--- a/client/src/components/cos/tabs/schedule/AppTaskTypeSection.jsx+++ b/client/src/components/cos/tabs/schedule/AppTaskTypeSection.jsx@@ -1,11 +1,14 @@-import { useState } from 'react';+import { useMemo, useState } from 'react';import { Search, X } from 'lucide-react';import AppTaskCard from './AppTaskCard';-import { TASK_FILTERS, DEFAULT_FILTER_ID, taskSortKey, taskLabels } from './scheduleConstants';+import { TASK_FILTERS, DEFAULT_FILTER_ID, TASK_SORTS, compareByStatus, compareBySuggestedOrder, suggestedOrderSteps, taskLabels } from './scheduleConstants';-export default function AppTaskTypeSection({ tasks, apps, providers, providersLoaded, activeProviderId, onTrigger, onUpdate, onSelectTask, improvementDisabled, filter, onFilterChange, label = '', onLabelChange }) {+export default function AppTaskTypeSection({ tasks, apps, providers, providersLoaded, activeProviderId, onTrigger, onUpdate, onSelectTask, improvementDisabled, filter, onFilterChange, label = '', onLabelChange, sort, onSortChange }) {const [search, setSearch] = useState('');const taskEntries = Object.entries(tasks || {});+ // Ranked over every task, not just the visible ones, so filtering to one+ // label doesn't renumber the sequence under the user.+ const orderSteps = useMemo(() => suggestedOrderSteps(tasks), [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]));@@ -16,11 +19,7 @@ export default function AppTaskTypeSection({ tasks, apps, providers, providersLo.filter(activeFilter.match).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);- return a.order - b.order || a.next - b.next || a.taskType.localeCompare(b.taskType);- });+ .sort(sort === 'suggested-order' ? compareBySuggestedOrder(orderSteps) : compareByStatus);if (taskEntries.length === 0) return null;@@ -84,6 +83,12 @@ export default function AppTaskTypeSection({ tasks, apps, providers, providersLo{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>}+ <label htmlFor="schedule-sort" className="text-sm text-gray-400">Sort</label>+ <select id="schedule-sort" value={sort} onChange={event => onSortChange(event.target.value)}+ className="max-w-full bg-port-card border border-port-border rounded px-3 py-2 text-sm text-white"+ title="Suggested order sorts by each task's advisory position — what to run first">+ {TASK_SORTS.map(option => <option key={option.id} value={option.id}>{option.label}</option>)}+ </select></div>{visibleEntries.length === 0 ? (@@ -110,6 +115,7 @@ export default function AppTaskTypeSection({ tasks, apps, providers, providersLoonUpdate={onUpdate}onConfigure={onSelectTask}improvementDisabled={improvementDisabled}+ orderStep={orderSteps[taskType]}/>))}</div>diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsxindex 8447bd2d2a..f984d7bb16 100644--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx@@ -16,6 +16,7 @@ import useTaskModelPins from '../../../../hooks/useTaskModelPins';import { effectiveModelFor, selectableProviders } from '../../../../utils/providers';import EffortSelect from '../../EffortSelect';import PromptEditor from './PromptEditor';+import TaskDependencyPicker from './TaskDependencyPicker';import RunTaskButton from './RunTaskButton';import TaskDataInputs from '../../TaskDataInputs';import { INTERVAL_DESCRIPTIONS, PERPETUAL_DESCRIPTION, toggleMetadataField, pipelineStages, IMPROVEMENT_DISABLED_TITLE, SAVING_TITLE, fileIssuesEffective, managedAgentOptionsFor, toggleFileIssuesMetadata } from './scheduleConstants';@@ -718,35 +719,38 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri</div>{allTaskTypes?.length > 1 && (- <div>- <span className="text-sm text-gray-400 block mb-2">Run After (dependencies)</span>- <div className="flex flex-wrap gap-2">- {allTaskTypes.filter(t => t !== taskType).map(dep => {- const isSelected = (config.runAfter || []).includes(dep);- return (- <button- key={dep}- onClick={() => {- const current = config.runAfter || [];- const updated = isSelected- ? current.filter(d => d !== dep)- : [...current, dep];- onUpdate(taskType, { runAfter: updated.length > 0 ? updated : null });- }}- disabled={updating}- className={`text-xs px-2 py-1 rounded border transition-colors ${- isSelected- ? 'bg-port-accent/20 border-port-accent/50 text-port-accent'- : 'bg-port-card border-port-border text-gray-400 hover:border-gray-500'- }`}- >- {dep}- </button>- );- })}- </div>- <p className="text-xs text-gray-500 mt-1">This task will wait for selected tasks to complete first within the same cycle</p>- </div>+ <>+ {/* Advisory first: it answers "which of these do I run first?", which+ is the question most users open this panel with. The enforced gate+ below it is the rarer, heavier choice. */}+ <TaskDependencyPicker+ label="Suggested order (advisory)"+ hint="Tasks worth running before this one. Advisory only — nothing is blocked, and this task still runs whether or not they have. Use Run After below for a hard gate."+ taskType={taskType}+ options={allTaskTypes}+ value={config.suggestedAfter || []}+ disabled={updating}+ onChange={(next) => {+ setUpdating(true);+ // Sent as-is: an emptied list saves `[]`, which the server reads+ // back as a deliberate clear rather than re-inheriting the+ // shipped order (see normalizeSuggestedAfter).+ onUpdate(taskType, { suggestedAfter: next }).finally(() => setUpdating(false));+ }}+ />+ <TaskDependencyPicker+ label="Run After (enforced dependencies)"+ hint="This task waits for the selected tasks to complete first within the same cycle."+ taskType={taskType}+ options={allTaskTypes}+ value={config.runAfter || []}+ disabled={updating}+ onChange={(next) => {+ setUpdating(true);+ onUpdate(taskType, { runAfter: next.length > 0 ? next : null }).finally(() => setUpdating(false));+ }}+ />+ </>)}<div className="flex gap-2">diff --git a/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx b/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsxindex 3ce26232d8..f3e7040a59 100644--- a/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx+++ b/client/src/components/cos/tabs/schedule/TaskConfigDrawer.jsx@@ -35,6 +35,7 @@ export default function TaskConfigDrawer({onUpdateOverride,onBulkToggleOverride,allTaskTypes,+ orderStep,improvementDisabled,dataInputCatalog,}) {@@ -70,7 +71,7 @@ export default function TaskConfigDrawer({>{config && (<div className="space-y-6">- <TaskHeader taskType={taskType} config={config} />+ <TaskHeader taskType={taskType} config={config} orderStep={orderStep} />{activeTab === 'stages' && hasStages && (<PipelineStageConfigdiff --git a/client/src/components/cos/tabs/schedule/TaskDependencyPicker.jsx b/client/src/components/cos/tabs/schedule/TaskDependencyPicker.jsxnew file mode 100644index 0000000000..80bc869386--- /dev/null+++ b/client/src/components/cos/tabs/schedule/TaskDependencyPicker.jsx@@ -0,0 +1,66 @@+import { useState } from 'react';+import { X } from 'lucide-react';+import { FormField } from '../../../ui/FormField';+import { badge } from './scheduleConstants';++/**+ * Pick a list of OTHER scheduled tasks by name — used for both dependency+ * fields on a task: the enforced `runAfter` gate and the advisory+ * `suggestedAfter` run order.+ *+ * Selected tasks render as removable chips and everything else lives behind one+ * "Add a task…" select. The earlier shape rendered every registered task type+ * as a toggle button, which on this install is a wall of ~60 chips per field —+ * so the two or three that were actually selected were the hardest thing on the+ * panel to find. Chips-plus-select keeps the answer ("these ones") at the top+ * and the roster one click away.+ */+export default function TaskDependencyPicker({ label, hint, taskType, options = [], value = [], disabled, onChange }) {+ const [pending, setPending] = useState('');+ const selected = value.filter(Boolean);+ const available = options+ .filter(option => option !== taskType && !selected.includes(option))+ .sort((a, b) => a.localeCompare(b));++ const commit = (next) => {+ setPending('');+ onChange(next);+ };++ // FormField owns the label/hint and the htmlFor pairing, so the chips sit+ // under the control it labels rather than between the two.+ return (+ <FormField label={label} hint={hint} labelClassName="text-sm text-gray-400 block mb-1">+ <select+ value={pending}+ disabled={disabled || available.length === 0}+ onChange={(event) => {+ const next = event.target.value;+ if (next) commit([...selected, next]);+ }}+ className="max-w-full bg-port-card border border-port-border rounded px-3 py-2 text-sm text-white disabled:opacity-50"+ >+ <option value="">{available.length === 0 ? 'No other tasks available' : 'Add a task…'}</option>+ {available.map(option => <option key={option} value={option}>{option}</option>)}+ </select>+ {selected.length > 0 && (+ <div className="flex flex-wrap gap-2 mt-2">+ {selected.map(dep => (+ <span key={dep} className={`${badge('accent')} inline-flex items-center gap-1 font-mono`}>+ {dep}+ <button+ type="button"+ onClick={() => commit(selected.filter(entry => entry !== dep))}+ disabled={disabled}+ aria-label={`Remove ${dep}`}+ className="text-port-accent/70 hover:text-white disabled:opacity-50"+ >+ <X size={12} />+ </button>+ </span>+ ))}+ </div>+ )}+ </FormField>+ );+}diff --git a/client/src/components/cos/tabs/schedule/TaskDependencyPicker.test.jsx b/client/src/components/cos/tabs/schedule/TaskDependencyPicker.test.jsxnew file mode 100644index 0000000000..036ef847c1--- /dev/null+++ b/client/src/components/cos/tabs/schedule/TaskDependencyPicker.test.jsx@@ -0,0 +1,46 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import TaskDependencyPicker from './TaskDependencyPicker';++const OPTIONS = ['simplify', 'module-hygiene', 'better-complexity', 'self'];++function renderPicker(props = {}) {+ const onChange = vi.fn();+ render(+ <TaskDependencyPicker+ label="Suggested order (advisory)"+ taskType="self"+ options={OPTIONS}+ value={['simplify']}+ onChange={onChange}+ {...props}+ />+ );+ return { onChange };+}++describe('TaskDependencyPicker', () => {+ it('offers only unselected tasks, and never the task itself', () => {+ renderPicker();+ const select = screen.getByLabelText('Suggested order (advisory)');+ const values = [...select.options].map(option => option.value);+ expect(values).toEqual(['', 'better-complexity', 'module-hygiene']);+ });++ it('appends the chosen task to the list', () => {+ const { onChange } = renderPicker();+ fireEvent.change(screen.getByLabelText('Suggested order (advisory)'), { target: { value: 'module-hygiene' } });+ expect(onChange).toHaveBeenCalledWith(['simplify', 'module-hygiene']);+ });++ it('removes a chip, handing back an empty list rather than nothing', () => {+ const { onChange } = renderPicker();+ fireEvent.click(screen.getByLabelText('Remove simplify'));+ expect(onChange).toHaveBeenCalledWith([]);+ });++ it('disables the roster when there is nothing left to add', () => {+ renderPicker({ value: ['simplify', 'module-hygiene', 'better-complexity'] });+ expect(screen.getByLabelText('Suggested order (advisory)')).toBeDisabled();+ });+});diff --git a/client/src/components/cos/tabs/schedule/TaskHeader.jsx b/client/src/components/cos/tabs/schedule/TaskHeader.jsxindex 5a786d6b1c..a5ab7e51dc 100644--- a/client/src/components/cos/tabs/schedule/TaskHeader.jsx+++ b/client/src/components/cos/tabs/schedule/TaskHeader.jsx@@ -1,11 +1,11 @@-import { GitBranch, GitMerge, Users } from 'lucide-react';+import { GitBranch, GitMerge, ListOrdered, Users } from 'lucide-react';import { taskLabels, badge, statusDot, getTaskStatusGroup, pipelineStages } from './scheduleConstants';import IntervalBadge from './IntervalBadge';// Shared task identity row — status dot, monospace name, pipeline + swarm// badges, and interval badge. Used by both the schedule card and the config// drawer so the header stays consistent in one place.-export default function TaskHeader({ taskType, config }) {+export default function TaskHeader({ taskType, config, orderStep }) {const group = getTaskStatusGroup(config);const stages = pipelineStages(config);const invocation = config.invocation;@@ -15,6 +15,10 @@ export default function TaskHeader({ taskType, config }) {// shows its own override select).const swarmCount = config.taskMetadata?.swarmCount;const swarmOn = Number.isInteger(swarmCount) && swarmCount >= 2;+ // Advisory predecessors, named by task type. `orderStep` is passed in rather+ // than read off the config: it is ranked across the whole schedule, which a+ // single task config cannot know.+ const suggestedAfter = Array.isArray(config.suggestedAfter) ? config.suggestedAfter : [];const branchesPerAgent = config.taskMetadata?.branchesPerAgent;const branchBatchOn = taskType === 'branch-reconcile' && Number.isInteger(branchesPerAgent) && branchesPerAgent > 0;return (@@ -33,6 +37,20 @@ export default function TaskHeader({ taskType, config }) {{invocation.label || 'Automation-only'}</span>)}+ {/* Where this task falls in the advisory order — only for tasks that+ actually participate in it, so an unordered task isn't mislabeled+ as "the first thing to run". */}+ {Number.isInteger(orderStep) && (+ <span+ className={`${badge('gray')} whitespace-nowrap`}+ title={suggestedAfter.length > 0+ ? `Suggested order step ${orderStep} — run ${suggestedAfter.join(', ')} first (advisory, never enforced)`+ : `Suggested order step ${orderStep} — nothing is suggested before this one`}+ >+ <ListOrdered size={11} className="inline mr-0.5" />+ {orderStep}+ </span>+ )}{swarmOn && (<span className={`${badge('cyan')} whitespace-nowrap`} title={`Swarm mode — claims & ships up to ${swarmCount} independent issues in parallel per run`}><Users size={11} className="inline mr-0.5" />@@ -57,7 +75,16 @@ 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>}+ {/* The chips name real scheduled task types; `runGuidance` below is the why. */}+ {suggestedAfter.length > 0 && (+ <p className="text-xs text-gray-400 flex flex-wrap items-center gap-1">+ <span className="text-gray-500">Run first:</span>+ {suggestedAfter.map(dep => (+ <span key={dep} className={`${badge('gray')} font-mono`} title={`${dep} is a scheduled task — running it before ${taskType} is suggested, not required`}>{dep}</span>+ ))}+ </p>+ )}+ {config.runGuidance && <p className="text-xs text-gray-500 line-clamp-2" title={config.runGuidance}>{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>)}diff --git a/client/src/components/cos/tabs/schedule/TaskHeader.test.jsx b/client/src/components/cos/tabs/schedule/TaskHeader.test.jsxnew file mode 100644index 0000000000..3bb91cb3b7--- /dev/null+++ b/client/src/components/cos/tabs/schedule/TaskHeader.test.jsx@@ -0,0 +1,34 @@+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import TaskHeader from './TaskHeader';++const baseConfig = { enabled: true, type: 'on-demand' };++function renderHeader(overrides = {}, orderStep = undefined, taskType = 'better-complexity') {+ render(<TaskHeader taskType={taskType} config={{ ...baseConfig, ...overrides }} orderStep={orderStep} />);+}++describe('TaskHeader advisory run order', () => {+ it('names the tasks to run first instead of describing them in prose', () => {+ renderHeader({ suggestedAfter: ['module-hygiene'] }, 4);+ expect(screen.getByText('Run first:')).toBeInTheDocument();+ expect(screen.getByText('module-hygiene')).toBeInTheDocument();+ });++ it('shows the order step for a task inside the sequence', () => {+ renderHeader({ suggestedAfter: ['module-hygiene'] }, 4);+ expect(screen.getByTitle(/Suggested order step 4 — run module-hygiene first/)).toBeInTheDocument();+ });++ it('shows no step for a task outside the sequence — unordered is not "first"', () => {+ renderHeader({}, undefined, 'claim-issue');+ expect(screen.queryByTitle(/Suggested order step/)).not.toBeInTheDocument();+ expect(screen.queryByText('Run first:')).not.toBeInTheDocument();+ });++ it('keeps the rationale prose as a separate line from the named order', () => {+ renderHeader({ suggestedAfter: ['module-hygiene'], runGuidance: 'Remeasures the functions that survived the ladder.' }, 4);+ expect(screen.getByText('Remeasures the functions that survived the ladder.')).toBeInTheDocument();+ expect(screen.getByText('Run first:')).toBeInTheDocument();+ });+});diff --git a/client/src/components/cos/tabs/schedule/scheduleConstants.js b/client/src/components/cos/tabs/schedule/scheduleConstants.jsindex 4a066cb5cf..feffbfe211 100644--- a/client/src/components/cos/tabs/schedule/scheduleConstants.js+++ b/client/src/components/cos/tabs/schedule/scheduleConstants.js@@ -154,6 +154,69 @@ export function taskSortKey(taskType, config) {return { order: STATUS_GROUPS[group]?.order ?? 9, next: Number.isFinite(next) ? next : Infinity, taskType };}+// The two card orderings the grid offers. "Status" is the long-standing+// default; "Suggested order" answers "which of these do I run first?" using the+// advisory `suggestedAfter` list each task carries.+export const TASK_SORTS = [+ { id: 'status', label: 'Status' },+ { id: 'suggested-order', label: 'Suggested order' },+];+export const DEFAULT_SORT_ID = TASK_SORTS[0].id;++/**+ * Rank the tasks that PARTICIPATE in the advisory `suggestedAfter` graph into a+ * 1-based step — one past the highest step among the predecessors present here.+ *+ * Derived on the client, over the tasks actually being shown, because the step+ * is a property of the whole graph rather than of one task: a server-sent+ * per-task number goes stale the instant any OTHER task's list is edited, and+ * ranking server-side would also number a card whose step-1 predecessor is+ * hidden by a disabled instance feature.+ *+ * A task nobody orders and that orders nothing gets NO step — it sits outside+ * the sequence, and calling every unordered task "step 1" would drown the+ * answer. Edges naming an absent task are ignored; a user-declared cycle simply+ * stops improving once the pass budget runs out (nothing enforces these).+ */+export function suggestedOrderSteps(tasks) {+ const entries = Object.entries(tasks || {});+ const known = new Set(entries.map(([taskType]) => taskType));+ const deps = new Map(entries.map(([taskType, config]) => [+ taskType,+ (Array.isArray(config?.suggestedAfter) ? config.suggestedAfter : []).filter(dep => dep !== taskType && known.has(dep)),+ ]));+ const participants = new Set([...deps].flatMap(([taskType, after]) => (after.length ? [taskType, ...after] : [])));++ const steps = Object.fromEntries([...participants].map(taskType => [taskType, 1]));+ let changed = true;+ let passes = 0;+ while (changed && passes <= participants.size) {+ changed = false;+ passes++;+ for (const taskType of participants) {+ const step = deps.get(taskType).reduce((max, dep) => Math.max(max, steps[dep] + 1), 1);+ if (step !== steps[taskType]) {+ steps[taskType] = step;+ changed = true;+ }+ }+ }+ return steps;+}++// Comparator for the default "Status" view: group order, then soonest next run.+export function compareByStatus([aType, aConfig], [bType, bConfig]) {+ const a = taskSortKey(aType, aConfig);+ const b = taskSortKey(bType, bConfig);+ return a.order - b.order || a.next - b.next || a.taskType.localeCompare(b.taskType);+}++// Comparator for the "Suggested order" view, over a `suggestedOrderSteps` map.+// Tasks OUTSIDE the advisory order sort last rather than first — they carry no+// ordering claim, and putting them on top would bury the answer.+export const compareBySuggestedOrder = (steps) => ([aType], [bType]) =>+ (steps[aType] ?? Infinity) - (steps[bType] ?? Infinity) || aType.localeCompare(bType);+// Tailwind tone for the per-task app-coverage bar/label (error none, success full, warning partial).export function coverageTone(enabled, total) {if (enabled === 0) return { text: 'text-port-error', bar: 'bg-port-error' };diff --git a/client/src/components/cos/tabs/schedule/scheduleConstants.test.js b/client/src/components/cos/tabs/schedule/scheduleConstants.test.jsindex 9bf8999546..a87dd0212e 100644--- a/client/src/components/cos/tabs/schedule/scheduleConstants.test.js+++ b/client/src/components/cos/tabs/schedule/scheduleConstants.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { getTaskStatusGroup, taskSortKey, TASK_FILTERS, STATUS_GROUPS, describeNextRun, coverageTone, setMetadataOverride, toggleMetadataField, fileIssuesEffective, managedAgentOptionsFor, toggleFileIssuesMetadata, prReviewerStageRole, stagePublicReviewPosture, togglePrReviewerActions } from './scheduleConstants';+import { getTaskStatusGroup, taskSortKey, TASK_FILTERS, STATUS_GROUPS, describeNextRun, coverageTone, setMetadataOverride, toggleMetadataField, fileIssuesEffective, managedAgentOptionsFor, toggleFileIssuesMetadata, prReviewerStageRole, stagePublicReviewPosture, togglePrReviewerActions, suggestedOrderSteps, compareBySuggestedOrder } from './scheduleConstants';describe('pr-reviewer pipeline helpers', () => {it('recognizes semantic roles and legacy prompt-key stages', () => {@@ -284,3 +284,37 @@ describe('coverageTone', () => {});});// @vitest-environment node++describe('suggestedOrderSteps', () => {+ it('ranks a chain one step past its latest predecessor', () => {+ const steps = suggestedOrderSteps({+ a: {},+ b: { suggestedAfter: ['a'] },+ c: { suggestedAfter: ['b'] },+ d: { suggestedAfter: ['a', 'c'] },+ });+ expect(steps).toEqual({ a: 1, b: 2, c: 3, d: 4 });+ });++ it('leaves a task that neither names nor is named unranked, not "step 1"', () => {+ const steps = suggestedOrderSteps({ ordered: { suggestedAfter: ['head'] }, head: {}, loner: {} });+ expect(steps.loner).toBeUndefined();+ expect(steps).toMatchObject({ head: 1, ordered: 2 });+ });++ it('ignores an edge naming a task this install does not have', () => {+ expect(suggestedOrderSteps({ here: { suggestedAfter: ['from-a-newer-peer'] } })).toEqual({});+ });++ it('terminates on a user-declared cycle instead of hanging', () => {+ const steps = suggestedOrderSteps({ a: { suggestedAfter: ['b'] }, b: { suggestedAfter: ['a'] } });+ expect(Number.isInteger(steps.a)).toBe(true);+ expect(Number.isInteger(steps.b)).toBe(true);+ });++ it('sorts unranked tasks last — they make no ordering claim', () => {+ const steps = { late: 3, early: 1 };+ const sorted = [['unranked', {}], ['late', {}], ['early', {}]].sort(compareBySuggestedOrder(steps));+ expect(sorted.map(([taskType]) => taskType)).toEqual(['early', 'late', 'unranked']);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 4325798daa..52a3163637 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -419,6 +419,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `taskStatusTransition.js` | The CoS task STATUS TRANSITION vocabulary (#6620) — `resolveTaskStatusTransition(previousStatus, nextStatus)` classifies one update's status pair ONCE and returns `{ action, isRevive, isRequeue, entersInProgress, leavesInProgress, leavesBlocked, isTerminal }`, so `writeTaskUpdate`'s blocked/pause clear, resume-pointer drop, retry-hold retire, claim release, requeue stamp and emitted `tasks:changed` action all read one answer instead of re-deriving seven. A falsy `nextStatus` means "this patch carries no status" (a lease-renewal heartbeat) and releases nothing. `isTerminalTaskStatus(status)` is the shared `completed`/`blocked` predicate `cosTaskStore` and `cosTaskMerge` both read. Pure — metadata predicates (is this block a pause?) stay at the application site. || `taskTargetBranch.js` | Pure task-branch contract: `resolveTaskTargetBranch(metadata)` reads a retry's legacy `existingBranch` or a review-loop follow-up's canonical `reviewLoopPRBranch`; `shouldStripTaskTargetBranch(metadata)` identifies only retry-owned pointers for terminal cleanup. || `scheduledTaskTypes.js` | Registered scheduled task names (`SELF_IMPROVEMENT_TASK_TYPES`), shared by schedule configuration and authoritative skill routing. |+| `scheduleRunOrder.js` | Storage rules for a task's advisory `suggestedAfter` list — which OTHER scheduled tasks to run first. `normalizeSuggestedAfter` drops blanks, duplicates and self-references and caps at `SUGGESTED_AFTER_MAX`; the shipped order it defaults to is `auditCatalog.AUDIT_SUGGESTED_AFTER`, layered at read time in `getScheduleStatus`. Advisory only — the ENFORCED dependency field is `runAfter`. Pure — no I/O. || `taskTargetScope.js` | Target scope for a scheduled task type: `INSTALL_WIDE_TASK_TYPES`, `MANAGED_APP_TARGET_TASK_TYPES`, `PROGRAMMATIC_SCHEDULED_TASK_TYPES`, `isProgrammaticScheduledTaskType`, `requiresManagedAppTarget`, `requiresInstallWideTarget`. Declared here (not in `services/taskScheduleRegistry.js`, which re-exports it) so `quotaBurnValidation.js` can reject a burn reference with the wrong target scope without importing upward into services. || `taxonomyTally.js` | Generic taxonomy tally + top-N-line render engine shared by the two Layered Intelligence leaf taxonomies (`services/layeredIntelligenceRejections.js`, `layeredIntelligenceExecutionFailures.js`). `createTaxonomyTally({predicate, select, field, vocabulary, sentinel, glossFn, gapWording})` is the single composed seam — it binds a taxonomy config into `{summarize, format}`, where `summarize(records)` yields the three-bucket `{entries, unknown, unclassified, diagnosed, total}` tally (commonest-first + taxonomy-order tie-break) and `format(records, limit)` renders one prompt line naming every non-zero gap. Also exports the two leaf utilities the classifiers use directly: `normalizeToken(value)` (lowercase + separator-collapse for label/category matching) and `formatTaxonomyToken(token, labels)` (gloss-map render, nullish→'', unglossed passthrough). Pure leaf — imports nothing from the LI graph. || `worktreeOwnership.js` | Pure ownership gate for destructive worktree operations. `worktreeOwnershipReason()` applies root, agent-id, lock, active-agent, liveness and claim policies IN THAT ORDER, so an unconditional hold always outranks a claim and callers never re-derive the precedence from the slug; the claim hold has two opt-outs (`allowStaleClaim` for reapers, `allowLiveClaim` for the dispatch side). `worktreeAgentId()` is separator-safe; `isHumanClaimWorktree()` and `isAgentWorktreeId()` make the protected namespaces explicit; `worktreeHoldExpiresAt()` names when a hold lapses on its own (the stale-claim window) so callers can wait exactly that long. |diff --git a/server/lib/auditCatalog.js b/server/lib/auditCatalog.jsindex da0c24acb3..097906d312 100644--- a/server/lib/auditCatalog.js+++ b/server/lib/auditCatalog.js@@ -607,22 +607,68 @@ export function getAuditScheduleMetadata(taskType) {};}-// Advisory phases for the SAME slice, not scheduler dependencies. Urgent bugs-// outrank this sequence; re-measure after each merged change to avoid stale work.+/**+ * Shipped advisory run order for the audit types, named by SCHEDULED TASK TYPE.+ *+ * This is the default for each task's editable `suggestedAfter` array, layered+ * at READ time by `getScheduleStatus` (services/taskSchedule.js) rather than+ * seeded onto the stored rows — like `runGuidance` and `displayName` beside it,+ * so an edit here reaches every existing install with no migration, while a+ * user's stored list (an explicit `[]` included) still wins. It is ADVISORY:+ * nothing in the scheduler reads it, and a task whose suggested predecessors+ * haven't run still runs. The ENFORCED field is `runAfter`, which blocks+ * dispatch until each named type has run since this task's last run.+ *+ * The prose it replaced ("After structural drift, remove dead code…") named the+ * audits by their subject matter rather than by their task type, so a reader+ * could not tell whether "structural drift" was another scheduled task or just+ * a concept — which is the whole question the guidance exists to answer.+ *+ * Each entry lists only its IMMEDIATE predecessors; transitive order follows+ * from the chain (better-cognitive-load comes after simplify because it comes+ * after better-complexity, which comes after module-hygiene, which comes after+ * simplify). Keeping the lists to one or two entries is deliberate — a list+ * that restates the whole chain is unreadable and drifts on every edit.+ *+ * The safety audits (security, data-safety, better-runtime-safety,+ * error-handling) and the broad code-quality triage seed EMPTY: they are the+ * head of the order, and an exploitable defect outranks the sequence anyway.+ */+export const AUDIT_SUGGESTED_AFTER = Object.freeze({+ // Broad triage first, then coverage, so the tests written next are aimed at+ // the findings the triage surfaced.+ 'test-coverage': Object.freeze(['code-quality']),+ 'better-test-quality': Object.freeze(['test-coverage']),+ // The restructuring ladder: consolidate sources of truth, delete what is+ // dead, then draw module boundaries, then reduce what survives.+ simplify: Object.freeze(['better-structural-drift']),+ 'module-hygiene': Object.freeze(['simplify']),+ 'better-dependency-freedom': Object.freeze(['module-hygiene']),+ 'better-complexity': Object.freeze(['module-hygiene']),+ 'better-cognitive-load': Object.freeze(['better-complexity']),+ // Measure and describe the shape that survived the ladder.+ performance: Object.freeze(['better-complexity']),+ documentation: Object.freeze(['better-cognitive-load']),+});++// WHY each audit sits where it does in the order above — rationale only. The+// sequence itself is AUDIT_SUGGESTED_AFTER, which names real task types; this+// text must never be the only place an ordering relationship is recorded.+// Urgent bugs outrank the sequence; re-measure after each merged change.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.',+ 'better-test-quality': 'Assesses whether the tests you have detect the regressions the other audits found — so refactors that follow have a safety net.',+ 'test-coverage': 'Adds the missing boundary coverage a refactor needs before it starts; avoid duplicating assertions a stronger test already makes.',+ security: 'Head of the order — an exploitable defect is fixed before any cleanup, whatever else is queued.',+ 'data-safety': 'Head of the order — data-loss and upgrade hazards are fixed before code moves around them.',+ 'better-runtime-safety': 'Head of the order — reachable runtime defects are fixed first; rerun once structure settles.',+ 'error-handling': 'Head of the order — safe failure behavior is established before the same code is restructured.',+ 'better-structural-drift': 'Start of the restructuring ladder: consolidating sources of truth first means every later refactor targets the surviving implementation.',+ simplify: 'Dead and duplicate code is removed before modules are reorganized, so the reorganization only moves live code.',+ 'module-hygiene': 'Ownership and module boundaries are settled before function-level work, so complexity is measured on the final layout.',+ 'better-dependency-freedom': 'Unnecessary dependencies go once ownership is clear, so no effort is spent polishing code a removal deletes.',+ 'better-complexity': 'Remeasures the functions that survived the ladder and reduces the costliest branching.',+ 'better-cognitive-load': 'Reviews names, abstraction levels, and readability of the shape everything else left behind.',+ 'code-quality': 'Broad triage that points at the focused audit worth running; avoid overlapping fixes in the same slice.',+ documentation: 'Describes the final result, so it runs once behavior and structure have settled.',+ performance: 'Measure a real bottleneck before optimizing, and remeasure after structural and complexity changes.',});diff --git a/server/lib/auditCatalog.test.js b/server/lib/auditCatalog.test.jsindex 26c58d85d7..61a4d2b86a 100644--- a/server/lib/auditCatalog.test.js+++ b/server/lib/auditCatalog.test.js@@ -16,6 +16,8 @@ import {modeContractFor,applyAuditModeWrapper,DO_BETTER_LENS_COVERAGE,+ AUDIT_RUN_GUIDANCE,+ AUDIT_SUGGESTED_AFTER,} from './auditCatalog.js';describe('AUDIT_DEFINITIONS', () => {@@ -261,3 +263,49 @@ describe('DO_BETTER_LENS_COVERAGE', () => {expect(missing).toEqual([]);});});++// The advisory run order and the prose that explains it are two halves of one+// answer to "which audit do I run first?" — the order names task types, the+// prose says why. They can drift silently (nothing dispatches on either), so+// pin the claims they make about each other.+describe('AUDIT_SUGGESTED_AFTER', () => {+ it('names only registered task types, in both directions', async () => {+ const { DEFAULT_TASK_INTERVALS } = await import('../services/taskScheduleRegistry.js');+ for (const [taskType, after] of Object.entries(AUDIT_SUGGESTED_AFTER)) {+ expect(DEFAULT_TASK_INTERVALS[taskType], taskType).toBeDefined();+ for (const dep of after) expect(DEFAULT_TASK_INTERVALS[dep], `${taskType} -> ${dep}`).toBeDefined();+ }+ });++ it('keeps each entry to its immediate predecessors — a restated chain is unreadable', () => {+ for (const [taskType, after] of Object.entries(AUDIT_SUGGESTED_AFTER)) {+ expect(after.length, taskType).toBeLessThanOrEqual(2);+ }+ });++ it('is acyclic, so the shipped ladder reads as one sequence', () => {+ const seen = new Set();+ const walk = (taskType, trail) => {+ expect(trail.includes(taskType), `cycle: ${[...trail, taskType].join(' -> ')}`).toBe(false);+ for (const dep of AUDIT_SUGGESTED_AFTER[taskType] || []) walk(dep, [...trail, taskType]);+ seen.add(taskType);+ };+ for (const taskType of Object.keys(AUDIT_SUGGESTED_AFTER)) walk(taskType, []);+ expect(seen.size).toBeGreaterThan(0);+ });++ // "Head of the order" is a claim about the DATA. A type given a predecessor+ // later must lose that phrasing, or the card contradicts its own chips.+ it('reserves the "head of the order" phrasing for types with no predecessor', () => {+ for (const [taskType, guidance] of Object.entries(AUDIT_RUN_GUIDANCE)) {+ if (!guidance.startsWith('Head of the order')) continue;+ expect(AUDIT_SUGGESTED_AFTER[taskType] || [], taskType).toEqual([]);+ }+ });++ it('explains every type it orders', () => {+ for (const taskType of Object.keys(AUDIT_SUGGESTED_AFTER)) {+ expect(AUDIT_RUN_GUIDANCE[taskType], taskType).toBeTruthy();+ }+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 9a78a100c9..06e103bbc3 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -390,6 +390,7 @@ export * from './taskRetryHold.js';export * from './taskStatusTransition.js';export * from './taskTargetBranch.js';export * from './scheduledTaskTypes.js';+export * from './scheduleRunOrder.js';export * from './taskTargetScope.js';export * from './taxonomyTally.js';export * from './worktreeOwnership.js';diff --git a/server/lib/scheduleRunOrder.js b/server/lib/scheduleRunOrder.jsnew file mode 100644index 0000000000..326ba23d01--- /dev/null+++ b/server/lib/scheduleRunOrder.js@@ -0,0 +1,53 @@+/**+ * Advisory run order for scheduled tasks.+ *+ * Every task carries an editable `suggestedAfter` array naming the task types a+ * user should generally run BEFORE it. It answers "which of these do I run+ * first?" by pointing at other scheduled tasks by name, which prose guidance+ * could not do.+ *+ * Advisory is the whole point: nothing here gates dispatch. The ENFORCED+ * dependency field is `runAfter` (taskSchedule.js `checkRunAfterDeps`), which+ * holds a due task until each named type has run since its own last run. A user+ * who wants a hard gate promotes the entry there; `suggestedAfter` only orders+ * the page and labels the cards.+ *+ * The 1-based STEP each task lands on is derived where it is rendered+ * (client/src/components/cos/tabs/schedule/scheduleConstants.js) — it is a+ * property of the whole visible graph, not of a task, so a per-task field on+ * the wire would go stale the moment any other task was edited.+ *+ * Pure — no I/O.+ */++/** The only cap on the list — a hand-edited schedule file cannot grow it unbounded. */+export const SUGGESTED_AFTER_MAX = 20;++/**+ * Normalize a `suggestedAfter` value into a clean array of task-type ids.+ *+ * Returns `[]` for a missing/invalid value AND for an explicitly emptied list.+ * The absent-vs-cleared distinction is resolved BEFORE this is called, by the+ * `interval.suggestedAfter ?? AUDIT_SUGGESTED_AFTER[taskType]` fallback in+ * `getScheduleStatus`: an absent key inherits the shipped order, while a stored+ * `[]` is the user's deliberate clear and `??` keeps it. That is also why the+ * route stores `[]` rather than nulling it the way `runAfter` does — a null+ * would read back as "never edited" and re-inherit.+ *+ * A self-reference is dropped (a task cannot precede itself), as are blanks and+ * duplicates. Order is preserved — it is the order the user chose.+ */+export function normalizeSuggestedAfter(value, taskType = null) {+ if (!Array.isArray(value)) return [];+ const seen = new Set();+ const out = [];+ for (const entry of value) {+ if (typeof entry !== 'string') continue;+ const trimmed = entry.trim();+ if (!trimmed || trimmed === taskType || seen.has(trimmed)) continue;+ seen.add(trimmed);+ out.push(trimmed);+ if (out.length >= SUGGESTED_AFTER_MAX) break;+ }+ return out;+}diff --git a/server/lib/scheduleRunOrder.test.js b/server/lib/scheduleRunOrder.test.jsnew file mode 100644index 0000000000..9cb48d4162--- /dev/null+++ b/server/lib/scheduleRunOrder.test.js@@ -0,0 +1,20 @@+import { describe, it, expect } from 'vitest';+import { normalizeSuggestedAfter, SUGGESTED_AFTER_MAX } from './scheduleRunOrder.js';++describe('normalizeSuggestedAfter', () => {+ it('drops blanks, duplicates and self-references while keeping the chosen order', () => {+ expect(normalizeSuggestedAfter([' simplify ', '', 'me', 'simplify', 'module-hygiene'], 'me'))+ .toEqual(['simplify', 'module-hygiene']);+ });++ it('treats a non-array (absent, null, a string) as no suggestion', () => {+ expect(normalizeSuggestedAfter(undefined)).toEqual([]);+ expect(normalizeSuggestedAfter(null)).toEqual([]);+ expect(normalizeSuggestedAfter('simplify')).toEqual([]);+ });++ it('caps a hand-edited list so a schedule file cannot grow one without bound', () => {+ const huge = Array.from({ length: SUGGESTED_AFTER_MAX + 5 }, (_, i) => `task-${i}`);+ expect(normalizeSuggestedAfter(huge)).toHaveLength(SUGGESTED_AFTER_MAX);+ });+});diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.jsindex 4d862305ae..5b71c5a627 100644--- a/server/routes/cosScheduleRoutes.js+++ b/server/routes/cosScheduleRoutes.js@@ -11,6 +11,7 @@ import { sanitizeTaskMetadata, taskDataInputsSchema, validateRequest, parsePaginimport { promptSourceSchema, PROMPT_SOURCES } from '../lib/cosValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';import { INTERVAL_TYPES, decodeIntervalType, isCronExpression, isKnownIntervalType } from '../services/taskScheduleConstants.js';+import { normalizeSuggestedAfter, SUGGESTED_AFTER_MAX } from '../lib/scheduleRunOrder.js';const templateTaskSchema = z.object({name: z.string().min(1),@@ -24,9 +25,16 @@ const templateTaskSchema = z.object({const scheduleLabelsSchema = z.array(z.string().trim().min(1).max(40)).max(20).transform(labels => [...new Set(labels.map(label => label.toLowerCase()))]);+// Shape only — normalizeSuggestedAfter does the trimming, self-drop and dedupe+// so the storage rules live with the field's own helper, not in the route.+const suggestedAfterSchema = z.array(z.string()).max(SUGGESTED_AFTER_MAX);+const router = Router();const SCHEDULE_FIELDS = ['type', 'perpetual', 'enabled', 'intervalMs', 'cronExpression', 'providerId', 'model', 'effort', 'prompt', 'description', 'labels', 'dataInputs', 'taskMetadata', 'runAfter',+ // Advisory run order — which OTHER scheduled tasks a user should generally run+ // first. Editable and unenforced; `runAfter` above is the enforced gate.+ 'suggestedAfter',// 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`.@@ -37,9 +45,11 @@ const SCHEDULE_FIELDS = ['type', 'perpetual', 'enabled', 'intervalMs', 'cronExpr'promptSource'];/**- * Pick only defined values from body for schedule settings updates+ * Pick only defined values from body for schedule settings updates. `taskType`+ * is the row being written, so a field that must not name itself (the advisory+ * `suggestedAfter`) can be cleaned here rather than again at the call site.*/-function pickScheduleSettings(body) {+function pickScheduleSettings(body, taskType) {const settings = {};for (const key of SCHEDULE_FIELDS) {if (body[key] !== undefined) settings[key] = body[key];@@ -133,6 +143,16 @@ function pickScheduleSettings(body) {if (settings.effort !== undefined && settings.effort !== null && !EFFORT_LEVELS.includes(settings.effort)) {throw new ServerError(`effort must be one of ${EFFORT_LEVELS.join(', ')} or null`, { status: 400, code: 'VALIDATION_ERROR' });}+ // Advisory ordering. `normalizeSuggestedAfter` owns the shape rules (self,+ // blanks, duplicates, cap) and why an emptied list stays `[]` rather than+ // becoming null the way `runAfter` does.+ if (settings.suggestedAfter !== undefined) {+ const parsed = suggestedAfterSchema.safeParse(settings.suggestedAfter ?? []);+ if (!parsed.success) {+ throw new ServerError(`suggestedAfter must be at most ${SUGGESTED_AFTER_MAX} task type strings, or null`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ settings.suggestedAfter = normalizeSuggestedAfter(parsed.data, taskType);+ }if (settings.runAfter !== undefined && settings.runAfter !== null) {if (!Array.isArray(settings.runAfter)) {throw new ServerError('runAfter must be an array of task type strings or null', { status: 400, code: 'VALIDATION_ERROR' });@@ -171,7 +191,7 @@ router.get('/schedule/task/:taskType', asyncHandler(async (req, res) => {// PUT /api/cos/schedule/task/:taskType - Update interval for a task type (unified)router.put('/schedule/task/:taskType', asyncHandler(async (req, res) => {const { taskType } = req.params;- const settings = pickScheduleSettings(req.body);+ const settings = pickScheduleSettings(req.body, taskType);// Filter self-references from runAfter to prevent permanent blockingif (Array.isArray(settings.runAfter)) {settings.runAfter = settings.runAfter.filter(dep => dep !== taskType);diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.jsindex 83786f2bfb..256e02a9d8 100644--- a/server/routes/cosScheduleRoutes.test.js+++ b/server/routes/cosScheduleRoutes.test.js@@ -171,6 +171,40 @@ describe('CoS Schedule Routes', () => {expect(JSON.stringify(recordUserAction.mock.calls.at(-1)[0])).not.toContain(prompt);});+ it('keeps an emptied suggestedAfter as [], so the shipped default is not re-seeded', async () => {+ taskSchedule.updateTaskInterval.mockResolvedValue({ type: 'on-demand' });++ const response = await request(app)+ .put('/api/cos/schedule/task/review')+ .send({ suggestedAfter: [] });++ expect(response.status).toBe(200);+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('review', expect.objectContaining({+ suggestedAfter: []+ }));+ });++ it('normalizes suggestedAfter — self-reference and duplicates dropped, never nulled', async () => {+ taskSchedule.updateTaskInterval.mockResolvedValue({ type: 'on-demand' });++ const response = await request(app)+ .put('/api/cos/schedule/task/review')+ .send({ suggestedAfter: ['review', 'deploy', 'deploy'] });++ expect(response.status).toBe(200);+ expect(taskSchedule.updateTaskInterval).toHaveBeenCalledWith('review', expect.objectContaining({+ suggestedAfter: ['deploy']+ }));+ });++ it('rejects a suggestedAfter that is not a list of task type strings', async () => {+ const response = await request(app)+ .put('/api/cos/schedule/task/review')+ .send({ suggestedAfter: [{ taskType: 'deploy' }] });++ expect(response.status).toBe(400);+ });+it('should set runAfter to null when only self-reference remains', async () => {taskSchedule.updateTaskInterval.mockResolvedValue({ type: 'rotation' });diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.jsindex c21f23c037..b81d54fe71 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, getAuditScheduleMetadata, AUDIT_RUN_GUIDANCE } from '../lib/auditCatalog.js';+import { isAuditTaskType, defaultFileIssuesFor, auditDoWorkRequiresWorktree, getAuditScheduleMetadata, AUDIT_RUN_GUIDANCE, AUDIT_SUGGESTED_AFTER } from '../lib/auditCatalog.js';import { DEFAULT_TASK_PROMPTS } from './taskPromptDefaults.js';import {DEFAULT_PERPETUAL_RECHECK_MS,@@ -53,6 +53,7 @@ import { loadSchedule, updateSchedule } from './taskScheduleStore.js';import { isInstanceFeatureEnabled } from './instanceFeatures.js';import { recordUserAction } from './userActions.js';import { getTaskDataInputCatalog } from '../lib/taskDataInputCatalog.js';+import { normalizeSuggestedAfter } from '../lib/scheduleRunOrder.js';import { normalizeQuotaBurnProvenance } from '../lib/quotaBurnOrigin.js';import { enabledAppIdsByTaskType, evaluateOnDemandEligibility } from '../lib/quotaBurnTaskRef.js';import {@@ -83,6 +84,10 @@ export {} from './taskScheduleBackoff.js';export { addTemplateTask, deleteTemplateTask, getTemplateTasks } from './taskScheduleTemplates.js';+// Settings whose edit is not an "I've addressed the cause" signal, so saving+// one leaves a failure-parked task parked (see the unpark block below).+const PRESENTATION_ONLY_SETTINGS = new Set(['labels', 'suggestedAfter']);+export const createFeatureGate = () => {const enabledByFeature = new Map();return async (interval) => {@@ -235,9 +240,11 @@ 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 = [];- // 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) {+ // Page-organizing edits do not signal that a failed task is repaired:+ // labels group the cards and `suggestedAfter` orders them, neither touching+ // what the task does when it runs.+ const presentationOnly = Object.keys(settings).every(key => PRESENTATION_ONLY_SETTINGS.has(key));+ if (topExec && !presentationOnly) {if (topExec.failureParkedAt) unparkedScopes.push(null);clearFailureLedgerFields(topExec);for (const [id, rec] of Object.entries(topExec.perApp || {})) {@@ -1302,6 +1309,17 @@ export async function getScheduleStatus() {...interval,...getAuditScheduleMetadata(taskType),labels: interval.labels || [],+ // Advisory ordering: WHICH tasks to run first, named by task type. Never+ // a dispatch gate — that is `runAfter`, spread in from `interval` above.+ //+ // Layered at READ time like every other catalog-derived field here+ // (displayName, defaultLabels, runGuidance): a stored value wins, and an+ // absent one inherits the shipped order — so editing AUDIT_SUGGESTED_AFTER+ // reaches existing installs without a migration. An explicit `[]` is a+ // user's clear and is key-present, so `??` keeps it.+ suggestedAfter: normalizeSuggestedAfter(interval.suggestedAfter ?? AUDIT_SUGGESTED_AFTER[taskType], taskType),+ // WHY this task sits where it does — rationale for the order above, not+ // the order itself.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,diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex 8e4501076c..5ba12cac14 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -2353,8 +2353,12 @@ describe('taskSchedule', () => {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')+ // Ordering is carried by NAMED task types, not by the prose — the prose+ // only says why. A reader of the old guidance couldn't tell whether+ // "structural drift" was another scheduled task or just a concept.+ expect(status.tasks['module-hygiene'].suggestedAfter).toEqual(['simplify'])+ expect(status.tasks['better-complexity'].suggestedAfter).toEqual(['module-hygiene'])+ expect(status.tasks['module-hygiene'].runGuidance).toContain('module boundaries')expect(status.tasks['claim-issue']).toMatchObject({ displayName: 'claim-issue', defaultLabels: [] })})