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: tighten renderOrPrependSection and its tests (#8921)
[._.]/ Adam Eivye627e888f3cc
diff --git a/server/lib/README.md b/server/lib/README.mdindex bce538ca45..eea745a3bc 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -205,10 +205,10 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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). || `stageModelTiers.js` | The prompt-stage `model`/`judgeModel` tier vocabulary (#8149): `STAGE_MODEL_TIERS` (`default` + the shared MODEL_TIERS), `STAGE_MODEL_TIER_OPTIONS` (the picker rows every stage model select renders), `LEGACY_STAGE_MODEL_TIERS` (`quick`→light, `coding`→medium, still readable from older peers/backups), `canonicalStageModelTier`, `isStageModelTier` (tier vs model-id pin). Pure — the client re-exports it. || `stagePinPolicy.js` | Run-scoped "ignore per-stage LLM pins" switch (AsyncLocalStorage) — `withStagePinsIgnored(ignore, fn)` marks an async subtree, `stagePinsIgnored()` reads it, and `services/stageRunner.js#effectiveStage` enumerates which stage-config fields it strips. Backs Series Autopilot's "use one provider/model for every stage" option. |+| `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 the CoS user-action section renderers. || `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 780457fa58..2b1551ab88 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -216,9 +216,9 @@ export * from './videoStreamingMode.js';export * from './videoTextEncoders.js';export * from './promptFencing.js';export * from './promptPartials.js';+export * from './promptSectionRenderer.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.jsindex 184c4b0c33..bf0aeb4477 100644--- a/server/lib/promptSectionRenderer.js+++ b/server/lib/promptSectionRenderer.js@@ -1,39 +1,14 @@-/**- * 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+ * Substitute `token` in a prompt template with `block`, or — when a+ * customized prompt dropped the token — prepend the block (under `## heading`+ * unless heading is null) so the operator's setting still takes effect.+ * The function replacer inserts `block` verbatim even when it contains `$&`.*/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}`;+ const text = typeof prompt === 'string' ? prompt : '';+ if (text.includes(token)) return text.replace(new RegExp(escapeRegExp(token), 'g'), () => block);+ const section = heading === null ? block : `## ${heading}\n\n${block}`;+ return `${section}\n\n---\n\n${text}`;}diff --git a/server/lib/promptSectionRenderer.test.js b/server/lib/promptSectionRenderer.test.jsindex 1d34ee8dea..8c7f8e6c8d 100644--- a/server/lib/promptSectionRenderer.test.js+++ b/server/lib/promptSectionRenderer.test.js@@ -2,63 +2,16 @@ 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('replaces every occurrence of the token when present', () => {+ expect(renderOrPrependSection('A {tok} B {tok}', '{tok}', 'Heading', 'X')).toBe('A X B X');});- 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 the block under a heading, or bare when heading is null, when the token is absent', () => {+ expect(renderOrPrependSection('Body', '{tok}', 'Heading', 'X')).toBe('## Heading\n\nX\n\n---\n\nBody');+ expect(renderOrPrependSection('Body', '{tok}', null, 'X')).toBe('X\n\n---\n\nBody');});- 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');+ it('inserts a block containing $& verbatim', () => {+ expect(renderOrPrependSection('A {tok} B', '{tok}', 'Heading', 'cost $& $1')).toBe('A cost $& $1 B');});});