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

I want to rethink a bit of how we order dependencies of the scheduled tasks and come up with a holis (#212)

[._.]/ Adam Eivyec66b781eeef
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index f1a38d9956..50303a97d6 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Workflow tab in Chief of Staff with canonical project-maintenance ordering.** A new `/cos/workflow` page (and a `Workflow` tab in the CoS panel) renders the full set of scheduled tasks and autonomous jobs as a left-to-right pipeline grouped into seven canonical stages — Hygiene → Review → Plan → Audit → Build → Report → Ambient — so it's obvious which work happens before which. Each card surfaces its own schedule, last-run time, run count, enabled state, and live "due / waiting / disabled / waiting-on-dependencies" badge, plus inline `runAfter` arrows showing hard prerequisites. Backed by a new `GET /api/cos/workflow` endpoint and `server/services/workflow.js` with stage definitions, gate state for jobs, and dependency edges. Two default `runAfter` wirings ship with this: `do-replan` runs after `pr-reviewer` and `branch-cleanup` (so the plan reflects merged reality), and `feature-ideas` runs after `do-replan` (so new feature work lands on a fresh plan). Both can be overridden per task or per app from the existing Schedule tab.
+
- **Dismissible AI Recommendations on the Learning tab.** Each recommendation in the Chief of Staff Learning Analytics panel now has an X to dismiss it. Dismissals persist to `data/cos/dismissed-recommendations.json` and are filtered out of future loads. For count-based alerts (e.g., "unknown errors occurred 74 times"), the dismissal records the count snapshot and only re-surfaces if the count grows materially worse (≥1.5× and at least +20). Rate-based recommendations stay dismissed until restored. A "Show dismissed" expander lets you restore individual entries or clear them all.
## Fixed
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 3ac3e06a68..4a3b9c4de7 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -78,7 +78,8 @@ import {
Archive,
Eraser,
Sun,
- Moon
+ Moon,
+ Workflow as WorkflowIcon
} from 'lucide-react';
/* global __APP_VERSION__ */
import Logo from './Logo';
@@ -169,7 +170,8 @@ const navItems = [
{ to: '/cos/memory', label: 'Memory', icon: Brain },
{ to: '/cos/schedule', label: 'Schedule', icon: Clock },
{ to: '/cos/productivity', label: 'Streaks', icon: Flame },
- { to: '/cos/tasks', label: 'Tasks', icon: FileText }
+ { to: '/cos/tasks', label: 'Tasks', icon: FileText },
+ { to: '/cos/workflow', label: 'Workflow', icon: WorkflowIcon }
]
},
{
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.js
index ba07174325..b651b9ceb4 100644
--- a/client/src/components/cos/constants.js
+++ b/client/src/components/cos/constants.js
@@ -10,7 +10,8 @@ import {
GraduationCap,
Bot,
Flame,
- Newspaper
+ Newspaper,
+ Workflow as WorkflowIcon
} from 'lucide-react';
export const TABS = [
@@ -19,6 +20,7 @@ export const TABS = [
{ id: 'agents', label: 'Agents', icon: Cpu },
{ id: 'jobs', label: 'System Tasks', icon: Bot },
{ id: 'schedule', label: 'Schedule', icon: Clock },
+ { id: 'workflow', label: 'Workflow', icon: WorkflowIcon },
{ id: 'digest', label: 'Digest', icon: Calendar },
{ id: 'gsd', label: 'GSD', icon: Compass },
{ id: 'productivity', label: 'Streaks', icon: Flame },
diff --git a/client/src/components/cos/index.js b/client/src/components/cos/index.js
index 438c85d0c0..4a15848bc7 100644
--- a/client/src/components/cos/index.js
+++ b/client/src/components/cos/index.js
@@ -28,6 +28,7 @@ export { default as TasksTab } from './tabs/TasksTab';
export { default as AgentsTab } from './tabs/AgentsTab';
export { default as JobsTab } from './tabs/JobsTab';
export { default as ScheduleTab } from './tabs/ScheduleTab';
+export { default as WorkflowTab } from './tabs/WorkflowTab';
export { default as LearningTab } from './tabs/LearningTab';
export { default as MemoryTab } from './tabs/MemoryTab';
export { default as HealthTab } from './tabs/HealthTab';
diff --git a/client/src/components/cos/tabs/WorkflowTab.jsx b/client/src/components/cos/tabs/WorkflowTab.jsx
new file mode 100644
index 0000000000..701bcd00d5
--- /dev/null
+++ b/client/src/components/cos/tabs/WorkflowTab.jsx
@@ -0,0 +1,298 @@
+import { useState, useEffect, useCallback, useMemo } from 'react';
+import { RefreshCw, Clock, AlertTriangle, CheckCircle2, Circle, GitBranch, Bot, ArrowRight, Info } from 'lucide-react';
+import * as api from '../../../services/api';
+import { timeAgo } from '../../../utils/formatters';
+import { describeCron } from '../../../utils/cronHelpers';
+
+// Stage palette — matches port-* tokens used elsewhere.
+// Keys are stage ids from the server's WORKFLOW_STAGES; ordering is server-driven (graph.stages).
+const STAGE_COLORS = {
+ hygiene: { ring: 'border-cyan-500/40', bg: 'bg-cyan-500/5', text: 'text-cyan-300', dot: 'bg-cyan-500' },
+ review: { ring: 'border-purple-500/40', bg: 'bg-purple-500/5', text: 'text-purple-300', dot: 'bg-purple-500' },
+ plan: { ring: 'border-blue-500/40', bg: 'bg-blue-500/5', text: 'text-blue-300', dot: 'bg-blue-500' },
+ audit: { ring: 'border-amber-500/40', bg: 'bg-amber-500/5', text: 'text-amber-300', dot: 'bg-amber-500' },
+ build: { ring: 'border-emerald-500/40', bg: 'bg-emerald-500/5', text: 'text-emerald-300', dot: 'bg-emerald-500' },
+ report: { ring: 'border-pink-500/40', bg: 'bg-pink-500/5', text: 'text-pink-300', dot: 'bg-pink-500' },
+ ambient: { ring: 'border-gray-600/40', bg: 'bg-gray-600/5', text: 'text-gray-400', dot: 'bg-gray-500' }
+};
+
+function describeSchedule(node) {
+ const s = node.schedule || {};
+ if (s.type === 'cron' && s.cronExpression) {
+ return describeCron(s.cronExpression) || s.cronExpression;
+ }
+ if (s.type === 'custom' && s.intervalMs) {
+ const hours = s.intervalMs / 3_600_000;
+ if (hours >= 24) return `every ${Math.round(hours / 24)}d`;
+ if (hours >= 1) return `every ${Math.round(hours)}h`;
+ return `every ${Math.round(s.intervalMs / 60_000)}m`;
+ }
+ if (s.type === 'on-demand') return 'on demand';
+ return s.type || 'unscheduled';
+}
+
+function statusBadge(node) {
+ if (!node.enabled) {
+ return { label: 'disabled', className: 'bg-gray-700/40 text-gray-500 border-gray-600/40' };
+ }
+ if (node.blocked) {
+ return { label: node.blocked, className: 'bg-port-warning/15 text-port-warning border-port-warning/30' };
+ }
+ if (node.shouldRun) {
+ return { label: 'due', className: 'bg-port-success/15 text-port-success border-port-success/30' };
+ }
+ return { label: 'waiting', className: 'bg-port-border/30 text-gray-400 border-port-border/50' };
+}
+
+function NodeCard({ node, allNodes, onHover, isHighlighted }) {
+ const palette = STAGE_COLORS[node.stage] || STAGE_COLORS.ambient;
+ const badge = statusBadge(node);
+ const Icon = node.kind === 'job' ? Bot : GitBranch;
+
+ // Map runAfter task IDs to nodes for richer hover hints. When the node is blocked on
+ // unmet dependencies, mark which prereqs are still outstanding so the user can see at
+ // a glance which gate hasn't cleared yet.
+ const pendingSet = new Set(Array.isArray(node.pendingDeps) ? node.pendingDeps : []);
+ const deps = node.runAfter
+ .map(t => {
+ const dep = allNodes.find(n => n.id === `task:${t}`);
+ return dep ? { ...dep, pending: pendingSet.has(t) } : null;
+ })
+ .filter(Boolean);
+ const isWaitingOnDeps = node.blocked === 'waiting-on-dependencies';
+
+ return (
+ <div
+ className={`relative rounded-md border ${palette.ring} ${palette.bg} p-2.5 transition-all ${
+ isHighlighted ? 'ring-2 ring-port-accent shadow-lg' : ''
+ } ${node.enabled ? '' : 'opacity-60'}`}
+ onMouseEnter={() => onHover(node.id)}
+ onMouseLeave={() => onHover(null)}
+ >
+ <div className="flex items-start justify-between gap-1.5 mb-1">
+ <div className="flex items-center gap-1.5 min-w-0 flex-1">
+ <Icon className={`w-3.5 h-3.5 shrink-0 ${palette.text}`} />
+ <span className="text-sm text-white font-medium truncate" title={node.label}>{node.label}</span>
+ </div>
+ {node.enabled
+ ? <CheckCircle2 className="w-3.5 h-3.5 text-port-success shrink-0" />
+ : <Circle className="w-3.5 h-3.5 text-gray-600 shrink-0" />}
+ </div>
+
+ <div className="flex items-center gap-1.5 text-xs text-gray-400 mb-1.5">
+ <Clock className="w-3 h-3" />
+ <span>{describeSchedule(node)}</span>
+ </div>
+
+ <span className={`inline-block text-[10px] font-medium px-1.5 py-0.5 rounded border ${badge.className}`}>
+ {badge.label}
+ </span>
+
+ {node.runAfter.length > 0 && (
+ <div className="mt-1.5 flex flex-wrap gap-1">
+ {deps.map(dep => {
+ const highlightPending = isWaitingOnDeps && dep.pending;
+ return (
+ <span
+ key={dep.id}
+ className={`inline-flex items-center gap-1 text-[10px] ${
+ highlightPending ? 'text-port-warning font-medium' : 'text-gray-500'
+ }`}
+ title={highlightPending
+ ? `Pending — ${dep.label} hasn't run since this task last ran`
+ : `Runs after ${dep.label}`}
+ >
+ <ArrowRight className="w-2.5 h-2.5" />
+ {dep.label}{highlightPending ? ' ⏳' : ''}
+ </span>
+ );
+ })}
+ </div>
+ )}
+
+ {(node.lastRun || node.runCount > 0) && (
+ <div className="mt-1 text-[10px] text-gray-500">
+ last {timeAgo(node.lastRun)} · {node.runCount} run{node.runCount === 1 ? '' : 's'}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function StageColumn({ stage, nodes, allNodes, hoveredId, setHoveredId }) {
+ const palette = STAGE_COLORS[stage.id] || STAGE_COLORS.ambient;
+ if (nodes.length === 0) return null;
+
+ const hoveredNode = hoveredId ? allNodes.find(n => n.id === hoveredId) : null;
+
+ return (
+ <div className="flex flex-col gap-2 min-w-[12rem] flex-shrink-0">
+ <div className={`rounded-md border ${palette.ring} ${palette.bg} px-3 py-2`}>
+ <div className="flex items-center gap-2">
+ <span className={`w-2 h-2 rounded-full ${palette.dot}`} />
+ <span className={`text-sm font-semibold ${palette.text}`}>{stage.label}</span>
+ <span className="text-xs text-gray-500">
+ {stage.enabledCount}/{stage.nodeCount}
+ </span>
+ </div>
+ <p className="text-[11px] text-gray-400 mt-1 leading-snug">{stage.description}</p>
+ </div>
+ <div className="flex flex-col gap-1.5">
+ {nodes.map(node => (
+ <NodeCard
+ key={node.id}
+ node={node}
+ allNodes={allNodes}
+ onHover={setHoveredId}
+ isHighlighted={hoveredId === node.id || nodeReferences(node, hoveredId, hoveredNode)}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+// Highlight nodes that participate in a runAfter relationship with the hovered node — both
+// directions. `node` is highlighted when:
+// - `node` declares `hoveredId` as one of its `runAfter` prerequisites (downstream), OR
+// - `node` is itself one of the hovered node's `runAfter` prerequisites (upstream).
+// `node` is the candidate being styled; `hoveredNode` is the full node currently under the
+// pointer (so we can read its `runAfter` list).
+function nodeReferences(node, hoveredId, hoveredNode) {
+ if (!hoveredId) return false;
+ if (node.runAfter.some(t => `task:${t}` === hoveredId)) return true;
+ if (hoveredNode && hoveredNode.runAfter.some(t => `task:${t}` === node.id)) return true;
+ return false;
+}
+
+function StageArrow() {
+ return (
+ <div className="flex items-center px-1 text-gray-600 shrink-0" aria-hidden="true">
+ <ArrowRight className="w-5 h-5" />
+ </div>
+ );
+}
+
+export default function WorkflowTab() {
+ const [graph, setGraph] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+ const [hoveredId, setHoveredId] = useState(null);
+
+ const fetchGraph = useCallback(async () => {
+ setLoading(true);
+ const data = await api.getCosWorkflow().catch(err => {
+ setError(err?.message || 'Failed to load workflow');
+ return null;
+ });
+ if (data) {
+ setGraph(data);
+ setError(null);
+ }
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { fetchGraph(); }, [fetchGraph]);
+
+ // Stages enriched with their nodes, in canonical order from the server, only including those
+ // that have content. Keeps node ordering stable: enabled first, then alphabetical.
+ const populatedStages = useMemo(() => {
+ if (!graph) return [];
+ const byStage = new Map();
+ for (const node of graph.nodes) {
+ if (!byStage.has(node.stage)) byStage.set(node.stage, []);
+ byStage.get(node.stage).push(node);
+ }
+ for (const list of byStage.values()) {
+ list.sort((a, b) => (a.enabled === b.enabled ? a.label.localeCompare(b.label) : a.enabled ? -1 : 1));
+ }
+ // graph.stages is already returned in canonical order; sort defensively by `order` in case
+ // a future server change emits them unordered.
+ const orderedStages = [...graph.stages].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
+ return orderedStages
+ .map(stage => {
+ const nodes = byStage.get(stage.id) || [];
+ return nodes.length > 0 ? { ...stage, nodes } : null;
+ })
+ .filter(Boolean);
+ }, [graph]);
+
+ // Total enabled across the whole pipeline
+ const totalEnabled = graph ? graph.nodes.filter(n => n.enabled).length : 0;
+ const totalNodes = graph ? graph.nodes.length : 0;
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-start justify-between gap-3 flex-wrap">
+ <div>
+ <h2 className="text-xl font-semibold text-white">Workflow</h2>
+ <p className="text-sm text-gray-400 mt-1 max-w-2xl">
+ Recommended project-maintenance pipeline. Stages are a visualization of how scheduled
+ tasks fit together — each task still runs on its own schedule. Hard execution gates
+ are enforced only by per-task <span className="font-mono text-gray-300">runAfter</span> dependencies (and per-job gates),
+ not by stage ordering.
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <span className="text-xs text-gray-500">
+ {totalEnabled}/{totalNodes} enabled
+ </span>
+ <button
+ onClick={fetchGraph}
+ disabled={loading}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm rounded bg-port-accent/20 hover:bg-port-accent/30 text-port-accent disabled:opacity-50"
+ >
+ <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
+ Refresh
+ </button>
+ </div>
+ </div>
+
+ <div className="rounded-md border border-port-border/50 bg-port-card/30 px-3 py-2 flex items-start gap-2 text-xs text-gray-400">
+ <Info className="w-3.5 h-3.5 shrink-0 mt-0.5 text-port-accent" />
+ <span>
+ Hard dependencies (<span className="font-mono text-gray-300">runAfter</span>) are enforced — a task
+ shows <span className="text-port-warning">waiting-on-dependencies</span> until its prerequisites have
+ run since its last execution. Stage ordering left-to-right is the recommended workflow; you can still
+ schedule tasks independently from the Schedule and System Tasks tabs.
+ </span>
+ </div>
+
+ {error && (
+ <div className="rounded-md border border-port-error/40 bg-port-error/10 p-3 flex items-center gap-2 text-sm text-port-error">
+ <AlertTriangle className="w-4 h-4" />
+ {error}
+ </div>
+ )}
+
+ {loading && !graph && (
+ <div className="text-center py-8 text-gray-500">Loading workflow…</div>
+ )}
+
+ {graph && (
+ <div className="overflow-x-auto pb-2">
+ <div className="flex items-stretch gap-2 min-w-min">
+ {populatedStages.map((stage, i) => (
+ <div key={stage.id} className="flex items-stretch">
+ <StageColumn
+ stage={stage}
+ nodes={stage.nodes}
+ allNodes={graph.nodes}
+ hoveredId={hoveredId}
+ setHoveredId={setHoveredId}
+ />
+ {i < populatedStages.length - 1 && <StageArrow />}
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {graph && (
+ <div className="text-xs text-gray-500">
+ Generated {timeAgo(graph.generatedAt)}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index 982f112171..9fabe500c2 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -29,6 +29,7 @@ import {
AgentsTab,
JobsTab,
ScheduleTab,
+ WorkflowTab,
DigestTab,
GsdTab,
ProductivityTab,
@@ -887,6 +888,11 @@ export default function ChiefOfStaff() {
<ScheduleTab apps={apps} />
</div>
)}
+ {activeTab === 'workflow' && (
+ <div role="tabpanel" id="tabpanel-workflow" aria-labelledby="tab-workflow">
+ <WorkflowTab />
+ </div>
+ )}
{activeTab === 'digest' && (
<div role="tabpanel" id="tabpanel-digest" aria-labelledby="tab-digest">
<DigestTab />
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index 6b2c17ae7c..7d50979f43 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -234,6 +234,9 @@ export const toggleCosJob = (id) => request(`/cos/jobs/${id}/toggle`, { method:
export const triggerCosJob = (id) => request(`/cos/jobs/${id}/trigger`, { method: 'POST' });
export const deleteCosJob = (id) => request(`/cos/jobs/${id}`, { method: 'DELETE' });
+// Workflow visualizer — canonical scheduled-task ordering across tasks + jobs
+export const getCosWorkflow = () => request('/cos/workflow');
+
// Feature Agents
export const getFeatureAgents = () => request('/feature-agents');
export const getFeatureAgent = (id) => request(`/feature-agents/${id}`);
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index d7d1f70bee..f9b8bc5aa7 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -56,6 +56,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.cos.learning', path: '/cos/learning', label: 'Learning', section: 'Chief of Staff', aliases: ['cos-learning'] },
{ id: 'nav.cos.memory', path: '/cos/memory', label: 'Memory', section: 'Chief of Staff', aliases: ['cos-memory'] },
{ id: 'nav.cos.schedule', path: '/cos/schedule', label: 'Schedule', section: 'Chief of Staff', aliases: ['schedule', 'cos-schedule'] },
+ { id: 'nav.cos.workflow', path: '/cos/workflow', label: 'Workflow', section: 'Chief of Staff', aliases: ['workflow', 'cos-workflow', 'pipeline'], keywords: ['pipeline', 'dependencies', 'order', 'stages'] },
{ id: 'nav.cos.productivity', path: '/cos/productivity', label: 'Streaks', section: 'Chief of Staff', aliases: ['streaks', 'cos-productivity'] },
{ id: 'nav.messages.inbox', path: '/messages/inbox', label: 'Inbox', section: 'Comms', aliases: ['messages'] },
diff --git a/server/routes/cos.js b/server/routes/cos.js
index 4e9fc43399..e8eb1c833c 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -12,6 +12,7 @@ import scheduleRoutes from './cosScheduleRoutes.js';
import jobRoutes from './cosJobRoutes.js';
import templateRoutes from './cosTemplateRoutes.js';
import insightRoutes from './cosInsightRoutes.js';
+import workflowRoutes from './cosWorkflowRoutes.js';
const router = Router();
@@ -24,5 +25,6 @@ router.use(scheduleRoutes);
router.use(jobRoutes);
router.use(templateRoutes);
router.use(insightRoutes);
+router.use(workflowRoutes);
export default router;
diff --git a/server/routes/cosWorkflowRoutes.js b/server/routes/cosWorkflowRoutes.js
new file mode 100644
index 0000000000..decc7c1e5a
--- /dev/null
+++ b/server/routes/cosWorkflowRoutes.js
@@ -0,0 +1,21 @@
+/**
+ * CoS Workflow Routes — exposes the canonical scheduled-task workflow graph
+ * (stages, nodes, dependency edges) for the Workflow visualizer tab.
+ */
+
+import { Router } from 'express';
+import { getWorkflowGraph, WORKFLOW_STAGES } from '../services/workflow.js';
+import { asyncHandler } from '../lib/errorHandler.js';
+
+const router = Router();
+
+router.get('/workflow', asyncHandler(async (req, res) => {
+ const graph = await getWorkflowGraph();
+ res.json(graph);
+}));
+
+router.get('/workflow/stages', (req, res) => {
+ res.json({ stages: WORKFLOW_STAGES });
+});
+
+export default router;
diff --git a/server/routes/cosWorkflowRoutes.test.js b/server/routes/cosWorkflowRoutes.test.js
new file mode 100644
index 0000000000..792fe70420
--- /dev/null
+++ b/server/routes/cosWorkflowRoutes.test.js
@@ -0,0 +1,55 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+
+vi.mock('../services/workflow.js', () => ({
+ getWorkflowGraph: vi.fn(),
+ WORKFLOW_STAGES: [
+ { id: 'plan', label: 'Plan', description: 'Plan stage', taskTypes: ['do-replan'], jobIds: [] },
+ { id: 'build', label: 'Build', description: 'Build stage', taskTypes: ['feature-ideas'], jobIds: [] }
+ ]
+}));
+
+import workflowRoutes from './cosWorkflowRoutes.js';
+import * as workflow from '../services/workflow.js';
+
+describe('CoS Workflow Routes', () => {
+ let app;
+
+ beforeEach(() => {
+ app = express();
+ app.use(express.json());
+ app.use('/api/cos', workflowRoutes);
+ vi.clearAllMocks();
+ });
+
+ describe('GET /api/cos/workflow', () => {
+ it('returns the workflow graph', async () => {
+ workflow.getWorkflowGraph.mockResolvedValue({
+ generatedAt: '2026-05-09T00:00:00.000Z',
+ stages: [{ id: 'plan', nodeCount: 1, enabledCount: 1 }],
+ nodes: [{ id: 'task:do-replan', stage: 'plan' }],
+ edges: []
+ });
+
+ const response = await request(app).get('/api/cos/workflow');
+ expect(response.status).toBe(200);
+ expect(response.body.nodes).toHaveLength(1);
+ expect(response.body.nodes[0].id).toBe('task:do-replan');
+ });
+
+ it('surfaces workflow service errors as 500', async () => {
+ workflow.getWorkflowGraph.mockRejectedValue(new Error('boom'));
+ const response = await request(app).get('/api/cos/workflow');
+ expect(response.status).toBe(500);
+ });
+ });
+
+ describe('GET /api/cos/workflow/stages', () => {
+ it('returns the canonical stage list', async () => {
+ const response = await request(app).get('/api/cos/workflow/stages');
+ expect(response.status).toBe(200);
+ expect(response.body.stages.map(s => s.id)).toEqual(['plan', 'build']);
+ });
+ });
+});
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 3ff8ebcca2..f2befec425 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -1424,7 +1424,9 @@ const DEFAULT_TASK_INTERVALS = {
'documentation': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null },
'ui-bugs': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null },
'mobile-responsive': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null },
- 'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
+ // feature-ideas waits for do-replan so new work is grounded in a fresh PLAN.md
+ // that already accounts for any in-flight or unmerged work.
+ 'feature-ideas': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['do-replan'], taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
'error-handling': { type: INTERVAL_TYPES.ROTATION, enabled: false, providerId: null, model: null, prompt: null },
'typing': { type: INTERVAL_TYPES.ONCE, enabled: false, providerId: null, model: null, prompt: null },
'release-check': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null },
@@ -1433,7 +1435,9 @@ const DEFAULT_TASK_INTERVALS = {
'code-reviewer-b': { ...CODE_REVIEWER_INTERVAL },
'jira-sprint-manager': { type: INTERVAL_TYPES.DAILY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true, simplify: true } },
'jira-status-report': { type: INTERVAL_TYPES.WEEKLY, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { readOnly: true } },
- 'do-replan': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: true } },
+ // do-replan audits PLAN.md after open PRs and stale branches have been cleaned up,
+ // so the plan reflects what actually merged.
+ 'do-replan': { type: INTERVAL_TYPES.WEEKLY, enabled: false, providerId: null, model: null, prompt: null, runAfter: ['pr-reviewer', 'branch-cleanup'], taskMetadata: { useWorktree: true, openPR: true } },
// Read-only by default — the agent's job is to propose, not implement.
// Worktree off because the task body itself reads from data/cos/reference-repos
// (managed clones the user can't accidentally clobber).
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 96696ddea8..7af94bf61d 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -375,8 +375,9 @@ describe('taskSchedule', () => {
it('should run daily task when enough time has passed', async () => {
const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
+ // Explicit runAfter: [] overrides the feature-ideas default that depends on do-replan
mockSchedule({
- tasks: { 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null } },
+ tasks: { 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null, runAfter: [] } },
executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }
})
@@ -389,7 +390,7 @@ describe('taskSchedule', () => {
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString()
mockSchedule({
- tasks: { 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null } },
+ tasks: { 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null, runAfter: [] } },
executions: { 'task:feature-ideas': { lastRun: oneHourAgo, count: 5, perApp: {} } }
})
@@ -397,6 +398,38 @@ describe('taskSchedule', () => {
expect(result.shouldRun).toBe(false)
expect(result.reason).toContain('daily-cooldown')
})
+
+ it('feature-ideas waits on do-replan (runAfter default)', async () => {
+ const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
+
+ // Default runAfter:['do-replan'] kicks in since the test doesn't override it
+ mockSchedule({
+ tasks: { 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null } },
+ executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }
+ })
+
+ const result = await shouldRunTask('feature-ideas')
+ expect(result.shouldRun).toBe(false)
+ expect(result.reason).toBe('waiting-on-dependencies')
+ expect(result.pendingDeps).toContain('do-replan')
+ })
+
+ it('feature-ideas runs when do-replan has run since its last run', async () => {
+ const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
+ const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
+
+ mockSchedule({
+ tasks: { 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null } },
+ executions: {
+ 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} },
+ 'task:do-replan': { lastRun: oneDayAgo, count: 1, perApp: {} }
+ }
+ })
+
+ const result = await shouldRunTask('feature-ideas')
+ expect(result.shouldRun).toBe(true)
+ expect(result.reason).toContain('daily-due')
+ })
})
describe('getDueTasks', () => {
diff --git a/server/services/workflow.js b/server/services/workflow.js
new file mode 100644
index 0000000000..49815f07ec
--- /dev/null
+++ b/server/services/workflow.js
@@ -0,0 +1,252 @@
+/**
+ * Workflow Service
+ *
+ * Defines the canonical project-maintenance workflow across PortOS scheduled
+ * tasks (taskSchedule.js, per-app improvement tasks) and autonomous jobs
+ * (autonomousJobs.js, system-level recurring jobs).
+ *
+ * The workflow is a conceptual ordering — actual execution remains driven by
+ * each item's own schedule. The `runAfter` field on a task type encodes a
+ * hard dependency (taskSchedule already enforces it); stage ordering here is
+ * a recommendation surfaced in the visualizer so users can reason about
+ * how their schedule fits together.
+ *
+ * Stages (in canonical order):
+ * 1. hygiene — reset state: cleanup branches and old agent data
+ * 2. review — review existing in-flight work (open PRs, codebase review)
+ * 3. plan — replan based on current state of the repo
+ * 4. audit — quality/security audits that don't depend on planning
+ * 5. build — implement new work from the (now fresh) plan
+ * 6. report — externalize status (JIRA, briefing, etc.)
+ * 7. ambient — recurring jobs that don't fit the dev-loop ordering
+ */
+
+import { getScheduleStatus } from './taskSchedule.js';
+import * as autonomousJobs from './autonomousJobs.js';
+import { checkJobGate, hasGate, getRegisteredGates } from './jobGates.js';
+
+/**
+ * Stage definitions. `taskTypes` are entries from taskSchedule's tasks map;
+ * `jobIds` are entries from autonomousJobs. An item can appear in only one
+ * stage; orphans are reported under the `ambient` stage by getWorkflowGraph().
+ */
+export const WORKFLOW_STAGES = [
+ {
+ id: 'hygiene',
+ label: 'Hygiene',
+ description: 'Reset state: clean up merged branches and stale agent data so downstream stages start clean.',
+ taskTypes: ['branch-cleanup'],
+ jobIds: ['job-agent-data-cleanup']
+ },
+ {
+ id: 'review',
+ label: 'Review',
+ description: 'Review existing in-flight work — open pull requests and the current codebase — before planning new work.',
+ taskTypes: ['pr-reviewer', 'code-reviewer-a', 'code-reviewer-b', 'reference-watch'],
+ jobIds: ['job-brain-review']
+ },
+ {
+ id: 'plan',
+ label: 'Plan',
+ description: 'Audit PLAN.md against what actually shipped and surface gaps. Runs only after review/cleanup so the plan reflects merged reality.',
+ taskTypes: ['do-replan'],
+ jobIds: []
+ },
+ {
+ id: 'audit',
+ label: 'Audit',
+ description: 'Quality, security, and accessibility audits. Independent of the plan, but typically scheduled lighter than build work.',
+ taskTypes: [
+ 'security',
+ 'code-quality',
+ 'test-coverage',
+ 'performance',
+ 'accessibility',
+ 'console-errors',
+ 'dependency-updates',
+ 'documentation',
+ 'error-handling',
+ 'typing',
+ 'ui-bugs',
+ 'mobile-responsive'
+ ],
+ jobIds: ['job-wiki-maintenance']
+ },
+ {
+ id: 'build',
+ label: 'Build',
+ description: 'Implement the next planned feature. Gated on do-replan so new work is grounded in a fresh plan.',
+ taskTypes: ['feature-ideas'],
+ jobIds: []
+ },
+ {
+ id: 'report',
+ label: 'Report',
+ description: 'Externalize status — JIRA tickets, daily briefing, release readiness — once the build cycle has settled.',
+ taskTypes: ['jira-sprint-manager', 'jira-status-report', 'release-check'],
+ jobIds: ['job-daily-briefing', 'job-datadog-error-monitor']
+ },
+ {
+ id: 'ambient',
+ label: 'Ambient',
+ description: 'Recurring jobs that run independently of the dev loop — system health, repo maintenance, personal prompts.',
+ taskTypes: [],
+ jobIds: [
+ 'job-github-repo-maintenance',
+ 'job-system-health-check',
+ 'job-autobiography-prompt',
+ 'job-moltworld-exploration',
+ 'job-goal-check-in'
+ ]
+ }
+];
+
+const STAGE_INDEX = new Map(WORKFLOW_STAGES.map((s, i) => [s.id, i]));
+
+/**
+ * Build a reverse map from task type / job id → stage id.
+ * Used to classify items the schedule contains that we haven't categorized.
+ */
+function buildItemStageMap() {
+ const map = new Map();
+ for (const stage of WORKFLOW_STAGES) {
+ for (const t of stage.taskTypes) map.set(`task:${t}`, stage.id);
+ for (const j of stage.jobIds) map.set(`job:${j}`, stage.id);
+ }
+ return map;
+}
+
+/**
+ * Build the workflow graph for the visualizer.
+ *
+ * Returns:
+ * { stages: [...], nodes: [...], edges: [...], generatedAt }
+ *
+ * - nodes: every scheduled task type and every autonomous job, with
+ * { id, kind ('task'|'job'), stage, label, schedule, enabled, lastRun,
+ * runAfter, gate, blocked }
+ * - edges: explicit runAfter dependencies and inter-stage flow hints
+ * { from, to, kind: 'depends-on' | 'stage-flow' }
+ * `depends-on` edges connect node ids (`task:foo` → `task:bar`).
+ * `stage-flow` edges connect entries in the `stages` list (bare stage ids
+ * like `plan` → `build`); they have no corresponding entries in `nodes`.
+ */
+export async function getWorkflowGraph() {
+ const [scheduleStatus, jobs] = await Promise.all([
+ getScheduleStatus(),
+ autonomousJobs.getAllJobs()
+ ]);
+
+ const itemStage = buildItemStageMap();
+ const nodes = [];
+ const edges = [];
+
+ // Task nodes — getScheduleStatus returns flat objects spreading interval + execution + status
+ for (const [taskType, info] of Object.entries(scheduleStatus.tasks || {})) {
+ const stageId = itemStage.get(`task:${taskType}`) || 'ambient';
+ const runAfter = Array.isArray(info.runAfter) ? info.runAfter : [];
+ nodes.push({
+ id: `task:${taskType}`,
+ kind: 'task',
+ stage: stageId,
+ label: taskType,
+ enabled: !!info.enabled,
+ schedule: {
+ type: info.type,
+ intervalMs: info.intervalMs ?? null,
+ cronExpression: info.cronExpression ?? null,
+ weekdaysOnly: !!info.weekdaysOnly
+ },
+ lastRun: info.lastRun || null,
+ runCount: info.runCount || 0,
+ runAfter,
+ gate: null,
+ // Only true gating reasons (waiting on hard prerequisites) are surfaced as `blocked`
+ // — that field drives warning styling in the UI. Other shouldRun=false states (cooldown,
+ // weekday-only, disabled-for-app, etc.) are exposed via `statusReason` so the UI can
+ // render them as neutral "waiting" rather than a warning.
+ blocked: info.status?.reason === 'waiting-on-dependencies' ? info.status.reason : null,
+ statusReason: info.status?.shouldRun === false ? info.status.reason : null,
+ shouldRun: info.status?.shouldRun === true,
+ pendingDeps: info.status?.pendingDeps || []
+ });
+
+ for (const dep of runAfter) {
+ edges.push({ from: `task:${dep}`, to: `task:${taskType}`, kind: 'depends-on' });
+ }
+ }
+
+ // Job nodes — include gate metadata and last-known evaluation. Gate checks may perform I/O
+ // (inbox counts, goals lookups, etc.), so run them in parallel rather than sequentially.
+ const gateIds = new Set(getRegisteredGates());
+ const gateResults = await Promise.all(
+ jobs.map(job => (gateIds.has(job.id) ? checkGateSafe(job.id) : Promise.resolve(null)))
+ );
+ for (let i = 0; i < jobs.length; i++) {
+ const job = jobs[i];
+ const stageId = itemStage.get(`job:${job.id}`) || 'ambient';
+ const gateInfo = gateResults[i];
+ nodes.push({
+ id: `job:${job.id}`,
+ kind: 'job',
+ stage: stageId,
+ label: job.name || job.id,
+ enabled: !!job.enabled,
+ schedule: {
+ type: job.interval || (job.cronExpression ? 'cron' : 'custom'),
+ intervalMs: job.intervalMs ?? null,
+ cronExpression: job.cronExpression ?? null,
+ scheduledTime: job.scheduledTime ?? null,
+ weekdaysOnly: !!job.weekdaysOnly
+ },
+ lastRun: job.lastRun || null,
+ runCount: job.runCount || 0,
+ runAfter: [],
+ gate: gateInfo,
+ // Jobs without gates are implicitly runnable; gate.shouldRun=false => blocked
+ blocked: gateInfo && gateInfo.shouldRun === false ? gateInfo.reason : null,
+ shouldRun: gateInfo ? gateInfo.shouldRun !== false : true
+ });
+ }
+
+ // Stage-flow edges — chain stages in canonical order so the visualizer can
+ // render a left-to-right pipeline. Skip empty stages. These edges target bare
+ // stage ids (matching the `stages` list), not node ids.
+ const populatedStages = WORKFLOW_STAGES.filter(stage =>
+ nodes.some(n => n.stage === stage.id)
+ );
+ for (let i = 0; i < populatedStages.length - 1; i++) {
+ edges.push({
+ from: populatedStages[i].id,
+ to: populatedStages[i + 1].id,
+ kind: 'stage-flow'
+ });
+ }
+
+ // Sort stages by canonical order
+ const stages = WORKFLOW_STAGES.map(s => ({
+ id: s.id,
+ label: s.label,
+ description: s.description,
+ order: STAGE_INDEX.get(s.id),
+ nodeCount: nodes.filter(n => n.stage === s.id).length,
+ enabledCount: nodes.filter(n => n.stage === s.id && n.enabled).length
+ }));
+
+ return {
+ generatedAt: new Date().toISOString(),
+ stages,
+ nodes,
+ edges
+ };
+}
+
+async function checkGateSafe(jobId) {
+ if (!hasGate(jobId)) return null;
+ const result = await checkJobGate(jobId).catch(err => ({
+ shouldRun: true,
+ reason: `gate-error: ${err?.message || err}`,
+ error: true
+ }));
+ return result;
+}
diff --git a/server/services/workflow.test.js b/server/services/workflow.test.js
new file mode 100644
index 0000000000..009ec94843
--- /dev/null
+++ b/server/services/workflow.test.js
@@ -0,0 +1,198 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./taskSchedule.js', () => ({
+ getScheduleStatus: vi.fn()
+}));
+
+vi.mock('./autonomousJobs.js', () => ({
+ getAllJobs: vi.fn()
+}));
+
+vi.mock('./jobGates.js', () => ({
+ checkJobGate: vi.fn(),
+ hasGate: vi.fn(),
+ getRegisteredGates: vi.fn()
+}));
+
+const { getScheduleStatus } = await import('./taskSchedule.js');
+const { getAllJobs } = await import('./autonomousJobs.js');
+const { checkJobGate, hasGate, getRegisteredGates } = await import('./jobGates.js');
+const { getWorkflowGraph, WORKFLOW_STAGES } = await import('./workflow.js');
+
+const STAGE_IDS = WORKFLOW_STAGES.map(s => s.id);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getRegisteredGates.mockReturnValue([]);
+ hasGate.mockReturnValue(false);
+});
+
+describe('WORKFLOW_STAGES contract', () => {
+ it('canonical stages exist in expected order', () => {
+ expect(STAGE_IDS).toEqual(['hygiene', 'review', 'plan', 'audit', 'build', 'report', 'ambient']);
+ });
+
+ it('places do-replan in the plan stage and feature-ideas in build', () => {
+ const planStage = WORKFLOW_STAGES.find(s => s.id === 'plan');
+ const buildStage = WORKFLOW_STAGES.find(s => s.id === 'build');
+ expect(planStage.taskTypes).toContain('do-replan');
+ expect(buildStage.taskTypes).toContain('feature-ideas');
+ });
+
+ it('places branch-cleanup in the hygiene stage and pr-reviewer in review', () => {
+ const hygiene = WORKFLOW_STAGES.find(s => s.id === 'hygiene');
+ const review = WORKFLOW_STAGES.find(s => s.id === 'review');
+ expect(hygiene.taskTypes).toContain('branch-cleanup');
+ expect(review.taskTypes).toContain('pr-reviewer');
+ });
+
+ it('does not place the same task type in two stages', () => {
+ const seen = new Set();
+ for (const stage of WORKFLOW_STAGES) {
+ for (const t of stage.taskTypes) {
+ expect(seen.has(t), `task type ${t} appears in multiple stages`).toBe(false);
+ seen.add(t);
+ }
+ }
+ });
+
+ it('does not place the same job id in two stages', () => {
+ const seen = new Set();
+ for (const stage of WORKFLOW_STAGES) {
+ for (const j of stage.jobIds) {
+ expect(seen.has(j), `job id ${j} appears in multiple stages`).toBe(false);
+ seen.add(j);
+ }
+ }
+ });
+});
+
+describe('getWorkflowGraph', () => {
+ it('returns nodes for tasks with their stage classification', async () => {
+ getScheduleStatus.mockResolvedValue({
+ tasks: {
+ 'do-replan': { type: 'weekly', enabled: true, runAfter: ['pr-reviewer'], lastRun: null, runCount: 0, status: { shouldRun: true, reason: 'weekly-due' } },
+ 'feature-ideas': { type: 'daily', enabled: true, runAfter: ['do-replan'], lastRun: null, runCount: 0, status: { shouldRun: false, reason: 'waiting-on-dependencies', pendingDeps: ['do-replan'] } }
+ }
+ });
+ getAllJobs.mockResolvedValue([]);
+
+ const graph = await getWorkflowGraph();
+
+ const replan = graph.nodes.find(n => n.id === 'task:do-replan');
+ expect(replan).toBeDefined();
+ expect(replan.stage).toBe('plan');
+ expect(replan.kind).toBe('task');
+ expect(replan.runAfter).toEqual(['pr-reviewer']);
+ expect(replan.shouldRun).toBe(true);
+
+ const featureIdeas = graph.nodes.find(n => n.id === 'task:feature-ideas');
+ expect(featureIdeas.stage).toBe('build');
+ expect(featureIdeas.blocked).toBe('waiting-on-dependencies');
+ expect(featureIdeas.pendingDeps).toEqual(['do-replan']);
+ });
+
+ it('emits a depends-on edge for every runAfter entry', async () => {
+ getScheduleStatus.mockResolvedValue({
+ tasks: {
+ 'feature-ideas': { type: 'daily', enabled: true, runAfter: ['do-replan'], lastRun: null, runCount: 0, status: { shouldRun: true } }
+ }
+ });
+ getAllJobs.mockResolvedValue([]);
+
+ const graph = await getWorkflowGraph();
+ const dep = graph.edges.find(e => e.kind === 'depends-on' && e.to === 'task:feature-ideas');
+ expect(dep).toEqual({ from: 'task:do-replan', to: 'task:feature-ideas', kind: 'depends-on' });
+ });
+
+ it('classifies known job IDs into their canonical stage', async () => {
+ getScheduleStatus.mockResolvedValue({ tasks: {} });
+ getAllJobs.mockResolvedValue([
+ { id: 'job-daily-briefing', name: 'Daily Briefing', enabled: true, interval: 'daily', lastRun: null, runCount: 0 },
+ { id: 'job-system-health-check', name: 'System Health Check', enabled: true, interval: 'custom', intervalMs: 900000, lastRun: null, runCount: 0 }
+ ]);
+
+ const graph = await getWorkflowGraph();
+ const briefing = graph.nodes.find(n => n.id === 'job:job-daily-briefing');
+ const health = graph.nodes.find(n => n.id === 'job:job-system-health-check');
+ expect(briefing.stage).toBe('report');
+ expect(health.stage).toBe('ambient');
+ });
+
+ it('falls back to ambient stage for unknown task types and jobs', async () => {
+ getScheduleStatus.mockResolvedValue({
+ tasks: {
+ 'custom-thing': { type: 'daily', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } }
+ }
+ });
+ getAllJobs.mockResolvedValue([
+ { id: 'job-custom', name: 'Custom', enabled: false, interval: 'daily', lastRun: null, runCount: 0 }
+ ]);
+
+ const graph = await getWorkflowGraph();
+ expect(graph.nodes.find(n => n.id === 'task:custom-thing').stage).toBe('ambient');
+ expect(graph.nodes.find(n => n.id === 'job:job-custom').stage).toBe('ambient');
+ });
+
+ it('emits stage-flow edges only between populated stages', async () => {
+ // Only plan and build populated — flow edge should connect plan → build directly
+ getScheduleStatus.mockResolvedValue({
+ tasks: {
+ 'do-replan': { type: 'weekly', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } },
+ 'feature-ideas': { type: 'daily', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } }
+ }
+ });
+ getAllJobs.mockResolvedValue([]);
+
+ const graph = await getWorkflowGraph();
+ const stageEdges = graph.edges.filter(e => e.kind === 'stage-flow');
+ expect(stageEdges).toEqual([{ from: 'plan', to: 'build', kind: 'stage-flow' }]);
+ });
+
+ it('includes gate state for jobs that have a registered gate', async () => {
+ getScheduleStatus.mockResolvedValue({ tasks: {} });
+ getAllJobs.mockResolvedValue([
+ { id: 'job-brain-review', name: 'Brain Review', enabled: true, interval: 'daily', lastRun: null, runCount: 0 }
+ ]);
+ getRegisteredGates.mockReturnValue(['job-brain-review']);
+ hasGate.mockImplementation(id => id === 'job-brain-review');
+ checkJobGate.mockResolvedValue({ shouldRun: false, reason: 'No inbox items need review' });
+
+ const graph = await getWorkflowGraph();
+ const node = graph.nodes.find(n => n.id === 'job:job-brain-review');
+ expect(node.gate).toEqual({ shouldRun: false, reason: 'No inbox items need review' });
+ expect(node.blocked).toBe('No inbox items need review');
+ expect(node.shouldRun).toBe(false);
+ });
+
+ it('treats gate errors as fail-open', async () => {
+ getScheduleStatus.mockResolvedValue({ tasks: {} });
+ getAllJobs.mockResolvedValue([
+ { id: 'job-brain-review', name: 'Brain Review', enabled: true, interval: 'daily', lastRun: null, runCount: 0 }
+ ]);
+ getRegisteredGates.mockReturnValue(['job-brain-review']);
+ hasGate.mockImplementation(id => id === 'job-brain-review');
+ checkJobGate.mockRejectedValue(new Error('boom'));
+
+ const graph = await getWorkflowGraph();
+ const node = graph.nodes.find(n => n.id === 'job:job-brain-review');
+ expect(node.gate.shouldRun).toBe(true);
+ expect(node.gate.error).toBe(true);
+ });
+
+ it('reports per-stage enabled/total counts', async () => {
+ getScheduleStatus.mockResolvedValue({
+ tasks: {
+ 'do-replan': { type: 'weekly', enabled: true, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: true } },
+ 'feature-ideas': { type: 'daily', enabled: false, runAfter: [], lastRun: null, runCount: 0, status: { shouldRun: false, reason: 'disabled' } }
+ }
+ });
+ getAllJobs.mockResolvedValue([]);
+
+ const graph = await getWorkflowGraph();
+ const planStage = graph.stages.find(s => s.id === 'plan');
+ const buildStage = graph.stages.find(s => s.id === 'build');
+ expect(planStage).toMatchObject({ nodeCount: 1, enabledCount: 1 });
+ expect(buildStage).toMatchObject({ nodeCount: 1, enabledCount: 0 });
+ });
+});