Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(datadog): add DataDog manager and error monitor job (#83)

[._.]/ Adam Eivy334d049f2dd8
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 34d07bc4d4..9c4362158f 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -47,6 +47,7 @@ const RunnerPage = lazyWithReload(() => import('./pages/DevTools').then(m => ({
const UsagePage = lazyWithReload(() => import('./pages/DevTools').then(m => ({ default: m.UsagePage })));
const ProcessesPage = lazyWithReload(() => import('./pages/DevTools').then(m => ({ default: m.ProcessesPage })));
const AgentsPage = lazyWithReload(() => import('./pages/DevTools').then(m => ({ default: m.AgentsPage })));
+const DataDog = lazyWithReload(() => import('./pages/DataDog'));
const GitHub = lazyWithReload(() => import('./pages/GitHub'));
const CyberCity = lazyWithReload(() => import('./pages/CyberCity'));
const AppDetail = lazyWithReload(() => import('./pages/AppDetail'));
@@ -77,6 +78,7 @@ export default function App() {
<Route index element={<Dashboard />} />
<Route path="apps" element={<Apps />} />
<Route path="devtools" element={<Navigate to="/devtools/runs" replace />} />
+ <Route path="devtools/datadog" element={<DataDog />} />
<Route path="devtools/github" element={<GitHub />} />
<Route path="devtools/history" element={<HistoryPage />} />
<Route path="devtools/runs" element={<RunsHistoryPage />} />
@@ -117,6 +119,7 @@ export default function App() {
<Route path="post" element={<Post />} />
<Route path="messages" element={<Navigate to="/messages/inbox" replace />} />
<Route path="messages/:tab" element={<Messages />} />
+ <Route path="datadog" element={<Navigate to="/devtools/datadog" replace />} />
<Route path="jira" element={<Navigate to="/devtools/jira" replace />} />
<Route path="devtools/jira" element={<Jira />} />
<Route path="city" element={<CyberCity />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index be9f037b7a..b2764f29a3 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -61,6 +61,7 @@ import {
Mail,
Inbox,
RefreshCw,
+ Dog,
FilePen
} from 'lucide-react';
/* global __APP_VERSION__ */
@@ -142,6 +143,7 @@ const navItems = [
{ href: '//:5560', label: 'Autofixer', icon: Wrench, external: true, dynamicHost: true },
{ to: '/browser', label: 'Browser', icon: Globe },
{ to: '/devtools/runner', label: 'Code', icon: Code2 },
+ { to: '/devtools/datadog', label: 'DataDog', icon: Dog },
{ to: '/devtools/github', label: 'GitHub', icon: Github },
{ to: '/devtools/history', label: 'History', icon: History },
{ to: '/devtools/jira', label: 'JIRA', icon: Ticket },
diff --git a/client/src/components/apps/EditAppModal.jsx b/client/src/components/apps/EditAppModal.jsx
index 56d3099d38..d7f37e1239 100644
--- a/client/src/components/apps/EditAppModal.jsx
+++ b/client/src/components/apps/EditAppModal.jsx
@@ -25,22 +25,32 @@ export default function EditAppModal({ app, onClose, onSave }) {
jiraLabels: (app.jira?.labels || []).join(', '),
jiraAssignee: app.jira?.assignee || '',
jiraEpicKey: app.jira?.epicKey || '',
- jiraCreatePR: app.jira?.createPR !== false
+ jiraCreatePR: app.jira?.createPR !== false,
+ datadogEnabled: app.datadog?.enabled || false,
+ datadogInstanceId: app.datadog?.instanceId || '',
+ datadogServiceName: app.datadog?.serviceName || '',
+ datadogEnvironment: app.datadog?.environment || ''
});
const [saving, setSaving] = useState(false);
const [error, setError] = useState(null);
const [jiraExpanded, setJiraExpanded] = useState(app.jira?.enabled || false);
const [jiraInstances, setJiraInstances] = useState([]);
+ const [datadogExpanded, setDatadogExpanded] = useState(app.datadog?.enabled || false);
+ const [datadogInstances, setDatadogInstances] = useState([]);
const [jiraProjects, setJiraProjects] = useState([]);
const [loadingProjects, setLoadingProjects] = useState(false);
const [projectSearch, setProjectSearch] = useState('');
const [projectDropdownOpen, setProjectDropdownOpen] = useState(false);
useEffect(() => {
- api.getJiraInstances().then(data => {
- const instances = data?.instances ? Object.values(data.instances) : [];
- setJiraInstances(instances);
- }).catch(() => setJiraInstances([]));
+ const toInstances = (data) => data?.instances ? Object.values(data.instances) : [];
+ Promise.all([
+ api.getJiraInstances().then(toInstances).catch(() => []),
+ api.getDatadogInstances().then(toInstances).catch(() => [])
+ ]).then(([jira, datadog]) => {
+ setJiraInstances(jira);
+ setDatadogInstances(datadog);
+ });
}, []);
useEffect(() => {
@@ -91,6 +101,12 @@ export default function EditAppModal({ app, onClose, onSave }) {
assignee: formData.jiraAssignee || undefined,
epicKey: formData.jiraEpicKey || undefined,
createPR: formData.jiraCreatePR
+ } : { enabled: false },
+ datadog: formData.datadogEnabled ? {
+ enabled: true,
+ instanceId: formData.datadogInstanceId || undefined,
+ serviceName: formData.datadogServiceName || undefined,
+ environment: formData.datadogEnvironment || undefined
} : { enabled: false }
};
@@ -440,6 +456,85 @@ export default function EditAppModal({ app, onClose, onSave }) {
)}
</div>
+ {/* DataDog Integration Section */}
+ <div className="border border-port-border rounded-lg overflow-hidden">
+ <button
+ type="button"
+ onClick={() => setDatadogExpanded(prev => !prev)}
+ className="w-full flex items-center justify-between px-4 py-3 bg-port-bg hover:bg-port-border/50 transition-colors"
+ >
+ <span className="text-sm font-medium text-gray-300">DataDog Integration</span>
+ <div className="flex items-center gap-2">
+ {formData.datadogEnabled && (
+ <span className="text-xs px-2 py-0.5 bg-port-accent/20 text-port-accent rounded">Enabled</span>
+ )}
+ {datadogExpanded ? <ChevronUp size={16} className="text-gray-400" /> : <ChevronDown size={16} className="text-gray-400" />}
+ </div>
+ </button>
+
+ {datadogExpanded && (
+ <div className="p-4 space-y-3 border-t border-port-border">
+ <label className="flex items-center gap-2 cursor-pointer">
+ <input
+ type="checkbox"
+ checked={formData.datadogEnabled}
+ onChange={e => setFormData({ ...formData, datadogEnabled: e.target.checked })}
+ className="rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
+ />
+ <span className="text-sm text-white">Enable DataDog Monitoring</span>
+ </label>
+
+ {formData.datadogEnabled && (
+ <>
+ {datadogInstances.length === 0 ? (
+ <div className="p-3 bg-port-warning/10 border border-port-warning/30 rounded-lg text-sm text-port-warning">
+ No DataDog instances configured. <Link to="/devtools/datadog" className="underline hover:text-white">Configure DataDog</Link> first.
+ </div>
+ ) : (
+ <>
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">DataDog Instance</label>
+ <select
+ value={formData.datadogInstanceId}
+ onChange={e => setFormData({ ...formData, datadogInstanceId: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ >
+ <option value="">Select instance...</option>
+ {datadogInstances.map(inst => (
+ <option key={inst.id} value={inst.id}>{inst.name} ({inst.site})</option>
+ ))}
+ </select>
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Service Name</label>
+ <input
+ type="text"
+ value={formData.datadogServiceName}
+ onChange={e => setFormData({ ...formData, datadogServiceName: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ placeholder="e.g., my-app-service"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Environment</label>
+ <input
+ type="text"
+ value={formData.datadogEnvironment}
+ onChange={e => setFormData({ ...formData, datadogEnvironment: e.target.value })}
+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white focus:border-port-accent focus:outline-hidden"
+ placeholder="e.g., production"
+ />
+ </div>
+ </>
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+
<div className="flex justify-end gap-3 pt-4">
<button
type="button"
diff --git a/client/src/pages/DataDog.jsx b/client/src/pages/DataDog.jsx
new file mode 100644
index 0000000000..739d06c129
--- /dev/null
+++ b/client/src/pages/DataDog.jsx
@@ -0,0 +1,436 @@
+import { useState, useEffect } from 'react';
+import toast from 'react-hot-toast';
+import api from '../services/api';
+
+const SITE_OPTIONS = [
+ { value: 'api.datadoghq.com', label: 'US1 (api.datadoghq.com)' },
+ { value: 'api.datadoghq.eu', label: 'EU (api.datadoghq.eu)' },
+ { value: 'api.us3.datadoghq.com', label: 'US3 (api.us3.datadoghq.com)' },
+ { value: 'api.us5.datadoghq.com', label: 'US5 (api.us5.datadoghq.com)' },
+ { value: 'api.ap1.datadoghq.com', label: 'AP1 (api.ap1.datadoghq.com)' },
+ { value: 'custom', label: 'Custom...' }
+];
+
+export default function DataDog() {
+ const [instances, setInstances] = useState({});
+ const [loading, setLoading] = useState(true);
+ const [editingInstance, setEditingInstance] = useState(null);
+ const [testingInstance, setTestingInstance] = useState(null);
+ const [testResults, setTestResults] = useState({});
+ const [saveError, setSaveError] = useState(null);
+ const [saving, setSaving] = useState(false);
+ const [deleteConfirm, setDeleteConfirm] = useState(null);
+ const [customSite, setCustomSite] = useState(false);
+
+ const [formData, setFormData] = useState({
+ id: '',
+ name: '',
+ site: 'api.datadoghq.com',
+ apiKey: '',
+ appKey: ''
+ });
+
+ useEffect(() => {
+ loadInstances();
+ }, []);
+
+ const loadInstances = async () => {
+ try {
+ setLoading(true);
+ const response = await api.get('/datadog/instances');
+ setInstances(response.instances || {});
+ } catch (error) {
+ console.error(`Failed to load DataDog instances: ${error.message}`);
+ toast.error(`Failed to load DataDog instances: ${error.message}`);
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ const handleEdit = (instance) => {
+ setEditingInstance(instance.id);
+ const isCustom = !SITE_OPTIONS.some(o => o.value !== 'custom' && o.value === instance.site);
+ setCustomSite(isCustom);
+ setFormData({
+ id: instance.id,
+ name: instance.name,
+ site: instance.site,
+ apiKey: '',
+ appKey: ''
+ });
+ setSaveError(null);
+ };
+
+ const handleCreate = () => {
+ setEditingInstance('new');
+ setCustomSite(false);
+ setFormData({
+ id: '',
+ name: '',
+ site: 'api.datadoghq.com',
+ apiKey: '',
+ appKey: ''
+ });
+ setSaveError(null);
+ };
+
+ const handleCancel = () => {
+ setEditingInstance(null);
+ setCustomSite(false);
+ setFormData({
+ id: '',
+ name: '',
+ site: 'api.datadoghq.com',
+ apiKey: '',
+ appKey: ''
+ });
+ setSaveError(null);
+ };
+
+ const handleSave = async () => {
+ try {
+ setSaving(true);
+ setSaveError(null);
+
+ const payload = {
+ id: formData.id || formData.name.toLowerCase().replace(/\s+/g, '-'),
+ name: formData.name,
+ site: formData.site,
+ ...(formData.apiKey && { apiKey: formData.apiKey }),
+ ...(formData.appKey && { appKey: formData.appKey })
+ };
+
+ await api.post('/datadog/instances', payload);
+
+ toast.success(`DataDog instance "${payload.name}" saved successfully`);
+ await loadInstances();
+ handleCancel();
+ } catch (error) {
+ console.error(`Failed to save DataDog instance: ${error.message}`);
+ setSaveError(error.message);
+ toast.error(`Failed to save: ${error.message}`);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const handleDeleteClick = (instanceId) => {
+ setDeleteConfirm(instanceId);
+ };
+
+ const handleDeleteConfirm = async () => {
+ const instanceId = deleteConfirm;
+ setDeleteConfirm(null);
+
+ try {
+ await api.delete(`/datadog/instances/${instanceId}`);
+ toast.success(`DataDog instance "${instanceId}" deleted`);
+ await loadInstances();
+ } catch (error) {
+ console.error(`Failed to delete DataDog instance: ${error.message}`);
+ toast.error(`Failed to delete: ${error.message}`);
+ }
+ };
+
+ const handleDeleteCancel = () => {
+ setDeleteConfirm(null);
+ };
+
+ const handleTest = async (instanceId) => {
+ try {
+ setTestingInstance(instanceId);
+ setTestResults(prev => ({ ...prev, [instanceId]: null }));
+
+ const response = await api.post(`/datadog/instances/${instanceId}/test`);
+ setTestResults(prev => ({ ...prev, [instanceId]: response }));
+
+ if (response.success) {
+ toast.success('Connection successful!');
+ }
+ } catch (error) {
+ setTestResults(prev => ({ ...prev, [instanceId]: { success: false, error: error.message } }));
+ toast.error(`Connection failed: ${error.message}`);
+ } finally {
+ setTestingInstance(null);
+ }
+ };
+
+ const handleInputChange = (e) => {
+ setFormData({
+ ...formData,
+ [e.target.name]: e.target.value
+ });
+ if (saveError) {
+ setSaveError(null);
+ }
+ };
+
+ const handleSiteChange = (e) => {
+ const value = e.target.value;
+ if (value === 'custom') {
+ setCustomSite(true);
+ setFormData({ ...formData, site: '' });
+ } else {
+ setCustomSite(false);
+ setFormData({ ...formData, site: value });
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex justify-center items-center h-screen">
+ <div className="text-gray-400">Loading DataDog instances...</div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="p-4 sm:p-6 max-w-6xl mx-auto">
+ <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-6">
+ <h1 className="text-xl sm:text-2xl font-bold text-white">DataDog Integration</h1>
+ {!editingInstance && (
+ <button
+ onClick={handleCreate}
+ className="w-full sm:w-auto px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded"
+ >
+ + Add DataDog Instance
+ </button>
+ )}
+ </div>
+
+ {/* Delete Confirmation Modal */}
+ {deleteConfirm && (
+ <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
+ <div className="bg-gray-800 rounded-lg p-4 sm:p-6 max-w-md w-full">
+ <h3 className="text-lg sm:text-xl font-bold text-white mb-4">Delete DataDog Instance?</h3>
+ <p className="text-gray-300 mb-6 text-sm sm:text-base break-words">
+ Are you sure you want to delete &quot;{deleteConfirm}&quot;? This will remove the stored keys.
+ </p>
+ <div className="flex flex-col-reverse sm:flex-row gap-2 sm:justify-end">
+ <button
+ onClick={handleDeleteCancel}
+ className="w-full sm:w-auto px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleDeleteConfirm}
+ className="w-full sm:w-auto px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded"
+ >
+ Delete
+ </button>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {editingInstance ? (
+ <div className="bg-gray-800 rounded-lg p-4 sm:p-6 mb-6">
+ <h2 className="text-lg sm:text-xl font-bold text-white mb-4">
+ {editingInstance === 'new' ? 'Add' : 'Edit'} DataDog Instance
+ </h2>
+
+ {saveError && (
+ <div className="mb-4 p-3 bg-red-900 border border-red-700 rounded">
+ <p className="text-red-300 font-medium">Error saving DataDog instance</p>
+ <p className="text-red-400 text-sm mt-1">{saveError}</p>
+ </div>
+ )}
+
+ <div className="space-y-4">
+ <div>
+ <label className="block text-sm font-medium text-gray-300 mb-1">
+ Instance ID
+ </label>
+ <input
+ type="text"
+ name="id"
+ value={formData.id}
+ onChange={handleInputChange}
+ disabled={editingInstance !== 'new'}
+ className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white disabled:opacity-50"
+ placeholder="e.g., company-datadog"
+ />
+ <p className="text-xs text-gray-400 mt-1">
+ Unique identifier (cannot be changed after creation)
+ </p>
+ </div>
+
+ <div>
+ <label className="block text-sm font-medium text-gray-300 mb-1">
+ Display Name
+ </label>
+ <input
+ type="text"
+ name="name"
+ value={formData.name}
+ onChange={handleInputChange}
+ className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
+ placeholder="e.g., Company DataDog"
+ />
+ </div>
+
+ <div>
+ <label className="block text-sm font-medium text-gray-300 mb-1">
+ Site
+ </label>
+ <select
+ value={customSite ? 'custom' : formData.site}
+ onChange={handleSiteChange}
+ className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white mb-2"
+ >
+ {SITE_OPTIONS.map(opt => (
+ <option key={opt.value} value={opt.value}>{opt.label}</option>
+ ))}
+ </select>
+ {customSite && (
+ <input
+ type="text"
+ name="site"
+ value={formData.site}
+ onChange={handleInputChange}
+ className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
+ placeholder="e.g., api.custom-datadog.com"
+ />
+ )}
+ </div>
+
+ <div>
+ <label className="block text-sm font-medium text-gray-300 mb-1">
+ API Key
+ </label>
+ <input
+ type="password"
+ name="apiKey"
+ value={formData.apiKey}
+ onChange={handleInputChange}
+ className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
+ placeholder={editingInstance === 'new' ? 'Enter your DataDog API Key' : 'Leave blank to keep existing key'}
+ />
+ <p className="text-xs text-gray-400 mt-1">
+ Found in DataDog Organization Settings &rarr; API Keys
+ </p>
+ </div>
+
+ <div>
+ <label className="block text-sm font-medium text-gray-300 mb-1">
+ Application Key
+ </label>
+ <input
+ type="password"
+ name="appKey"
+ value={formData.appKey}
+ onChange={handleInputChange}
+ className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded text-white"
+ placeholder={editingInstance === 'new' ? 'Enter your DataDog Application Key' : 'Leave blank to keep existing key'}
+ />
+ <p className="text-xs text-gray-400 mt-1">
+ Found in DataDog Organization Settings &rarr; Application Keys
+ </p>
+ </div>
+
+ <div className="flex flex-col sm:flex-row gap-2">
+ <button
+ onClick={handleSave}
+ disabled={saving || !formData.name || !formData.site || (editingInstance === 'new' && (!formData.apiKey || !formData.appKey))}
+ className="w-full sm:w-auto px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded disabled:opacity-50 disabled:cursor-not-allowed"
+ >
+ {saving ? 'Saving...' : 'Save'}
+ </button>
+ <button
+ onClick={handleCancel}
+ disabled={saving}
+ className="w-full sm:w-auto px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ </div>
+ ) : null}
+
+ <div className="space-y-4">
+ {Object.values(instances).length === 0 ? (
+ <div className="bg-gray-800 rounded-lg p-8 text-center">
+ <p className="text-gray-400">No DataDog instances configured.</p>
+ <p className="text-gray-500 text-sm mt-2">
+ Add a DataDog instance to enable error monitoring for your apps.
+ </p>
+ </div>
+ ) : (
+ Object.values(instances).map((instance) => (
+ <div key={instance.id} className="bg-gray-800 rounded-lg p-4 sm:p-6">
+ <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-4">
+ <div className="flex-1 min-w-0">
+ <h3 className="text-lg font-bold text-white truncate">{instance.name}</h3>
+ <p className="text-gray-400 text-sm mt-1 break-all">Site: {instance.site}</p>
+ <p className="text-gray-500 text-sm">
+ API Key: {instance.hasApiKey ? 'Configured' : 'Not set'}
+ </p>
+ <p className="text-gray-500 text-sm">
+ App Key: {instance.hasAppKey ? 'Configured' : 'Not set'}
+ </p>
+ </div>
+
+ <div className="flex flex-wrap gap-2 sm:flex-nowrap">
+ <button
+ onClick={() => handleTest(instance.id)}
+ disabled={testingInstance === instance.id}
+ className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-blue-600 hover:bg-blue-700 text-white text-sm rounded disabled:opacity-50"
+ >
+ {testingInstance === instance.id ? 'Testing...' : 'Test'}
+ </button>
+ <button
+ onClick={() => handleEdit(instance)}
+ className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-yellow-600 hover:bg-yellow-700 text-white text-sm rounded"
+ >
+ Edit
+ </button>
+ <button
+ onClick={() => handleDeleteClick(instance.id)}
+ className="flex-1 sm:flex-none px-3 py-2 sm:py-1 bg-red-600 hover:bg-red-700 text-white text-sm rounded"
+ >
+ Delete
+ </button>
+ </div>
+ </div>
+
+ {testResults[instance.id] && testResults[instance.id].success !== undefined && (
+ <div
+ className={`mt-4 p-3 rounded ${
+ testResults[instance.id].success
+ ? 'bg-green-900 border border-green-700'
+ : 'bg-red-900 border border-red-700'
+ }`}
+ >
+ {testResults[instance.id].success ? (
+ <p className="text-green-300 font-medium">API key validated</p>
+ ) : (
+ <>
+ <p className="text-red-300 font-medium">Connection failed</p>
+ <p className="text-red-400 text-sm mt-1">{testResults[instance.id].error}</p>
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ ))
+ )}
+ </div>
+
+ <div className="mt-6 sm:mt-8 bg-gray-800 rounded-lg p-4 sm:p-6">
+ <h2 className="text-base sm:text-lg font-bold text-white mb-3 sm:mb-4">Usage</h2>
+ <div className="space-y-2 text-xs sm:text-sm text-gray-300">
+ <p>1. Add one or more DataDog instances above</p>
+ <p>2. Go to Apps and enable DataDog monitoring in each app&apos;s settings</p>
+ <p>3. The error monitor job will periodically check for new errors:</p>
+ <ul className="list-disc list-inside ml-2 sm:ml-4 space-y-1 text-gray-400">
+ <li>Query DataDog for recent error events matching the app&apos;s service name</li>
+ <li>Surface new errors in notifications and app insights</li>
+ <li>Track error trends over time</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 1e5482610f..88dcbbbbc4 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1573,6 +1573,9 @@ export const updateLifeEvent = (id, data) => request(`/meatspace/life-events/${i
});
export const removeLifeEvent = (id) => request(`/meatspace/life-events/${id}`, { method: 'DELETE' });
+// DataDog
+export const getDatadogInstances = () => request('/datadog/instances');
+
// JIRA
export const getJiraInstances = () => request('/jira/instances');
export const getJiraProjects = (instanceId) => request(`/jira/instances/${instanceId}/projects`);
diff --git a/data.sample/prompts/skills/jobs/datadog-error-monitor.md b/data.sample/prompts/skills/jobs/datadog-error-monitor.md
new file mode 100644
index 0000000000..6c431735e0
--- /dev/null
+++ b/data.sample/prompts/skills/jobs/datadog-error-monitor.md
@@ -0,0 +1,78 @@
+# DataDog Error Monitor Job
+
+Autonomous job that monitors DataDog for new application errors across all configured apps. Runs daily at 8 AM. Creates CoS tasks for new errors and optionally creates JIRA tickets for apps with JIRA integration enabled.
+
+## Prompt Template
+
+You are acting as my Chief of Staff, monitoring DataDog for new application errors.
+
+## Steps
+
+### Phase 1 — Discover
+
+1. **Find DataDog-enabled apps**
+ - Call `GET /api/apps` to get all managed apps
+ - Filter for apps where `datadog.enabled === true` and both `datadog.instanceId` and `datadog.serviceName` are set
+ - Skip archived apps
+
+### Phase 2 — Check Errors
+
+2. **Search for errors in each app**
+ - For each DataDog-enabled app, call:
+ ```
+ POST /api/datadog/instances/:instanceId/search-errors
+ Body: { "serviceName": "<app.datadog.serviceName>", "environment": "<app.datadog.environment>", "fromTime": "<24h ago ISO>" }
+ ```
+ - Compare results against the error cache in `/data/cos/datadog-errors.json`
+ - Identify new errors by fingerprint or message hash
+
+### Phase 3 — Act on New Errors
+
+3. **Create tasks and tickets for new errors**
+ - For each new error:
+ - Create a CoS task describing the error, affected app, stack trace, and frequency
+ - If the app also has `jira.enabled === true`, create a JIRA ticket:
+ ```
+ POST /api/jira/instances/:instanceId/tickets
+ Body: { "projectKey": "<app.jira.projectKey>", "summary": "DD Error: <error message>", "description": "<full error details>", "issueType": "Bug" }
+ ```
+ - Update the error cache with the new error fingerprint
+
+### Phase 4 — Report
+
+4. **Generate summary report** covering:
+ - Apps checked and error counts per app
+ - New errors found and tasks/tickets created
+ - Recurring errors that are increasing in frequency
+ - Overall error trend (improving or degrading)
+
+## API Endpoints Used
+
+| Endpoint | Method | Purpose |
+|----------|--------|---------|
+| `/api/apps` | GET | List all managed apps |
+| `/api/datadog/instances/:id/search-errors` | POST | Search DataDog logs for errors |
+| `/api/jira/instances/:id/tickets` | POST | Create JIRA ticket for error |
+
+## Expected Outputs
+
+1. **CoS Tasks** - One per new error discovered
+2. **JIRA Tickets** - Created for errors in apps with JIRA enabled
+3. **Error Cache Update** - New fingerprints added to prevent duplicate alerts
+4. **Summary Report** - Saved via CoS reporting system
+
+## Success Criteria
+
+- All DataDog-enabled apps are checked
+- New errors are identified by comparing against cached fingerprints
+- CoS tasks created for each new error
+- JIRA tickets created where applicable
+- Error cache updated with new fingerprints
+- Report provides clear visibility into error trends
+
+## Job Metadata
+
+- **Category**: datadog-error-monitor
+- **Interval**: Daily at 8:00 AM
+- **Priority**: MEDIUM
+- **Autonomy Level**: manager (creates tasks and tickets but does not fix errors)
diff --git a/server/index.js b/server/index.js
index 158f30bafd..55ec0c4810 100644
--- a/server/index.js
+++ b/server/index.js
@@ -46,6 +46,7 @@ import browserRoutes from './routes/browser.js';
import moltworldToolsRoutes from './routes/moltworldTools.js';
import moltworldWsRoutes from './routes/moltworldWs.js';
import insightsRoutes from './routes/insights.js';
+import datadogRoutes from './routes/datadog.js';
import jiraRoutes from './routes/jira.js';
import autobiographyRoutes from './routes/autobiography.js';
import backupRoutes from './routes/backup.js';
@@ -237,6 +238,7 @@ app.use('/api/digital-twin/autobiography', autobiographyRoutes);
app.use('/api/digital-twin', digitalTwinRoutes);
app.use('/api/lmstudio', lmstudioRoutes);
app.use('/api/browser', browserRoutes);
+app.use('/api/datadog', datadogRoutes);
app.use('/api/jira', jiraRoutes);
app.use('/api/health', appleHealthRoutes);
app.use('/api/insights', insightsRoutes);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index a1908a7a74..703831d089 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -164,6 +164,14 @@ export const jiraConfigSchema = z.object({
createPR: z.boolean().optional().default(true)
});
+// DataDog integration config for apps
+export const datadogConfigSchema = z.object({
+ enabled: z.boolean().default(false),
+ instanceId: z.string().optional(),
+ serviceName: z.string().optional(),
+ environment: z.string().optional()
+});
+
// App schema for registration/update
export const appSchema = z.object({
name: z.string().min(1).max(100),
@@ -189,7 +197,8 @@ export const appSchema = z.object({
interval: z.string().nullable().optional()
})).optional(), // Per-task overrides: { [taskType]: { enabled, interval } }
defaultUseWorktree: z.boolean().optional().default(false),
- jira: jiraConfigSchema.optional().nullable()
+ jira: jiraConfigSchema.optional().nullable(),
+ datadog: datadogConfigSchema.optional().nullable()
});
// Partial schema for updates
diff --git a/server/routes/datadog.js b/server/routes/datadog.js
new file mode 100644
index 0000000000..99d260179a
--- /dev/null
+++ b/server/routes/datadog.js
@@ -0,0 +1,141 @@
+/**
+ * DataDog API Routes
+ */
+
+import express from 'express';
+import * as datadogService from '../services/datadog.js';
+import { ServerError } from '../lib/errorHandler.js';
+
+const router = express.Router();
+
+function sanitizeInstance(instance) {
+ return {
+ id: instance.id,
+ name: instance.name,
+ site: instance.site,
+ hasApiKey: !!instance.apiKey,
+ hasAppKey: !!instance.appKey,
+ createdAt: instance.createdAt,
+ updatedAt: instance.updatedAt
+ };
+}
+
+/**
+ * GET /api/datadog/instances
+ * Get all DataDog instances
+ */
+router.get('/instances', async (req, res, next) => {
+ try {
+ const config = await datadogService.getInstances();
+
+ const sanitized = {
+ instances: Object.fromEntries(
+ Object.entries(config.instances).map(([id, instance]) => [id, sanitizeInstance(instance)])
+ )
+ };
+
+ res.json(sanitized);
+ } catch (error) {
+ next(error);
+ }
+});
+
+/**
+ * POST /api/datadog/instances
+ * Create or update DataDog instance
+ */
+router.post('/instances', async (req, res, next) => {
+ try {
+ const { id, name, site, apiKey, appKey } = req.body;
+
+ if (!id || !name || !site) {
+ throw new ServerError('Missing required fields: id, name, site', {
+ status: 400,
+ code: 'INVALID_INPUT'
+ });
+ }
+
+ // For new instances, both keys are required
+ const config = await datadogService.getInstances();
+ const isNew = !config.instances[id];
+ if (isNew && (!apiKey || !appKey)) {
+ throw new ServerError('API Key and Application Key are required for new instances', {
+ status: 400,
+ code: 'INVALID_INPUT'
+ });
+ }
+
+ const instance = await datadogService.upsertInstance(id, {
+ name,
+ site,
+ ...(apiKey && { apiKey }),
+ ...(appKey && { appKey })
+ });
+
+ res.json(sanitizeInstance(instance));
+ } catch (error) {
+ next(error);
+ }
+});
+
+/**
+ * DELETE /api/datadog/instances/:id
+ * Delete DataDog instance
+ */
+router.delete('/instances/:id', async (req, res, next) => {
+ try {
+ await datadogService.deleteInstance(req.params.id);
+ res.json({ success: true });
+ } catch (error) {
+ next(error);
+ }
+});
+
+/**
+ * POST /api/datadog/instances/:id/test
+ * Test DataDog instance connection
+ */
+router.post('/instances/:id/test', async (req, res, next) => {
+ try {
+ const result = await datadogService.testConnection(req.params.id);
+ res.json(result);
+ } catch (error) {
+ next(error);
+ }
+});
+
+/**
+ * POST /api/datadog/instances/:id/search-errors
+ * Search for errors in DataDog logs
+ */
+router.post('/instances/:id/search-errors', async (req, res, next) => {
+ try {
+ const { serviceName, environment, fromTime } = req.body;
+
+ if (!serviceName) {
+ throw new ServerError('serviceName is required', {
+ status: 400,
+ code: 'INVALID_INPUT'
+ });
+ }
+
+ if (fromTime && isNaN(Date.parse(fromTime))) {
+ throw new ServerError('fromTime must be a valid ISO 8601 date string', {
+ status: 400,
+ code: 'INVALID_INPUT'
+ });
+ }
+
+ const result = await datadogService.searchErrors(
+ req.params.id,
+ serviceName,
+ environment,
+ fromTime
+ );
+ res.json(result);
+ } catch (error) {
+ next(error);
+ }
+});
+
+export default router;
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index 48063f6e91..2368b235ae 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -86,6 +86,7 @@ const JOB_SKILL_MAP = {
'job-daily-briefing': 'daily-briefing',
'job-github-repo-maintenance': 'github-repo-maintenance',
'job-brain-review': 'brain-review',
+ 'job-datadog-error-monitor': 'datadog-error-monitor',
'job-jira-sprint-manager': 'jira-sprint-manager',
'job-autobiography-prompt': 'autobiography-prompt'
}
@@ -262,6 +263,48 @@ Phase 3 — Report:
createdAt: null,
updatedAt: null
},
+ {
+ id: 'job-datadog-error-monitor',
+ name: 'DataDog Error Monitor',
+ description: 'Check DataDog for new errors in configured apps, create tasks for new errors, and optionally create JIRA tickets.',
+ category: 'datadog-error-monitor',
+ interval: 'daily',
+ intervalMs: DAY,
+ scheduledTime: '08:00',
+ enabled: false,
+ priority: 'MEDIUM',
+ autonomyLevel: 'manager',
+ promptTemplate: `[Autonomous Job] DataDog Error Monitor
+
+You are acting as my Chief of Staff, monitoring DataDog for new application errors.
+
+Phase 1 — Discover:
+1. Call GET /api/apps to get all managed apps
+2. Filter for apps with datadog.enabled = true and datadog.instanceId + datadog.serviceName set
+3. Skip archived apps
+
+Phase 2 — Check Errors:
+4. For each DataDog-enabled app:
+ - Call POST /api/datadog/instances/:instanceId/search-errors with serviceName, environment, and fromTime (24h ago)
+ - Compare results against the error cache in /data/cos/datadog-errors.json
+ - Identify new errors (by fingerprint/message hash)
+
+Phase 3 — Act on New Errors:
+5. For each new error:
+ - Create a CoS task describing the error and the app it affects
+ - If the app also has jira.enabled = true, create a JIRA ticket for the error
+ - Update the error cache with the new error fingerprint
+
+Phase 4 — Report:
+6. Generate a summary report covering:
+ - Apps checked and error counts
+ - New errors found and tasks/tickets created
+ - Recurring errors that are increasing in frequency`,
+ lastRun: null,
+ runCount: 0,
+ createdAt: null,
+ updatedAt: null
+ },
{
id: 'job-autobiography-prompt',
name: 'Autobiography Story Prompt',
diff --git a/server/services/datadog.js b/server/services/datadog.js
new file mode 100644
index 0000000000..1a71b1523b
--- /dev/null
+++ b/server/services/datadog.js
@@ -0,0 +1,150 @@
+/**
+ * DataDog API Service
+ * Supports multiple DataDog instances with API/App key authentication
+ */
+
+import axios from 'axios';
+import fs from 'fs/promises';
+import path from 'path';
+import { PATHS, readJSONFile } from '../lib/fileUtils.js';
+
+const DATADOG_CONFIG_FILE = path.join(PATHS.data, 'datadog.json');
+
+// Hostname-only pattern: no scheme, no path, no port, no special chars
+const VALID_HOSTNAME_RE = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*$/;
+
+function validateSite(site) {
+ if (!site || !VALID_HOSTNAME_RE.test(site)) {
+ throw new Error(`Invalid DataDog site hostname: "${site}". Must be a valid hostname (e.g., api.datadoghq.com)`);
+ }
+}
+
+function sanitizeQueryValue(value) {
+ return value.replace(/"/g, '');
+}
+/**
+ * Get DataDog instances configuration
+ */
+export async function getInstances() {
+ return await readJSONFile(DATADOG_CONFIG_FILE, { instances: {} });
+}
+
+/**
+ * Save DataDog instances configuration
+ */
+export async function saveInstances(config) {
+ await fs.mkdir(path.dirname(DATADOG_CONFIG_FILE), { recursive: true });
+ await fs.writeFile(
+ DATADOG_CONFIG_FILE,
+ JSON.stringify(config, null, 2),
+ 'utf-8'
+ );
+}
+
+/**
+ * Add or update DataDog instance
+ */
+export async function upsertInstance(instanceId, instanceData) {
+ validateSite(instanceData.site);
+ const config = await getInstances();
+
+ const existing = config.instances[instanceId];
+
+ config.instances[instanceId] = {
+ id: instanceId,
+ name: instanceData.name,
+ site: instanceData.site,
+ apiKey: instanceData.apiKey || existing?.apiKey,
+ appKey: instanceData.appKey || existing?.appKey,
+ createdAt: existing?.createdAt || new Date().toISOString(),
+ updatedAt: new Date().toISOString()
+ };
+
+ await saveInstances(config);
+ return config.instances[instanceId];
+}
+
+/**
+ * Delete DataDog instance
+ */
+export async function deleteInstance(instanceId) {
+ const config = await getInstances();
+ delete config.instances[instanceId];
+ await saveInstances(config);
+}
+
+/**
+ * Create axios client for DataDog instance
+ */
+function createDatadogClient(instance) {
+ return axios.create({
+ baseURL: `https://${instance.site}`,
+ headers: {
+ 'DD-API-KEY': instance.apiKey,
+ 'DD-APPLICATION-KEY': instance.appKey,
+ 'Content-Type': 'application/json'
+ },
+ timeout: 30000
+ });
+}
+
+/**
+ * Test DataDog instance connection
+ */
+export async function testConnection(instanceId) {
+ const config = await getInstances();
+ const instance = config.instances[instanceId];
+
+ if (!instance) {
+ throw new Error(`DataDog instance ${instanceId} not found`);
+ }
+
+ const client = createDatadogClient(instance);
+
+ try {
+ await client.get('/api/v1/validate');
+ return { success: true };
+ } catch (error) {
+ return {
+ success: false,
+ error: error.response?.data?.errors?.[0] || error.message
+ };
+ }
+}
+
+/**
+ * Search for errors in DataDog logs
+ */
+export async function searchErrors(instanceId, serviceName, environment = 'production', fromTime) {
+ const config = await getInstances();
+ const instance = config.instances[instanceId];
+
+ if (!instance) {
+ throw new Error(`DataDog instance ${instanceId} not found`);
+ }
+
+ const client = createDatadogClient(instance);
+ const from = fromTime || new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
+
+ const response = await client.post('/api/v2/logs/events/search', {
+ filter: {
+ query: `status:error service:"${sanitizeQueryValue(serviceName)}" env:"${sanitizeQueryValue(environment)}"`,
+ from
+ },
+ sort: '-timestamp',
+ page: {
+ limit: 100
+ }
+ });
+
+ return response.data;
+}
+
+export default {
+ getInstances,
+ saveInstances,
+ upsertInstance,
+ deleteInstance,
+ testConnection,
+ searchErrors
+};
diff --git a/server/services/datadog.test.js b/server/services/datadog.test.js
new file mode 100644
index 0000000000..99a9f4bd61
--- /dev/null
+++ b/server/services/datadog.test.js
@@ -0,0 +1,245 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('fs/promises', () => {
+ const mod = {
+ readFile: vi.fn(),
+ writeFile: vi.fn(),
+ mkdir: vi.fn()
+ };
+ return { ...mod, default: mod };
+});
+
+vi.mock('fs', () => ({
+ existsSync: vi.fn(() => true)
+}));
+
+vi.mock('../lib/fileUtils.js', () => ({
+ PATHS: { data: '/mock/data' },
+ readJSONFile: vi.fn()
+}));
+
+vi.mock('axios', () => ({
+ default: {
+ create: vi.fn(() => ({
+ get: vi.fn(),
+ post: vi.fn()
+ }))
+ }
+}));
+
+import { writeFile, mkdir } from 'fs/promises';
+import { readJSONFile } from '../lib/fileUtils.js';
+import axios from 'axios';
+import {
+ getInstances,
+ upsertInstance,
+ deleteInstance,
+ testConnection,
+ searchErrors
+} from './datadog.js';
+
+const EMPTY_CONFIG = { instances: {} };
+
+const MOCK_INSTANCE = {
+ id: 'test-dd',
+ name: 'Test DataDog',
+ site: 'api.datadoghq.com',
+ apiKey: 'test-api-key',
+ appKey: 'test-app-key',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ readJSONFile.mockResolvedValue(EMPTY_CONFIG);
+ writeFile.mockResolvedValue(undefined);
+ mkdir.mockResolvedValue(undefined);
+});
+
+describe('DataDog Service', () => {
+ describe('getInstances', () => {
+ it('should return instances from config file', async () => {
+ readJSONFile.mockResolvedValue({ instances: { 'test-dd': MOCK_INSTANCE } });
+ const result = await getInstances();
+ expect(result.instances['test-dd']).toEqual(MOCK_INSTANCE);
+ });
+
+ it('should return empty instances when no config exists', async () => {
+ const result = await getInstances();
+ expect(result).toEqual(EMPTY_CONFIG);
+ });
+ });
+
+ describe('upsertInstance', () => {
+ it('should create a new instance', async () => {
+ const result = await upsertInstance('new-dd', {
+ name: 'New DD',
+ site: 'api.datadoghq.com',
+ apiKey: 'key1',
+ appKey: 'key2'
+ });
+
+ expect(result.id).toBe('new-dd');
+ expect(result.name).toBe('New DD');
+ expect(result.site).toBe('api.datadoghq.com');
+ expect(result.apiKey).toBe('key1');
+ expect(result.appKey).toBe('key2');
+ expect(result.createdAt).toBeDefined();
+ expect(writeFile).toHaveBeenCalled();
+ });
+
+ it('should preserve existing keys when not provided on update', async () => {
+ readJSONFile.mockResolvedValue({
+ instances: { 'test-dd': MOCK_INSTANCE }
+ });
+
+ const result = await upsertInstance('test-dd', {
+ name: 'Updated Name',
+ site: 'api.datadoghq.com'
+ });
+
+ expect(result.name).toBe('Updated Name');
+ expect(result.apiKey).toBe('test-api-key');
+ expect(result.appKey).toBe('test-app-key');
+ expect(result.createdAt).toBe('2026-01-01T00:00:00.000Z');
+ });
+
+ it('should update keys when provided on update', async () => {
+ readJSONFile.mockResolvedValue({
+ instances: { 'test-dd': MOCK_INSTANCE }
+ });
+
+ const result = await upsertInstance('test-dd', {
+ name: 'Updated',
+ site: 'api.datadoghq.com',
+ apiKey: 'new-api-key',
+ appKey: 'new-app-key'
+ });
+
+ expect(result.apiKey).toBe('new-api-key');
+ expect(result.appKey).toBe('new-app-key');
+ });
+
+ it('should reject invalid site hostnames', async () => {
+ await expect(upsertInstance('bad', {
+ name: 'Bad',
+ site: 'evil.com/path#',
+ apiKey: 'k1',
+ appKey: 'k2'
+ })).rejects.toThrow('Invalid DataDog site hostname');
+
+ await expect(upsertInstance('bad', {
+ name: 'Bad',
+ site: 'localhost:8080',
+ apiKey: 'k1',
+ appKey: 'k2'
+ })).rejects.toThrow('Invalid DataDog site hostname');
+
+ await expect(upsertInstance('bad', {
+ name: 'Bad',
+ site: 'https://api.datadoghq.com',
+ apiKey: 'k1',
+ appKey: 'k2'
+ })).rejects.toThrow('Invalid DataDog site hostname');
+ });
+
+ it('should accept valid site hostnames', async () => {
+ const result = await upsertInstance('valid', {
+ name: 'Valid',
+ site: 'api.us3.datadoghq.com',
+ apiKey: 'k1',
+ appKey: 'k2'
+ });
+ expect(result.site).toBe('api.us3.datadoghq.com');
+ });
+ });
+
+ describe('deleteInstance', () => {
+ it('should remove instance from config', async () => {
+ readJSONFile.mockResolvedValue({
+ instances: { 'test-dd': MOCK_INSTANCE }
+ });
+
+ await deleteInstance('test-dd');
+
+ const savedConfig = JSON.parse(writeFile.mock.calls[0][1]);
+ expect(savedConfig.instances['test-dd']).toBeUndefined();
+ });
+ });
+
+ describe('testConnection', () => {
+ it('should throw if instance not found', async () => {
+ await expect(testConnection('nonexistent')).rejects.toThrow('not found');
+ });
+
+ it('should return success on valid connection', async () => {
+ readJSONFile.mockResolvedValue({
+ instances: { 'test-dd': MOCK_INSTANCE }
+ });
+
+ const mockClient = { get: vi.fn().mockResolvedValue({}) };
+ axios.create.mockReturnValue(mockClient);
+
+ const result = await testConnection('test-dd');
+ expect(result).toEqual({ success: true });
+ expect(mockClient.get).toHaveBeenCalledWith('/api/v1/validate');
+ });
+
+ it('should return failure on connection error', async () => {
+ readJSONFile.mockResolvedValue({
+ instances: { 'test-dd': MOCK_INSTANCE }
+ });
+
+ const mockClient = {
+ get: vi.fn().mockRejectedValue({
+ response: { data: { errors: ['Invalid API key'] } },
+ message: 'Request failed'
+ })
+ };
+ axios.create.mockReturnValue(mockClient);
+
+ const result = await testConnection('test-dd');
+ expect(result).toEqual({ success: false, error: 'Invalid API key' });
+ });
+ });
+
+ describe('searchErrors', () => {
+ it('should throw if instance not found', async () => {
+ await expect(searchErrors('nonexistent', 'my-service')).rejects.toThrow('not found');
+ });
+
+ it('should quote service and environment in query', async () => {
+ readJSONFile.mockResolvedValue({
+ instances: { 'test-dd': MOCK_INSTANCE }
+ });
+
+ const mockClient = {
+ post: vi.fn().mockResolvedValue({ data: { data: [] } })
+ };
+ axios.create.mockReturnValue(mockClient);
+
+ await searchErrors('test-dd', 'my service', 'staging env');
+
+ const callArgs = mockClient.post.mock.calls[0];
+ expect(callArgs[0]).toBe('/api/v2/logs/events/search');
+ expect(callArgs[1].filter.query).toBe('status:error service:"my service" env:"staging env"');
+ });
+
+ it('should strip double quotes from service and environment to prevent injection', async () => {
+ readJSONFile.mockResolvedValue({
+ instances: { 'test-dd': MOCK_INSTANCE }
+ });
+
+ const mockClient = {
+ post: vi.fn().mockResolvedValue({ data: { data: [] } })
+ };
+ axios.create.mockReturnValue(mockClient);
+
+ await searchErrors('test-dd', 'my-service" status:warn', 'prod" OR env:dev');
+
+ const callArgs = mockClient.post.mock.calls[0];
+ expect(callArgs[1].filter.query).toBe('status:error service:"my-service status:warn" env:"prod OR env:dev"');
+ });
+ });
+});