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([issue-1840]): consolidate countWords into server/lib/textUtils.js

[._.]/ Adam Eivy8e04355c4210
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index d14d3e9e8b..8f433ffeb7 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -171,12 +171,13 @@ export function formatContextLength(tokens) {
}
/**
- * Count whitespace-separated words in a string. Matches the server-side
- * countWords in writers-room storage so client + server agree.
+ * Count whitespace-separated words in a string. Mirrors the canonical
+ * server-side `countWords` in `server/lib/textUtils.js` (the client cannot
+ * import from `server/`) so client + server word counts always agree.
*/
export function countWords(text) {
- if (!text) return 0;
- const m = String(text).trim().match(/\S+/g);
+ if (typeof text !== 'string') return 0;
+ const m = text.trim().match(/\S+/g);
return m ? m.length : 0;
}
diff --git a/server/lib/README.md b/server/lib/README.md
index 25d60119c5..5d4631304d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -207,6 +207,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `mediaItemKey.js` | `<kind>:<ref>` key vocabulary for media items. |
| `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 server-side prose helpers. `countWords(text)` — canonical whitespace-token count (`\S+`), the single home for what `writersRoom/local.js`, `issueLength.js`, and the client's `formatters.js` used to each re-implement. |
| `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. |
| `planIds.js` | Utilities for PLAN.md `[slug]` IDs. |
| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 6f474f9512..35fb829b23 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -187,6 +187,7 @@ export * from './pipelineIssueOrder.js';
export * from './planIds.js';
export * from './renderSlot.js';
export * from './telegramClient.js';
+export * from './textUtils.js';
// === Model & config ===
export * from './browserConfig.js';
diff --git a/server/lib/issueLength.js b/server/lib/issueLength.js
index 657efb262b..72fdaa67ee 100644
--- a/server/lib/issueLength.js
+++ b/server/lib/issueLength.js
@@ -22,6 +22,8 @@
* baseline so the upstream stages still have something concrete.
*/
+import { countWords } from './textUtils.js';
+
export const LENGTH_PROFILES = Object.freeze({
teaser: Object.freeze({
label: 'Teaser',
@@ -146,11 +148,6 @@ export function computeIssueTargets(issue = {}) {
// 44-page finale produced scope overrun into the next issue's climax.
export const THIN_SYNOPSIS_BASE_WORDS = 25;
-const countWords = (text) => {
- const trimmed = typeof text === 'string' ? text.trim() : '';
- return trimmed ? trimmed.split(/\s+/).length : 0;
-};
-
/**
* Assess whether an issue's synopsis (the idea-stage seed) is too thin for its
* length profile to expand without padding — the pressure that makes the beat
diff --git a/server/lib/textUtils.js b/server/lib/textUtils.js
new file mode 100644
index 0000000000..1f80b00049
--- /dev/null
+++ b/server/lib/textUtils.js
@@ -0,0 +1,26 @@
+// Shared, dependency-free text helpers for server-side prose analysis.
+//
+// `countWords` was previously re-implemented three times with subtly different
+// regexes (`server/services/writersRoom/local.js`, `server/lib/issueLength.js`,
+// and the client's `client/src/utils/formatters.js`). They all converge on the
+// same intent — count whitespace-delimited tokens — so this is the canonical
+// server-side home. The client copy (which cannot import from `server/`) mirrors
+// this exact semantics so client and server word counts always agree.
+
+/**
+ * Count whitespace-separated words in a string.
+ *
+ * Non-strings, `null`/`undefined`, and empty/whitespace-only input all return 0.
+ * Uses `\S+` matching (equivalent to splitting on `\s+` after a trim) so runs of
+ * mixed whitespace — spaces, tabs, newlines — collapse to a single delimiter.
+ * Non-string input returns 0 rather than being coerced, so a stray number can't
+ * masquerade as a one-word body.
+ *
+ * @param {unknown} text
+ * @returns {number}
+ */
+export function countWords(text) {
+ if (typeof text !== 'string') return 0;
+ const matches = text.trim().match(/\S+/g);
+ return matches ? matches.length : 0;
+}
diff --git a/server/lib/textUtils.test.js b/server/lib/textUtils.test.js
new file mode 100644
index 0000000000..3de85558d2
--- /dev/null
+++ b/server/lib/textUtils.test.js
@@ -0,0 +1,28 @@
+import { describe, it, expect } from 'vitest';
+import { countWords } from './textUtils.js';
+
+describe('countWords', () => {
+ it('counts whitespace-separated tokens', () => {
+ expect(countWords('one two three')).toBe(3);
+ expect(countWords('one')).toBe(1);
+ });
+
+ it('collapses runs of mixed whitespace', () => {
+ expect(countWords(' hello world ')).toBe(2);
+ expect(countWords('one two\nthree\tfour')).toBe(4);
+ });
+
+ it('treats hyphenates and contractions as single words', () => {
+ expect(countWords("don't stop now")).toBe(3);
+ expect(countWords('hyphen-ated counts once')).toBe(3);
+ });
+
+ it('returns 0 for empty, whitespace-only, and non-string input', () => {
+ expect(countWords('')).toBe(0);
+ expect(countWords(' ')).toBe(0);
+ expect(countWords(null)).toBe(0);
+ expect(countWords(undefined)).toBe(0);
+ expect(countWords(42)).toBe(0);
+ expect(countWords({})).toBe(0);
+ });
+});
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index ca3c996cc2..9074aa0347 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -17,6 +17,7 @@
import { randomUUID, createHash } from 'crypto';
import { readFile, rm } from 'fs/promises';
import { atomicWrite, ensureDir } from '../../lib/fileUtils.js';
+import { countWords } from '../../lib/textUtils.js';
import { WORK_KINDS, WORK_STATUSES } from '../../lib/writersRoomPresets.js';
import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';
import { nowIso, badRequest, notFound, wrWorkDir, wrDraftPath } from './_shared.js';
@@ -27,11 +28,10 @@ const store = () => writersRoomStore();
// ---------- text analysis ----------
-export function countWords(text) {
- if (!text) return 0;
- const matches = String(text).trim().match(/\S+/g);
- return matches ? matches.length : 0;
-}
+// `countWords` now lives in lib/textUtils.js (the canonical home that
+// issueLength.js and the editorial checks also share). Re-exported here so
+// existing importers of this module keep working unchanged.
+export { countWords };
export function contentHash(text) {
return createHash('sha256').update(text || '').digest('hex');