Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: share pipeline ID validation without changing accepted IDs (#7869)

[._.]/ Adam Eivy045291b03527
diff --git a/server/lib/README.md b/server/lib/README.md
index 130ef776e2..50f9473eab 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -541,6 +541,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `noReplaceMove.js` | `moveWithoutReplace(from, to)` — publish a staged file into its final name WITHOUT ever clobbering an existing one. `fs.rename` silently replaces its destination, which is the wrong default for a derived artifact; this uses `link(2)` + `unlink(2)`, so an existing destination fails atomically with `MOVE_DEST_EXISTS` and both files survive. Refuses rather than degrading when the filesystem cannot express it (`MOVE_CROSS_DEVICE`, `MOVE_NO_REPLACE_UNSUPPORTED`) — a `stat`-then-`rename` fallback would be a race. Used by the rigging publication contract (`services/rigging/autoSkin.js`). |
| `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. A pure leaf — `client/src/lib/personaTraitBlend.js` re-exports it for the Personas UI preview. |
| `textUtils.js` | Pure dependency-free prose helpers. `isStr(v)` and `isNonBlankStr(v)` are the ONLY string predicates under `server/` (#6837) — the bare type check, and type check plus a non-empty `trim()` for ids, keys, hosts, model names and prose fields where whitespace-only is already invalid; the "no private string predicate or bounder" guard in `textUtils.test.js` fails the suite when a copy of either, or a `trimTo`-shaped bounder, is re-declared in any non-test source under `server/` or any source under `client/src/` (`client/src/lib/textUtils.js` re-exports both for the browser bundle). `countWords(text)` is the canonical whitespace-token count (`\S+`) and the only one — every server word count (Writers Room, lettering density, rapid reader, autobiography, script-video beats) and the client's (`client/src/lib/textUtils.js` re-exports it) resolve here, and the "no private countWords" guard in `textUtils.test.js` fails the suite when a re-spelled count (the whitespace-token match, a split-and-filter, or a helper under either conventional name) reappears in any non-test source under `server/` or any source under `client/src/`; the editorial prose-analysis checks deliberately count LETTER words instead, through `editorial/proseTics.js#tokenizeWords`, which owns that tokenizer the same way; `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 (the sibling guard in `textUtils.test.js` fails the suite when a copy reappears in any non-test source under `server/`, or in ANY source under `client/src/`, tests and `.jsx` included — `client/src/lib/textUtils.js` re-exports this module for the browser bundle); `trimToClause(v, max)` is its boundary-aware twin for PROSE fields — it backs off to the last sentence terminator, then the last clause boundary, then the last whole word, so a capped field never ends mid-thought (it lives here rather than in `storyBible.js`, which re-exports it, so the pure story-model leaves the browser bundle shares can cap prose without pulling `crypto` / `fileUtils`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels), and `truncateOnBoundary(slug, max)` is its bounder — back off to the last `-` at or before `max` so a slug a human reads (a PLAN.md id, the app segment of a CoS worktree directory) is never cut mid-word, which `trimTo` would reintroduce; `clampToCharLimit(text, max)` is `trimTo`'s reader-facing twin — it cuts on a sentence end (when one sits 60%+ into the allowance) or a word boundary rather than mid-word and returns `{ text, truncated }` so the caller can say the text was cut, which is what bounds an AI-enhanced render prompt to a backend's hard cap (reactor.inc fast-h3 rejects an over-length prompt outright). `firstLine(text)` is the first non-blank line, trimmed — the CoS task headline `addTask` dedupes on, declared here rather than in the task store so a closure-sensitive caller can reach it (`cosTaskStore.js` re-exports it). |
+| `pipelineIds.js` | Shared `assertValidSeriesId` / `assertValidIssueId` path-segment guards for pipeline snapshots, preserving the safe charset and domain-specific errors. |
| `pipelineIssueOrder.js` | Volume-based renumbering and `compareIssuesInSeries` for globally ordered manuscripts and production. |
| `pipelineStages.js` | Canonical pipeline data-stage groups, visible tab order, UI/voice labels, spoken aliases, and derived voice-intent regex. |
| `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. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 3dfa2300d3..86eb0a43cc 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -524,6 +524,7 @@ export * from './providerRouteRecipes.js';
export * from './serviceDefinitions.js';
export * from './providerRouteSettings.js';
export * from './personaTraitBlend.js';
+export * from './pipelineIds.js';
export * from './pipelineIssueOrder.js';
export * from './pipelineStages.js';
export * from './postAdaptive.js';
diff --git a/server/lib/pipelineIds.js b/server/lib/pipelineIds.js
new file mode 100644
index 0000000000..b5a7179fef
--- /dev/null
+++ b/server/lib/pipelineIds.js
@@ -0,0 +1,15 @@
+// Path-segment guards for pipeline snapshots. Keep the historical safe charset:
+// these assertions do not require the stricter ser-/iss- prefixes used on import.
+const SAFE_ID = /^[a-zA-Z0-9_-]+$/;
+
+export function assertValidSeriesId(id) {
+ if (typeof id !== 'string' || !SAFE_ID.test(id)) {
+ throw new Error(`Invalid series id: ${id}`);
+ }
+}
+
+export function assertValidIssueId(id) {
+ if (typeof id !== 'string' || !SAFE_ID.test(id)) {
+ throw new Error(`Invalid issue id: ${id}`);
+ }
+}
diff --git a/server/services/pipeline/continuityBible.js b/server/services/pipeline/continuityBible.js
index 986b1d7346..eaad15a989 100644
--- a/server/services/pipeline/continuityBible.js
+++ b/server/services/pipeline/continuityBible.js
@@ -25,6 +25,7 @@
import { join } from 'path';
import { contentHash } from './contentHash.js';
+import { assertValidSeriesId } from '../../lib/pipelineIds.js';
import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { createKeyedFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { createSseRunner } from '../../lib/sseUtils.js';
@@ -74,14 +75,6 @@ const LEDGER_OUTPUT_RESERVE_TOKENS = 6_000;
const nowIso = () => new Date().toISOString();
-// Defense-in-depth: refuse path-traversal-shaped ids before they reach the
-// on-disk ledger path. Series ids are `ser-<uuid>` — restrict to a safe charset.
-function assertValidSeriesId(id) {
- if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
- throw new Error(`Invalid series id: ${id}`);
- }
-}
-
// ---------- per-series write tail ----------
const queueLedgerWrite = createKeyedFileWriteQueue();
diff --git a/server/services/pipeline/editorial/comparativeRank.js b/server/services/pipeline/editorial/comparativeRank.js
index cd212ddcad..942b8bbf0c 100644
Binary files a/server/services/pipeline/editorial/comparativeRank.js and b/server/services/pipeline/editorial/comparativeRank.js differ
diff --git a/server/services/pipeline/editorialAnalysis.js b/server/services/pipeline/editorialAnalysis.js
index 39defb951e..24f379ca91 100644
--- a/server/services/pipeline/editorialAnalysis.js
+++ b/server/services/pipeline/editorialAnalysis.js
@@ -17,6 +17,7 @@
import { join } from 'path';
import { contentHash } from './contentHash.js';
+import { assertValidIssueId } from '../../lib/pipelineIds.js';
import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
import { runStagedLLM, resolveStageContext } from '../stageRunner.js';
import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';
@@ -48,15 +49,6 @@ const ANALYSIS_OUTPUT_RESERVE_TOKENS = 4_000;
const nowIso = () => new Date().toISOString();
-// Defense-in-depth: refuse path-traversal-shaped ids before interpolating into
-// the on-disk snapshot path. Issue ids are `iss-<uuid>` — restrict to a safe
-// charset.
-function assertValidIssueId(id) {
- if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
- throw new Error(`Invalid issue id: ${id}`);
- }
-}
-
const editorialDir = () => join(PATHS.data, 'pipeline-editorial');
const snapshotPath = (issueId) => join(editorialDir(), `${issueId}.json`);
diff --git a/server/services/pipeline/editorialScore.js b/server/services/pipeline/editorialScore.js
index 1f49e4ebe9..97291d31b1 100644
--- a/server/services/pipeline/editorialScore.js
+++ b/server/services/pipeline/editorialScore.js
@@ -21,6 +21,7 @@
*/
import { join } from 'path';
+import { assertValidSeriesId } from '../../lib/pipelineIds.js';
import { PATHS, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { createKeyedFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { getReview } from './manuscriptReview.js';
@@ -55,15 +56,6 @@ const MAX_TREND_SNAPSHOTS = 100;
const nowIso = () => new Date().toISOString();
-// Defense-in-depth: refuse path-traversal-shaped ids before interpolating into
-// the on-disk ledger path. Series ids are `ser-<uuid>` — restrict to a safe
-// charset (mirrors editorialAnalysis.assertValidIssueId).
-function assertValidSeriesId(id) {
- if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
- throw new Error(`Invalid series id: ${id}`);
- }
-}
-
const healthDir = () => join(PATHS.data, 'pipeline-editorial-health');
const ledgerPath = (seriesId) => join(healthDir(), `${seriesId}.json`);
diff --git a/server/services/pipeline/foundationJudge.js b/server/services/pipeline/foundationJudge.js
index 765ed05e06..58aa0ce638 100644
--- a/server/services/pipeline/foundationJudge.js
+++ b/server/services/pipeline/foundationJudge.js
@@ -36,6 +36,7 @@
*/
import { join } from 'path';
+import { assertValidSeriesId } from '../../lib/pipelineIds.js';
import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
import { runStagedLLM, resolveStageContext, resolveJudgeForStage } from '../stageRunner.js';
import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';
@@ -165,14 +166,6 @@ function formatArcBlockerProfile(findings) {
return `${profile.total} blocker(s): ${profile.high} high, ${profile.medium} medium, ${profile.low} low`;
}
-// Defense-in-depth: refuse path-traversal-shaped ids before interpolating into
-// the on-disk snapshot path (series ids are `ser-<uuid>`).
-function assertValidSeriesId(id) {
- if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
- throw new Error(`Invalid series id: ${id}`);
- }
-}
-
const foundationDir = () => join(PATHS.data, 'pipeline-foundation-judge');
const snapshotPath = (seriesId) => join(foundationDir(), `${seriesId}.json`);
diff --git a/server/services/pipeline/issuesShared.js b/server/services/pipeline/issuesShared.js
index 7cc406b8c4..fa2efe3225 100644
--- a/server/services/pipeline/issuesShared.js
+++ b/server/services/pipeline/issuesShared.js
@@ -18,6 +18,8 @@
* data/pipeline-issues/{id}/index.json (PG-backed via the store facade).
*/
+export { assertValidIssueId } from '../../lib/pipelineIds.js';
+
import { getIssuesStore, stripRunHistoryFromIssue } from './issuesStore/store.js';
import { createKeyCachedQueue } from '../../lib/createKeyCachedQueue.js';
import { IMAGE_GEN_MODE, QUEUEABLE_IMAGE_MODES } from '../imageGen/modes.js';
diff --git a/server/services/pipeline/perspectiveRewrite.js b/server/services/pipeline/perspectiveRewrite.js
index 32e279d728..9cdffad8c9 100644
--- a/server/services/pipeline/perspectiveRewrite.js
+++ b/server/services/pipeline/perspectiveRewrite.js
@@ -21,6 +21,7 @@
import { join } from 'path';
import { randomUUID } from 'crypto';
import { contentHash } from './contentHash.js';
+import { assertValidIssueId } from '../../lib/pipelineIds.js';
import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
import { createKeyedFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { runStagedLLM, resolveStageContext } from '../stageRunner.js';
@@ -66,14 +67,6 @@ const clampNum = (v, min, max, fallback = 0) => {
return Math.max(min, Math.min(max, Math.round(n)));
};
-// Defense-in-depth: refuse path-traversal-shaped ids before interpolating into
-// the on-disk path. Issue ids are `iss-<uuid>` — restrict to a safe charset.
-function assertValidIssueId(id) {
- if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
- throw new Error(`Invalid issue id: ${id}`);
- }
-}
-
const rewritesDir = () => join(PATHS.data, 'pipeline-pov-rewrites');
const docPath = (issueId) => join(rewritesDir(), `${issueId}.json`);
diff --git a/server/services/pipeline/pipelineJudge.js b/server/services/pipeline/pipelineJudge.js
index 4f26856eee..966dc2fe04 100644
--- a/server/services/pipeline/pipelineJudge.js
+++ b/server/services/pipeline/pipelineJudge.js
@@ -29,6 +29,7 @@
import { join } from 'path';
import { contentHash } from './contentHash.js';
+import { assertValidIssueId } from '../../lib/pipelineIds.js';
import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
import { runStagedLLM, resolveStageContext, resolveJudgeForStage } from '../stageRunner.js';
import { manuscriptContentBudgetChars, estimateTokens } from '../../lib/contextBudget.js';
@@ -82,14 +83,6 @@ const JUDGE_OUTPUT_RESERVE_TOKENS = 2_500;
const nowIso = () => new Date().toISOString();
-// Defense-in-depth: refuse path-traversal-shaped ids before interpolating into
-// the on-disk snapshot path (issue ids are `iss-<uuid>`).
-function assertValidIssueId(id) {
- if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
- throw new Error(`Invalid issue id: ${id}`);
- }
-}
-
const judgeDir = () => join(PATHS.data, 'pipeline-judge');
const snapshotPath = (issueId) => join(judgeDir(), `${issueId}.json`);
diff --git a/server/services/pipeline/readerPanel.js b/server/services/pipeline/readerPanel.js
index d5c69c575e..b855f990ab 100644
--- a/server/services/pipeline/readerPanel.js
+++ b/server/services/pipeline/readerPanel.js
@@ -20,6 +20,7 @@
import { join } from 'path';
import { rm } from 'fs/promises';
+import { assertValidSeriesId } from '../../lib/pipelineIds.js';
import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../../lib/fileUtils.js';
import { runStagedLLM } from '../stageRunner.js';
import {
@@ -34,14 +35,6 @@ import { seedReviewFromFindings } from './manuscriptReview.js';
const CONSENSUS_CHECK_ID = 'reader-panel.consensus';
const nowIso = () => new Date().toISOString();
-// Series ids are `ser-<uuid>` — restrict to a safe charset before interpolating
-// into the on-disk snapshot path (defense-in-depth against path traversal).
-function assertValidSeriesId(id) {
- if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
- throw new Error(`Invalid series id: ${id}`);
- }
-}
-
const panelDir = () => join(PATHS.data, 'pipeline-reader-panel');
const snapshotPath = (seriesId) => join(panelDir(), `${seriesId}.json`);
diff --git a/server/services/pipeline/reverseOutline.js b/server/services/pipeline/reverseOutline.js
index 35832b73a4..9770f5a0fd 100644
--- a/server/services/pipeline/reverseOutline.js
+++ b/server/services/pipeline/reverseOutline.js
@@ -22,6 +22,7 @@
import { join } from 'path';
import { contentHash } from './contentHash.js';
+import { assertValidSeriesId } from '../../lib/pipelineIds.js';
import { atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { createKeyedFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { createSseRunner } from '../../lib/sseUtils.js';
@@ -87,14 +88,6 @@ const UNASSIGNED_PLOTLINE = Object.freeze({ id: '_unassigned', label: 'Unassigne
const nowIso = () => new Date().toISOString();
const colorForIndex = (i) => PLOTLINE_COLORS[i % PLOTLINE_COLORS.length];
-// Defense-in-depth: refuse path-traversal-shaped ids before they reach the
-// on-disk outline path. Series ids are `ser-<uuid>` — restrict to a safe charset.
-function assertValidSeriesId(id) {
- if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
- throw new Error(`Invalid series id: ${id}`);
- }
-}
-
// ---------- per-series write tail ----------
const queueOutlineWrite = createKeyedFileWriteQueue();
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index ab689ee9dd..7102b6fc03 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -11,6 +11,8 @@
* collection (server/services/pipeline/issues.js) and reference a series by id.
*/
+export { assertValidSeriesId } from '../../lib/pipelineIds.js';
+
import { randomUUID } from 'crypto';
import { getSeriesStore } from './seriesStore/store.js';
import { sanitizeArc, sanitizeSeasonList, sanitizeSeriesDesign } from '../../lib/storyArc.js';
diff --git a/server/services/pipeline/seriesAutopilotBarrel.test.js b/server/services/pipeline/seriesAutopilotBarrel.test.js
index cf7a2cccdf..bf1dc6be3d 100644
--- a/server/services/pipeline/seriesAutopilotBarrel.test.js
+++ b/server/services/pipeline/seriesAutopilotBarrel.test.js
@@ -31,7 +31,7 @@ describe('seriesAutopilot barrel re-exports (issue #2842)', () => {
});
it.each(MODULE_FILES)('%s exports are reachable from the barrel as the same objects', async (f) => {
- const mod = await import(`./seriesAutopilot/${f}`);
+ const mod = await import(`./seriesAutopilot/${f.slice(0, -3)}.js`);
const keys = Object.keys(mod);
expect(keys.length, `${f} exports nothing`).toBeGreaterThan(0);
for (const key of keys) {
@@ -43,7 +43,7 @@ describe('seriesAutopilot barrel re-exports (issue #2842)', () => {
const seen = new Map();
const collisions = [];
for (const f of MODULE_FILES) {
- const mod = await import(`./seriesAutopilot/${f}`);
+ const mod = await import(`./seriesAutopilot/${f.slice(0, -3)}.js`);
for (const key of Object.keys(mod)) {
if (seen.has(key) && seen.get(key).value !== mod[key]) {
collisions.push(`${key}: ${seen.get(key).file} vs ${f}`);
diff --git a/server/services/pipeline/seriesReview.js b/server/services/pipeline/seriesReview.js
index 3292a242de..9869f21b0d 100644
--- a/server/services/pipeline/seriesReview.js
+++ b/server/services/pipeline/seriesReview.js
@@ -40,6 +40,7 @@
import { join } from 'path';
import { unlink } from 'fs/promises';
+import { assertValidSeriesId } from '../../lib/pipelineIds.js';
import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse, sha256Text } from '../../lib/fileUtils.js';
import { canonicalStringify } from '../../lib/objects.js';
import { createSseRunner } from '../../lib/sseUtils.js';
@@ -69,15 +70,6 @@ const FEEDBACK_MAX = 4000;
const nowIso = () => new Date().toISOString();
-// Defense-in-depth: refuse path-traversal-shaped ids before interpolating into
-// the on-disk snapshot path (series ids are `ser-<uuid>`). Mirrors the sibling
-// pipeline services.
-function assertValidSeriesId(id) {
- if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]+$/.test(id)) {
- throw new Error(`Invalid series id: ${id}`);
- }
-}
-
const reviewDir = () => join(PATHS.data, 'pipeline-series-review');
const snapshotPath = (seriesId) => join(reviewDir(), `${seriesId}.json`);