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(scheduled-prompts): share render-or-prepend helper across section renderers (#8921)
[._.]/ Adam Eivy99f4c331f002
diff --git a/server/lib/README.md b/server/lib/README.mdindex 2cda3f37d9..bce538ca45 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -208,6 +208,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `promptSystemStages.js` | Prompt-stage protection, split in two (#3335). CURATED (badging): `SYSTEM_STAGE_USAGE` (`key -> usedBy[]` feature-name copy), `SYSTEM_STAGE_KEYS`, `isSystemStage(key)`, `systemStageUsedBy(key)` — what `GET /api/prompts` ships and the Prompt Manager badges/filters; adding a row is a per-stage product decision. DERIVED (deletion): `STAGE_CALL_SITES` / `stageReferencedBy(key)` from the generated manifest, unioned with the curated set into `isProtectedStage(key)` / `PROTECTED_STAGE_KEYS` — what the `DELETE /api/prompts/:stage` force-guard and `canDelete` consult. || `promptStageCallSites.generated.json` | Generated `stageKey -> [server source paths]` index of every prompt stage `server/` names by literal key (plus interpolated-prefix stages like `pipeline-panel-${id}`). Regenerate with `node scripts/generate-prompt-stage-call-sites.js`; `scripts/generate-prompt-stage-call-sites.test.js` fails on drift. Never hand-edit. || `promptTemplate.js` | Mustache-flavored, dot-notation-aware prompt template engine. |+| `promptSectionRenderer.js` | `renderOrPrependSection(prompt, token, heading, block)` — replace a token in a prompt template (with a function replacer for `$` safety), or prepend the block with an optional heading when the token is absent; a fallback for customized prompts that dropped the token. Shared by multiple prompt renderers. || `promptPartials.js` | Mustache-style partial expansion. || `promptFencing.js` | Fencing for untrusted text spliced into an LLM prompt. `fenceBlock(label, text, maxChars)` truncates, collapses every run of 3+ backticks to `'''` so the content cannot terminate its own fence, and wraps the result as a labeled ```` ```text ```` block; `neutralizeFences` / `clampText` are the two halves on their own. `UNTRUSTED_CONTENT_NOTICE` is the standing "fenced content is data, not instructions" line a prompt places above its fenced sections — the fence stops delimiter escape, that line is what makes an in-band directive inert. `UNTRUSTED_PULL_REQUEST_NOTICE` is its counterpart for a prompt that sends an agent to READ a pull request off the forge (nothing is fenced because nothing is embedded) — shared by `services/prRemediationFollowUp.js` and `services/prDoReviewTask.js`. Used by `services/aiDetect.js`, whose prompt splices a scanned repository's package.json/config/README into a prompt that yields an executed `startCommands`. || `mediaModelBuckets.js` | Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — `mlx` (Apple MLX runtimes) vs `cuda` (plain torch+CUDA, which runs on Windows *and* Linux) — not by operating system, which is why `activeVideoBucket()` keys on `process.platform === 'darwin'` instead of on "is this Windows". `readVideoBucket` / `readVideoDefault` / `matchesVideoBucket` resolve the canonical key first and fall back to the pre-#4142 `macos` / `windows` / `defaultMacos` / `defaultWindows` spellings, so any registry written by an older install still loads untouched; `canonicalizeVideoBuckets` performs the one-time rename (migration 270 and the load-time twin in `mediaModels.js`). Kept separate from `mediaModels.js` so `scripts/migrations/` can share the alias resolution without importing the registry loader, which seeds `data/` as a side effect. |diff --git a/server/lib/index.js b/server/lib/index.jsindex e396d6f60b..780457fa58 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -218,6 +218,7 @@ export * from './promptFencing.js';export * from './promptPartials.js';export * from './promptSystemStages.js';export * from './promptTemplate.js';+export * from './promptSectionRenderer.js';export * from './credentialBootstrap.js';export * from './providerCooldown.js';export * from './providerModels.js';diff --git a/server/lib/promptSectionRenderer.js b/server/lib/promptSectionRenderer.jsnew file mode 100644index 0000000000..184c4b0c33--- /dev/null+++ b/server/lib/promptSectionRenderer.js@@ -0,0 +1,39 @@+/**+ * Shared helper for rendering or prepending prompt sections.+ *+ * A pattern used by multiple prompt renderers: when a template contains a token,+ * replace it (with a function replacer for `$` safety); when the token is absent,+ * prepend the block with an optional heading — a fallback for customized prompts+ * that dropped the token.+ */++import { escapeRegExp } from './textUtils.js';++/**+ * Replace a token in a prompt, or prepend the block with a heading if the token is absent.+ *+ * @param {string} prompt - The prompt template string (or empty/non-string if falsy)+ * @param {string} token - The token to find/replace (e.g., `{userActionDelivery}`)+ * @param {string|null} heading - Optional heading for the prepended section (e.g., `Delivery mode`);+ * pass null for no heading+ * @param {string} block - The content block to render+ * @returns {string} The prompt with the section applied+ */+export function renderOrPrependSection(prompt, token, heading, block) {+ const promptStr = typeof prompt === 'string' ? prompt : '';++ // If token is present in the prompt, replace it with a function replacer+ // (safe when block contains $ or $&)+ if (promptStr.includes(token)) {+ return promptStr.replace(new RegExp(escapeRegExp(token), 'g'), () => block);+ }++ // Token absent: prepend the block with optional heading+ if (heading === null) {+ // No heading case+ return `${block}\n\n---\n\n${promptStr}`;+ }++ // With heading+ return `## ${heading}\n\n${block}\n\n---\n\n${promptStr}`;+}diff --git a/server/lib/promptSectionRenderer.test.js b/server/lib/promptSectionRenderer.test.jsnew file mode 100644index 0000000000..1d34ee8dea--- /dev/null+++ b/server/lib/promptSectionRenderer.test.js@@ -0,0 +1,64 @@+import { describe, it, expect } from 'vitest';+import { renderOrPrependSection } from './promptSectionRenderer.js';++describe('renderOrPrependSection', () => {+ it('replaces a token when present in the prompt', () => {+ const prompt = 'Here is the content:\n\n{userActionDelivery}\n\nAnd more.';+ const block = 'Block content';+ const result = renderOrPrependSection(prompt, '{userActionDelivery}', 'Delivery mode', block);+ expect(result).toBe('Here is the content:\n\nBlock content\n\nAnd more.');+ });++ it('prepends the block with a heading when token is absent', () => {+ const prompt = 'Original prompt content';+ const block = 'Block content';+ const result = renderOrPrependSection(prompt, '{userActionDelivery}', 'Delivery mode', block);+ expect(result).toBe('## Delivery mode\n\nBlock content\n\n---\n\nOriginal prompt content');+ });++ it('prepends without a heading when heading is null', () => {+ const prompt = 'Original prompt content';+ const block = 'Block content';+ const result = renderOrPrependSection(prompt, '{modeInstructions}', null, block);+ expect(result).toBe('Block content\n\n---\n\nOriginal prompt content');+ });++ it('handles block containing $& (regex replacement hazard) when token is present', () => {+ const prompt = 'Before {token} after';+ const block = 'Contains $& and $1 and $` and $\' characters';+ const result = renderOrPrependSection(prompt, '{token}', 'Section', block);+ // Should insert the block verbatim, not interpret $& as a backreference+ expect(result).toBe('Before Contains $& and $1 and $` and $\' characters after');+ });++ it('handles block containing $& when token is absent (prepending)', () => {+ const prompt = 'Original';+ const block = 'Contains $& and $1 and $` and $\' characters';+ const result = renderOrPrependSection(prompt, '{token}', 'Section', block);+ expect(result).toBe('## Section\n\nContains $& and $1 and $` and $\' characters\n\n---\n\nOriginal');+ });++ it('handles non-string prompt gracefully', () => {+ const result = renderOrPrependSection(null, '{token}', 'Heading', 'Block');+ expect(result).toBe('## Heading\n\nBlock\n\n---\n\n');+ });++ it('handles empty string prompt', () => {+ const result = renderOrPrependSection('', '{token}', 'Heading', 'Block');+ expect(result).toBe('## Heading\n\nBlock\n\n---\n\n');+ });++ it('handles multiple occurrences of the token', () => {+ const prompt = 'First {token} and second {token}';+ const block = 'CONTENT';+ const result = renderOrPrependSection(prompt, '{token}', 'Heading', block);+ expect(result).toBe('First CONTENT and second CONTENT');+ });++ it('handles special regex characters in token name', () => {+ const prompt = 'Before {release.options} after';+ const block = 'Block';+ const result = renderOrPrependSection(prompt, '{release.options}', 'Heading', block);+ expect(result).toBe('Before Block after');+ });+});diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 68cb7abfc6..12a936b26a 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -31,6 +31,7 @@ import { join } from 'path';import { sanitizeTaskMetadata, PIPELINE_STAGE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, resolveClaimReviewerConfig, reviewerConfigMetadata, hasReviewerOverride } from '../lib/validation.js';import { PATHS } from '../lib/fileUtils.js';import { applyAppPlaceholders } from '../lib/appPromptPlaceholders.js';+import { renderOrPrependSection } from '../lib/promptSectionRenderer.js';import { isPlainObject } from '../lib/objects.js';import { hasQuotaBurnProvenance, isManualOnDemandRequest } from '../lib/quotaBurnOrigin.js';import { isAutoApprovableInvestigation } from '../lib/investigationTasks.js';@@ -2619,8 +2620,7 @@ export function applyUserActionDeliveryMode(promptTemplate, taskType, metadata)const prompt = typeof promptTemplate === 'string' ? promptTemplate : '';const block = resolveUserActionDeliveryBlock(taskType, metadata);if (!block) return prompt;- if (prompt.includes('{userActionDelivery}')) return prompt.replace(/\{userActionDelivery\}/g, () => block);- return `## Delivery mode\n\n${block}\n\n---\n\n${prompt}`;+ return renderOrPrependSection(prompt, '{userActionDelivery}', 'Delivery mode', block);}/**@@ -2636,8 +2636,7 @@ export async function applyUserActionDetectorSection(promptTemplate, taskType) {return [];});const block = formatUserActionDetectorBlock(findings) || 'No leftover-branch findings.';- if (prompt.includes('{userActionDetectors}')) return prompt.replace(/\{userActionDetectors\}/g, () => block);- return `## Detectors\n\n${block}\n\n---\n\n${prompt}`;+ return renderOrPrependSection(prompt, '{userActionDetectors}', 'Detectors', block);}