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: import the shared escapeRegExp instead of 22 private copies (#5667)
Adam Eivy892259189f77
diff --git a/server/lib/README.md b/server/lib/README.mdindex ca562e8659..64be10b151 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -383,7 +383,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `goalFeatureMap.js` | Deterministic goal `category` → PortOS feature-area map (deep-links sourced from `NAV_COMMANDS`). `getGoalFeatureAreas(goal)` honors the per-goal `featureAreas` override, else the category default. Mirrored byte-for-byte to `client/src/lib/`. || `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. || `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. Mirrored to `client/src/lib/`. |-| `textUtils.js` | Pure dependency-free prose helpers. `countWords(text)` is the canonical whitespace-token count (`\S+`); `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape; `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels). |+| `textUtils.js` | Pure dependency-free prose helpers. `countWords(text)` is the canonical whitespace-token count (`\S+`); `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape (a guard in `textUtils.test.js` fails the suite when a copy reappears anywhere under `server/`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels). || `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. || `postAdaptive.js` | Pure POST adaptive-difficulty policy — nudges a math drill's primary knob (`steps`/`maxDigits`/`maxExponent`/`tolerancePct`) up/down within clamped bounds from recent scored performance. Opt-in via the config Adaptive toggle. || `postAppliedNumeracy.js` | Pure seeded Applied Numeracy pack — everyday percentage, ratio, unit, rate, and estimation scenarios plus server-authoritative numeric/fraction/unit scoring with explicit tolerance handling. |diff --git a/server/lib/editorial/balloonAttribution.js b/server/lib/editorial/balloonAttribution.jsindex 3d1169f102..eac2b182f3 100644--- a/server/lib/editorial/balloonAttribution.js+++ b/server/lib/editorial/balloonAttribution.js@@ -35,6 +35,8 @@* `low` when no one is clearly visible (an orphaned/unclear balloon).*/+import { escapeRegExp } from '../textUtils.js';+// Speaker modifiers that mean "this speaker need not be drawn in the panel" —// broadcast/PA, off-panel/off-screen, voice-over/narration, and transmission// devices (the remote party isn't in frame). Mirrors the disembodied + device@@ -48,8 +50,6 @@ export const OFFPANEL_OK_MODIFIER =// module stays self-contained.const ATTRIBUTION_SEVERITIES = ['high', 'medium', 'low'];-const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-// Split a `NAME (MODIFIER)` speaker token into { speaker, modifier }. Tolerates// stacked parentheticals by treating the whole inner-paren blob as the modifier.// Mirrors formatBalloon's split in visualStages.js.@@ -69,9 +69,9 @@ export function nameInText(name, text) {const n = (typeof name === 'string' ? name : '').trim().toLowerCase();const t = (typeof text === 'string' ? text : '').toLowerCase();if (!n || !t) return false;- if (new RegExp(`\\b${escapeRe(n)}\\b`).test(t)) return true;+ if (new RegExp(`\\b${escapeRegExp(n)}\\b`).test(t)) return true;const tokens = n.split(/[^a-z0-9]+/).filter((tok) => tok.length >= 4);- return tokens.some((tok) => new RegExp(`\\b${escapeRe(tok)}\\b`).test(t));+ return tokens.some((tok) => new RegExp(`\\b${escapeRegExp(tok)}\\b`).test(t));}/**diff --git a/server/lib/editorial/checkInfra/rosterCast.js b/server/lib/editorial/checkInfra/rosterCast.jsindex f786921993..06ceb9c7d5 100644--- a/server/lib/editorial/checkInfra/rosterCast.js+++ b/server/lib/editorial/checkInfra/rosterCast.js@@ -4,6 +4,7 @@*/import { normalizeName } from './externals.js';+import { escapeRegExp } from '../../textUtils.js';// ---------------------------------------------------------------------------// Roster economy (#1292) — character-appearance accounting over the stitched@@ -19,10 +20,6 @@ import { normalizeName } from './externals.js';// characters needs an LLM pass and is tracked as its own check (see the issue).// ----------------------------------------------------------------------------// Escape a name so it rides inside a RegExp alternation literally — names carry-// regex-significant punctuation ("D'Argo", "Anne-Marie", "T.A.R.D.I.S.").-const escapeRegExp = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-// A character's match tokens: its name plus every alias, trimmed + de-duped.// Empty when the character has no usable name.export function characterNameTokens(c) {diff --git a/server/lib/editorial/cliches.js b/server/lib/editorial/cliches.jsindex 3bec849844..c8b7db421e 100644--- a/server/lib/editorial/cliches.js+++ b/server/lib/editorial/cliches.js@@ -12,6 +12,8 @@* purple-prose overwriting beyond a simple adjective run.*/+import { escapeRegExp } from '../textUtils.js';+// Seed cliché phrase list — stock similes/idioms that pull readers out of the// prose. Curated, not exhaustive; a series can extend it (extraPhrases) or mute// entries for voice/genre (allowPhrases). Phrases are matched whole-word and@@ -104,10 +106,6 @@ const COMMON_ADJECTIVES = new Set([// gerund/verb-list shapes that would otherwise be false positives.const MODIFIER_SUFFIX = /(?:ous|ful|ive|ent|ant|ical|ic|less|able|ible|ish|ese|like|some|ward|most|ed|ing|ly)$/i;-function escapeRegExp(s) {- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-}-// A phrase matches with word boundaries on each edge and flexible internal// whitespace, so "time stood\nstill" still trips "time stood still". Internal// non-word characters (apostrophes) are matched literally.diff --git a/server/lib/editorial/cutApplier.js b/server/lib/editorial/cutApplier.jsindex 2c511e84b9..922fc734fc 100644--- a/server/lib/editorial/cutApplier.js+++ b/server/lib/editorial/cutApplier.js@@ -19,6 +19,7 @@*/import { SAFE_CUT_TYPES, CUT_TYPES } from './checkInfra.js';+import { escapeRegExp } from '../textUtils.js';export { SAFE_CUT_TYPES, CUT_TYPES };@@ -31,7 +32,7 @@ export const MIN_ANCHOR_CHARS = 25;* even when the quote clearly targets a real span.*/export function buildWhitespaceTolerantRegex(quote) {- const escaped = quote.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const escaped = escapeRegExp(quote);return new RegExp(escaped.replace(/\s+/g, '\\s+'), 'g');}diff --git a/server/lib/editorial/dialogue.js b/server/lib/editorial/dialogue.jsindex b5082ad923..ed914b45a3 100644--- a/server/lib/editorial/dialogue.js+++ b/server/lib/editorial/dialogue.js@@ -20,6 +20,8 @@* the pipeline use double-quote dialogue, so this is a safe simplification.*/+import { escapeRegExp } from '../textUtils.js';+// Straight + curly double quotes. Used both as a character class body (DQUOTE)// and to build "quoted span" / "non-quote run" regexes.const DQUOTE = '"“”';@@ -85,10 +87,6 @@ export const PLAIN_SPEECH_TAG_GROUPS = Object.freeze([// only needs "is this token a plain speech tag", not which lemma it maps to.const PLAIN_SPEECH_TAGS = Object.freeze(PLAIN_SPEECH_TAG_GROUPS.flatMap((g) => g.forms));-function escapeRegExp(s) {- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-}-function normalizeWord(p) {return typeof p === 'string' ? p.trim().toLowerCase() : '';}diff --git a/server/lib/editorial/proseTics.js b/server/lib/editorial/proseTics.jsindex 44af97c7a1..666e3233cc 100644--- a/server/lib/editorial/proseTics.js+++ b/server/lib/editorial/proseTics.js@@ -19,6 +19,8 @@* judgment case these pure scanners deliberately avoid (false-positive-prone).*/+import { escapeRegExp } from '../textUtils.js';+// ---------------------------------------------------------------------------// Seed word/phrase lists. Each is curated, not exhaustive; a series can extend// (extraWords) or mute (allowWords) entries per house style. Entries are@@ -177,10 +179,6 @@ const NON_ADVERB_LY = new Set(['surly', 'gnarly', 'pearly', 'hourly', 'daily', 'doily', 'gaily',]);-function escapeRegExp(s) {- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-}-function normalizeWord(p) {return typeof p === 'string' ? p.trim().toLowerCase() : '';}diff --git a/server/lib/editorial/slopScore.js b/server/lib/editorial/slopScore.jsindex 5df5f1ef9a..7ba9063a0c 100644--- a/server/lib/editorial/slopScore.js+++ b/server/lib/editorial/slopScore.js@@ -33,10 +33,7 @@import { tokenizeWords, splitSentences } from './proseTics.js';import { measureSentenceRhythm } from './repetition.js';--function escapeRegExp(s) {- return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-}+import { escapeRegExp } from '../textUtils.js';function normalizeWord(p) {return typeof p === 'string' ? p.trim().toLowerCase() : '';diff --git a/server/lib/loraDataset.js b/server/lib/loraDataset.jsindex 19ab00b3de..2010860f47 100644--- a/server/lib/loraDataset.js+++ b/server/lib/loraDataset.js@@ -12,6 +12,8 @@* `server/services/loraDatasets.js`.*/+import { escapeRegExp } from './textUtils.js';+export const LORA_DATASET_SCHEMA_VERSION = 1;// Minimum ready+captioned images before a training run is allowed. Below@@ -149,8 +151,6 @@ export function deriveTriggerWord(name, { taken = [] } = {}) {return `${candidate}_${Date.now().toString(36)}`;}-const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-/*** Ensure a caption starts with exactly one `"<triggerWord>, "` prefix.* Idempotent; also strips a stale prefix when the trigger word changed@@ -166,7 +166,7 @@ export function prefixCaption(triggerWord, text, { previousTriggerWord = null }// [a-z0-9_] tokens that often prefix a real word (e.g. `her` in `heroic`),// and the trailing comma is optional — without the boundary, stripping// `her` from `heroic stance` would amputate it to `oic stance`.- return value.replace(new RegExp(`^${escapeRe(token)}(?=[\\s,]|$)\\s*,?\\s*`, 'i'), '');+ return value.replace(new RegExp(`^${escapeRegExp(token)}(?=[\\s,]|$)\\s*,?\\s*`, 'i'), '');};body = stripPrefix(body, word);const prev = trim(previousTriggerWord);@@ -231,7 +231,7 @@ export function captionHasTriggerWord(caption, triggerWord) {const text = trim(caption);if (!text) return false;if (!word) return true; // no trigger configured yet — any caption counts- return new RegExp(`(?:^|[^a-z0-9_])${escapeRe(word)}(?:[^a-z0-9_]|$)`, 'i').test(text);+ return new RegExp(`(?:^|[^a-z0-9_])${escapeRegExp(word)}(?:[^a-z0-9_]|$)`, 'i').test(text);}/**@@ -299,7 +299,7 @@ const captionBody = (caption, triggerWord) => {const word = trim(triggerWord);let body = trim(caption);if (word) {- body = body.replace(new RegExp(`^${escapeRe(word)}(?=[\\s,]|$)\\s*,?\\s*`, 'i'), '');+ body = body.replace(new RegExp(`^${escapeRegExp(word)}(?=[\\s,]|$)\\s*,?\\s*`, 'i'), '');}return body;};diff --git a/server/lib/loraTriggers.js b/server/lib/loraTriggers.jsindex 34e40369e9..bdfc0c7af1 100644--- a/server/lib/loraTriggers.js+++ b/server/lib/loraTriggers.js@@ -14,6 +14,8 @@* videoGen/local.js) own the sidecar reads and the provenance stamping.*/+import { escapeRegExp } from './textUtils.js';+// Only the FIRST trigger word of each LoRA is woven. Civitai's `trainedWords`// routinely lists a dozen loosely-related tags (style hints, sample-prompt// fragments); appending all of them would rewrite the render rather than@@ -25,8 +27,6 @@ export const firstTriggerWord = (words) => {return first ? first.trim() : null;};-const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-// What counts as "inside a word" for the boundary assertions below. Unicode// letters/digits, not just ASCII, so a non-ASCII trigger or an accented prompt// gets the same treatment — `\b` and a bare `[A-Za-z0-9_]` class would bothdiff --git a/server/lib/markedSection.js b/server/lib/markedSection.jsindex f984016e07..2f087e077e 100644--- a/server/lib/markedSection.js+++ b/server/lib/markedSection.js@@ -11,6 +11,8 @@* `brainJournal.upsertAutoSection()` splices it in.*/+import { escapeRegExp } from './textUtils.js';+// Build a matched start/end marker pair for a stable section id. HTML-comment// syntax so the markers render invisibly in Markdown / Obsidian previews and// never collide with user prose.@@ -22,11 +24,6 @@ export function buildMarkers(id) {};}-// Escape a literal string for embedding inside a RegExp.-function escapeRegExp(s) {- return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-}-// Match the full marker region plus any leading blank line(s) the writer added// so a replace/remove doesn't accumulate (or leave) widening gaps. Non-greedy// body so two regions can't be swallowed as one.diff --git a/server/lib/mirrorCoverage.test.js b/server/lib/mirrorCoverage.test.jsindex 5f2891bbd8..d58bab8d48 100644--- a/server/lib/mirrorCoverage.test.js+++ b/server/lib/mirrorCoverage.test.js@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import { readFileSync, readdirSync } from 'fs';import { basename, dirname, join } from 'path';import { fileURLToPath } from 'url';+import { escapeRegExp } from './textUtils.js';const here = dirname(fileURLToPath(import.meta.url));const CLIENT_LIB = join(here, '../../client/src/lib');@@ -50,7 +51,7 @@ function uniquePairs(pairs) {// mentioning a filename, or an unrelated same-prefix fixture, must not count// as "this test imports that file".function importsRef(source, ref) {- const escaped = ref.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const escaped = escapeRegExp(ref);// Quote characters only — no backtick. Backtick-fenced prose is this// codebase's dominant style for referencing a file path in a comment or// JSDoc header (see every existing parity-test docstring), so treating itdiff --git a/server/lib/pathSafety.js b/server/lib/pathSafety.jsindex 8e7304d054..6b17156690 100644--- a/server/lib/pathSafety.js+++ b/server/lib/pathSafety.js@@ -3,6 +3,7 @@ import { existsSync, statSync } from 'fs';import { basename, join, resolve as resolvePath, sep as PATH_SEP } from 'path';import { ServerError } from './errorHandler.js';import { PATHS } from './paths.js';+import { escapeRegExp } from './textUtils.js';/*** Validate a user-supplied filename is a safe basename with one of the@@ -182,7 +183,7 @@ export function makePathResolver(getRoot, { extensions, cache = false } = {}) {// passes an extension containing `.`/`+`/etc.const extRegex = Array.isArray(extensions) && extensions.length > 0? new RegExp(`\\.(${extensions- .map((e) => String(e).replace(/^\./, '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))+ .map((e) => escapeRegExp(String(e).replace(/^\./, ''))).join('|')})$`, 'i'): null;const memo = cache ? new Map() : null;diff --git a/server/lib/textUtils.js b/server/lib/textUtils.jsindex 0600d8f8f3..6940098e1d 100644--- a/server/lib/textUtils.js+++ b/server/lib/textUtils.js@@ -39,10 +39,16 @@ export const trimTo = (value, max) => (/*** Escape a string for literal use inside a RegExp.*- * Exported because this was hand-rolled privately in seven other modules- * (markedSection, loraTriggers, loraDataset, scenePrompt, assetMounts,- * editorial/cutApplier, editorial/proseTics) — none of them exported it, so the- * eighth caller copied it too. This is the one to import.+ * This is the ONE copy — import it, never re-inline the character class. It was+ * hand-rolled privately in a dozen modules before the extraction, and because+ * none of them exported it every new caller copied the nearest one again. The+ * `no private escapeRegExp` guard in textUtils.test.js scans the server tree and+ * fails the build if a private copy reappears.+ *+ * Non-string input is coerced rather than throwing: the callers escape+ * user-supplied tokens (LoRA trigger words, character aliases, catalog type+ * labels) on the way into `new RegExp(...)`, where a TypeError would surface as+ * an opaque 500 instead of a harmless non-match.*/export function escapeRegExp(value) {return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');diff --git a/server/lib/textUtils.test.js b/server/lib/textUtils.test.jsindex 770e71bf5f..00777721fd 100644--- a/server/lib/textUtils.test.js+++ b/server/lib/textUtils.test.js@@ -1,5 +1,6 @@import { describe, it, expect } from 'vitest';-import { countWords, trimTo } from './textUtils.js';+import { countWords, escapeRegExp, trimTo } from './textUtils.js';+import { collectServerSources, readServerSource } from './testHelper.js';describe('countWords', () => {it('counts whitespace-separated tokens', () => {@@ -35,3 +36,80 @@ describe('trimTo', () => {expect(trimTo(42, 20)).toBe('');});});++describe('escapeRegExp', () => {+ it('escapes every RegExp metacharacter and nothing else', () => {+ expect(escapeRegExp('a.c')).toBe('a\\.c');+ expect(escapeRegExp('C++ (faction) [v1.0]')).toBe('C\\+\\+ \\(faction\\) \\[v1\\.0\\]');+ expect(escapeRegExp('a|b {x} ^$ *? \\')).toBe('a\\|b \\{x\\} \\^\\$ \\*\\? \\\\');+ expect(escapeRegExp('plain words 42')).toBe('plain words 42');+ });++ it('makes a metacharacter-laden token match only itself', () => {+ const token = 'C++ (faction) [v1.0]';+ expect(new RegExp(`^${escapeRegExp(token)}$`).test(token)).toBe(true);+ expect(new RegExp(`^${escapeRegExp('a.c')}$`).test('abc')).toBe(false);+ });++ // Seven of the migrated copies were `s.replace(...)`, which threw a TypeError on+ // a non-string; the shared helper coerces. Every migrated call site already+ // filters to strings upstream, so the change is unreachable today — but it is+ // the one semantic the migration altered, so it is pinned here rather than left+ // to be "fixed" back into a throw by someone reading only this module. Coercion+ // is deliberate: these callers splice user-supplied tokens (LoRA triggers,+ // character aliases, catalog labels) into `new RegExp(...)`, where a throw+ // surfaces as an opaque 500. The trade is that a stray non-string becomes a+ // literal 'null'/'42' pattern rather than an error, which is why callers must+ // keep filtering rather than lean on the coercion.+ it('coerces non-string input instead of throwing', () => {+ expect(escapeRegExp(null)).toBe('null');+ expect(escapeRegExp(undefined)).toBe('undefined');+ expect(escapeRegExp(42)).toBe('42');+ expect(escapeRegExp(1.5)).toBe('1\\.5');+ });+});++// The extraction of `escapeRegExp` into this module landed once and then rotted:+// twenty-odd server modules kept (or re-added) a private copy — some named+// `escapeRe`/`escapeRegex`, most just inlined at the call site — because nothing+// failed when they did, and the copies drifted (`s.replace` threw on a non-string+// where `String(s).replace` coerced). This guard is what makes the extraction+// stick: a fresh copy fails the suite instead of shipping.+//+// It keys on the escape's CHARACTER CLASS, not on the identifier, because every+// copy this repo ever grew was a byte-identical paste under a different name (or+// no name at all). Consequence: even naming the class in a comment trips the+// guard — describe the rule in prose, or put the example here in textUtils, which+// is the one file exempt.+//+// Scope note: `collectServerSources` skips `*.test.js`, so this covers product+// code only. That is the surface that matters — a private copy in a test can't+// change what the server does.+const ESCAPE_COPY = [+ // The escape's character class, however the copy names (or doesn't name) it.+ String.raw`\[\.\*\+\?\^\$\{\}\(\)\|\[\\\]\\\\\]`,+ // A copy that reorders the class but keeps the conventional name.+ String.raw`(?:^|[^\w$.])(?:const|let|var|function)\s+escapeRegExp\b`,+].map((source) => new RegExp(source));++// `scenePrompt.js` is held byte-for-byte identical to `client/src/lib/scenePrompt.js`+// by the mirror-parity suite in scenePrompt.test.js, and the browser cannot import+// `server/lib`. Migrating it needs a client-side textUtils mirror first — #5790,+// which also deletes this entry. It is the ONLY exemption; do not add another+// without an issue that removes it.+const EXEMPT = ['lib/textUtils.js', 'lib/scenePrompt.js'];++describe('no private escapeRegExp', () => {+ it('leaves lib/textUtils.js as the only RegExp-escape implementation under server/', () => {+ const offenders = collectServerSources()+ .filter((rel) => !EXEMPT.includes(rel))+ .filter((rel) => {+ const source = readServerSource(rel);+ return ESCAPE_COPY.some((pattern) => pattern.test(source));+ });+ expect(+ offenders,+ `these re-inline the RegExp escape — import escapeRegExp from lib/textUtils.js instead: ${offenders.join(', ')}`+ ).toEqual([]);+ });+});diff --git a/server/lib/universeVisualStyle.js b/server/lib/universeVisualStyle.jsindex 8d13ab5821..4d23ce78b3 100644--- a/server/lib/universeVisualStyle.js+++ b/server/lib/universeVisualStyle.js@@ -23,6 +23,8 @@* there `styleNotes` is exactly the right context and stays included.*/+import { escapeRegExp } from './textUtils.js';+const tokenList = (values) => (Array.isArray(values) ? values : []).map((token) => (typeof token === 'string' ? token.trim() : '')).filter(Boolean);@@ -58,8 +60,6 @@ export function buildVisualStyleClause(universe, { override = '', mode = 'prepenreturn parts.filter(Boolean).join('. ');}-const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-/*** Remove a style clause the authored prompt already leads with.*diff --git a/server/services/assetMounts.js b/server/services/assetMounts.jsindex 11b054ece3..4ab3a4d10b 100644--- a/server/services/assetMounts.js+++ b/server/services/assetMounts.js@@ -19,6 +19,7 @@ import { PATHS } from '../lib/fileUtils.js';import { ServerError, sendErrorResponse } from '../lib/errorHandler.js';import { ASSET_ROUTE_PREFIXES, SERVER_OWNED_PREFIXES } from '../lib/assetRoutePrefixes.js';import { wrWorksDir } from './writersRoom/_shared.js';+import { escapeRegExp } from '../lib/textUtils.js';// `acceptRanges: true` is the serve-static default already, but we set it// explicitly because the federated peer-sync receiver@@ -107,7 +108,7 @@ function toRouteMatcher(pattern) {.map((segment) => {if (segment.startsWith(':')) return '[^/]+';if (segment === '*') return '.*';- return segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ return escapeRegExp(segment);}).join('/');const regex = new RegExp(`^${source}$`);diff --git a/server/services/catalogExtraction.js b/server/services/catalogExtraction.jsindex 0fe6d73723..9ff9cb02e3 100644--- a/server/services/catalogExtraction.js+++ b/server/services/catalogExtraction.js@@ -25,6 +25,7 @@ import { CATALOG_TYPES } from '../lib/catalogTypes.js';import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';import { catalogEvents } from './catalogEvents.js';import { getScrap, listChildScraps, listIngredientsForRef } from './catalogDB.js';+import { escapeRegExp } from '../lib/textUtils.js';// Light-shape ingredient type ids, sourced from the shared registry// (`extractionShape === 'light'`). Adding a light type to `catalogTypes.js`@@ -455,7 +456,7 @@ export async function scanProseForIngredientRefs(text, scope = {}) {// are user-controlled, so escape regex metacharacters; the \p{L}\p{N}// lookarounds keep multi-word phrases ("The Drowned Harbor") matching as a// unit while still treating the whole name as one token boundary-wise.- const esc = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const esc = escapeRegExp(needle);const re = new RegExp(`(?<![\\p{L}\\p{N}])${esc}(?![\\p{L}\\p{N}])`, 'iu');if (re.test(text)) matched.push(id);}diff --git a/server/services/digital-twin-avatar-bio.js b/server/services/digital-twin-avatar-bio.jsindex 78af8b012b..ded44b9ad4 100644--- a/server/services/digital-twin-avatar-bio.js+++ b/server/services/digital-twin-avatar-bio.js@@ -22,6 +22,7 @@ import { getGoals } from './identity.js';import { getProviderById } from './providers.js';import { estimateTokens, trimContextToBudget } from '../lib/contextBudget.js';import { tryReadFile } from '../lib/fileUtils.js';+import { escapeRegExp } from '../lib/textUtils.js';// Bio length presets. `blurb` is a single paragraph per section (avatar persona// fields are often short); `persona` is the balanced default; `knowledge` keeps@@ -112,7 +113,7 @@ function pullLabeledLine(md, label) {*/function extractSection(md, heading) {if (!md) return null;- const escaped = heading.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const escaped = escapeRegExp(heading);const headingRe = new RegExp(`^(#{2,3})\\s+${escaped}\\s*$`, 'i');const lines = md.split('\n');let start = -1;diff --git a/server/services/obsidian.js b/server/services/obsidian.jsindex db0f19c9c0..a462b9b75f 100644--- a/server/services/obsidian.js+++ b/server/services/obsidian.js@@ -12,6 +12,7 @@ import { join, relative, resolve, basename, dirname, extname, isAbsolute } fromimport { v4 as uuidv4 } from '../lib/uuid.js';import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';import { ICLOUD_NOT_MATERIALIZED, isSuspectedDataless, materializeAndWait, readIfMaterialized } from '../lib/icloudFile.js';+import { escapeRegExp } from '../lib/textUtils.js';const VAULTS_FILE = join(PATHS.brain, 'obsidian-vaults.json');@@ -479,7 +480,7 @@ export async function searchNotes(vaultId, query) {const results = [];const queryLower = query.toLowerCase();// Compile regex once for count matching- const countRe = new RegExp(escapeRegex(queryLower), 'g');+ const countRe = new RegExp(escapeRegExp(queryLower), 'g');const skipped = newSkipTally();await searchDir(vault.path, vault.path, queryLower, countRe, results, skipped);@@ -810,7 +811,3 @@ async function collectFolders(rootPath, currentPath, results) {}}}--function escapeRegex(str) {- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-}diff --git a/server/services/pipeline/audioMux.test.js b/server/services/pipeline/audioMux.test.jsindex 10df7e6306..ccc1e3c7df 100644--- a/server/services/pipeline/audioMux.test.js+++ b/server/services/pipeline/audioMux.test.js@@ -2,14 +2,10 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { mkdir, rm, writeFile } from 'fs/promises';import { join } from 'path';import { tmpdir } from 'os';+import { escapeRegExp } from '../../lib/textUtils.js';const TEST_HOME = join(tmpdir(), `portos-audiomux-test-${process.pid}-${Date.now()}`);-// Escape every RegExp metacharacter so a filesystem path can be spliced into a-// pattern literally. `\` and `]` are the two that matter most here: `\` is the-// Windows path separator, and a class that forgets to escape `]` closes itself-// early and silently stops escaping anything.-const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');const FAKE_MUSIC_DIR = join(TEST_HOME, 'music');vi.mock('../../lib/fileUtils.js', async () => {diff --git a/server/services/pipeline/manuscriptFix.js b/server/services/pipeline/manuscriptFix.jsindex a30b717748..c1e330e2b8 100644--- a/server/services/pipeline/manuscriptFix.js+++ b/server/services/pipeline/manuscriptFix.js@@ -19,6 +19,7 @@ import { getSeries, MANUSCRIPT_TYPES } from './series.js';import { getIssue, updateStageWithLatest, updateStagesWithLatest } from './issues.js';import { collectManuscriptSections, stageVersionsOf, sectionsCorpus, manuscriptSectionHeader } from './arcPlanner.js';import { getComment, updateComment } from './manuscriptReview.js';+import { escapeRegExp } from '../../lib/textUtils.js';export const ERR_VALIDATION = 'PIPELINE_MANUSCRIPT_FIX_VALIDATION';export const ERR_NOT_FOUND = 'PIPELINE_MANUSCRIPT_FIX_NOT_FOUND';@@ -231,7 +232,7 @@ function locateFind(text, find, anchorQuote) {// the matched { start, end } in the ORIGINAL text (so the splice covers the real// span, whose length may differ from `find.length`), or null if not found.function buildWhitespaceTolerantRegex(find) {- const escaped = find.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const escaped = escapeRegExp(find);return new RegExp(escaped.replace(/\s+/g, '\\s+'));}diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex d0c1da5690..84584f5b52 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -34,6 +34,7 @@ import { composeStyleNotes } from '../../lib/styleGuide.js';import { renderTickingClock } from '../../lib/storyArc.js';import { filterCanonForIssue } from '../../lib/storyBible.js';import { usableInputTokens, trimContextToBudget, CHARS_PER_TOKEN } from '../../lib/contextBudget.js';+import { escapeRegExp } from '../../lib/textUtils.js';const STAGE_TO_TEMPLATE = Object.freeze({idea: 'pipeline-idea-expansion',@@ -356,7 +357,7 @@ const PRINCIPAL_ROLE_RE = /\b(main|lead|protagonist|principal|recurring|primary|// also calls it).const wordInText = (needle, haystack) => {if (!needle) return false;- const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const escaped = escapeRegExp(needle);return new RegExp(`(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])`, 'iu').test(haystack);};@@ -378,7 +379,7 @@ const firstNameToken = (c) => {// team…") still matches — that's the safe over-inclusion direction.const properNounInText = (needle, haystack) => {if (!needle) return false;- const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const escaped = escapeRegExp(needle);const re = new RegExp(`(?<![\\p{L}\\p{N}_])${escaped}(?![\\p{L}\\p{N}_])`, 'giu');for (const m of String(haystack || '').matchAll(re)) {const ch = m[0][0];diff --git a/server/services/voice/tools/catalog.js b/server/services/voice/tools/catalog.jsindex 23656a9862..589147ffd2 100644--- a/server/services/voice/tools/catalog.js+++ b/server/services/voice/tools/catalog.js@@ -8,6 +8,7 @@import { listIngredients as listCatalogIngredients, listRefsForIngredient } from '../../catalogDB.js';import { getActiveCatalogTypes, isActiveType } from '../../../lib/catalogTypes.js';import { clampLimit } from './shared.js';+import { escapeRegExp } from '../../../lib/textUtils.js';// Creative catalog lookups — "find my character X", "what scenes feature Y",// "look up the place named Z", "search my catalog for …". Tight enough that@@ -30,10 +31,6 @@ const activeCatalogTypeIds = () => {// spec-builder to widen the static schema with user-defined types.export const catalogTypeEnum = () => activeCatalogTypeIds();-// Escape a freeform string (a user-type label can be anything) for safe use-// inside a `new RegExp(...)` so a label like "C++ faction" can't throw or inject.-const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');-// The static `catalog` regex only knows the six built-in nouns. A user-defined// type (e.g. "wardrobe", "faction") wouldn't trip it, so "search my wardrobes"// would never surface `catalog_lookup` (the enum-widening in catalogTypeEnum