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
feat(cos): add LLM gate system for autonomous jobs
Adam Eivy82a0e3fe3085
diff --git a/server/routes/cos.js b/server/routes/cos.jsindex 341c6a986f..79c4941204 100644--- a/server/routes/cos.js+++ b/server/routes/cos.js@@ -10,6 +10,7 @@ import * as taskLearning from '../services/taskLearning.js';import * as weeklyDigest from '../services/weeklyDigest.js';import * as taskSchedule from '../services/taskSchedule.js';import * as autonomousJobs from '../services/autonomousJobs.js';+import { checkJobGate, hasGate, getRegisteredGates } from '../services/jobGates.js';import * as taskTemplates from '../services/taskTemplates.js';import { enhanceTaskPrompt } from '../services/taskEnhancer.js';import * as productivity from '../services/productivity.js';@@ -813,7 +814,8 @@ router.get('/schedule/interval-types', (req, res) => {router.get('/jobs', asyncHandler(async (req, res) => {const jobs = await autonomousJobs.getAllJobs();const stats = await autonomousJobs.getJobStats();- res.json({ jobs, stats });+ const jobsWithGates = jobs.map(j => ({ ...j, hasGate: hasGate(j.id) }));+ res.json({ jobs: jobsWithGates, stats, registeredGates: getRegisteredGates() });}));// GET /api/cos/jobs/due - Get jobs that are due to run@@ -832,6 +834,24 @@ router.get('/jobs/allowed-commands', (req, res) => {res.json({ commands: autonomousJobs.getAllowedCommands() });});+// GET /api/cos/jobs/gates - Get all registered LLM gates+router.get('/jobs/gates', asyncHandler(async (req, res) => {+ const gateIds = getRegisteredGates();+ const results = await Promise.all(+ gateIds.map(async (id) => {+ const result = await checkJobGate(id);+ return { jobId: id, ...result };+ })+ );+ res.json({ gates: results });+}));++// POST /api/cos/jobs/:id/gate-check - Check a job's LLM gate without running+router.post('/jobs/:id/gate-check', asyncHandler(async (req, res) => {+ const result = await checkJobGate(req.params.id);+ res.json({ jobId: req.params.id, hasGate: hasGate(req.params.id), ...result });+}));+// GET /api/cos/jobs/:id - Get a single jobrouter.get('/jobs/:id', asyncHandler(async (req, res) => {const job = await autonomousJobs.getJob(req.params.id);diff --git a/server/services/cos.js b/server/services/cos.jsindex 5700873a1d..fab8028ecf 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -22,6 +22,7 @@ import { schedule as scheduleEvent, cancel as cancelEvent, getStats as getScheduimport { createMutex } from '../lib/asyncMutex.js';import { generateProactiveTasks as generateMissionTasks, getStats as getMissionStats } from './missions.js';import { generateTaskFromJob, recordJobExecution, isScriptJob, executeScriptJob, isShellJob, executeShellJob } from './autonomousJobs.js';+import { checkJobGate, hasGate } from './jobGates.js';import { formatDuration, safeJSONParse } from '../lib/fileUtils.js';import { sanitizeTaskMetadata } from '../lib/validation.js';import { addNotification, NOTIFICATION_TYPES } from './notifications.js';@@ -3741,6 +3742,17 @@ async function executeScheduledJob(jobId) {return;}+ // Run gate check — skip LLM if precondition not met+ const gateResult = await checkJobGate(jobId);+ if (!gateResult.shouldRun) {+ emitLog('debug', `Job ${job.name} gate skipped: ${gateResult.reason}`, { jobId, gate: gateResult });+ await registerSingleJobSchedule(jobId);+ return;+ }+ if (hasGate(jobId)) {+ emitLog('info', `Job ${job.name} gate passed: ${gateResult.reason}`, { jobId, gate: gateResult });+ }+// Mark as spawning before emitting task:ready to prevent racesaddSpawningJob(jobId);try {diff --git a/server/services/jobGates.js b/server/services/jobGates.jsnew file mode 100644index 0000000000..bd3d5a3ac4--- /dev/null+++ b/server/services/jobGates.js@@ -0,0 +1,90 @@+/**+ * Job Gates Service+ *+ * Provides precondition checks ("gates") for autonomous jobs that determine+ * whether an LLM agent actually needs to be spawned. When a gate returns+ * { shouldRun: false }, the job completes successfully without consuming+ * an agent slot or incurring LLM costs.+ *+ * Gate functions are pure async predicates registered by job ID. Each returns:+ * { shouldRun: boolean, reason: string, context?: object }+ *+ * To add a new gate, register it in the GATES object below.+ */++import { getInboxLogCounts } from './brainStorage.js';++/**+ * Brain Review gate: skip if there are no needs_review inbox items+ * and no active ideas to process.+ */+async function brainReviewGate() {+ const counts = await getInboxLogCounts();+ const needsReview = counts.needs_review || 0;+ const classifying = counts.classifying || 0;++ if (needsReview > 0) {+ return {+ shouldRun: true,+ reason: `${needsReview} inbox item(s) need review`,+ context: { needsReview, classifying }+ };+ }++ // If items are still classifying, wait for them to finish+ if (classifying > 0) {+ return {+ shouldRun: false,+ reason: `${classifying} item(s) still classifying, no items need review yet`,+ context: { needsReview, classifying }+ };+ }++ return {+ shouldRun: false,+ reason: 'No inbox items need review',+ context: { needsReview, classifying }+ };+}++/**+ * Registry of gate functions keyed by job ID.+ * Jobs without a gate entry always run (no precondition).+ */+const GATES = {+ 'job-brain-review': brainReviewGate+};++/**+ * Check whether a job should run by evaluating its gate function.+ * Jobs without a registered gate always pass (shouldRun: true).+ *+ * @param {string} jobId - The job ID to check+ * @returns {Promise<{shouldRun: boolean, reason: string, context?: object}>}+ */+export async function checkJobGate(jobId) {+ const gateFn = GATES[jobId];+ if (!gateFn) {+ return { shouldRun: true, reason: 'No gate configured' };+ }+ return gateFn();+}++/**+ * Check if a job has a gate registered.+ * @param {string} jobId+ * @returns {boolean}+ */+export function hasGate(jobId) {+ return jobId in GATES;+}++/**+ * Get all registered gate IDs (for introspection/UI).+ * @returns {string[]}+ */+export function getRegisteredGates() {+ return Object.keys(GATES);+}++// GATES is not exported to prevent external mutation — use checkJobGate/hasGate/getRegisteredGates insteaddiff --git a/server/services/jobGates.test.js b/server/services/jobGates.test.jsnew file mode 100644index 0000000000..90f4683cee--- /dev/null+++ b/server/services/jobGates.test.js@@ -0,0 +1,91 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./brainStorage.js', () => ({+ getInboxLogCounts: vi.fn()+}));++import { checkJobGate, hasGate, getRegisteredGates } from './jobGates.js';+import { getInboxLogCounts } from './brainStorage.js';++describe('jobGates', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('hasGate', () => {+ it('returns true for registered gate', () => {+ expect(hasGate('job-brain-review')).toBe(true);+ });++ it('returns false for unregistered job', () => {+ expect(hasGate('job-unknown')).toBe(false);+ });+ });++ describe('getRegisteredGates', () => {+ it('returns all registered gate IDs', () => {+ const gates = getRegisteredGates();+ expect(gates).toContain('job-brain-review');+ expect(Array.isArray(gates)).toBe(true);+ });+ });++ describe('checkJobGate', () => {+ it('returns shouldRun:true for jobs without a gate', async () => {+ const result = await checkJobGate('job-no-gate');+ expect(result.shouldRun).toBe(true);+ expect(result.reason).toBe('No gate configured');+ });++ describe('brain-review gate', () => {+ it('returns shouldRun:true when needs_review items exist', async () => {+ getInboxLogCounts.mockResolvedValue({+ total: 10,+ needs_review: 3,+ classifying: 0,+ filed: 7,+ corrected: 0,+ done: 0,+ error: 0+ });++ const result = await checkJobGate('job-brain-review');+ expect(result.shouldRun).toBe(true);+ expect(result.reason).toContain('3 inbox item(s) need review');+ expect(result.context.needsReview).toBe(3);+ });++ it('returns shouldRun:false when no needs_review items', async () => {+ getInboxLogCounts.mockResolvedValue({+ total: 5,+ needs_review: 0,+ classifying: 0,+ filed: 5,+ corrected: 0,+ done: 0,+ error: 0+ });++ const result = await checkJobGate('job-brain-review');+ expect(result.shouldRun).toBe(false);+ expect(result.reason).toBe('No inbox items need review');+ });++ it('returns shouldRun:false when items are still classifying', async () => {+ getInboxLogCounts.mockResolvedValue({+ total: 2,+ needs_review: 0,+ classifying: 2,+ filed: 0,+ corrected: 0,+ done: 0,+ error: 0+ });++ const result = await checkJobGate('job-brain-review');+ expect(result.shouldRun).toBe(false);+ expect(result.reason).toContain('2 item(s) still classifying');+ });+ });+ });+});