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 composable Three.js prompt guidance (#4389)

[._.]/ Adam Eivy8bd0882a5c73
diff --git a/.changelog/next/added-issue-4389.md b/.changelog/next/added-issue-4389.md
new file mode 100644
index 0000000000..5418e9ad25
--- /dev/null
+++ b/.changelog/next/added-issue-4389.md
@@ -0,0 +1 @@
+- CoS agents now receive focused Three.js scene guidance alongside their task workflow.
diff --git a/data.reference/prompts/skills/threejs-visual.md b/data.reference/prompts/skills/threejs-visual.md
new file mode 100644
index 0000000000..2d7eaa62f1
--- /dev/null
+++ b/data.reference/prompts/skills/threejs-visual.md
@@ -0,0 +1,29 @@
+# Three.js Visual Work Skill Template
+
+## Routing
+**Use when**: The task explicitly names Three.js, React Three Fiber, R3F, or a WebGL scene.
+**Don't use when**: A task merely mentions WebGL availability, browser capabilities, or a non-scene graphics API.
+
+## Task-Specific Guidelines
+
+You are working on a visual scene or model surface. Build the clearest reliable result before adding effects.
+
+### 1. Inspect Before Choosing an API
+- Identify the installed renderer, framework version, and the existing component or scene ownership boundary.
+- Reuse the app's established scene, asset-loading, controls, and quality-control paths instead of introducing a second renderer or render loop.
+- Confirm whether the surface is declarative React Three Fiber, imperative Three.js, or an existing preview pipeline before changing lifecycle code.
+
+### 2. Establish Visual Evidence
+- Define the intended silhouette, readable geometry, material response, camera framing, and lighting before optional post-processing or image effects.
+- Prefer simple primitives and legible composition while validating the model; add texture, particles, bloom, or other polish only when they support the intended read.
+- Make the default camera view communicate the result without requiring hidden controls or an ideal viewport size.
+
+### 3. Preserve Render Ownership and Budget
+- Keep one owner for each render loop, canvas lifecycle, and output conversion path. Do not add competing animation loops, render targets, or image-export pipelines.
+- Measure or reason about scene cost using the existing render budget and preview-quality controls where they apply; keep mobile and reduced-quality paths functional.
+- Dispose or reuse renderer-owned resources according to the surrounding code's lifecycle pattern.
+
+### 4. Verify the Delivered Surface
+- Test the narrow scene behavior and its non-visual integration points.
+- Where the project has an existing visual-preview or render-budget check, use it and record the observable result (silhouette, framing, material, and performance behavior).
+- Keep fallbacks and existing non-WebGL behavior intact when the renderer is unavailable.
diff --git a/docs/features/agent-skills.md b/docs/features/agent-skills.md
index 62770f8ad7..861360fb09 100644
--- a/docs/features/agent-skills.md
+++ b/docs/features/agent-skills.md
@@ -10,11 +10,11 @@ Created specialized prompt templates per task category with routing, examples, a
- **Task-specific guidelines**: Security audit includes OWASP checklist; feature includes validation/convention requirements; refactor emphasizes behavior preservation
**Implementation:**
-- Added `data/prompts/skills/` directory with 6 task-type templates: `bug-fix.md`, `feature.md`, `security-audit.md`, `refactor.md`, `documentation.md`, `mobile-responsive.md`
-- Added `detectSkillTemplate()` and `loadSkillTemplate()` in `subAgentSpawner.js` with keyword-based matching (ordered by specificity -- security/mobile before generic bug-fix/feature)
-- Updated `buildAgentPrompt()` to inject matched skill template into both the Mustache template system and the fallback template
+- Added shipped `data.reference/prompts/skills/` templates: `bug-fix.md`, `feature.md`, `security-audit.md`, `refactor.md`, `documentation.md`, `mobile-responsive.md`, and `threejs-visual.md`
+- Added primary lifecycle routing plus an optional bounded domain guide in `agentPromptBuilder.js`; a Three.js, React Three Fiber, or WebGL scene task receives the visual guide after its lifecycle guidance, so a security task retains its security checklist
+- Updated `buildAgentPrompt()` to inject matched templates into both the Mustache template system and the fallback template
- Updated `cos-agent-briefing.md` with `{{#skillSection}}` conditional block
-- Templates only loaded when matched to avoid token inflation
+- Templates only load when matched to avoid token inflation; generic WebGL mentions do not trigger the scene guide
## P2: Agent Context Compaction
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index df395481b1..04a3b6bf2a 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -123,6 +123,21 @@ const SKILL_MATCHERS = [
}
];
+// Domain templates complement (rather than replace) the lifecycle template
+// selected above. Keep this list narrow: broad graphics terms would add prompt
+// weight to tasks that do not involve scene construction or rendering.
+const DOMAIN_SKILL_MATCHERS = [
+ {
+ skill: 'threejs-visual',
+ patterns: [
+ /\bthree(?:\.?js)\b/,
+ /\breact[-\s]?three[-\s]?fiber\b/,
+ /\br3f\b/,
+ /\bwebgl\s+scene\b/,
+ ],
+ },
+];
+
/**
* Detect the best matching skill template for a task based on description keywords.
* @param {Object} task - Task object with description
@@ -138,6 +153,32 @@ export function detectSkillTemplate(task) {
return null;
}
+/**
+ * Detect one optional domain template to append after the primary lifecycle
+ * template. Domain routing is deliberately independent so, for example, a
+ * Three.js security audit keeps its security guidance.
+ * @param {Object} task - Task object with description
+ * @returns {string|null} Domain skill template name or null
+ */
+export function detectDomainSkillTemplate(task) {
+ const desc = (task?.description || '').toLowerCase();
+ for (const matcher of DOMAIN_SKILL_MATCHERS) {
+ if (matcher.patterns.some((pattern) => pattern.test(desc))) {
+ return matcher.skill;
+ }
+ }
+ return null;
+}
+
+/**
+ * Resolve the primary lifecycle template and at most one domain guide.
+ * @param {Object} task - Task object with description
+ * @returns {string[]} Ordered template names
+ */
+export function detectSkillTemplates(task) {
+ return [detectSkillTemplate(task), detectDomainSkillTemplate(task)].filter(Boolean);
+}
+
/**
* Load a skill template from disk if it exists.
* @param {string} skillName - Name of the skill template file (without .md)
@@ -149,6 +190,23 @@ export async function loadSkillTemplate(skillName) {
return content;
}
+/**
+ * Load ordered templates as one prompt section, retaining the primary guidance
+ * even when an optional domain template is unavailable on an older install.
+ * @param {string[]} skillNames - Ordered skill template names
+ * @param {(skillName: string) => Promise<string|null>} loadTemplate - Loader seam for tests
+ * @returns {Promise<string|null>} Joined template content or null
+ */
+export async function loadSkillTemplates(skillNames, loadTemplate = loadSkillTemplate) {
+ const templates = await Promise.all(skillNames.map((skillName) => (
+ Promise.resolve(loadTemplate(skillName)).catch((err) => {
+ console.log(`⚠️ Skill template load failed for ${skillName}: ${err.message}`);
+ return null;
+ })
+ )));
+ return templates.filter(Boolean).join('\n\n') || null;
+}
+
// Nested-CLAUDE.md discovery bounds (#3866). On-demand nested memory files are a
// Claude Code feature — an API-provider agent reads nothing natively, so PortOS
// has to splice them in itself or a subtree rule (including a data-loss guard)
@@ -1744,14 +1802,9 @@ Include the ticket ID (${task.metadata.jiraTicketId}) in your commit messages, e
${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch branches.' : ''}
` : '';
- // Detect and load task-type-specific skill template (only when matched)
- const matchedSkill = detectSkillTemplate(task);
- const skillSection = matchedSkill
- ? await loadSkillTemplate(matchedSkill).catch(err => {
- console.log(`⚠️ Skill template load failed for ${matchedSkill}: ${err.message}`);
- return null;
- })
- : null;
+ // Keep the existing lifecycle template first, then append one narrow domain
+ // guide when the task explicitly concerns a supported visual stack.
+ const skillSection = await loadSkillTemplates(detectSkillTemplates(task));
// Build onboard tools section for agent awareness
const toolsSection = await getToolsSummaryForPrompt().catch(err => {
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 1956c659a8..c0a108bfe7 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -92,7 +92,7 @@ vi.mock('./codeReview.js', () => ({
getCodeReviewDefaults: vi.fn().mockResolvedValue({ reviewers: ['copilot'] }),
}));
-import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext, buildReviewLoopFollowUpSection, getAppWorkspace, getClaudeMdContext, UNATTENDED_RUN_RULE } from './agentPromptBuilder.js';
+import { buildLightContextPrompt, buildAgentPrompt, buildCompletionGuidelineBullet, reconcileSplitContext, buildReviewLoopFollowUpSection, getAppWorkspace, getClaudeMdContext, detectSkillTemplates, loadSkillTemplates, UNATTENDED_RUN_RULE } from './agentPromptBuilder.js';
import { getCodeReviewDefaults } from './codeReview.js'; // mocked above — control the configured default
import { isTruthyMeta } from './agentState.js';
import { buildPrompt } from './promptService.js'; // mocked above — inspect call args
@@ -109,6 +109,38 @@ function makeTask(overrides = {}) {
};
}
+describe('composable skill template routing', () => {
+ it('appends the Three.js guide after the primary feature template', () => {
+ expect(detectSkillTemplates(makeTask({
+ description: 'Implement a React Three Fiber product preview scene',
+ }))).toEqual(['feature', 'threejs-visual']);
+ });
+
+ it('does not route generic WebGL work through the scene guide', () => {
+ expect(detectSkillTemplates(makeTask({
+ description: 'Add WebGL capability reporting to the diagnostics panel',
+ }))).toEqual(['feature']);
+ });
+
+ it('keeps security guidance ahead of one visual domain guide on a collision', () => {
+ expect(detectSkillTemplates(makeTask({
+ description: 'Security audit the Three.js scene asset pipeline',
+ }))).toEqual(['security-audit', 'threejs-visual']);
+ });
+
+ it('joins templates in routing order and tolerates an unavailable domain guide', async () => {
+ const loadTemplate = vi.fn(async (name) => ({
+ 'security-audit': 'Security lifecycle guidance',
+ 'threejs-visual': null,
+ })[name]);
+
+ await expect(loadSkillTemplates(['security-audit', 'threejs-visual'], loadTemplate))
+ .resolves.toBe('Security lifecycle guidance');
+ expect(loadTemplate).toHaveBeenNthCalledWith(1, 'security-audit');
+ expect(loadTemplate).toHaveBeenNthCalledWith(2, 'threejs-visual');
+ });
+});
+
describe('reconcileSplitContext', () => {
it('folds context back into description when it is the queue-path split', () => {
const body = 'Line one is the title\n\nLine two is the body.';