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
collapse ten re-spelled word counts onto textUtils.countWords and the editorial letter-word tokenizer onto proseTics.tokenizeWords
[._.]/ Adam Eivyd501bef5cf67
diff --git a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx b/client/src/components/digital-twin/tabs/AutobiographyTab.jsxindex 1bdb270e15..f43b8f28b4 100644--- a/client/src/components/digital-twin/tabs/AutobiographyTab.jsx+++ b/client/src/components/digital-twin/tabs/AutobiographyTab.jsx@@ -19,6 +19,7 @@ import BrailleSpinner from '../../BrailleSpinner';import InlineConfirmRow from '../../ui/InlineConfirmRow';import * as api from '../../../services/api';import { copyToClipboard } from '../../../lib/clipboard';+import { countWords } from '../../../lib/textUtils';import toast from '../../ui/Toast';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';import { formatDateTime, formatDateNumeric } from '../../../utils/formatters';@@ -220,7 +221,7 @@ export default function AutobiographyTab({ onRefresh }) {}};- const wordCount = storyContent.split(/\s+/).filter(Boolean).length;+ const wordCount = countWords(storyContent);if (loading) {return (diff --git a/client/src/components/writers-room/ExercisePanel.jsx b/client/src/components/writers-room/ExercisePanel.jsxindex 0486aa44f6..0c1102ea0c 100644--- a/client/src/components/writers-room/ExercisePanel.jsx+++ b/client/src/components/writers-room/ExercisePanel.jsx@@ -8,7 +8,8 @@ import {discardWritersRoomExercise,promoteWritersRoomExercise,} from '../../services/apiWritersRoom';-import { countWords, formatCountdown } from '../../utils/formatters';+import { formatCountdown } from '../../utils/formatters';+import { countWords } from '../../lib/textUtils';import { FormField } from '../ui/FormField';import useMounted from '../../hooks/useMounted';diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex 5e9ae335eb..3dd6fec67e 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -46,7 +46,8 @@ import {} from '../../services/apiWritersRoom';import { safeReadStorage, safeWriteStorage } from '../../lib/safeStorage';import { STATUS_LABELS } from './labels';-import { countWords, formatDurationSec } from '../../utils/formatters';+import { formatDurationSec } from '../../utils/formatters';+import { countWords } from '../../lib/textUtils';import StoryboardPanel, { STORYBOARD_TAB, STORYBOARD_TAB_VALUES } from './StoryboardPanel';import LiveContinuationPanel from './LiveContinuationPanel';import LiveRenderPanel from './LiveRenderPanel';diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex b0dfaa1d2c..e357bf6ce6 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -147,7 +147,7 @@ grep -i "what you want to do" client/src/lib/README.md| `kanbanColumns.js` | `bucketTickets` / `ticketInColumn` / `columnConfig` / `FALLBACK_COLUMNS` — pure column logic for the Jira Kanban board (`components/KanbanBoard.jsx`). Buckets tickets into resolved workflow columns (by status name, or statusCategory for the fallback board), assigns each column a stable unique `id` (Jira `name` is not unique — same-named columns map to different statuses), appends an orphan column for any unmatched status, and precomputes per-column Tailwind color config (Blocked→red, Review/QA→purple, else by category). || `localLlmBackends.js` | `LOCAL_LLM_BACKENDS` (id/label/lucide icon for Ollama + LM Studio) and `localLlmBackendLabel(id)`. The two backends PortOS keeps a model catalog for, shared by the Runtimes view's backend cards and the Model Library's backend picker so a third backend is added in one place. Exported under qualified names because the barrel is flat and `BACKENDS`/`labelFor` are too generic to claim there. || `localLlmTargetKey.js` | `localLlmTargetKey({ backend, modelId })` — stable string key for a local-LLM compare target. Shared by the LocalLlmTab checkbox grid and the LocalLlmPlayground compare URL so a delimiter change can't desync the round-trip. |-| `letteringDensity.js` | Re-export of `server/lib/editorial/letteringDensity.js` — `analyzeComicLettering` / `panelLetteringMetrics` / `countWords` / `overflowSeverity` / `sanitizeLetteringThresholds` / `DEFAULT_LETTERING_THRESHOLDS`. Powers the comic-script stage's INLINE per-page warnings (#1313) from the same code the authoritative `comic.lettering-density` check runs. |+| `letteringDensity.js` | Re-export of `server/lib/editorial/letteringDensity.js` — `analyzeComicLettering` / `panelLetteringMetrics` / `overflowSeverity` / `sanitizeLetteringThresholds` / `DEFAULT_LETTERING_THRESHOLDS`. Powers the comic-script stage's INLINE per-page warnings (#1313) from the same code the authoritative `comic.lettering-density` check runs. || `loomLayout.js` | FableLoom canvas layout — `layoutLoomGraph(episode, { viewportWidth, orientation })` (BFS + barycenter-ordered positions, persisted `pos` overrides on left-to-right only, orthogonal port-fanned edges, canvas extents), `pickLoomOrientation` (stacks top-to-bottom under `LOOM_STACK_WIDTH` when orientation is not pinned), `loomGraphLayers`, `routeLoomEdges` (forward edges in packed gap lanes; backward/skip edges around the card band), `placeEdgeLabels` (de-collides intent labels), `loomEdgePath(from, to, { laneY, self, orientation })`, `LOOM_NODE_W`/`LOOM_NODE_H`/`LOOM_EDGE_LABEL_MAX`/`LOOM_ORIENTATION`/`LOOM_STACK_WIDTH`. A view-layer layering (shows unreachable nodes in trailing columns), deliberately NOT a mirror of the server's analysis-oriented `computeGraphLayers`. Pure/DOM-free. || `loopbackHost.js` | `isLoopbackHost(host)` / `isLoopbackOrigin()` / `describeMicAvailability()` — Secure Context / loopback-origin heuristics. Use these in any new mic, clipboard, or `getUserMedia`-gated surface; matches the full `127.0.0.0/8` range, IPv6 `::1`, and the browser-bracketed `[::1]` form. || `manuscriptAnchors.js` | `locateFind` / `locateAnchors` / `buildHighlightSegments` — resolve editorial-comment `anchorQuote`s to spans in manuscript text and tile the text into plain + highlighted (severity-toned) segments for the Manuscript editor's in-context feedback. Mirrors the nearest-occurrence `locateFind` in `server/services/pipeline/manuscriptFix.js`. |@@ -226,7 +226,7 @@ grep -i "what you want to do" client/src/lib/README.md| `terminalDictation.js` | Voice-dictation/IME bridge for the Shell's xterm.js terminal. Apple dictation streams progressively refined guesses and *replaces* what it already typed; xterm forwards each insertion and drops the matching deletions, so the PTY accumulates a garble (`determin` + `determine` + `determines`…). `attachDictationBridge(terminal, sendData)` binds capture-phase listeners on `terminal.element` — ahead of xterm's own textarea listeners, which it stops — and forwards a diff instead: `TERMINAL_DEL` (`0x7f`) per dropped character, then the added text. `sendData` returns `false` to report a dropped send, which leaves the mirror where the PTY actually is. Paths that reach the PTY some other way (a keystroke xterm handles itself, paste, blur, composition end, screen-reader mode) resync the mirror without emitting. `planFieldEdit(mirror, next, floor)` → `{ data, committed }` is the pure core: `floor` is the prefix we did not write and must never rewind through, and `committed` (what the PTY holds afterward, which is *not* the field's value when the floor blocked a rewind) is what the caller must track. The prefix scan never splits a surrogate pair — cutting between the halves of an astral character would send a lone surrogate that serializes to `U+FFFD`. Wired in `useShellSession`; the test suite pins the seam against a real `Terminal`. || `terminalScroll.js` | Scrolling the Shell terminal by touch, wheel, and page controls. xterm 6 binds **no touch handlers at all**, and a TUI’s ALTERNATE screen buffer has no terminal scrollback, so `scrollLines()` clamps to a no-op there. Normal shell scrollback uses `scrollLines()`; alternate-screen wheel gestures are captured before xterm’s mouse listener and translated to standard PageUp/PageDown input, which OpenCode supports for its message viewport, while apps that explicitly enable terminal mouse tracking keep xterm’s native wheel path. `attachTerminalTouchScroll(terminal)` (→ detach fn) makes a one-finger drag scroll in either buffer, `attachTerminalWheelScroll(terminal)` handles native wheel input, and `scrollTerminalPage(terminal, direction)` powers the `SCROLL_KEYS` buttons. `measureTerminalGeometry(terminal)` takes one layout read per gesture; `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession`. || `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. |-| `textUtils.js` | `escapeRegExp(value)` re-exported from `server/lib/textUtils.js` — the one member the bundle has a caller for. Named export only, so the server's `countWords` does not collide with the one in `utils/formatters.js`. |+| `textUtils.js` | `escapeRegExp(value)` and `countWords(text)` re-exported from `server/lib/textUtils.js` — the two members the bundle has callers for (the Writers Room editor and exercise panel and the autobiography tab count words with the same `\S+` rule the server stores). Named exports rather than `export *`, so the file stays the list of what the browser actually uses. || `threejsAnimation.js` | Pure pose evaluator for the declarative clip contract in `server/lib/threejsModel.js`, used by the Three.js Models preview transport. `evaluateThreejsClipPose(clip, timeSeconds)` → `{ timeSeconds, pose, activeSequenceIds, activePartIds }` where `pose` is a null-prototype partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }` map: each part+channel resolves from the one sequence that owns the instant (the window containing it, else the most recent behind it, else the next ahead), `visible` steps at the window's end rather than interpolating, and a part no sequence drives is absent so the spec renders as authored. `collectThreejsCues(clip, from, to)` returns the data-only sound cues a play loop crossed in the half-open `[from, to)` interval — a scrub calls it never, which is what makes scrubbing silent. `listThreejsClips` / `listThreejsCues` / `resolveThreejsClip` / `getThreejsClipDuration` read a spec that may have no `animation` key at all. || `threejsEnvironment.js` | Image-based lighting for the procedural sculpt spec, used by the Three.js Models preview. `spec.lights` are punctual — they light a surface but give it nothing to REFLECT, so `metalness`, `transmission`, `clearcoat` and `iridescence` read off an environment or read off nothing, and a plausible conductor renders near-black without one. `createSculptEnvironmentTarget(renderer, preset)` builds a preset locally from three's own primitives and prefilters it through `PMREMGenerator` — `neutral` is three's bundled `RoomEnvironment`, `studio` a dark shell with three emissive softbox panels plus a floor bounce — returning null for `none`; the caller owns the render TARGET and disposes it (disposing only `.texture` leaks the framebuffer behind it). `THREEJS_RENDER_PROFILE` mirrors the server's colour-space/tone-map/exposure contract so the preview renders at what the export stamps on the model. Deliberately NOT drei's `<Environment preset=…>`, which fetches an HDR from a CDN: rendering a local model makes no outbound request. `resolveSculptEnvironment(spec)` is the client mirror of `resolveThreejsEnvironment` in `server/lib/threejsModel.js`, reading a spec with no `environment` key as the `none` it was actually authored against. || `threejsExplode.js` | Disassembly + part-picking maths for the procedural sculpt spec, shared by the Three.js Models preview so explode and the picker agree on what "a part" is. `computeExplodeLayout(parts, amount)` → `{ offsets, meshOffsets, unitIds, growth }`: separation is a layout **scale about the model centre** (≈2× at full explode) plus a base clearance for parts sitting at the centre — never a uniform outward push, which slides the arrangement without opening gaps — where `offsets` add to a unit's own `position` and `meshOffsets` apply to a group around a container's own geometry (moving its group instead would drag its child units along), and `growth` measures how much the layout actually grew so the camera re-fits on real change. `buildPartSelectionIndex(parts)` → `{ owners, ancestry, names }` for click resolution, subtree highlight, and the selection label. All maps are null-prototype — part ids are provider-authored and `idSchema` accepts `toString`. `isReliefPart` / `isContainerPart` expose the shared part definition: a part flagged `explodeWithParent` is surface relief that rides its parent and resolves selection up to it (unless it has no parent to ride), every other geometry-bearing part is both a movable unit and a selectable component, a part whose descendants carry geometry is additionally descended through, and a part with no geometry in its subtree moves nothing. |diff --git a/client/src/lib/letteringDensity.js b/client/src/lib/letteringDensity.jsindex b5e57e9a94..4995c66e4d 100644--- a/client/src/lib/letteringDensity.js+++ b/client/src/lib/letteringDensity.js@@ -9,7 +9,6 @@ export {DEFAULT_LETTERING_THRESHOLDS,LETTERING_SEVERITIES,analyzeComicLettering,- countWords,overflowSeverity,panelLetteringMetrics,sanitizeLetteringThresholds,diff --git a/client/src/lib/letteringDensity.test.js b/client/src/lib/letteringDensity.test.jsindex 3d61c878a0..b243aae1c3 100644--- a/client/src/lib/letteringDensity.test.js+++ b/client/src/lib/letteringDensity.test.js@@ -1,6 +1,5 @@import { describe, it, expect } from 'vitest';import {- countWords,overflowSeverity,panelLetteringMetrics,analyzeComicLettering,@@ -13,11 +12,6 @@ import {const balloon = (character, n) => ({ character, line: Array.from({ length: n }, (_, i) => `w${i}`).join(' ') });describe('letteringDensity (client mirror)', () => {- it('countWords counts whitespace tokens, 0 for non-strings', () => {- expect(countWords('one two three')).toBe(3);- expect(countWords(null)).toBe(0);- });-it('overflowSeverity scales by overflow ratio', () => {expect(overflowSeverity(26, 25)).toBe('low');expect(overflowSeverity(35, 25)).toBe('medium');diff --git a/client/src/lib/textUtils.js b/client/src/lib/textUtils.jsindex 5a67bbf78a..48ab9b7e3e 100644--- a/client/src/lib/textUtils.js+++ b/client/src/lib/textUtils.js@@ -1,11 +1,12 @@/**- * The RegExp escape, from the module that owns it on both sides.+ * Pure prose helpers, from the module that owns them on both sides.*- * Only `escapeRegExp` is re-exported — it is the only member the browser bundle- * has a caller for, and a flat `export *` would put the server’s `countWords`- * in the client barrel beside the one in `utils/formatters.js`.- *- * Imported rather than copied so the two runtimes cannot drift; the file stays so- * every `lib/textUtils` import path in the client is unchanged.+ * `escapeRegExp` and `countWords` are named re-exports of+ * `server/lib/textUtils.js` — imported rather than copied so the two runtimes+ * cannot drift: the word count the Writers Room and autobiography editors show+ * beside a draft is the same `\S+` rule the server stores for it. Named rather+ * than `export *` so this file stays the list of what the browser bundle has a+ * caller for; the file itself stays so every `lib/textUtils` import path in the+ * client is unchanged.*/-export { escapeRegExp } from '../../../server/lib/textUtils.js';+export { countWords, escapeRegExp } from '../../../server/lib/textUtils.js';diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 359362ca08..1bb0ee30d4 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -22,7 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md| Module | Purpose ||---|---|-| `formatters` | Date/time/duration/byte/word formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `formatCompactCountOrDash` (same, but an ABSENT count renders "—" rather than "0"), `timeAgo`, `formatAgeDays` (age in whole DAYS — "412 days ago" — where `timeAgo` would collapse to "1y ago"; model-download lists), `localDateKey` (browser-local `YYYY-MM-DD`), `shiftISODate` (DST-safe calendar-day shifts), `formatTimecode`, `formatDurationMs`, `formatDateShort`, `formatContextTokens` (suffix-less context length, "4K"), `throughputLabel` (a measured model's speed as one label — tok/s where the runtime reported token counts, `~` prefixed when frame-counted, else chars/s; never both), `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. `formatHourOfDay` renders a bare hour-of-day number (0-23) as a 12-hour label in one of four styles (`long` "3 PM", `compact` "3PM", `tiny` "3p", `lower` "3pm") — the canonical home for what five components each hand-rolled, so the same 3pm no longer renders four ways across screens. Date display helpers anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |+| `formatters` | Date/time/duration/byte formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `formatCompactCountOrDash` (same, but an ABSENT count renders "—" rather than "0"), `timeAgo`, `formatAgeDays` (age in whole DAYS — "412 days ago" — where `timeAgo` would collapse to "1y ago"; model-download lists), `localDateKey` (browser-local `YYYY-MM-DD`), `shiftISODate` (DST-safe calendar-day shifts), `formatTimecode`, `formatDurationMs`, `formatDateShort`, `formatContextTokens` (suffix-less context length, "4K"), `throughputLabel` (a measured model's speed as one label — tok/s where the runtime reported token counts, `~` prefixed when frame-counted, else chars/s; never both), `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. `formatHourOfDay` renders a bare hour-of-day number (0-23) as a 12-hour label in one of four styles (`long` "3 PM", `compact` "3PM", `tiny` "3p", `lower` "3pm") — the canonical home for what five components each hand-rolled, so the same 3pm no longer renders four ways across screens. Date display helpers anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". || `cronHelpers` | Cron preset list, friendly cron parsing/building, anchored recurrence parsing/building/description, `isCronExpression` detection, `describeCron` human-readable rendering, `cronFromIntervalMs` numeric-interval → expression conversion (mirrors the server helper), and `JOB_INTERVAL_OPTIONS` / `ON_DEMAND_INTERVAL` — the interval-mode cadences for autonomous jobs, mirroring the server's `INTERVAL_OPTIONS` (`on-demand` = stays enabled and manually runnable, but arms no timer). Import it rather than re-declaring the list in a scheduling component. || `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. || `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex f820ce85f6..885e0e22e1 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -534,17 +534,6 @@ export function throughputLabel(perf) {return typeof chars === 'number' && Number.isFinite(chars) ? `${chars} chars/s` : null;}-/**- * 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 (typeof text !== 'string') return 0;- const m = text.trim().match(/\S+/g);- return m ? m.length : 0;-}-/*** Format a number of seconds as MM:SS (e.g. 75 → "01:15"), or H:MM:SS once the* total reaches an hour (e.g. 3661 → "1:01:01"). Used for sprint timers anddiff --git a/server/lib/README.md b/server/lib/README.mdindex 6433abdfa8..e9e738a8b6 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -449,7 +449,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. || `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. `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 in any non-test source under `server/`, or in ANY source under `client/src/`, tests and `.jsx` included — the escape half is mirrored on the client at `client/src/lib/textUtils.js`, which the browser imports since it cannot reach `server/lib`); `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); `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). |+| `textUtils.js` | Pure dependency-free prose helpers. `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); `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). || `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/README.md b/server/lib/editorial/README.mdindex abbbdb1566..fadb7ba178 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -214,14 +214,14 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of| `nameSimilarity.js` | Pure, dependency-free name-confusability primitives for `naming.dissimilar-names` (#1291): `normalizeName`, `vowelSkeleton`, `soundex` (phonetic key), `levenshtein` (edit distance), `nameSimilaritySignals` (the per-pair signal list, with option toggles), and `firstLetterHistogram` / `findFirstLetterClusters` (cast first-letter crowding). || `cliches.js` | Pure, dependency-free cliché + overwriting primitives for `prose.cliches` and `prose.modifier-stacking` (#1308): `CLICHE_PHRASES` (seed stock-simile/idiom list), `findCliches` (whole-word phrase scan with house-style allow/extra lists), and `findModifierStacking` (cumulative no-comma runs of 3+ stacked adjectives/adverbs). The LLM sibling `prose.dead-metaphor` handles the judgment cases (mixed/dead metaphor, novel clichés, purple prose). || `italicThoughts.js` | Pure, dependency-free italic-thought primitive for `prose.italic-thoughts` (#1300): `findItalicThoughts` (multi-word markdown `*…*` / `_…_` italic runs, dedup + word-count threshold so single-word emphasis, bold, and `snake_case` are skipped). The LLM siblings (`opening.wrong-start`, `prose.mirror-description`, `dialogue.pleasantries`, `prose.kill-your-darlings`) handle the judgment cases in the #1300 anti-pattern bundle. |-| `proseTics.js` | Pure, dependency-free copy-edit prose-tic primitives for the #1306 line-edit group: `tokenizeWords` / `splitSentences` (shared tokenization), `findFilterWords` (`prose.filter-words`), `findHedgeWords` (`prose.hedge-words` — hedge/weasel distance markers: metaphorical distance, dialogue hedges, cognitive weasel words), `findCrutchWords` (`prose.crutch-words`), `findAdverbs` (`prose.adverbs` — `-ly` adverbs + dialogue-tag adverbs), `findPassiveVoice` (`prose.passive-voice` — be-verb + past-participle heuristic; classifies each hit `weak`/`stative`/`mood` + `byAgent` so #1593 context tuning can suppress intentional passive) and its `filterPassiveVoice` companion (drops `stative` predicate-adjectives + `mood` setting images unless `suppressIntentional` is off), `findGestures` (`prose.repeated-gestures` — gesture tally + body-part autonomy), plus the seed `FILTER_WORDS` / `HEDGE_WORDS` / `CRUTCH_WORDS` / `GESTURE_WORDS` lists. The LLM sibling `prose.telling-emotion` handles the named-emotion judgment case. |+| `proseTics.js` | Pure, dependency-free copy-edit prose-tic primitives for the #1306 line-edit group: `tokenizeWords` / `splitSentences` (the ONE prose-word tokenizer — `tokenizeWords(text).length` is the letter-word count every density rate, rhythm metric and slop score shares, distinct on purpose from `lib/textUtils.js#countWords`; `proseTics.test.js` fails the suite when the character class is re-spelled elsewhere under server/), `findFilterWords` (`prose.filter-words`), `findHedgeWords` (`prose.hedge-words` — hedge/weasel distance markers: metaphorical distance, dialogue hedges, cognitive weasel words), `findCrutchWords` (`prose.crutch-words`), `findAdverbs` (`prose.adverbs` — `-ly` adverbs + dialogue-tag adverbs), `findPassiveVoice` (`prose.passive-voice` — be-verb + past-participle heuristic; classifies each hit `weak`/`stative`/`mood` + `byAgent` so #1593 context tuning can suppress intentional passive) and its `filterPassiveVoice` companion (drops `stative` predicate-adjectives + `mood` setting images unless `suppressIntentional` is off), `findGestures` (`prose.repeated-gestures` — gesture tally + body-part autonomy), plus the seed `FILTER_WORDS` / `HEDGE_WORDS` / `CRUTCH_WORDS` / `GESTURE_WORDS` lists. The LLM sibling `prose.telling-emotion` handles the named-emotion judgment case. || `repetition.js` | Pure, dependency-free word-echo & rhythm primitives for #1306: `findWordEchoes` (`prose.word-echoes` — distinctive word repeated within a window), `findRepeatedOpeners` (runs of sentences sharing an opener, "He… He… He…"), and `measureSentenceRhythm` (`prose.sentence-rhythm` — sentence-length variation). Reuses `tokenizeWords` / `splitSentences` from `proseTics.js`. || `slopScore.js` | Pure, dependency-free deterministic "AI slop" scoring primitives for #2165 (CWQE Phase 1) — EXTENDS proseTics.js/cliches.js/repetition.js rather than duplicating them: tiered banned-word scanners (`findBannedWordsTier1` hard-ban, `findSuspiciousWordClusters` Tier 2 cluster-of-3+) backing `prose.slop-banned-words`; fiction AI-tell idiom regexes (`findAiTells`) backing `prose.ai-tells`; rhetorical structural-tic detectors (`findNotJustButPatterns`, `findNotSayingPatterns`, `findNegativeAssertions`, `findTheWaySimiles`, `findTriadicShortSentences`, combined by `findStructuralTics`) backing `prose.structural-tics`; and quantitative burstiness signals (`emDashDensityPer1000`, `transitionOpenerRatio`, `paragraphLengthUniformity`, `countSectionBreaks`) backing `prose.burstiness`. `computeSlopPenalty()` composites all of the above — plus `repetition.js`'s sentence-length CV, read but never re-reported as its own finding — into a documented-weight 0–10 penalty for Phase 3's `qualityScore = judgeOverall − slopPenalty`. || `voiceFingerprint.js` | Pure, dependency-free statistical voice-fingerprint primitives for the deterministic `style.voice-drift` check (#2166 — CWQE Phase 2), the cheap sibling of the LLM `style.voice-consistency`. Reuses `tokenizeWords`/`splitSentences` (proseTics.js) + `splitParagraphs`/`emDashDensityPer1000` (slopScore.js) rather than re-implementing them. `computeFingerprint(text)` measures one issue's metric vector (sentence mean/σ/CV, fragment %, long-sentence %, paragraph mean/σ, dialogue ratio, em-dash rate, abstract-noun & simile density per 1k, dominant sentence-opener %, plus optional `well:*` vocabulary coverage); `splitManuscriptByIssue` / `voiceFingerprintMatrix` fingerprint every `# Issue N` section; `computeVoiceDrift` computes series mean/σ per metric and flags issues > threshold·σ out (small-N gated below `minIssues`), and — under an exemplar/blended baseline (#2248) — emits a `seriesFindings[]` of series-level "the whole corpus is uniformly off the chosen voice" mismatches for metrics whose drafted σ≈0 but whose shared value sits a scale-free relative distance from the chosen-voice center; `parseVoiceWells` parses the `name: word, word; …` config spec; `describeDrift` renders a per-issue finding sentence and `describeSeriesDrift` the series-level one; `renderFingerprintTable` renders the issues×metrics matrix (outliers marked); `describeMetricColumn(key)` / `metricUnit(key)` give the self-describing column header (label/unit/higher/lower/isWell) shared by the finding text and the deep-linkable matrix view (#2194). `VOICE_METRICS` is the static metric descriptor list. || `comicPacing.js` | Pure, dependency-free comic-pacing primitives for the #1314 comic-pacing group: `isSplashPage`, `comicSpreadLayout` (recto/verso + spread + `beginsSpread` page-turn map), `summarizeComicPages`, `analyzePanelRhythm` (`comic.panel-rhythm` — splash overuse / back-to-back splashes / overcrowded pages / grid monotony), `comicPageTurnSummary` + `authoredRevealSummary` (LLM-context renderers for `comic.page-turn-beats`). Operates on already-parsed comic pages (the runner parses each issue's stored comic script and injects them as the `comicScript` source) so the editorial dir stays import-pure. || `shotContinuity.js` | Pure, dependency-free storyboard shot-continuity primitives for the deterministic `visual.shot-continuity` check (#1315): `findAxisReversals` (180°-rule axis flips across a continuity-linked shot pair using `screenDirection`) and `findShotTypeMonotony` (a scene whose classified shots all share one `shotType`). Also `summarizeStoryboardShots` (#1466) — renders the collected `{ issueNumber, scene }` storyboard list into a compact per-scene shot block shared by the LLM siblings `visual.eyeline-match` (gaze reciprocity / eyeline-vs-screen-direction) and `visual.appearance-continuity` (#1467 — diffs the same entity's wardrobe/prop/setting descriptions across shots for contradictions). Reads the shot-grammar fields from `server/lib/shotGrammar.js`. || `dialogue.js` | Pure, dependency-free dialogue-tag primitives for the #1307 dialogue-craft group: `findSaidBookisms` (`dialogue.said-bookisms` — ornate speech tags like *expostulated*/*opined* and non-speech tags like "she smiled", matched only when adjacent to a double-quote span) and `findUnattributedDialogueRuns` (`dialogue.attribution-clarity` — runs of consecutive untagged/unbeated dialogue lines where the speaker can't be tracked), plus `attributeDialogueByOwner` (the coarse per-character dialogue-line tally behind `cast.representation-balance`'s dialogue-share signal, #1312 — credits each quoted paragraph to the first owner named in its beat) and the seed `SAID_BOOKISMS` / `NON_SPEECH_TAGS` lists. Also `inventoryDialogueTags` + `splitScenes` + `findDialogueTagVariety` (`dialogue.tag-variety`, #1587 — per-scene tag inventory flagging within-scene **monotony** (one verb dominates) and **over-variation** (a fresh verb on nearly every line); collapses inflections onto a base lemma via `PLAIN_SPEECH_TAG_GROUPS`). The LLM siblings `dialogue.on-the-nose` (subtext-free / "as you know, Bob" dialogue), `dialogue.voice-distinctiveness` (per-character voice against canon `speechPattern`/`speechAccent`) and `dialogue.reported-speech` (#3592 — a decisive utterance narrated as reported speech instead of quoted, which no quote-delimited scan can see because there is no quote on the page) handle the judgment cases. |-| `letteringDensity.js` | Pure, dependency-free comic lettering-density primitives for `comic.lettering-density` (#1313): `countWords`, `panelLetteringMetrics` (per-panel balloon/caption/SFX word + balloon tally over the `comicScriptParser` output), `analyzeComicLettering` (flags balloons/panels/pages over the configurable thresholds in `DEFAULT_LETTERING_THRESHOLDS`), `overflowSeverity` (severity scaled by how far over the limit), and `sanitizeLetteringThresholds`. Mirrored to `client/src/lib/letteringDensity.js` for the comic-script stage's inline warnings — keep the two in sync. |+| `letteringDensity.js` | Pure, dependency-free comic lettering-density primitives for `comic.lettering-density` (#1313): `panelLetteringMetrics` (per-panel balloon/caption/SFX word + balloon tally over the `comicScriptParser` output), `analyzeComicLettering` (flags balloons/panels/pages over the configurable thresholds in `DEFAULT_LETTERING_THRESHOLDS`), `overflowSeverity` (severity scaled by how far over the limit), and `sanitizeLetteringThresholds`. Word counts come from `lib/textUtils.js#countWords` (the whitespace count readers see, not the letter-word tokenizer the prose checks share); `client/src/lib/letteringDensity.js` re-exports this module for the comic-script stage's inline warnings. || `balloonAttribution.js` | Pure, dependency-free comic speech-balloon attribution primitives for `comic.balloon-attribution`: `analyzeBalloonAttribution` (flags a dialogue line whose speaker isn't shown in the panel description and carries no off-panel/broadcast cue — the case the image model mis-attributes to a visible character), `splitSpeaker`, `nameInText`, and `OFFPANEL_OK_MODIFIER` (the broadcast/off-panel/V.O./transmission modifier vocabulary — mirrors `visualStages.js` `BALLOON_STYLE_HINTS`, keep in sync). Severity scales `medium`/`low` by whether another canon character is visibly named in the panel. || `panelDisagreement.js` | Pure reader-panel disagreement-mining primitives for the four-persona reader panel (#2170 — CWQE Phase 6): the `PANEL_PERSONAS` / `PANEL_QUESTIONS` vocabulary, `sanitizePersonaResponse` (one persona's raw LLM answer → stable `{ persona, answers:{<qid>:{text,issues[]}}, verdict }` shape), `minePanelDisagreements` (cross-persona `consensus` ≥3-persona concern citations / `attention` some-but-not-all / `polarizing` best-vs-worst-scene splits), and `consensusToFindings` (consensus entries → `seedReviewFromFindings` finding shapes). Pure — all I/O (digest build, per-persona LLM calls, snapshot storage, review seeding) lives in `server/services/pipeline/readerPanel.js`. || `cutApplier.js` | Pure, dependency-free adversarial-cut matcher/applier shared by the pipeline manuscript applier (`server/services/pipeline/applyCuts.js`) and the Writers Room polish loop (#2173): `locateCutSpan` (exact → whitespace-normalized regex → refuse ambiguous/short), `planCutsForSection` (safe-type filter + overlap guard → `{ applicable, refused }`), `applyCutsToText` (reverse-order span removal), `collapseBlankLines`, `buildWhitespaceTolerantRegex`, and `MIN_ANCHOR_CHARS`. Re-exports `CUT_TYPES`/`SAFE_CUT_TYPES` from `checkInfra.js`. Extracted from `applyCuts.js` so a freeform work body and per-issue stage sections share one matcher without coupling Writers Room to the pipeline. |diff --git a/server/lib/editorial/checkInfra/externals.js b/server/lib/editorial/checkInfra/externals.jsindex 5fc07c900a..a6629d6efa 100644--- a/server/lib/editorial/checkInfra/externals.js+++ b/server/lib/editorial/checkInfra/externals.js@@ -29,6 +29,7 @@ import {findPassiveVoice,filterPassiveVoice,findGestures,+ tokenizeWords,} from '../proseTics.js';import {findWordEchoes,@@ -110,6 +111,7 @@ export {renderCharacterEvolutionsForPrompt,splitScenes,summarizeStoryboardShots,+ tokenizeWords,transitionOpenerRatio,canonHasRevealGated,revealGatedCanonRows,diff --git a/server/lib/editorial/checkInfra/proseDensity.js b/server/lib/editorial/checkInfra/proseDensity.jsindex a6e80c8766..251b42117f 100644--- a/server/lib/editorial/checkInfra/proseDensity.js+++ b/server/lib/editorial/checkInfra/proseDensity.js@@ -2,6 +2,8 @@* Density-scaled prose-tic finding helpers (#1306) (#2842 split of checkInfra.js).*/+import { tokenizeWords } from '../proseTics.js';+// ---------------------------------------------------------------------------// Registry entries.// ---------------------------------------------------------------------------@@ -22,12 +24,6 @@ export function splitPhraseList(value) {// high. Findings anchor on the FIRST offending occurrence in each section.// ----------------------------------------------------------------------------// Word count of a section's prose (for per-1000-word density). Cheap word-// tokenization — apostrophes kept inside words so contractions count once.-export function countWords(text) {- return (String(text || '').match(/[A-Za-z][A-Za-z']*/g) || []).length;-}-// Map a section to its issue label/number once (used by every prose-tic check).export function sectionIssue(s) {const number = Number.isInteger(s?.number) ? s.number : null;@@ -49,7 +45,9 @@ export function runDensityCheck(ctx, opts) {for (const s of sections) {if (findings.length >= max) break;const text = s?.content || '';- const words = countWords(text);+ // Letter-word count — the denominator every prose-analysis rate shares (see+ // tokenizeWords), not lib/textUtils' whitespace count.+ const words = tokenizeWords(text).length;if (words === 0) continue;const hits = opts.scan(text, cfg);if (!hits.length) continue;diff --git a/server/lib/editorial/checks/proseStyle.js b/server/lib/editorial/checks/proseStyle.jsindex 1eae4caed0..7e193e903e 100644--- a/server/lib/editorial/checks/proseStyle.js+++ b/server/lib/editorial/checks/proseStyle.js@@ -12,7 +12,6 @@ import {STYLE_CONFORMANCE_STAGE,TELLING_EMOTION_STAGE,VOICE_CONSISTENCY_STAGE,- countWords,escalateSeverity,filterPassiveVoice,findAdverbs,@@ -37,6 +36,7 @@ import {sectionIssue,splitPhraseList,styleGuideExpectations,+ tokenizeWords,z,} from '../checkInfra.js';import {@@ -564,7 +564,7 @@ export const proseStyleChecks = [for (const s of sections) {if (findings.length >= max) break;const text = s?.content || '';- const words = countWords(text);+ const words = tokenizeWords(text).length;if (words === 0) continue;const hits = findAdverbs(text, { allowWords, extraWords });if (!hits.length) continue;diff --git a/server/lib/editorial/checks/slop.js b/server/lib/editorial/checks/slop.jsindex 710f4ba995..f53d29cc76 100644--- a/server/lib/editorial/checks/slop.js+++ b/server/lib/editorial/checks/slop.js@@ -6,7 +6,6 @@import {MIN_DENSITY_OCCURRENCES,countSectionBreaks,- countWords,emDashDensityPer1000,findAiTells,findBannedWordsTier1,@@ -15,6 +14,7 @@ import {paragraphLengthUniformity,sectionIssue,splitPhraseList,+ tokenizeWords,transitionOpenerRatio,z,} from '../checkInfra.js';@@ -83,7 +83,7 @@ export const slopChecks = [const { number, location } = sectionIssue(s);// Tier 1 — density-scaled, one finding per offending section.- const words = countWords(text);+ const words = tokenizeWords(text).length;const hits = words > 0 ? findBannedWordsTier1(text, { allowWords, extraWords }) : [];if (hits.length) {const rate = Math.round((hits.length / words) * 1000 * 10) / 10;@@ -264,7 +264,7 @@ export const slopChecks = [for (const s of sections) {if (findings.length >= max) break;const text = s?.content || '';- const words = countWords(text);+ const words = tokenizeWords(text).length;const { number, location } = sectionIssue(s);const emDash = emDashDensityPer1000(text);diff --git a/server/lib/editorial/italicThoughts.js b/server/lib/editorial/italicThoughts.jsindex ce2df04802..e89c8095b5 100644--- a/server/lib/editorial/italicThoughts.js+++ b/server/lib/editorial/italicThoughts.js@@ -14,6 +14,8 @@* siblings handle the judgment cases this can't.*/+import { countWords } from '../textUtils.js';+// Markdown italic delimiters. Asterisk italics are a single `*` NOT part of a// `**`/`***` bold run; underscore italics are a single `_` with non-word edges// (so `snake_case` and `__bold__` are never mistaken for emphasis). Each span is@@ -22,12 +24,6 @@const ASTERISK_ITALIC_RE = /(?<!\*)\*(?!\*)([^*\n]+?)\*(?!\*)/g;const UNDERSCORE_ITALIC_RE = /(?<![\w_])_(?!_)([^_\n]+?)_(?![\w_])/g;-// Count whitespace-delimited words in an italic span's inner text.-function wordCount(text) {- const m = String(text).trim().match(/\S+/g);- return m ? m.length : 0;-}-/*** Find italicized runs in `text` that read as internal-thought narration —* multi-word italic spans (markdown `*…*` or `_…_`). Returns the FIRST occurrence@@ -54,7 +50,7 @@ export function findItalicThoughts(text, opts = {}) {let m;while ((m = re.exec(text)) !== null) {const inner = m[1].trim();- const words = wordCount(inner);+ const words = countWords(inner);if (words < minWords) continue;matches.push({ inner, index: m.index, anchor: m[0], words });}diff --git a/server/lib/editorial/letteringDensity.js b/server/lib/editorial/letteringDensity.jsindex 975d8956b0..bd84674552 100644--- a/server/lib/editorial/letteringDensity.js+++ b/server/lib/editorial/letteringDensity.js@@ -12,8 +12,9 @@** PURE + side-effect-free so it is unit-testable and so the SAME helper backs* both the server-side editorial check (`comic.lettering-density` in- * checkRegistry.js) and the client comic-script stage inline warnings (mirrored- * to `client/src/lib/letteringDensity.js` — keep the two byte-for-byte in sync).+ * checkRegistry.js) and the client comic-script stage inline warnings+ * (`client/src/lib/letteringDensity.js` re-exports this module, so the browser+ * bundle runs this code rather than a copy).** A "balloon" is a discrete lettering element the reader's eye lands on: each* dialogue entry is one balloon, and each caption box is one (captions repeat —@@ -23,6 +24,8 @@* balloon, so it does NOT count toward the balloon tally.*/+import { countWords } from '../textUtils.js';+// Industry rules-of-thumb (all overridable via the check's config). A balloon// much over ~20–25 words reads as a wall of text; a panel over ~45–50 words// crowds the art; more than ~3 balloons in a panel is hard to follow; and a@@ -39,15 +42,6 @@ export const DEFAULT_LETTERING_THRESHOLDS = Object.freeze({// from checkRegistry.const LETTERING_SEVERITIES = ['high', 'medium', 'low'];-// Count words in a free-text lettering string. A "word" is a run of-// non-whitespace, so hyphenates and contractions count once and punctuation-// rides along — close enough for a density heuristic. Non-strings → 0.-export function countWords(text) {- if (typeof text !== 'string') return 0;- const matched = text.trim().match(/\S+/g);- return matched ? matched.length : 0;-}-// Severity scaled by how far over the threshold a count runs (#1313 "severity// scaled by overflow"): ≥2× the limit is `high`, ≥1.4× is `medium`, otherwise a// mild overflow is `low`. Pure so it's unit-testable. A count at/under thediff --git a/server/lib/editorial/letteringDensity.test.js b/server/lib/editorial/letteringDensity.test.jsindex 4163615e1c..f791e7310b 100644--- a/server/lib/editorial/letteringDensity.test.js+++ b/server/lib/editorial/letteringDensity.test.js@@ -1,6 +1,5 @@import { describe, it, expect } from 'vitest';import {- countWords,overflowSeverity,sanitizeLetteringThresholds,panelLetteringMetrics,@@ -11,21 +10,6 @@ import {// Build a panel of N words across a single balloon.const balloon = (character, n) => ({ character, line: Array.from({ length: n }, (_, i) => `w${i}`).join(' ') });-describe('countWords', () => {- it('counts whitespace-separated tokens', () => {- expect(countWords('one two three')).toBe(3);- expect(countWords(' spaced out ')).toBe(2);- expect(countWords('hyphen-ated counts once')).toBe(3);- });- it('returns 0 for empty / non-string', () => {- expect(countWords('')).toBe(0);- expect(countWords(' ')).toBe(0);- expect(countWords(null)).toBe(0);- expect(countWords(undefined)).toBe(0);- expect(countWords(42)).toBe(0);- });-});-describe('overflowSeverity', () => {it('scales with how far over the threshold the count runs', () => {expect(overflowSeverity(26, 25)).toBe('low'); // ~1.04×diff --git a/server/lib/editorial/proseTics.js b/server/lib/editorial/proseTics.jsindex 666e3233cc..92c7809ca8 100644--- a/server/lib/editorial/proseTics.js+++ b/server/lib/editorial/proseTics.js@@ -191,8 +191,15 @@ function toWordSet(words) {/*** Tokenize prose into words with their absolute character offsets. Apostrophes- * are kept inside a word ("couldn't") so contractions stay whole. Exported so- * ./repetition.js shares one tokenization with the word-level scanners.+ * are kept inside a word ("couldn't") so contractions stay whole.+ *+ * This is the ONE spelling of the editorial "prose word" — a run of letters, so+ * numerals, dashes and markdown tokens never pad a per-1000-word denominator —+ * and `tokenizeWords(text).length` is the prose word count every density rate,+ * rhythm metric and slop score shares. It differs on purpose from+ * `lib/textUtils.js#countWords`, the whitespace count the rest of the app shows+ * readers. `proseTics.test.js` fails the suite when the character class is+ * re-spelled anywhere else under server/.** @param {string} text* @returns {Array<{ word: string, lower: string, index: number }>}diff --git a/server/lib/editorial/proseTics.test.js b/server/lib/editorial/proseTics.test.jsindex b4b6d6092f..36afe1e885 100644--- a/server/lib/editorial/proseTics.test.js+++ b/server/lib/editorial/proseTics.test.js@@ -1,4 +1,5 @@import { describe, it, expect } from 'vitest';+import { collectServerSources, readServerSource } from '../testHelper.js';import {tokenizeWords,splitSentences,@@ -326,3 +327,31 @@ describe('findGestures', () => {expect(findGestures('')).toEqual({ gestures: [], bodyParts: [] });});});++// `tokenizeWords` is the one spelling of the editorial "prose word" — a run of+// letters with inner apostrophes, so numerals, dashes and markdown tokens never+// pad a per-1000-word denominator. It had been re-spelled as a bare regex in+// repetition.js (twice), slopScore.js and checkInfra/proseDensity.js — the last+// exported as `countWords`, the name lib/textUtils.js gives the WHITESPACE+// count, so a check could import the wrong denominator by name alone. Like the+// escape guard in textUtils.test.js this keys on the idiom (the character+// class), so a paste under any name fails the suite. Server-only: nothing in the+// browser bundle runs the prose checks.+const PROSE_WORD_CLASS = /\[A-Za-z\]\[A-Za-z'\]\*/;++describe('no private prose-word tokenizer', () => {+ it('leaves lib/editorial/proseTics.js as the only letter-word tokenizer under server/', () => {+ const offenders = collectServerSources()+ .filter((rel) => rel !== 'lib/editorial/proseTics.js')+ .filter((rel) => PROSE_WORD_CLASS.test(readServerSource(rel)));+ expect(+ offenders,+ `these re-spell the prose-word tokenizer — use tokenizeWords from lib/editorial/proseTics.js instead: ${offenders.join(', ')}`+ ).toEqual([]);+ });++ it('detects the tokenizer where it lives, so an empty offender list means nobody spells it', () => {+ expect(PROSE_WORD_CLASS.test(readServerSource('lib/editorial/proseTics.js'))).toBe(true);+ expect(collectServerSources().length).toBeGreaterThan(100);+ });+});diff --git a/server/lib/editorial/repetition.js b/server/lib/editorial/repetition.jsindex 37c82a3303..94f624e620 100644--- a/server/lib/editorial/repetition.js+++ b/server/lib/editorial/repetition.js@@ -76,8 +76,8 @@ export function findRepeatedOpeners(text, opts = {}) {const minRun = Math.max(2, Number.isInteger(opts.minRun) ? opts.minRun : 3);// The opening word of each sentence (lowercased) + its offset.const openers = sentences.map((s) => {- const m = /[A-Za-z][A-Za-z']*/.exec(s.text);- return { word: m ? m[0] : '', lower: m ? m[0].toLowerCase() : '', index: s.index };+ const [first] = tokenizeWords(s.text);+ return { word: first?.word ?? '', lower: first?.lower ?? '', index: s.index };});const out = [];let runStart = 0;@@ -113,7 +113,7 @@ export function measureSentenceRhythm(text, opts = {}) {const sentences = splitSentences(text);const minSentences = Number.isInteger(opts.minSentences) && opts.minSentences > 1 ? opts.minSentences : 5;if (sentences.length < minSentences) return null;- const lengths = sentences.map((s) => (s.text.match(/[A-Za-z][A-Za-z']*/g) || []).length);+ const lengths = sentences.map((s) => tokenizeWords(s.text).length);const count = lengths.length;const mean = lengths.reduce((a, b) => a + b, 0) / count;if (mean <= 0) return null;diff --git a/server/lib/editorial/slopScore.js b/server/lib/editorial/slopScore.jsindex 7ba9063a0c..60ec290b4c 100644--- a/server/lib/editorial/slopScore.js+++ b/server/lib/editorial/slopScore.js@@ -368,10 +368,6 @@ export function findTheWaySimiles(text) {return out;}-function countSentenceWords(s) {- return (s.match(/[A-Za-z][A-Za-z']*/g) || []).length;-}-/*** Runs of `minRun`+ consecutive very short sentences ("Fast. Precise.* Deadly.") — the punchy triadic-fragment rhythm LLM prose overuses.@@ -401,7 +397,7 @@ export function findTriadicShortSentences(text, opts = {}) {runCount = 0;};for (let i = 0; i < sentences.length; i += 1) {- const wc = countSentenceWords(sentences[i].text);+ const wc = tokenizeWords(sentences[i].text).length;if (wc > 0 && wc <= maxWords) {if (runStart === -1) runStart = i;runCount += 1;diff --git a/server/lib/scriptVideoCompiler.js b/server/lib/scriptVideoCompiler.jsindex 582b62f775..7314953337 100644--- a/server/lib/scriptVideoCompiler.js+++ b/server/lib/scriptVideoCompiler.js@@ -22,6 +22,8 @@* this with the linter and the backend submission.*/+import { countWords } from './textUtils.js';+export const BEAT_MAX_WORDS = 35;export const BEAT_MAX_SPEAKERS = 2;export const MAX_CHAIN_LENGTH = 6;@@ -39,11 +41,6 @@ export const DEFAULT_FPS = 24;export const H3_FRAME_STEP = 17;export const H3_FRAME_OFFSET = 5;-const countWords = (text) => {- const t = (text || '').trim();- return t ? t.split(/\s+/).length : 0;-};-/** Total words across a beat's action + dialogue lines. */export const beatWordCount = (beat) => (beat?.lines || []).reduce((sum, l) => sum + countWords(l.text), 0);diff --git a/server/lib/textUtils.test.js b/server/lib/textUtils.test.jsindex 74ff277535..296980f3ef 100644--- a/server/lib/textUtils.test.js+++ b/server/lib/textUtils.test.js@@ -136,10 +136,13 @@ const ESCAPE_IDIOMS = [/(?:^|[^\w$.])(?:const|let|var|function)\s+escapeRegExp\b/,];-const escapeIdiomCount = (source) => ESCAPE_IDIOMS+// How many times the most-spelled idiom in `idioms` appears in `source`.+const idiomCount = (idioms) => (source) => idioms.map((idiom) => source.match(new RegExp(idiom.source, 'g'))?.length ?? 0).reduce((most, count) => Math.max(most, count), 0);+const escapeIdiomCount = idiomCount(ESCAPE_IDIOMS);+describe('no private escapeRegExp', () => {it('leaves lib/textUtils.js as the only RegExp-escape implementation under server/', () => {const offenders = collectServerSources()@@ -179,6 +182,64 @@ describe('no private escapeRegExp', () => {});});+// `countWords` had the same history as the escape: extracted here as "the+// canonical whitespace-token count", then re-spelled in five product modules and+// the client's formatters — whose copy justified itself with "the client cannot+// import from server/", untrue since #6364. Same remedy: key on the counting+// IDIOMS rather than the identifier, since the copies were pastes under three+// names and four under none. The whitespace-token match is how every named copy+// counted; split-and-drop-empties is how the inline ones did. A `matchAll` or a+// `re.exec` loop over the same class is NOT matched — those are the tokenizers+// that need each token's position (rapid reader, tab notation, clichés), and a+// tokenizer is not a count.+//+// A bare split-on-whitespace `.length` (no filter) is deliberately absent: it is+// the five-field cron check's spelling far more often than a word count, and the+// one word-count use (the brain digest's word cap) truncates with the same split,+// so it is at least internally consistent.+const WORD_COUNT_IDIOMS = [+ // The whitespace-token match used as a count.+ /\.match\(\/\\S\+\/g\)/,+ // The split-and-drop-empties count.+ /\.split\(\/\\s\+\/\)\.filter\(Boolean\)\.length/,+ // A helper re-declared under either conventional name.+ /(?:^|[^\w$.])(?:(?:const|let|var)\s+(?:countWords|wordCount)\s*=\s*(?:async\s*)?\(|function\s+(?:countWords|wordCount)\s*\()/,+];++const wordCountIdiomCount = idiomCount(WORD_COUNT_IDIOMS);++describe('no private countWords', () => {+ it('leaves lib/textUtils.js as the only whitespace word count under server/', () => {+ const offenders = collectServerSources()+ .filter((rel) => rel !== 'lib/textUtils.js')+ .filter((rel) => wordCountIdiomCount(readServerSource(rel)) > 0);+ expect(+ offenders,+ `these re-spell the word count — import countWords from lib/textUtils.js instead: ${offenders.join(', ')}`+ ).toEqual([]);+ });++ // The client walk allows no exemption either: `client/src/lib/textUtils.js`+ // re-exports this module's count, and the formatters copy is gone.+ it('leaves no whitespace word count anywhere under client/src/', () => {+ const offenders = collectClientSources()+ .filter((rel) => wordCountIdiomCount(readClientSource(rel)) > 0);+ expect(+ offenders,+ `these re-spell the word count — import countWords from lib/textUtils.js instead: ${offenders.join(', ')}`+ ).toEqual([]);+ });++ it('detects a re-spelled count under any of its idioms, and not a tokenizer', () => {+ expect(wordCountIdiomCount(readServerSource('lib/textUtils.js'))).toBeGreaterThan(0);+ expect(wordCountIdiomCount('const wordCount = (t) => t.split(/\\s+/).filter(Boolean).length;')).toBeGreaterThan(0);+ expect(wordCountIdiomCount('function countWords(text) { return 0; }')).toBeGreaterThan(0);+ expect(wordCountIdiomCount('for (const m of text.matchAll(/\\S+/g)) {}')).toBe(0);+ expect(wordCountIdiomCount('const isCron = value.trim().split(/\\s+/).length === 5;')).toBe(0);+ expect(wordCountIdiomCount('const wordCount = useMemo(() => countWords(body), [body]);')).toBe(0);+ });+});+describe('trimToClause (boundary-aware prose cap)', () => {it('returns text untouched when it fits', () => {expect(trimToClause('A short logline.', 500)).toBe('A short logline.');diff --git a/server/services/autobiography.js b/server/services/autobiography.jsindex 7ee5c9279e..dde53e18fc 100644--- a/server/services/autobiography.js+++ b/server/services/autobiography.js@@ -11,6 +11,7 @@ import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../lib/fileUtils.js';import { recordTombstone } from '../lib/tombstones.js';+import { countWords } from '../lib/textUtils.js';import {queueAutobiographyConfigWrite,queueAutobiographyStoriesWrite@@ -298,7 +299,7 @@ export async function saveStory({ promptId, content, parentStoryId, customPromptthemeLabel: isFollowUp ? (parentStory?.themeLabel || 'Unknown') : (prompt?.themeLabel || 'Unknown'),promptText: customPromptText || prompt?.text || '',content,- wordCount: content.split(/\s+/).filter(Boolean).length,+ wordCount: countWords(content),createdAt: new Date().toISOString(),...(parentStoryId && { parentStoryId })};@@ -329,7 +330,7 @@ export async function updateStory(storyId, content) {if (!story) return null;story.content = content;- story.wordCount = content.split(/\s+/).filter(Boolean).length;+ story.wordCount = countWords(content);story.updatedAt = new Date().toISOString();await saveStories(data);diff --git a/server/services/pipeline/foundationJudgeContext.js b/server/services/pipeline/foundationJudgeContext.jsindex 2fc0513c68..5128b805ce 100644--- a/server/services/pipeline/foundationJudgeContext.js+++ b/server/services/pipeline/foundationJudgeContext.js@@ -7,6 +7,7 @@import { createHash } from 'crypto';import { composeStyleNotes } from '../../lib/styleGuide.js';+import { countWords } from '../../lib/textUtils.js';import { renderCharacterArcsForPrompt } from '../../lib/seriesCharacterArc.js';import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';import { isBlankString, isBlankArray } from '../universeCharacterExpand.js';@@ -410,7 +411,7 @@ export function renderArc(series, issues = [], { maxChars = Infinity, includeArc.filter((issue) => issue?.seasonId === season.id).map((issue) => {const synopsis = issue?.stages?.idea?.input || '(no synopsis)';- const words = synopsis === '(no synopsis)' ? 0 : synopsis.trim().split(/\s+/).filter(Boolean).length;+ const words = synopsis === '(no synopsis)' ? 0 : countWords(synopsis);const metadata = [issue.arcRole ? `role=${issue.arcRole}` : 'role=unset',issue.lengthProfile ? `length=${issue.lengthProfile}` : 'length=unset',diff --git a/server/services/rapidReaderLibrary.js b/server/services/rapidReaderLibrary.jsindex b458b8cf0e..83ea9f9e30 100644--- a/server/services/rapidReaderLibrary.js+++ b/server/services/rapidReaderLibrary.js@@ -3,13 +3,13 @@ import { createCollectionStore } from '../lib/collectionStore.js';import { ServerError } from '../lib/errorHandler.js';import { htmlToText } from '../lib/htmlToText.js';import { fetchPublicText } from '../lib/safeUrlFetch.js';+import { countWords } from '../lib/textUtils.js';import { v4 as uuidv4 } from '../lib/uuid.js';export const RAPID_READER_LIBRARY_SCHEMA_VERSION = 1;export const MAX_RAPID_READER_TEXT_BYTES = 2 * 1024 * 1024;const MAX_TITLE_LENGTH = 200;const now = () => new Date().toISOString();-const wordCount = (text) => (text.match(/\S+/g) || []).length;const textBytes = (text) => Buffer.byteLength(text, 'utf8');const normalizeText = (text) => typeof text === 'string' ? text.trim() : '';const normalizeTitle = (title) => typeof title === 'string' ? title.trim().slice(0, MAX_TITLE_LENGTH) : '';@@ -22,7 +22,7 @@ export const rapidReaderLibraryStore = createCollectionStore({const text = normalizeText(record?.text);const title = normalizeTitle(record?.title);if (!record?.id || !text || !title || !['paste', 'fetch', 'accelerando'].includes(record.sourceType)) return null;- return { ...record, title, text, author: typeof record.author === 'string' ? record.author : null, sourceUrl: typeof record.sourceUrl === 'string' ? record.sourceUrl : null, wordCount: wordCount(text) };+ return { ...record, title, text, author: typeof record.author === 'string' ? record.author : null, sourceUrl: typeof record.sourceUrl === 'string' ? record.sourceUrl : null, wordCount: countWords(text) };},});@@ -57,17 +57,17 @@ export async function createPastedRapidReaderEntry({ title, author, text }) {const cleanText = normalizeText(text); const cleanTitle = normalizeTitle(title); assertText(cleanText);if (!cleanTitle) throw new ServerError('Title is required', { status: 400, code: 'VALIDATION_ERROR' });const timestamp = now();- return saveEntry({ id: uuidv4(), title: cleanTitle, author: normalizeTitle(author) || null, sourceUrl: null, sourceType: 'paste', text: cleanText, wordCount: wordCount(cleanText), addedAt: timestamp, updatedAt: timestamp });+ return saveEntry({ id: uuidv4(), title: cleanTitle, author: normalizeTitle(author) || null, sourceUrl: null, sourceType: 'paste', text: cleanText, wordCount: countWords(cleanText), addedAt: timestamp, updatedAt: timestamp });}export async function fetchRapidReaderEntry({ url, title }) {const source = await fetchPublicText(url, { blockPrivate: true, maxBytes: MAX_RAPID_READER_TEXT_BYTES, timeoutMs: 20_000 });if (!source) throw new ServerError('Could not fetch the requested URL', { status: 502, code: 'FETCH_FAILED' });const text = normalizeText(htmlToText(source)); assertText(text);const timestamp = now(); const derivedTitle = normalizeTitle(title) || normalizeTitle(titleFromHtml(source)) || hostnameFor(url);- return saveEntry({ id: uuidv4(), title: derivedTitle, author: null, sourceUrl: url, sourceType: 'fetch', text, wordCount: wordCount(text), addedAt: timestamp, updatedAt: timestamp });+ return saveEntry({ id: uuidv4(), title: derivedTitle, author: null, sourceUrl: url, sourceType: 'fetch', text, wordCount: countWords(text), addedAt: timestamp, updatedAt: timestamp });}export async function deleteRapidReaderLibraryEntry(id) { await getRapidReaderLibraryEntry(id); await rapidReaderLibraryStore.deleteOne(id); }export async function upsertAccelerandoShelfEntry(book) {const current = await rapidReaderLibraryStore.loadOne('accelerando'); const timestamp = now(); const text = normalizeText(book.text); assertText(text);- return saveEntry({ id: 'accelerando', title: book.title, author: book.author, sourceUrl: book.sourceUrl, sourceType: 'accelerando', text, wordCount: wordCount(text), addedAt: current?.addedAt || timestamp, updatedAt: timestamp });+ return saveEntry({ id: 'accelerando', title: book.title, author: book.author, sourceUrl: book.sourceUrl, sourceType: 'accelerando', text, wordCount: countWords(text), addedAt: current?.addedAt || timestamp, updatedAt: timestamp });}diff --git a/server/services/repoSync.js b/server/services/repoSync.jsindex dc3f0b49ba..e986a7f0a9 100644--- a/server/services/repoSync.js+++ b/server/services/repoSync.js@@ -51,6 +51,7 @@ import {} from './git.js';import { getOriginInfo } from '../lib/gitRemote.js';import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';+import { countWords } from '../lib/textUtils.js';import {DEFAULT_REPO_SYNC_VERIFY_MODE, REPO_SYNC_ACTION_KEYS, REPO_SYNC_VERIFY_MODES, sanitizeTaskMetadata} from '../lib/cosValidation.js';@@ -199,7 +200,7 @@ export function parseStashList(stdout) {.map(([ref, sha, parents, ...rest]) => ({ref: ref.trim(),sha: sha.trim(),- parentCount: parents.trim().split(/\s+/).filter(Boolean).length,+ parentCount: countWords(parents), // whitespace-separated parent SHAsmessage: rest.join('\x1f').trim()}));}diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.jsindex a87c591aae..853a3781ac 100644--- a/server/services/writersRoom/local.js+++ b/server/services/writersRoom/local.js@@ -30,11 +30,12 @@ const store = () => writersRoomStore();// ---------- text analysis -----------// `countWords` now lives in lib/textUtils.js (the canonical home it shares with-// issueLength.js). Re-exported here so existing importers of this module keep-// working unchanged. (The editorial checks keep their own copies on purpose:-// checkInfra.js uses a different alphabetic-only tokenizer, and-// letteringDensity.js is held byte-for-byte in sync with its client mirror.)+// `countWords` lives in lib/textUtils.js — the one whitespace word count, on+// both sides of the client/server line (`textUtils.test.js` fails the suite on a+// re-spelled copy). Re-exported here so existing importers of this module keep+// working unchanged. The editorial prose checks count LETTER words instead,+// through lib/editorial/proseTics.js#tokenizeWords — a different rule on+// purpose, owned the same way.export { countWords };export function contentHash(text) {