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(cos): add deterministic workflow skills for M40-P4

Adam Eivy69de8b507797
diff --git a/.changelog/v0.12.x.md b/.changelog/v0.12.x.md
index d29d839ac8..35e7b2fe31 100644
--- a/.changelog/v0.12.x.md
+++ b/.changelog/v0.12.x.md
@@ -445,7 +445,7 @@ This release adds branch management and automated release workflow capabilities
- **Task-type-specific prompt templates** ✅: New `data/prompts/skills/` directory with 6 specialized agent briefings per task category (bug-fix, feature, security-audit, refactor, documentation, mobile-responsive) — each with routing descriptions, embedded examples, and task-specific guidelines. `buildAgentPrompt()` now detects skill type via keyword matching and injects the matched template into the agent briefing. Templates only load when matched to avoid token inflation.
- **Agent context compaction** ✅: Context-limit and output-limit error patterns now include compaction metadata (output size, retry hints) that propagates through task retry metadata. When an agent retries after a context-limit failure, the briefing prompt includes a "Context Compaction Required" section with mandatory output constraints. Agent briefing template updated with task-type-specific output format constraints for documentation, refactors, security audits, and bug fixes.
- **Negative example routing** ✅: Anti-pattern recording in task learning — every task completion now records a `routingAccuracy` cross-reference (taskType × modelTier) with success/failure counts. `suggestModelTier()` enhanced to avoid tiers with <40% success and prefer proven-successful tiers. New "Routing Accuracy" section in Learning tab shows misroutes, tier overview cards, and a full task-type × tier matrix table. New `GET /api/cos/learning/routing` endpoint. Reset also cleans up routing data.
-- **Deterministic workflow skills**: Recurring autonomous jobs (daily briefing, git maintenance, security audit, app improvement) converted from inline prompts to versioned, editable skill templates with defined steps, outputs, and success criteria
+- **Deterministic workflow skills** ✅: Recurring autonomous jobs (daily briefing, git maintenance, brain processing, project review) converted from inline prompt strings to versioned skill templates in `data/prompts/skills/jobs/`. Each template defines structured sections (Steps, Expected Outputs, Success Criteria) that `generateTaskFromJob()` assembles into effective prompts. New API routes (`GET/PUT /api/prompts/skills/jobs/:name`, preview endpoint) and a "Job Skills" tab in the Prompt Manager UI for editing templates without touching code.
### CyberCity — Borough Layout Redesign
- **Borough neighborhoods**: Each app is now its own borough — a main skyscraper surrounded by smaller process buildings in a ring, creating distinct neighborhoods with organic spacing
diff --git a/PLAN.md b/PLAN.md
index 732bc4a8f8..a8f763fb18 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -146,11 +146,13 @@ Improve task-to-model routing accuracy by adding negative examples to the model
- ✅ Surface routing accuracy metrics in the Learning tab so the user can see misroutes
- ✅ Enhanced `suggestModelTier()` to use negative signal data for smarter tier avoidance
-### P4: Deterministic Workflow Skills
+### P4: Deterministic Workflow Skills ✅
For recurring autonomous jobs (daily briefing, git maintenance, security audit, app improvement), encode the full workflow as a deterministic skill:
-- Each skill defines exact steps, expected outputs, and success criteria
-- Prevents prompt drift across runs (currently the same autonomous job prompt can produce different quality results)
-- Skills are versioned and editable via the Prompt Manager UI
+- ✅ Each skill defines exact steps, expected outputs, and success criteria in `data/prompts/skills/jobs/`
+- ✅ Prevents prompt drift across runs — jobs now load structured skill templates instead of inline prompt strings
+- ✅ Skills are versioned and editable via the Prompt Manager UI (Job Skills tab)
+- ✅ `generateTaskFromJob()` builds effective prompts from skill template sections (Steps, Expected Outputs, Success Criteria)
+- ✅ API routes added: GET/PUT `/api/prompts/skills/jobs/:name`, preview via GET `/api/prompts/skills/jobs/:name/preview`
---
diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsx
index 03234d66b2..d02b7ba576 100644
--- a/client/src/pages/PromptManager.jsx
+++ b/client/src/pages/PromptManager.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
-import { FileText, Variable, RefreshCw, Save, Plus, Trash2, Eye } from 'lucide-react';
+import { FileText, Variable, RefreshCw, Save, Plus, Trash2, Eye, Briefcase } from 'lucide-react';
export default function PromptManager() {
const [tab, setTab] = useState('stages');
@@ -37,6 +37,13 @@ export default function PromptManager() {
template: ''
});
+ // Job skills
+ const [jobSkills, setJobSkills] = useState([]);
+ const [selectedJobSkill, setSelectedJobSkill] = useState(null);
+ const [jobSkillContent, setJobSkillContent] = useState('');
+ const [jobSkillMeta, setJobSkillMeta] = useState({});
+ const [jobSkillPreview, setJobSkillPreview] = useState('');
+
const [saving, setSaving] = useState(false);
useEffect(() => {
@@ -45,12 +52,14 @@ export default function PromptManager() {
const loadData = async () => {
setLoading(true);
- const [stagesRes, varsRes] = await Promise.all([
+ const [stagesRes, varsRes, jobSkillsRes] = await Promise.all([
fetch('/api/prompts').then(r => r.json()),
- fetch('/api/prompts/variables').then(r => r.json())
+ fetch('/api/prompts/variables').then(r => r.json()),
+ fetch('/api/prompts/skills/jobs').then(r => r.json()).catch(() => ({ skills: [] }))
]);
setStages(stagesRes.stages || {});
setVariables(varsRes.variables || {});
+ setJobSkills(jobSkillsRes.skills || []);
setLoading(false);
};
@@ -199,6 +208,30 @@ export default function PromptManager() {
}
};
+ // Job skill functions
+ const loadJobSkill = async (name) => {
+ setSelectedJobSkill(name);
+ setJobSkillPreview('');
+ const res = await fetch(`/api/prompts/skills/jobs/${name}`).then(r => r.json());
+ setJobSkillContent(res.content || '');
+ setJobSkillMeta({ jobName: res.jobName, jobId: res.jobId, category: res.category, interval: res.interval });
+ };
+
+ const saveJobSkill = async () => {
+ setSaving(true);
+ await fetch(`/api/prompts/skills/jobs/${selectedJobSkill}`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ content: jobSkillContent })
+ });
+ setSaving(false);
+ };
+
+ const previewJobSkill = async () => {
+ const res = await fetch(`/api/prompts/skills/jobs/${selectedJobSkill}/preview`).then(r => r.json());
+ setJobSkillPreview(res.preview || '');
+ };
+
if (loading) {
return <div className="flex items-center justify-center h-64 text-gray-500">Loading...</div>;
}
@@ -238,6 +271,14 @@ export default function PromptManager() {
>
<Variable size={16} /> Variables
</button>
+ <button
+ onClick={() => setTab('job-skills')}
+ className={`flex items-center gap-2 px-3 sm:px-4 py-2 rounded-lg transition-colors text-sm sm:text-base ${
+ tab === 'job-skills' ? 'bg-port-accent text-white' : 'bg-port-card text-gray-400 hover:text-white'
+ }`}
+ >
+ <Briefcase size={16} /> Job Skills
+ </button>
</div>
{/* Stages Tab */}
@@ -492,6 +533,107 @@ export default function PromptManager() {
</div>
)}
+ {/* Job Skills Tab */}
+ {tab === 'job-skills' && (
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
+ {/* Job Skill List */}
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <div className="mb-3">
+ <h3 className="text-sm font-medium text-gray-400">Autonomous Job Skills</h3>
+ <p className="text-xs text-gray-500 mt-1">Versioned prompt templates for recurring jobs</p>
+ </div>
+ <div className="space-y-1">
+ {jobSkills.map((skill) => (
+ <button
+ key={skill.name}
+ onClick={() => loadJobSkill(skill.name)}
+ className={`w-full text-left px-3 py-2 rounded-lg text-sm ${
+ selectedJobSkill === skill.name
+ ? 'bg-port-accent/20 text-port-accent'
+ : 'text-gray-300 hover:bg-port-border'
+ }`}
+ >
+ <div className="flex items-center gap-1">
+ <span className="font-medium">{skill.name}</span>
+ {skill.hasTemplate && (
+ <span className="flex-shrink-0 text-[10px] px-1.5 py-0.5 bg-port-success/20 text-port-success rounded uppercase font-semibold">
+ Active
+ </span>
+ )}
+ </div>
+ <div className="text-xs text-gray-500">{skill.jobId}</div>
+ </button>
+ ))}
+ {jobSkills.length === 0 && (
+ <div className="text-sm text-gray-500 px-3 py-2">No job skill templates found</div>
+ )}
+ </div>
+ </div>
+
+ {/* Job Skill Editor */}
+ <div className="lg:col-span-2 space-y-4">
+ {selectedJobSkill ? (
+ <>
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <div className="flex items-center justify-between mb-4">
+ <div>
+ <h3 className="text-lg font-medium text-white">{jobSkillMeta.jobName || selectedJobSkill}</h3>
+ <div className="flex gap-3 text-xs text-gray-500 mt-1">
+ {jobSkillMeta.category && <span>Category: {jobSkillMeta.category}</span>}
+ {jobSkillMeta.interval && <span>Interval: {jobSkillMeta.interval}</span>}
+ {jobSkillMeta.jobId && <span>ID: {jobSkillMeta.jobId}</span>}
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <button
+ onClick={previewJobSkill}
+ className="flex items-center gap-1 px-3 py-1 text-sm bg-port-border hover:bg-port-border/80 text-white rounded"
+ >
+ <Eye size={14} /> Preview
+ </button>
+ <button
+ onClick={saveJobSkill}
+ disabled={saving}
+ className="flex items-center gap-1 px-3 py-1 text-sm bg-port-accent hover:bg-port-accent/80 text-white rounded disabled:opacity-50"
+ >
+ <Save size={14} /> Save
+ </button>
+ </div>
+ </div>
+
+ <div>
+ <label className="block text-sm text-gray-400 mb-1">Skill Template (Markdown)</label>
+ <textarea
+ value={jobSkillContent}
+ onChange={(e) => setJobSkillContent(e.target.value)}
+ className="w-full h-96 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white font-mono text-sm focus:border-port-accent focus:outline-none"
+ />
+ <p className="text-xs text-gray-500 mt-1">
+ Sections: ## Prompt Template, ## Steps, ## Expected Outputs, ## Success Criteria
+ </p>
+ </div>
+ </div>
+
+ {/* Preview Panel */}
+ {jobSkillPreview && (
+ <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <h4 className="text-sm font-medium text-gray-400 mb-2">Effective Prompt Preview</h4>
+ <pre className="text-sm text-gray-300 whitespace-pre-wrap bg-port-bg p-3 rounded max-h-64 overflow-auto">
+ {jobSkillPreview}
+ </pre>
+ </div>
+ )}
+ </>
+ ) : (
+ <div className="bg-port-card border border-port-border rounded-xl p-12 text-center text-gray-500">
+ <p>Select a job skill to edit its prompt template</p>
+ <p className="text-xs mt-2">These templates define how recurring autonomous jobs execute</p>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
{/* Create Stage Modal */}
{creatingStage && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
diff --git a/server/routes/cos.js b/server/routes/cos.js
index ab35afd530..8aa6961346 100644
--- a/server/routes/cos.js
+++ b/server/routes/cos.js
@@ -769,7 +769,7 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {
// Generate task and add to CoS internal task queue
// Job execution is recorded via the job:spawned event when the agent actually starts
- const task = autonomousJobs.generateTaskFromJob(job);
+ const task = await autonomousJobs.generateTaskFromJob(job);
const result = await cos.addTask({
description: task.description,
priority: task.priority,
diff --git a/server/routes/prompts.js b/server/routes/prompts.js
index 2ae62e5278..43aaca2d93 100644
--- a/server/routes/prompts.js
+++ b/server/routes/prompts.js
@@ -1,5 +1,13 @@
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import {
+ listJobSkillTemplates,
+ loadJobSkillTemplate,
+ saveJobSkillTemplate,
+ getJobEffectivePrompt,
+ getJob,
+ JOB_SKILL_MAP
+} from '../services/autonomousJobs.js';
/**
* Create PortOS-specific prompts routes
@@ -53,6 +61,61 @@ export function createPortOSPromptsRoutes(aiToolkit) {
res.json({ success: true });
}));
+ // === Job Skill Templates (must be before /:stage wildcard) ===
+
+ // GET /api/prompts/skills/jobs - List all job skill templates
+ router.get('/skills/jobs', asyncHandler(async (req, res) => {
+ const skills = await listJobSkillTemplates();
+ res.json({ skills });
+ }));
+
+ // GET /api/prompts/skills/jobs/:name - Get a job skill template
+ router.get('/skills/jobs/:name', asyncHandler(async (req, res) => {
+ const content = await loadJobSkillTemplate(req.params.name);
+ if (!content) {
+ throw new ServerError('Job skill template not found', { status: 404, code: 'NOT_FOUND' });
+ }
+
+ // Find associated job ID
+ const jobId = Object.entries(JOB_SKILL_MAP).find(([, name]) => name === req.params.name)?.[0];
+ const job = jobId ? await getJob(jobId) : null;
+
+ res.json({
+ name: req.params.name,
+ jobId,
+ content,
+ jobName: job?.name || null,
+ category: job?.category || null,
+ interval: job?.interval || null
+ });
+ }));
+
+ // PUT /api/prompts/skills/jobs/:name - Update a job skill template
+ router.put('/skills/jobs/:name', asyncHandler(async (req, res) => {
+ const { content } = req.body;
+ if (!content) {
+ throw new ServerError('content is required', { status: 400, code: 'VALIDATION_ERROR' });
+ }
+ await saveJobSkillTemplate(req.params.name, content);
+ res.json({ success: true });
+ }));
+
+ // GET /api/prompts/skills/jobs/:name/preview - Preview the effective prompt from a job skill
+ router.get('/skills/jobs/:name/preview', asyncHandler(async (req, res) => {
+ const jobId = Object.entries(JOB_SKILL_MAP).find(([, name]) => name === req.params.name)?.[0];
+ if (!jobId) {
+ throw new ServerError('No job associated with this skill', { status: 404, code: 'NOT_FOUND' });
+ }
+ const job = await getJob(jobId);
+ if (!job) {
+ throw new ServerError('Associated job not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ const prompt = await getJobEffectivePrompt(job);
+ res.json({ preview: prompt });
+ }));
+
+ // === Stage Routes (wildcard - must be after specific paths) ===
+
// GET /api/prompts/:stage - Get stage with template
router.get('/:stage', asyncHandler(async (req, res) => {
const stage = promptsService.getStage(req.params.stage);
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index aec57d824a..cafaba4e34 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -14,14 +14,28 @@
* - Custom user-defined jobs
*/
-import { writeFile } from 'fs/promises'
-import { join } from 'path'
+import { writeFile, readFile } from 'fs/promises'
+import { join, dirname } from 'path'
+import { fileURLToPath } from 'url'
import { v4 as uuidv4 } from 'uuid'
import { cosEvents } from './cosEvents.js'
import { ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js'
+const __filename = fileURLToPath(import.meta.url)
+const __dirname = dirname(__filename)
const DATA_DIR = PATHS.cos
const JOBS_FILE = join(DATA_DIR, 'autonomous-jobs.json')
+const JOBS_SKILLS_DIR = join(__dirname, '../../data/prompts/skills/jobs')
+
+/**
+ * Map job IDs to their skill template filenames
+ */
+const JOB_SKILL_MAP = {
+ 'job-daily-briefing': 'daily-briefing',
+ 'job-git-maintenance': 'git-maintenance',
+ 'job-brain-processing': 'brain-processing',
+ 'job-project-review': 'project-review'
+}
// Time constants
const HOUR = 60 * 60 * 1000
@@ -408,15 +422,105 @@ async function toggleJob(jobId) {
return job
}
+/**
+ * Load a job skill template from disk
+ * @param {string} skillName - The skill template name (e.g., 'daily-briefing')
+ * @returns {Promise<string|null>} Template content or null if not found
+ */
+async function loadJobSkillTemplate(skillName) {
+ const filePath = join(JOBS_SKILLS_DIR, `${skillName}.md`)
+ const content = await readFile(filePath, 'utf-8').catch(() => null)
+ if (content) {
+ console.log(`🎯 Loaded job skill template: ${skillName}`)
+ }
+ return content
+}
+
+/**
+ * Save a job skill template to disk
+ * @param {string} skillName - The skill template name
+ * @param {string} content - The template content
+ */
+async function saveJobSkillTemplate(skillName, content) {
+ await ensureDir(JOBS_SKILLS_DIR)
+ const filePath = join(JOBS_SKILLS_DIR, `${skillName}.md`)
+ await writeFile(filePath, content)
+ console.log(`💾 Saved job skill template: ${skillName}`)
+}
+
+/**
+ * List all job skill templates
+ * @returns {Promise<Array>} Array of { name, jobId, hasTemplate }
+ */
+async function listJobSkillTemplates() {
+ const results = []
+ for (const [jobId, skillName] of Object.entries(JOB_SKILL_MAP)) {
+ const content = await loadJobSkillTemplate(skillName)
+ results.push({
+ name: skillName,
+ jobId,
+ hasTemplate: !!content
+ })
+ }
+ return results
+}
+
+/**
+ * Get the effective prompt for a job, using skill template if available
+ * Extracts the prompt from the skill template's structured format
+ * @param {Object} job - The job object
+ * @returns {Promise<string>} The effective prompt template
+ */
+async function getJobEffectivePrompt(job) {
+ const skillName = JOB_SKILL_MAP[job.id]
+ if (!skillName) return job.promptTemplate
+
+ const template = await loadJobSkillTemplate(skillName)
+ if (!template) return job.promptTemplate
+
+ // Extract structured sections from the skill template and build a prompt
+ // The skill template has: Prompt Template header, Steps, Expected Outputs, Success Criteria
+ const lines = template.split('\n')
+ const sections = { prompt: '', steps: '', expectedOutputs: '', successCriteria: '' }
+ let currentSection = null
+
+ for (const line of lines) {
+ if (line.startsWith('## Prompt Template')) { currentSection = 'prompt'; continue }
+ if (line.startsWith('## Steps')) { currentSection = 'steps'; continue }
+ if (line.startsWith('## Expected Outputs')) { currentSection = 'expectedOutputs'; continue }
+ if (line.startsWith('## Success Criteria')) { currentSection = 'successCriteria'; continue }
+ if (line.startsWith('## Job Metadata')) { currentSection = 'metadata'; continue }
+ if (line.startsWith('# ')) { currentSection = null; continue }
+ if (currentSection && currentSection !== 'metadata') {
+ sections[currentSection] += line + '\n'
+ }
+ }
+
+ // Build the effective prompt from structured sections
+ let prompt = sections.prompt.trim()
+ if (sections.steps.trim()) {
+ prompt += '\n\nTasks to perform:\n' + sections.steps.trim()
+ }
+ if (sections.expectedOutputs.trim()) {
+ prompt += '\n\nExpected outputs:\n' + sections.expectedOutputs.trim()
+ }
+ if (sections.successCriteria.trim()) {
+ prompt += '\n\nSuccess criteria:\n' + sections.successCriteria.trim()
+ }
+
+ return prompt
+}
+
/**
* Generate a CoS task from a due job
* @param {Object} job - The job to generate a task for
- * @returns {Object} Task data suitable for cos.addTask()
+ * @returns {Promise<Object>} Task data suitable for cos.addTask()
*/
-function generateTaskFromJob(job) {
+async function generateTaskFromJob(job) {
+ const description = await getJobEffectivePrompt(job)
return {
id: `${job.id}-${Date.now().toString(36)}`,
- description: job.promptTemplate,
+ description,
priority: job.priority,
metadata: {
autonomousJob: true,
@@ -522,5 +626,10 @@ export {
generateTaskFromJob,
getJobStats,
getNextDueJob,
- INTERVAL_OPTIONS
+ INTERVAL_OPTIONS,
+ loadJobSkillTemplate,
+ saveJobSkillTemplate,
+ listJobSkillTemplates,
+ getJobEffectivePrompt,
+ JOB_SKILL_MAP
}
diff --git a/server/services/autonomousJobs.test.js b/server/services/autonomousJobs.test.js
index 30d01c2cab..8419c7f071 100644
--- a/server/services/autonomousJobs.test.js
+++ b/server/services/autonomousJobs.test.js
@@ -123,12 +123,11 @@ describe('autonomousJobs', () => {
})
describe('generateTaskFromJob', () => {
- it('returns correct task structure with metadata', () => {
+ it('returns correct task structure with metadata', async () => {
const job = mockJobsData.jobs[0]
- const task = generateTaskFromJob(job)
+ const task = await generateTaskFromJob(job)
expect(task).toMatchObject({
- description: job.promptTemplate,
priority: job.priority,
metadata: {
autonomousJob: true,
@@ -141,15 +140,16 @@ describe('autonomousJobs', () => {
autoApprove: false
})
expect(task.id).toContain(job.id)
+ expect(task.description).toBeTruthy()
})
- it('autoApprove true when autonomyLevel is yolo', () => {
+ it('autoApprove true when autonomyLevel is yolo', async () => {
const yoloJob = {
...mockJobsData.jobs[0],
autonomyLevel: 'yolo'
}
- const task = generateTaskFromJob(yoloJob)
+ const task = await generateTaskFromJob(yoloJob)
expect(task.autoApprove).toBe(true)
expect(task.metadata.autonomyLevel).toBe('yolo')
diff --git a/server/services/cos.js b/server/services/cos.js
index 41331334e7..56472994d2 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -670,7 +670,7 @@ export async function evaluateTasks() {
for (const job of dueJobs) {
if (tasksToSpawn.length >= availableSlots) break;
- const task = generateTaskFromJob(job);
+ const task = await generateTaskFromJob(job);
tasksToSpawn.push(task);
emitLog('info', `Autonomous job due: ${job.name} (${job.reason})`, {
jobId: job.id,