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
refactor: serve the prompt system-stage list from the API (#3314)
[._.]/ Adam Eivy591782ff4b4d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c7cb9baa66..2b868feb37 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -13,6 +13,7 @@## Prompt Manager- **[issue-3284] The prompt stage list is now searchable, grouped, and safe to scroll past.** Settings → Prompts listed all 127 stages as one flat column with no search box, so finding "Creative Director — Treatment" meant scrolling a page seven screens tall and reading two-line descriptions to tell near-identical names apart — and every row carried a bare trash icon right beside its own click target, so a mis-tap while hunting offered to delete a stage instead of opening it. There is now a search box pinned above the list that filters on title, description, and stage id as you type, a SYSTEM-only toggle, and collapsible groups (Pipeline, Writers Room, Creative Director, Brain, CoS, …) built from the naming convention the stages already followed. Delete has moved off the row and into the selected stage's editor pane.+- **[issue-3314] The SYSTEM badge and "System only" filter now come from the server instead of a client-side copy that had already drifted.** The list of stages PortOS features call by name was written out three separate times — twice in the prompts API and once in the client — and the client copy was purely advisory, so a key missing from it made that stage unreachable through the new "System only" filter even though the server would still refuse to delete it. `GET /api/prompts` now ships the list alongside the stages and the client renders exactly what it is told. The drift this uncovered is fixed too: `cos-task-enhance` was badged as a system stage but had no prompt entry at all, so CoS task enhancement quietly ignored the Prompt Manager and used a hardcoded prompt with the active provider's default model — it now ships a real, editable stage (seeded into existing installs) whose model tier is honoured.## Documentationdiff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 936603df47..4479c65376 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -148,7 +148,7 @@ grep -i "what you want to do" client/src/lib/README.md| `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. || `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. || `powersBreakdown.js` | Pure, DOM-free Powers mental-math lessons — maps supported base/exponent pairs to named techniques and deterministic worked steps for drill misses and historical review. |-| `promptStageGroups.js` | Search + grouping for the Prompt Manager's Stages pane (#3284). `buildStageGroups(stages, { query, systemOnly })` → `{ groups, matchCount, totalCount }`, filtering the `{ key: config }` stage map on title + description + key (AND-token, reusing `mediaSearch.js`'s `tokenizeQuery`/`matchHaystack`) and bucketing survivors into ordered `[{ key, label, stages: [[key, config], …] }]` groups (`Other` pinned last). `stageGroupLabel(name)` derives the family from the `Family — Specific` dash convention (em dash, en dash, or a spaced ASCII hyphen — a user typing their own stage name reaches for the last), falling back to the `STAGE_WORD_PREFIXES` word list (`CoS Agent Briefing`) and then `Other`; `stageGroupKey(label)` case-folds it into the group's identity, so `Pipeline — X` and `pipeline — y` are one group rather than twin headers that render alike under `uppercase`; `stageGroupLabelFor(key, config)` / `stageGroupKeyFor(key, config)` are the name-or-key forms both the bucketing and the page's auto-expand call, so a deep-linked stage opens the group it actually renders in. `stageHaystack(key, config)`, `isSystemStage(key)` / `SYSTEM_STAGE_KEYS` (cosmetic mirror of the server's `systemStages` table — deletion is guarded server-side). Pure — no React, no I/O. |+| `promptStageGroups.js` | Search + grouping for the Prompt Manager's Stages pane (#3284). `buildStageGroups(stages, { query, systemOnly, systemStageKeys })` → `{ groups, matchCount, totalCount }`, filtering the `{ key: config }` stage map on title + description + key (AND-token, reusing `mediaSearch.js`'s `tokenizeQuery`/`matchHaystack`) and bucketing survivors into ordered `[{ key, label, stages: [[key, config], …] }]` groups (`Other` pinned last). `stageGroupLabel(name)` derives the family from the `Family — Specific` dash convention (em dash, en dash, or a spaced ASCII hyphen — a user typing their own stage name reaches for the last), falling back to the `STAGE_WORD_PREFIXES` word list (`CoS Agent Briefing`) and then `Other`; `stageGroupKey(label)` case-folds it into the group's identity, so `Pipeline — X` and `pipeline — y` are one group rather than twin headers that render alike under `uppercase`; `stageGroupLabelFor(key, config)` / `stageGroupKeyFor(key, config)` are the name-or-key forms both the bucketing and the page's auto-expand call, so a deep-linked stage opens the group it actually renders in. `stageHaystack(key, config)` is the searchable string. The system-stage list is NOT mirrored here — `GET /api/prompts` ships it as `systemStages` from `server/lib/promptSystemStages.js` and the page threads it in as `systemStageKeys` (#3314). Pure — no React, no I/O. || `spriteCollectionActions.js` | Gating for the Sprite Manager asset collection's inline actions (#2931). `buildCollectionActions({ detail, walkPending, referencePending, generateWalk, generateAnchor, onRequestTrim })` → `{ regenerateFor(asset), trimFor(asset) }`, each returning `null` for an asset it can't act on. Regenerate mirrors the authoritative workflow surfaces exactly — a walk direction is regenerable only when its anchor is locked, the direction isn't approved, the walk set isn't finalized and no render is in flight; a reference anchor only while it's an unlocked candidate (`south`/main is excluded, since it needs a design prompt or upload). Trim is offered only for a run that actually packed a strip (the trim endpoint 409s otherwise). Each actionable regenerate also names the `correctionKey` (#3134) the card binds its inline correction note to — `walk:<dir>` for a walk output, the bare direction for an anchor — so the card can never write a still-image note into a video re-roll. Pure — takes callbacks, performs no I/O. Consumes the facets from `spriteFacets.js` and the key vocabulary from `spriteCorrections.js`. || `spriteCorrections.js` | The Sprite Manager's correction-note key vocabulary + request fragment (#2964, extended to every regeneration surface by #3134). Every re-roll surface writes into ONE page-owned `corrections` map (`Sprites.jsx`); this module owns its keys so the pure gating layer (`spriteCollectionActions.js`) and the React surfaces (`CorrectionNote.jsx` + hosts) agree without the pure layer importing a component. Keys are namespaced per SURFACE, not per direction — `anchorCorrectionKey(dir)` keeps the bare direction (pre-#3134 state untouched) while `walkCorrectionKey(dir)` / `MAIN_CORRECTION_KEY` / `AMBIENT_REFERENCE_CORRECTION_KEY` prefix, so a still-image anchor note can never ride a walk-VIDEO re-roll. `trackCorrectionKey(trackId, dir)` (#3136) replaces the per-track keys the scanner/ambient surfaces each spelled by hand, so a user-defined animation track gets a namespaced key with nothing to add here. `correctionPromptPayload(corrections, key)` → `{ correctionPrompt }` only when the note is non-empty after trimming, else `{}` — the guarantee that a blank note leaves the server prompt byte-identical to a blind regenerate. Pure — no React, no I/O. || `spriteFacets.js` | Client-side facet classifier for the Sprite Manager's asset collection (#2931), mirroring the source pipeline's `classify_asset()`. `classifySpriteAsset(path)` decodes a record-relative asset path into `{ family, status, role, direction, runId }` — `status ∈ runtime/approved/candidate/superseded/rejected/source`, `role ∈ reference/strip/animation/frame/atlas/evidence/sprite/manifest` — and is total (an unknown path degrades to `sprite`/`source` rather than throwing). `classifySpriteAssets(assets)` adds the one facet only knowable across a listing: an approved asset below the highest `-vN` of its stem becomes `superseded`. `groupSpriteAssetsByRole(assets)` returns render-ready `{ role, label, assets }` sections in `SPRITE_ASSET_ROLES` order — it does NOT render a `manifest` group: each runtime atlas's sidecar manifest is folded onto its atlas row as `row.manifest`, and other behind-the-scenes JSON is omitted. `runtimeVersionDir(path)` / `isRuntimeVersionPath(path)` / `isRuntimeSidecarManifest(path)` expose the `runtime/vN` grammar (the sidecar-pairing key and the "is this a build manifest" predicate) so callers like `AssetInspector` reuse one definition instead of re-regexing. Also exports `SPRITE_DIRECTIONS` (mirror of `server/services/sprites/prompts.js`) — the `direction`/`runId` facets are what drive the collection's Regenerate and Edit-in-Loop-Trimmer actions. Pure — no React, no I/O. |diff --git a/client/src/lib/promptStageGroups.js b/client/src/lib/promptStageGroups.jsindex 23e9932795..39336411f5 100644--- a/client/src/lib/promptStageGroups.js+++ b/client/src/lib/promptStageGroups.js@@ -16,22 +16,6 @@import { tokenizeQuery, matchHaystack } from './mediaSearch.js';-// Stages PortOS features call by name. Mirror of the `systemStages` table in-// `server/routes/prompts.js` — the server is authoritative for *deletion*-// (it force-guards on its own copy); this copy only drives the SYSTEM badge and-// the SYSTEM-only filter, so a drift here is cosmetic, never destructive.-export const SYSTEM_STAGE_KEYS = [- 'cos-agent-briefing', 'cos-evaluate', 'cos-report-summary', 'cos-self-improvement',- 'cos-task-enhance', 'brain-classifier', 'brain-daily-digest', 'brain-weekly-review',- 'memory-evaluate', 'app-detection',-];--const SYSTEM_STAGE_SET = new Set(SYSTEM_STAGE_KEYS);--export function isSystemStage(key) {- return SYSTEM_STAGE_SET.has(key);-}-// Bucket for names that carry neither a dash prefix nor a known leading word.export const OTHER_GROUP_LABEL = 'Other';@@ -123,15 +107,21 @@ export function stageHaystack(key, config) {* identity to store open/closed state under, `label` the first spelling seen.* Groups sort alphabetically with `Other` pinned last, stages by display name.*+ * `systemStageKeys` is the `systemStages` list `GET /api/prompts` ships — the+ * server's own table (`server/lib/promptSystemStages.js`), not a client mirror,+ * so the "System only" filter can never disagree with the stages the server+ * actually protects from deletion (#3314).+ ** An empty query and `systemOnly: false` return everything, so the same call* drives both the unfiltered and the filtered render.*/-export function buildStageGroups(stages, { query = '', systemOnly = false } = {}) {+export function buildStageGroups(stages, { query = '', systemOnly = false, systemStageKeys = [] } = {}) {const entries = Object.entries(stages || {});const tokens = tokenizeQuery(query);+ const systemSet = new Set(systemStageKeys);const matched = entries.filter(([key, config]) => {- if (systemOnly && !isSystemStage(key)) return false;+ if (systemOnly && !systemSet.has(key)) return false;if (tokens.length === 0) return true;return matchHaystack(stageHaystack(key, config), tokens);});diff --git a/client/src/lib/promptStageGroups.test.js b/client/src/lib/promptStageGroups.test.jsindex f5c2c62c00..086281e3d9 100644--- a/client/src/lib/promptStageGroups.test.js+++ b/client/src/lib/promptStageGroups.test.js@@ -8,8 +8,6 @@ import {stageGroupLabelFor,stageGroupKeyFor,stageHaystack,- isSystemStage,- SYSTEM_STAGE_KEYS,OTHER_GROUP_LABEL,} from './promptStageGroups.js';@@ -62,16 +60,6 @@ describe('stageGroupLabel', () => {});});-describe('isSystemStage', () => {- it('recognizes the mirrored server list', () => {- for (const key of SYSTEM_STAGE_KEYS) expect(isSystemStage(key)).toBe(true);- });- it('is false for user stages', () => {- expect(isSystemStage('pipeline-prose-draft')).toBe(false);- expect(isSystemStage(undefined)).toBe(false);- });-});-describe('stageHaystack', () => {it('covers title, description and key, lowercased', () => {const h = stageHaystack('brain-daily-digest', stage('Brain Daily Digest', 'Summarize the day'));@@ -145,17 +133,31 @@ describe('buildStageGroups', () => {expect(buildStageGroups(stages, { query: ' ' }).matchCount).toBe(6);});+ // The list the server ships as `systemStages` on GET /api/prompts.+ const systemStageKeys = ['cos-evaluate', 'brain-classifier'];+it('narrows to system stages when systemOnly is set', () => {- const { groups, matchCount, totalCount } = buildStageGroups(stages, { systemOnly: true });+ const { groups, matchCount, totalCount } = buildStageGroups(stages, { systemOnly: true, systemStageKeys });expect(totalCount).toBe(6);expect(matchCount).toBe(2);expect(groups.flatMap(g => g.stages.map(([k]) => k)).sort()).toEqual(['brain-classifier', 'cos-evaluate']);});it('composes systemOnly with a query', () => {- const { matchCount } = buildStageGroups(stages, { query: 'classify', systemOnly: true });+ const { matchCount } = buildStageGroups(stages, { query: 'classify', systemOnly: true, systemStageKeys });expect(matchCount).toBe(1);- expect(buildStageGroups(stages, { query: 'prose', systemOnly: true }).matchCount).toBe(0);+ expect(buildStageGroups(stages, { query: 'prose', systemOnly: true, systemStageKeys }).matchCount).toBe(0);+ });++ // A server that predates the `systemStages` key (or a failed load) leaves the+ // list empty — System-only must then read as "nothing known", never throw.+ it('matches nothing under systemOnly when no keys were served', () => {+ expect(buildStageGroups(stages, { systemOnly: true }).matchCount).toBe(0);+ expect(buildStageGroups(stages, { systemOnly: true, systemStageKeys: [] }).groups).toEqual([]);+ });++ it('ignores systemStageKeys when systemOnly is off', () => {+ expect(buildStageGroups(stages, { systemStageKeys }).matchCount).toBe(6);});it('returns no groups but a real total when nothing matches', () => {diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsxindex 2aa2dbc505..d6f6a5846a 100644--- a/client/src/pages/PromptManager.jsx+++ b/client/src/pages/PromptManager.jsx@@ -23,9 +23,7 @@ import {} from '../services/apiPrompts';import { getProviders } from '../services/apiProviders';import Pill from '../components/ui/Pill';-// Aliased: `confirmDeleteStage` destructures an `isSystemStage` field off the-// pending-delete record, which would otherwise shadow this import.-import { buildStageGroups, stageGroupKeyFor, isSystemStage as isSystemStageKey } from '../lib/promptStageGroups';+import { buildStageGroups, stageGroupKeyFor } from '../lib/promptStageGroups';const VALID_PROMPT_TABS = ['stages', 'variables', 'job-skills'];@@ -54,6 +52,11 @@ export default function PromptManager() {const setSelectedStage = (name) => setParam('stage', name);const setSelectedVar = (key) => setParam('var', key);const [stages, setStages] = useState({});+ // Which stage keys PortOS features call by name. Served by GET /api/prompts+ // (`server/lib/promptSystemStages.js`) rather than mirrored client-side, so+ // the SYSTEM badge and the "System only" filter can never disagree with the+ // stages the server actually force-guards on delete (#3314).+ const [systemStageKeys, setSystemStageKeys] = useState([]);const [variables, setVariables] = useState({});const [loading, setLoading] = useState(true);@@ -109,12 +112,16 @@ export default function PromptManager() {const loadData = async () => {setLoading(true);const [stagesRes, varsRes, jobSkillsRes, providersRes] = await Promise.all([- getPrompts({ silent: true }).catch(() => ({ stages: {} })),+ getPrompts({ silent: true }).catch(() => ({ stages: {}, systemStages: [] })),getPromptVariables({ silent: true }).catch(() => ({ variables: {} })),getJobSkills({ silent: true }).catch(() => ({ skills: [] })),getProviders({ silent: true }).catch(() => ({ providers: [] }))]);setStages(stagesRes.stages || {});+ // `Array.isArray` rather than `|| []`: an older server that predates the+ // `systemStages` key sends nothing, which must read as "no system stages+ // known" (no badges, empty System-only filter) — never as a crash.+ setSystemStageKeys(Array.isArray(stagesRes.systemStages) ? stagesRes.systemStages : []);setVariables(varsRes.variables || {});setJobSkills(jobSkillsRes.skills || []);setProviders((providersRes.providers || []).filter(p => p.enabled));@@ -295,9 +302,12 @@ export default function PromptManager() {const stageFilterActive = stageQuery.trim() !== '' || systemOnly;const { groups: stageGroups, matchCount: stageMatchCount, totalCount: stageTotalCount } = useMemo(- () => buildStageGroups(stages, { query: stageQuery, systemOnly }),- [stages, stageQuery, systemOnly],+ () => buildStageGroups(stages, { query: stageQuery, systemOnly, systemStageKeys }),+ [stages, stageQuery, systemOnly, systemStageKeys],);+ // Badge lookup for the row render — a Set so the O(n) list render doesn't+ // re-scan the key array per row.+ const systemStageSet = useMemo(() => new Set(systemStageKeys), [systemStageKeys]);// The group holding the open stage expands itself so a deep link / reload// lands with its row visible. Seeding STATE (rather than forcing it open at@@ -490,7 +500,7 @@ export default function PromptManager() {><div className="flex items-center gap-1"><span className="font-medium truncate">{config.name || name}</span>- {isSystemStageKey(name) && (+ {systemStageSet.has(name) && (<Pill tone="bare" size="xs" bordered={false} className="shrink-0 bg-port-accent/20 text-port-accent uppercase font-semibold">System</Pill>diff --git a/client/src/pages/PromptManager.test.jsx b/client/src/pages/PromptManager.test.jsxindex 19e7dc31dd..d21e49fe81 100644--- a/client/src/pages/PromptManager.test.jsx+++ b/client/src/pages/PromptManager.test.jsx@@ -43,6 +43,10 @@ const STAGES = {'brain-classifier': { name: 'Brain Classifier', description: 'Classify a thought' },};+// The system-stage list is served, not mirrored client-side (#3314) — the page+// badges and filters exactly what GET /api/prompts names in `systemStages`.+const SYSTEM_STAGES = ['brain-classifier'];+const renderPage = (entry = '/prompts') => render(<MemoryRouter initialEntries={[entry]}><PromptManager />@@ -54,7 +58,7 @@ const groupHeader = (label) => screen.getByRole('button', { name: new RegExp(`^$describe('PromptManager stage list', () => {beforeEach(() => {- getPrompts.mockReset().mockResolvedValue({ stages: STAGES });+ getPrompts.mockReset().mockResolvedValue({ stages: STAGES, systemStages: SYSTEM_STAGES });getPrompt.mockReset().mockResolvedValue({ name: 'Pipeline — Prose Draft', template: 'body', variables: [] });getPromptUsage.mockReset().mockResolvedValue({ isSystemStage: false, usedBy: [] });});@@ -165,6 +169,7 @@ describe('PromptManager stage list', () => {...STAGES,'pipeline-lowercase': { name: 'pipeline — hand typed', description: 'user made' },},+ systemStages: SYSTEM_STAGES,});renderPage();await screen.findByText('Prompt Stages');@@ -220,6 +225,33 @@ describe('PromptManager stage list', () => {expect(screen.getByText('1 of 4')).toBeTruthy();});+ // The badge and the filter follow the SERVED list, not a client-side copy of+ // it (#3314) — a stage the server names is reachable even though no hardcoded+ // client array ever mentioned it.+ it('badges and filters whatever the server names in systemStages', async () => {+ getPrompts.mockResolvedValue({ stages: STAGES, systemStages: ['creative-director-treatment'] });+ renderPage();+ await screen.findByText('Prompt Stages');++ fireEvent.click(screen.getByRole('button', { name: /system only/i }));+ expect(screen.getByText('Creative Director — Treatment')).toBeTruthy();+ expect(screen.queryByText('Brain Classifier')).toBeNull();+ expect(screen.getByText('1 of 4')).toBeTruthy();+ expect(screen.getAllByText('System')).toHaveLength(1);+ });++ // An older server (or a failed load) sends no list: badge nothing, filter to+ // nothing — never crash on a missing key.+ it('degrades to no system stages when the server omits the list', async () => {+ getPrompts.mockResolvedValue({ stages: STAGES });+ renderPage();+ await screen.findByText('Prompt Stages');++ fireEvent.click(screen.getByRole('button', { name: /system only/i }));+ expect(screen.getByText('No stages match that search')).toBeTruthy();+ expect(screen.getByText('0 of 4')).toBeTruthy();+ });+it('selects a stage into the URL from a filtered row', async () => {renderPage();await screen.findByText('Prompt Stages');@@ -243,7 +275,7 @@ describe('PromptManager stage list', () => {describe('PromptManager delete demotion', () => {beforeEach(() => {- getPrompts.mockReset().mockResolvedValue({ stages: STAGES });+ getPrompts.mockReset().mockResolvedValue({ stages: STAGES, systemStages: SYSTEM_STAGES });getPrompt.mockReset().mockResolvedValue({ name: 'Brain Classifier', template: 'body', variables: [] });getPromptUsage.mockReset().mockResolvedValue({ isSystemStage: true, usedBy: ['Brain thought classification'] });});diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex ea9ba5b022..4f033e1a70 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -145,6 +145,13 @@"returnsJson": true,"variables": []},+ "cos-task-enhance": {+ "name": "CoS Task Enhancement",+ "description": "Research the codebase and expand a brief task description into an executable agent prompt",+ "model": "default",+ "returnsJson": false,+ "variables": []+ },"memory-evaluate": {"name": "Memory Evaluation","description": "Evaluate agent output to extract useful memories",diff --git a/data.reference/prompts/stages/cos-task-enhance.md b/data.reference/prompts/stages/cos-task-enhance.mdnew file mode 100644index 0000000000..eb70a38ecf--- /dev/null+++ b/data.reference/prompts/stages/cos-task-enhance.md@@ -0,0 +1,43 @@+You are a task prompt enhancer for an AI agent system. Your job is to take a brief task description, research the relevant parts of the codebase, and produce a comprehensive, codebase-informed prompt that an AI coding agent can execute effectively.++## Process++### Step 1: Research the Codebase++Before writing the enhanced prompt, investigate the codebase to understand:+- Which files and directories are relevant to this task+- Existing patterns, conventions, and code structure in those areas+- Related functionality that may be affected+- Any tests, configs, or documentation that should be updated++Use your tools to search for files, read relevant code, and understand the current state. Focus your research on what's directly relevant to the task.++### Step 2: Plan the Approach++Based on your research, determine:+- The specific files that need to be created or modified+- The order of changes and any dependencies between them+- Patterns to follow from existing code+- Tests that should be run or written+- Potential pitfalls or edge cases specific to this codebase++### Step 3: Write the Enhanced Prompt++Produce a detailed prompt that gives the executing agent everything it needs to complete the task without redundant exploration. Include:+- Specific file paths discovered during research+- Code patterns and conventions to follow (with examples from the codebase)+- Step-by-step implementation plan grounded in the actual code structure+- Success criteria and verification steps+- Any caveats or constraints discovered during research++## Original Task Description+{{description}}++{{#context}}+## Additional Context+{{context}}+{{/context}}++## Your Enhanced Prompt++Research the codebase, then provide an enhanced version of this task that an AI agent can execute. The prompt should be grounded in actual file paths, existing patterns, and codebase structure — not generic advice. Output ONLY the enhanced prompt text, nothing else. Do not include any preamble like "Here is the enhanced prompt:" - just output the prompt itself.diff --git a/docs/features/prompt-manager.md b/docs/features/prompt-manager.mdindex 396fd39eb1..a17878a957 100644--- a/docs/features/prompt-manager.md+++ b/docs/features/prompt-manager.md@@ -40,7 +40,7 @@ Templates use Mustache-like syntax:| Route | Description ||-------|-------------|-| GET /api/prompts | List all prompt stages |+| GET /api/prompts | List all prompt stages — `{ stages, systemStages }`, where `systemStages` is the key list from `server/lib/promptSystemStages.js` (the stages PortOS features call by name, which the client badges and DELETE force-guards) || GET /api/prompts/:stage | Get stage template || PUT /api/prompts/:stage | Update stage/template || POST /api/prompts/:stage/preview | Preview compiled prompt |diff --git a/scripts/migrations/218-cos-task-enhance-stage.js b/scripts/migrations/218-cos-task-enhance-stage.jsnew file mode 100644index 0000000000..c72601c46d--- /dev/null+++ b/scripts/migrations/218-cos-task-enhance-stage.js@@ -0,0 +1,22 @@+/**+ * Seed the `cos-task-enhance` prompt stage into existing installs (#3314).+ *+ * `server/services/taskEnhancer.js` has resolved its provider/model and prompt+ * through this stage since v0.10.29 ("configure via Prompt Manager instead of+ * hardcoded defaults"), and both the delete guard and the Prompt Manager's+ * SYSTEM badge have listed the key — but no `stage-config.json` entry ever+ * shipped, so the stage rendered no row and there was nothing to configure. The+ * service fell back to its hardcoded template and the active provider's default+ * model on every run.+ *+ * Shipping the reference template + config entry alone would only reach FRESH+ * installs: boot runs migrations (`server/index.js`) but NOT `setup-data.js`, so+ * an upgrade that pulls and `pm2 restart`s would keep silently using the+ * fallback. Customization-safe + idempotent per `_seedStageHelpers.js` — the+ * template is copied only when missing and the config entry merged only when+ * absent, so an install that hand-created the stage keeps its own version.+ */++import { makeSeedMigration } from './_seedStageHelpers.js';++export default makeSeedMigration('cos-task-enhance');diff --git a/scripts/migrations/218-cos-task-enhance-stage.test.js b/scripts/migrations/218-cos-task-enhance-stage.test.jsnew file mode 100644index 0000000000..d4db1694cf--- /dev/null+++ b/scripts/migrations/218-cos-task-enhance-stage.test.js@@ -0,0 +1,16 @@+import { describe } from 'vitest';++import migration from './218-cos-task-enhance-stage.js';+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';++// The CoS task-enhancement stage (#3314). The drift catch is the point: this+// key was already named by the delete guard and the Prompt Manager's SYSTEM+// badge while shipping no template or config entry at all, which is exactly the+// state this suite now fails on.+describe('migration 218 — seed the cos-task-enhance stage', () => {+ runSeedStageMigrationTests({+ migration,+ stages: ['cos-task-enhance'],+ prefix: 'migration-218-',+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 0d65d6da75..6e356cd346 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -97,6 +97,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. || `tuiUsageScrape.js` | `scrapeTuiUsage({ command, slashCommand, … })` + `USAGE_SANDBOX_DIR` — drive an agy/grok TUI in a sandbox PTY, send a slash command, return the ANSI-stripped screen (for quota panels `--print` can't reach). || `stageRunner.js` | Shared staged-LLM runner. |+| `promptSystemStages.js` | Single source of truth for the prompt stages PortOS features resolve by literal key — `SYSTEM_STAGE_USAGE` (`key -> usedBy[]` feature-name copy), the derived `SYSTEM_STAGE_KEYS`, `isSystemStage(key)`, `systemStageUsedBy(key)`. Read by `GET /api/prompts` (ships the key list to the client), `GET /api/prompts/:stage/usage`, and the `DELETE /api/prompts/:stage` force-guard. Adding a feature that names a stage by literal key means adding a row here. || `promptTemplate.js` | Mustache-flavored, dot-notation-aware prompt template engine. || `promptPartials.js` | Mustache-style partial expansion. || `mediaModels.js` | Single source of truth for image/video model metadata. |diff --git a/server/lib/index.js b/server/lib/index.jsindex f6868b25e0..4bbebb3ca1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -105,6 +105,7 @@ export * from './kimi.js';export * from './mediaModels.js';export * from './promptPartials.js';export * from './promptRunner.js';+export * from './promptSystemStages.js';export * from './promptTemplate.js';export * from './providerModels.js';export * from './providerTranscriptUsage.js';diff --git a/server/lib/promptSystemStages.js b/server/lib/promptSystemStages.jsnew file mode 100644index 0000000000..b76bbb4fde--- /dev/null+++ b/server/lib/promptSystemStages.js@@ -0,0 +1,62 @@+/**+ * The prompt stages PortOS features call by name — the single source of truth+ * for "which stage keys are system stages" (#3314).+ *+ * These are the stages a feature resolves by literal key (`getStage('cos-evaluate')`,+ * `runStage('brain-classifier')`, …) rather than ones the user authored in the+ * Prompt Manager. Deleting one silently breaks the feature that names it, so+ * `DELETE /api/prompts/:stage` refuses without `?force=true`, and the Prompt+ * Manager badges + filters them.+ *+ * The map was previously restated three times — the usage handler's+ * `key -> usedBy[]` table, the DELETE guard's bare key array, and a client-side+ * `SYSTEM_STAGE_KEYS` mirror in `client/src/lib/promptStageGroups.js`. The+ * client copy could (and did) drift out of the server's, which after #3284 was+ * no longer cosmetic: a key missing from the client list made that stage+ * unreachable through the Stages pane's "System only" filter even though the+ * server would refuse to delete it. `GET /api/prompts` now ships the key list+ * so the client has nothing left to guess.+ *+ * Pure data + predicates — no I/O, no toolkit dependency. Adding a feature that+ * resolves a stage by literal key means adding a row here.+ */++/**+ * `stageKey -> human-readable feature names that call it`. The values are what+ * `GET /api/prompts/:stage/usage` surfaces as `usedBy` in the delete-confirm+ * dialog, so they read as UI copy rather than module paths.+ */+export const SYSTEM_STAGE_USAGE = Object.freeze({+ 'cos-agent-briefing': Object.freeze(['CoS sub-agent task briefing']),+ 'cos-evaluate': Object.freeze(['CoS task evaluation']),+ 'cos-report-summary': Object.freeze(['CoS daily reports']),+ 'cos-self-improvement': Object.freeze(['CoS self-improvement tasks']),+ 'cos-task-enhance': Object.freeze(['CoS task prompt enhancement']),+ 'brain-classifier': Object.freeze(['Brain thought classification']),+ 'brain-daily-digest': Object.freeze(['Brain daily digest generation']),+ 'brain-weekly-review': Object.freeze(['Brain weekly review generation']),+ 'memory-evaluate': Object.freeze(['Memory extraction from agent output']),+ 'app-detection': Object.freeze(['Project directory analysis']),+});++/** Derived, never restated — the DELETE guard and the API response both read this. */+export const SYSTEM_STAGE_KEYS = Object.freeze(Object.keys(SYSTEM_STAGE_USAGE));++const SYSTEM_STAGE_SET = new Set(SYSTEM_STAGE_KEYS);++/** True when `key` names a stage a PortOS feature resolves by literal key. */+export function isSystemStage(key) {+ return SYSTEM_STAGE_SET.has(key);+}++/**+ * The feature names that call `key`, or an empty array for a user-authored+ * stage. Always an array so callers can render it without a null guard.+ *+ * Gated on the Set rather than indexing the object directly — a stage literally+ * named `toString` or `constructor` would otherwise resolve to an inherited+ * `Object.prototype` member and be reported as in-use.+ */+export function systemStageUsedBy(key) {+ return isSystemStage(key) ? SYSTEM_STAGE_USAGE[key] : [];+}diff --git a/server/lib/promptSystemStages.test.js b/server/lib/promptSystemStages.test.jsnew file mode 100644index 0000000000..fc44d0d9db--- /dev/null+++ b/server/lib/promptSystemStages.test.js@@ -0,0 +1,63 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { dirname, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++import {+ SYSTEM_STAGE_USAGE,+ SYSTEM_STAGE_KEYS,+ isSystemStage,+ systemStageUsedBy,+} from './promptSystemStages.js';++describe('promptSystemStages', () => {+ it('derives the key list from the usage map rather than restating it', () => {+ expect(SYSTEM_STAGE_KEYS).toEqual(Object.keys(SYSTEM_STAGE_USAGE));+ });++ it('recognizes every system stage', () => {+ for (const key of SYSTEM_STAGE_KEYS) expect(isSystemStage(key)).toBe(true);+ });++ it('is false for user-authored stages and non-keys', () => {+ expect(isSystemStage('pipeline-prose-draft')).toBe(false);+ expect(isSystemStage(undefined)).toBe(false);+ expect(isSystemStage('')).toBe(false);+ // Prototype keys must not read as system stages.+ expect(isSystemStage('toString')).toBe(false);+ expect(isSystemStage('constructor')).toBe(false);+ });++ it('describes each system stage with at least one non-empty usage string', () => {+ for (const key of SYSTEM_STAGE_KEYS) {+ const usedBy = systemStageUsedBy(key);+ expect(usedBy.length).toBeGreaterThan(0);+ for (const entry of usedBy) expect(entry.trim()).not.toBe('');+ }+ });++ it('returns an empty usage array for an unknown stage', () => {+ expect(systemStageUsedBy('pipeline-prose-draft')).toEqual([]);+ expect(systemStageUsedBy(undefined)).toEqual([]);+ // Inherited Object.prototype members must not leak through as usage.+ expect(systemStageUsedBy('toString')).toEqual([]);+ expect(systemStageUsedBy('constructor')).toEqual([]);+ });+});++// Drift guard for the failure this module exists to end (#3314): a system-stage+// key with no shipped stage-config entry never renders a row in the Prompt+// Manager, so the SYSTEM badge and the System-only filter silently reference a+// stage the user cannot see or configure. `cos-task-enhance` sat in that state+// until it was given a real entry.+describe('shipped stage catalog parity', () => {+ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..');+ const shipped = JSON.parse(+ readFileSync(resolve(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),+ ).stages;++ it('ships a stage-config entry for every system stage', () => {+ const missing = SYSTEM_STAGE_KEYS.filter((key) => !shipped[key]);+ expect(missing).toEqual([]);+ });+});diff --git a/server/routes/prompts.js b/server/routes/prompts.jsindex 8363f78d0b..9312e280e1 100644--- a/server/routes/prompts.js+++ b/server/routes/prompts.js@@ -1,6 +1,7 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { stageConfigUpdateSchema, validateRequest } from '../lib/validation.js';+import { SYSTEM_STAGE_KEYS, isSystemStage, systemStageUsedBy } from '../lib/promptSystemStages.js';import {listJobSkillTemplates,loadJobSkillTemplate,@@ -18,10 +19,12 @@ export function createPortOSPromptsRoutes(aiToolkit) {const router = Router();const promptsService = aiToolkit.services.prompts;- // GET /api/prompts - List all stages (wrapped in {stages: ...})+ // GET /api/prompts - List all stages (wrapped in {stages: ...}) plus the+ // system-stage key list, so the Prompt Manager badges/filters them off the+ // server's own table instead of a client-side mirror that can drift (#3314).router.get('/', asyncHandler(async (req, res) => {const stages = promptsService.getStages();- res.json({ stages });+ res.json({ stages, systemStages: SYSTEM_STAGE_KEYS });}));// GET /api/prompts/variables - List all variables (wrapped in {variables: ...})@@ -162,29 +165,13 @@ export function createPortOSPromptsRoutes(aiToolkit) {// GET /api/prompts/:stage/usage - Check if stage is in userouter.get('/:stage/usage', asyncHandler(async (req, res) => {const stageName = req.params.stage;-- // Known system stages that are referenced in code- const systemStages = {- 'cos-agent-briefing': ['CoS sub-agent task briefing'],- 'cos-evaluate': ['CoS task evaluation'],- 'cos-report-summary': ['CoS daily reports'],- 'cos-self-improvement': ['CoS self-improvement tasks'],- 'cos-task-enhance': ['CoS task prompt enhancement'],- 'brain-classifier': ['Brain thought classification'],- 'brain-daily-digest': ['Brain daily digest generation'],- 'brain-weekly-review': ['Brain weekly review generation'],- 'memory-evaluate': ['Memory extraction from agent output'],- 'app-detection': ['Project directory analysis']- };-- const isSystemStage = stageName in systemStages;- const usedBy = systemStages[stageName] || [];+ const isSystem = isSystemStage(stageName);res.json({- isSystemStage,- usedBy,- canDelete: !isSystemStage,- warning: isSystemStage ? 'This is a system stage used by PortOS features. Deleting it may break functionality.' : null+ isSystemStage: isSystem,+ usedBy: systemStageUsedBy(stageName),+ canDelete: !isSystem,+ warning: isSystem ? 'This is a system stage used by PortOS features. Deleting it may break functionality.' : null});}));@@ -192,14 +179,7 @@ export function createPortOSPromptsRoutes(aiToolkit) {router.delete('/:stage', asyncHandler(async (req, res) => {const stageName = req.params.stage;- // Check if it's a system stage- const systemStages = [- 'cos-agent-briefing', 'cos-evaluate', 'cos-report-summary', 'cos-self-improvement',- 'cos-task-enhance', 'brain-classifier', 'brain-daily-digest', 'brain-weekly-review',- 'memory-evaluate', 'app-detection'- ];-- if (systemStages.includes(stageName) && req.query.force !== 'true') {+ if (isSystemStage(stageName) && req.query.force !== 'true') {throw new ServerError('Cannot delete system stage. This stage is used by PortOS features. Add ?force=true to delete anyway.',{ status: 400, code: 'SYSTEM_STAGE_PROTECTED' }diff --git a/server/routes/prompts.test.js b/server/routes/prompts.test.jsnew file mode 100644index 0000000000..e6665717f5--- /dev/null+++ b/server/routes/prompts.test.js@@ -0,0 +1,105 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';++// The job-skill routes reach into autonomousJobs (PM2 + fs); this suite only+// covers the stage/system-stage contract, so stub the module out entirely.+vi.mock('../services/autonomousJobs.js', () => ({+ listJobSkillTemplates: vi.fn(async () => []),+ loadJobSkillTemplate: vi.fn(async () => null),+ saveJobSkillTemplate: vi.fn(async () => {}),+ getJobEffectivePrompt: vi.fn(async () => ''),+ getJob: vi.fn(async () => null),+ JOB_SKILL_MAP: {},+}));++import { errorMiddleware } from '../lib/errorHandler.js';+import { createPortOSPromptsRoutes } from './prompts.js';+import { SYSTEM_STAGE_KEYS } from '../lib/promptSystemStages.js';++const STAGES = {+ 'brain-classifier': { name: 'Brain Classifier', description: 'Classify a thought' },+ 'my-own-stage': { name: 'My Own Stage', description: 'User authored' },+};++function makeApp(overrides = {}) {+ const deleteStage = vi.fn(async () => {});+ const toolkit = {+ services: {+ prompts: {+ getStages: () => STAGES,+ getStage: (name) => STAGES[name] || null,+ getStageTemplate: async () => 'body',+ deleteStage,+ ...overrides,+ },+ },+ };+ const app = express();+ app.use(express.json());+ app.use('/api/prompts', createPortOSPromptsRoutes(toolkit));+ app.use(errorMiddleware);+ return { app, deleteStage };+}++describe('prompts routes — system stages', () => {+ let app;+ let deleteStage;+ beforeEach(() => {+ ({ app, deleteStage } = makeApp());+ });++ // The wire body is the contract the Prompt Manager consumes; the client+ // suite mocks apiPrompts, so this is the only place the shape is pinned.+ it('GET / returns the stage map AND the system-stage key list', async () => {+ const r = await request(app).get('/api/prompts');+ expect(r.status).toBe(200);+ expect(r.body.stages).toEqual(STAGES);+ expect(r.body.systemStages).toEqual(SYSTEM_STAGE_KEYS);+ expect(r.body.systemStages).toContain('cos-task-enhance');+ });++ it('GET /:stage/usage reports a system stage with its usage list', async () => {+ const r = await request(app).get('/api/prompts/brain-classifier/usage');+ expect(r.status).toBe(200);+ expect(r.body.isSystemStage).toBe(true);+ expect(r.body.canDelete).toBe(false);+ expect(r.body.usedBy).toEqual(['Brain thought classification']);+ expect(r.body.warning).toMatch(/system stage/i);+ });++ it('GET /:stage/usage reports a user stage as deletable with no usage', async () => {+ const r = await request(app).get('/api/prompts/my-own-stage/usage');+ expect(r.body).toMatchObject({ isSystemStage: false, canDelete: true, usedBy: [], warning: null });+ });++ it('DELETE /:stage refuses a system stage without force', async () => {+ const r = await request(app).delete('/api/prompts/brain-classifier');+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('SYSTEM_STAGE_PROTECTED');+ expect(deleteStage).not.toHaveBeenCalled();+ });++ it('DELETE /:stage honors ?force=true on a system stage', async () => {+ const r = await request(app).delete('/api/prompts/brain-classifier?force=true');+ expect(r.status).toBe(200);+ expect(deleteStage).toHaveBeenCalledWith('brain-classifier');+ });++ it('DELETE /:stage deletes a user stage outright', async () => {+ const r = await request(app).delete('/api/prompts/my-own-stage');+ expect(r.status).toBe(200);+ expect(deleteStage).toHaveBeenCalledWith('my-own-stage');+ });++ // The guard and the usage report must agree on the SAME list — the drift+ // between two hand-copied arrays is what #3314 removed.+ it('guards exactly the keys the usage endpoint calls system stages', async () => {+ for (const key of SYSTEM_STAGE_KEYS) {+ const usage = await request(app).get(`/api/prompts/${key}/usage`);+ expect(usage.body.isSystemStage).toBe(true);+ const del = await request(app).delete(`/api/prompts/${key}`);+ expect(del.status).toBe(400);+ }+ });+});diff --git a/server/services/taskEnhancer.js b/server/services/taskEnhancer.jsindex ee5af41309..632b1ae6aa 100644--- a/server/services/taskEnhancer.js+++ b/server/services/taskEnhancer.js@@ -10,6 +10,7 @@import { getActiveProvider, getProviderById } from './providers.js';import { getStage, buildPrompt } from './promptService.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { resolveModel } from '../lib/stageRunner.js';const STAGE_NAME = 'cos-task-enhance';@@ -70,20 +71,28 @@ export async function enhanceTaskPrompt(description, context = '') {// Get prompt stage configuration for cos-task-enhanceconst stage = getStage(STAGE_NAME);- // Determine provider and model from stage config or fallback+ // Determine provider and model from stage config or fallback.+ // `stage.model` is usually a TIER name (`default`/`quick`/`coding`/`heavy`)+ // rather than a model id — that is what the Prompt Manager's model dropdown+ // writes — so it has to go through `resolveModel`, which maps the tier onto+ // the provider's per-tier model field and falls back to defaultModel /+ // models[0]. Passing the raw value straight through would send the literal+ // string `default` to the provider as a model name (#3314: shipping the+ // `cos-task-enhance` stage-config entry is what first made stage.model+ // non-null here).let provider;let model;if (stage?.provider) {// Use stage-configured providerprovider = await getProviderById(stage.provider).catch(() => null);- model = stage.model || provider?.defaultModel;+ if (provider) model = resolveModel(provider, stage.model);}// Fallback to active provider if stage provider not availableif (!provider) {provider = await getActiveProvider();- model = stage?.model || provider?.defaultModel || provider?.models?.[0];+ if (provider) model = resolveModel(provider, stage?.model);}if (!provider) {