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
fix: route percent/USD/log/port drift through the shared helpers and guard it (#9951)
Adam Eivy5f8ab0daef29
diff --git a/client/src/apiWrapperOptionsConventions.test.js b/client/src/apiWrapperOptionsConventions.test.jsnew file mode 100644index 0000000000..d9e4e75a7c--- /dev/null+++ b/client/src/apiWrapperOptionsConventions.test.js@@ -0,0 +1,232 @@+// @vitest-environment node++/**+ * Repo-wide guard: a call site that passes `{ silent: true }` to an API wrapper+ * must be passing it somewhere the wrapper actually forwards (#9951).+ *+ * `request(endpoint, options)` in `services/apiCore.js` reads `silent` out of its+ * second argument to suppress the error toast. A wrapper such as+ *+ * export const getThing = (id) => request(`/things/${id}`);+ *+ * has no parameter for it, so `getThing(id, { silent: true })` type-checks, runs,+ * and silently toasts anyway — and `export const saveThing = (id, data) => …`+ * receives the options object AS THE PAYLOAD. Three call sites shipped that way.+ *+ * ## The rule+ *+ * For every call `wrapper(…, { …silent… }, …)` to an export of+ * `client/src/services/api*.js`, the wrapper's parameter at that argument+ * position must be one of:+ *+ * - named `options` / `opts` (or any name the wrapper passes straight through+ * or spreads, `...name`),+ * - a rest parameter (`...args`), or+ * - a destructuring pattern that names `silent` or collects `...rest`.+ *+ * A wrapper with no parameter at that position fails.+ *+ * ## What this guard CANNOT see+ *+ * It is a lexer-assisted source scan, not a type check. It judges only a LITERAL+ * object argument (an options object built in a variable, or spread+ * `{ ...opts }`, is invisible), resolves a callee by its exported NAME (judged+ * only in a file that imports it, or via `api.name`; a same-named local binding+ * in an importing file is treated as the wrapper), and reads a+ * wrapper's forwarding from its source text up to the next `export`. A wrapper+ * that is itself a re-export alias (`export const a = b`) is not judged.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { trackedSourceFiles } from './test/trackedFiles.js';+import { blankCommentBodies, blankLiterals, matchBracket } from '../../server/lib/sourceScan.js';++const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const SERVICE_FILE = /^src\/services\/api[^/]*\.js$/;+const OPTIONS_NAMES = new Set(['options', 'opts']);++/** Split `text[start, end)` on top-level commas, using the blanked copy to find them. */+function splitTopLevel(blanked, text, start, end) {+ const parts = [];+ let depth = 0;+ let from = start;+ for (let i = start; i < end; i++) {+ const c = blanked[i];+ if ('([{'.includes(c)) depth++;+ else if (')]}'.includes(c)) depth--;+ else if (c === ',' && depth === 0) {+ parts.push(text.slice(from, i).trim());+ from = i + 1;+ }+ }+ const last = text.slice(from, end).trim();+ if (last) parts.push(last);+ return parts;+}++const WRAPPER_HEAD = /^[ \t]*export\s+(?:(?:async\s+)?function\s+(\w+)\s*\(|const\s+(\w+)\s*=\s*(?:async\s*)?\()/gm;++/** Exported function wrappers in one service file: `[{ name, params, text }]`. */+export function wrapperExports(src) {+ const code = blankCommentBodies(src);+ const blanked = blankLiterals(src);+ const heads = [...blanked.matchAll(WRAPPER_HEAD)];+ const allExports = [...blanked.matchAll(/^[ \t]*export\s/gm)].map((m) => m.index);+ return heads.map((head) => {+ const open = head.index + head[0].length - 1;+ const close = matchBracket(blanked, open);+ if (close === -1) return null;+ const next = allExports.find((index) => index > head.index) ?? src.length;+ return {+ name: head[1] || head[2],+ params: splitTopLevel(blanked, code, open + 1, close - 1),+ text: code.slice(close, next),+ };+ }).filter(Boolean);+}++/** The parameter text with its top-level `= default` dropped (a destructured default stays inside the pattern). */+const stripDefault = (param) => {+ let depth = 0;+ for (let i = 0; i < param.length; i++) {+ const c = param[i];+ if ('([{'.includes(c)) depth++;+ else if (')]}'.includes(c)) depth--;+ else if (c === '=' && depth === 0 && param[i + 1] !== '=' && param[i + 1] !== '>') return param.slice(0, i).trim();+ }+ return param.trim();+};++/** Does `wrapper` forward the argument it receives at `index` to `request`'s options? */+export function forwardsOptionsAt(wrapper, index) {+ if (wrapper.params.some((param) => param.startsWith('...')) && wrapper.params.findIndex((p) => p.startsWith('...')) <= index) return true;+ if (index >= wrapper.params.length) return false;+ const param = stripDefault(wrapper.params[index]);+ if (param.startsWith('{')) return /\bsilent\b|\.\.\./.test(param);+ if (OPTIONS_NAMES.has(param)) return true;+ if (!/^[A-Za-z_$][\w$]*$/.test(param)) return false;+ const escaped = param.replace(/\$/g, '\\$');+ return new RegExp(`\\.\\.\\.${escaped}\\b|\\b${escaped}\\??\\.silent\\b|,\\s*${escaped}\\s*\\)`).test(wrapper.text);+}++const SILENT_KEY = /[{,]\s*silent\s*(?::|,|\})/;++/**+ * `{ line, name, index }` for every call of one of `names` that passes a literal+ * object containing a `silent` key, with `index` the argument position. A bare+ * `name(…)` counts only in a file that imports `name` (a hook handed the callback+ * as a parameter owns its own contract); `api.name(…)` always counts.+ */+export function silentCalls(src, names) {+ if (!src.includes('silent')) return [];+ const code = blankCommentBodies(src);+ const blanked = blankLiterals(src);+ const imported = new Set([...code.matchAll(/import\s*\{([^}]*)\}\s*from/g)]+ .flatMap((m) => m[1].split(',').map((part) => part.trim().split(/\s+as\s+/).pop())));+ const hits = [];+ for (const match of blanked.matchAll(/(?<![\w$.])(api\.)?([A-Za-z_$][\w$]*)\s*\(/g)) {+ const [, namespace, name] = match;+ if (!names.has(name) || (!namespace && !imported.has(name))) continue;+ const open = match.index + match[0].length - 1;+ const close = matchBracket(blanked, open);+ if (close === -1) continue;+ splitTopLevel(blanked, code, open + 1, close - 1).forEach((arg, index) => {+ if (arg.startsWith('{') && SILENT_KEY.test(arg)) {+ hits.push({ line: src.slice(0, match.index).split('\n').length, name, index });+ }+ });+ }+ return hits;+}++/** Every `file: name(arg N)` where the wrapper at that position drops the options object. */+export function findDroppedSilent(files, wrappers) {+ const violations = [];+ const byName = new Map();+ for (const wrapper of wrappers) {+ if (!byName.has(wrapper.name)) byName.set(wrapper.name, []);+ byName.get(wrapper.name).push(wrapper);+ }+ const names = new Set(byName.keys());+ for (const { file, src } of files) {+ for (const { line, name, index } of silentCalls(src, names)) {+ if (byName.get(name).some((wrapper) => !forwardsOptionsAt(wrapper, index))) {+ violations.push(`${file}:${line} ${name}(…) passes { silent } as argument ${index + 1}`);+ }+ }+ }+ return violations;+}++const read = (file) => ({ file, src: readFileSync(join(CLIENT_ROOT, file), 'utf8') });++describe('silent options reach the API wrapper that reads them (#9951)', () => {+ it('has no { silent } passed to a position the wrapper drops', () => {+ const tracked = trackedSourceFiles(CLIENT_ROOT);+ expect(tracked.length).toBeGreaterThan(100);+ const wrappers = tracked.filter((file) => SERVICE_FILE.test(file)).flatMap((file) => wrapperExports(read(file).src));+ // A broken parse would otherwise pass by judging nothing.+ expect(wrappers.length).toBeGreaterThan(500);++ const violations = findDroppedSilent(tracked.map(read), wrappers);+ expect(+ violations,+ 'These calls pass `{ silent: … }` to an API wrapper whose parameter at that position does not '+ + 'forward it to `request()` — the toast still fires, or the object lands in the request body. Give the '+ + 'wrapper an `options` parameter and spread it into `request(…, { …, ...options })`.\n'+ + `Offenders:\n ${violations.join('\n ')}`,+ ).toEqual([]);+ });++ // Guards the guard: if the recognizer stops reading wrappers or call sites, the+ // scan above goes vacuously green and the dropped-option class walks back in.+ it('reads wrapper parameters and silent call sites', () => {+ const wrappers = wrapperExports(`+ export const noOptions = (id) => request(\`/x/\${id}\`);+ export const named = (id, options) => request(\`/x/\${id}\`, options);+ export const optsDefault = (id, opts = {}) => request(\`/x/\${id}\`, opts);+ export const spreads = (id, data, extra) => request('/x', { method: 'PUT', body: JSON.stringify(data), ...extra });+ export const destructured = (id, { silent, limit } = {}) => request('/x', { silent });+ export const payloadOnly = (id, data) => request('/x', { method: 'POST', body: JSON.stringify(data) });+ export async function restArgs(...args) { return request('/x', args[0]); }+ export const passThrough = (id, o) => request('/x', o);+ `);+ const byName = Object.fromEntries(wrappers.map((w) => [w.name, w]));+ expect(wrappers).toHaveLength(8);+ expect(forwardsOptionsAt(byName.noOptions, 1)).toBe(false);+ expect(forwardsOptionsAt(byName.named, 1)).toBe(true);+ expect(forwardsOptionsAt(byName.optsDefault, 1)).toBe(true);+ expect(forwardsOptionsAt(byName.spreads, 2)).toBe(true);+ expect(forwardsOptionsAt(byName.spreads, 1)).toBe(false);+ expect(forwardsOptionsAt(byName.destructured, 1)).toBe(true);+ expect(forwardsOptionsAt(byName.payloadOnly, 1)).toBe(false);+ expect(forwardsOptionsAt(byName.restArgs, 1)).toBe(true);+ expect(forwardsOptionsAt(byName.passThrough, 1)).toBe(true);++ const names = new Set(['noOptions', 'named']);+ const imp = "import { noOptions, named } from './services/api';\n";+ expect(silentCalls(`${imp}noOptions(id, { silent: true });`, names)).toEqual([{ line: 2, name: 'noOptions', index: 1 }]);+ expect(silentCalls('api.noOptions(id, { retries: 1, silent });', names)).toHaveLength(1);+ expect(silentCalls(`${imp}named(id, { silent: true });`, names)).toHaveLength(1);+ // A callback handed in as a parameter (not imported) is the caller's contract.+ expect(silentCalls('function f({ noOptions }) { noOptions(id, { silent: true }); }', names)).toEqual([]);+ // A different callee, a method call, and a comment are not wrapper calls.+ expect(silentCalls('other(id, { silent: true });', names)).toEqual([]);+ expect(silentCalls(`${imp}thing.named(id, { silent: true });`, names)).toEqual([]);+ expect(silentCalls(`${imp}// noOptions(id, { silent: true })`, names)).toEqual([]);+ });++ it('flags a call whose position the wrapper drops and accepts a forwarding one', () => {+ const wrappers = wrapperExports(`+ export const noOptions = (id) => request(\`/x/\${id}\`);+ export const named = (id, options) => request(\`/x/\${id}\`, options);+ `);+ const files = [+ { file: 'a.jsx', src: "import { noOptions, named } from './services/api';\nnoOptions(1, { silent: true });\nnamed(1, { silent: true });" },+ ];+ expect(findDroppedSilent(files, wrappers)).toEqual(['a.jsx:2 noOptions(…) passes { silent } as argument 2']);+ });+});diff --git a/client/src/components/brain/tabs/BrainGraph.jsx b/client/src/components/brain/tabs/BrainGraph.jsxindex 99a136ec0d..95ac5c4083 100644--- a/client/src/components/brain/tabs/BrainGraph.jsx+++ b/client/src/components/brain/tabs/BrainGraph.jsx@@ -16,7 +16,7 @@ import InlineConfirmRow from '../../ui/InlineConfirmRow';import BrailleSpinner from '../../BrailleSpinner';import useGraphNodeDetail from '../../../hooks/useGraphNodeDetail';import usePrefersReducedMotion from '../../../hooks/usePrefersReducedMotion';-import { formatDateNumeric } from '../../../utils/formatters';+import { formatDateNumeric, formatPercent } from '../../../utils/formatters';const EDGE_COLORS = {similar: '#3b82f6',@@ -728,7 +728,7 @@ export default function BrainGraph() {<span className="inline-block w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: BRAIN_TYPE_HEX[cn.brainType] }} /><span className="text-xs text-gray-300 truncate flex-1">{cn.label}</span><span className="text-[10px] text-gray-600 shrink-0">- {cn.edgeType === 'linked' ? 'linked' : cn.edgeType === 'shared_tag' ? 'tag' : `${((cn.weight || 0) * 100).toFixed(0)}%`}+ {cn.edgeType === 'linked' ? 'linked' : cn.edgeType === 'shared_tag' ? 'tag' : formatPercent((cn.weight || 0) * 100, { decimals: 0 })}</span></button>))}diff --git a/client/src/components/brain/tabs/ConfigTab.jsx b/client/src/components/brain/tabs/ConfigTab.jsxindex fa5ad66bb5..1dc87a627e 100644--- a/client/src/components/brain/tabs/ConfigTab.jsx+++ b/client/src/components/brain/tabs/ConfigTab.jsx@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react';import * as api from '../../../services/api';import { filterSelectableModels } from '../../../utils/providers';import ProviderModelSelector from '../../ProviderModelSelector';-import { formatDateTime } from '../../../utils/formatters';+import { formatDateTime, formatPercent } from '../../../utils/formatters';import {Settings,Save,Zap,@@ -357,7 +357,7 @@ export default function ConfigTab({ onRefresh }) {<div><label htmlFor="confidence" className="block text-sm font-medium text-gray-300 mb-2">- Confidence Threshold: {(confidenceThreshold * 100).toFixed(0)}%+ Confidence Threshold: {formatPercent(confidenceThreshold * 100, { decimals: 0 })}</label><div className="flex items-center gap-4"><input@@ -371,7 +371,7 @@ export default function ConfigTab({ onRefresh }) {className="flex-1 h-2 bg-port-bg rounded-lg appearance-none cursor-pointer accent-port-accent"/><span className="text-sm text-gray-400 w-12 text-right">- {(confidenceThreshold * 100).toFixed(0)}%+ {formatPercent(confidenceThreshold * 100, { decimals: 0 })}</span></div><p className="mt-2 text-xs text-gray-500">diff --git a/client/src/components/cos/tabs/AgentRuntimeStatus.jsx b/client/src/components/cos/tabs/AgentRuntimeStatus.jsxindex 1f36eedf51..cb3465f52b 100644--- a/client/src/components/cos/tabs/AgentRuntimeStatus.jsx+++ b/client/src/components/cos/tabs/AgentRuntimeStatus.jsx@@ -1,6 +1,6 @@import { Link } from 'react-router';import { Activity, Clock, Hourglass, MessageSquare, Skull, Terminal } from 'lucide-react';-import { formatDateTime, formatDurationMs, formatMonthDay, formatTimeOfDay } from '../../../utils/formatters';+import { formatDateTime, formatDurationMs, formatMonthDay, formatTimeOfDay, formatPercent } from '../../../utils/formatters';import { describeEstimateBasis } from '../../../lib/cosDurationEstimate';const ETA_PRESENTATION = {@@ -100,7 +100,7 @@ export function AgentRuntimeStatus({<Activity size={10} aria-hidden="true" className="shrink-0" /><span className="font-mono">PID {processStats.pid}</span><span className="text-port-success/70">|</span>- <span className="font-mono">{processStats.cpu?.toFixed(1)}%</span>+ <span className="font-mono">{formatPercent(processStats.cpu)}</span><span className="text-port-success/70">|</span><span className="font-mono">{processStats.memoryMb}MB</span></span>diff --git a/client/src/components/cos/tabs/MemoryEditModal.jsx b/client/src/components/cos/tabs/MemoryEditModal.jsxindex 1abe23c03a..aafa8647bf 100644--- a/client/src/components/cos/tabs/MemoryEditModal.jsx+++ b/client/src/components/cos/tabs/MemoryEditModal.jsx@@ -5,7 +5,7 @@ import Modal from '../../ui/Modal';import { FormField } from '../../ui/FormField';import * as api from '../../../services/api';import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';-import { getAppName } from '../../../utils/formatters';+import { getAppName, formatPercent } from '../../../utils/formatters';export default function MemoryEditModal({ memory, apps, onSave, onClose }) {const [formData, setFormData] = useState({@@ -251,7 +251,7 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {{/* Importance and Confidence */}<div className="flex flex-col sm:flex-row gap-4"><FormField- label={<>Importance: {(formData.importance * 100).toFixed(0)}%</>}+ label={<>Importance: {formatPercent(formData.importance * 100, { decimals: 0 })}</>}className="flex-1"labelClassName="block text-sm text-gray-400 mb-2">@@ -266,7 +266,7 @@ export default function MemoryEditModal({ memory, apps, onSave, onClose }) {/></FormField><FormField- label={<>Confidence: {(formData.confidence * 100).toFixed(0)}%</>}+ label={<>Confidence: {formatPercent(formData.confidence * 100, { decimals: 0 })}</>}className="flex-1"labelClassName="block text-sm text-gray-400 mb-2">diff --git a/client/src/components/cos/tabs/MemoryGraph.jsx b/client/src/components/cos/tabs/MemoryGraph.jsxindex ccfd00c5c9..0aa093ba49 100644--- a/client/src/components/cos/tabs/MemoryGraph.jsx+++ b/client/src/components/cos/tabs/MemoryGraph.jsx@@ -10,7 +10,7 @@ import TouchDragHint from '../../graph3d/TouchDragHint';import BrailleSpinner from '../../BrailleSpinner';import useGraphNodeDetail from '../../../hooks/useGraphNodeDetail';import usePrefersReducedMotion from '../../../hooks/usePrefersReducedMotion';-import { formatDateNumeric } from '../../../utils/formatters';+import { formatDateNumeric, formatPercent } from '../../../utils/formatters';const TYPE_HEX = {fact: '#3b82f6',@@ -241,7 +241,7 @@ export default function MemoryGraph() {<span className="text-[10px] text-gray-500">{hoveredNode.category}</span></div><p className="text-xs text-white leading-snug">{hoveredNode.summary}</p>- <p className="text-[10px] text-gray-500 mt-1">importance: {((hoveredNode.importance ?? 0.5) * 100).toFixed(0)}%</p>+ <p className="text-[10px] text-gray-500 mt-1">importance: {formatPercent((hoveredNode.importance ?? 0.5) * 100, { decimals: 0 })}</p></div>)}</div>@@ -256,7 +256,7 @@ export default function MemoryGraph() {{selectedNode.type}</span><span className="text-xs text-gray-500">{selectedNode.category}</span>- <span className="text-xs text-gray-500">importance: {((selectedNode.importance ?? 0.5) * 100).toFixed(0)}%</span>+ <span className="text-xs text-gray-500">importance: {formatPercent((selectedNode.importance ?? 0.5) * 100, { decimals: 0 })}</span></div>{fullMemory ? (<div className="space-y-3">@@ -271,7 +271,7 @@ export default function MemoryGraph() {<div className="text-xs text-gray-500 flex flex-wrap gap-3"><span>Created: {formatDateNumeric(fullMemory.createdAt)}</span>{fullMemory.accessCount > 0 && <span>Accessed: {fullMemory.accessCount}x</span>}- {fullMemory.confidence != null && <span>Confidence: {(fullMemory.confidence * 100).toFixed(0)}%</span>}+ {fullMemory.confidence != null && <span>Confidence: {formatPercent(fullMemory.confidence * 100, { decimals: 0 })}</span>}</div></div>) : (@@ -301,7 +301,7 @@ export default function MemoryGraph() {<span className="inline-block w-2 h-2 rounded-full shrink-0" style={{ backgroundColor: TYPE_HEX[cn.type] }} /><span className="text-xs text-gray-300 truncate flex-1">{cn.summary}</span><span className="text-[10px] text-gray-600 shrink-0">- {cn.edgeType === 'linked' ? 'linked' : `${(cn.weight * 100).toFixed(0)}%`}+ {cn.edgeType === 'linked' ? 'linked' : `${formatPercent(cn.weight * 100, { decimals: 0 })}`}</span></button>))}diff --git a/client/src/components/cos/tabs/MemoryTab.jsx b/client/src/components/cos/tabs/MemoryTab.jsxindex 05807d5930..f24704a1a7 100644--- a/client/src/components/cos/tabs/MemoryTab.jsx+++ b/client/src/components/cos/tabs/MemoryTab.jsx@@ -5,7 +5,7 @@ import toast from '../../ui/Toast';import Banner from '../../ui/Banner';import * as api from '../../../services/api';import { MEMORY_TYPES, MEMORY_TYPE_COLORS } from '../constants';-import { getAppName, formatDateNumeric } from '../../../utils/formatters';+import { getAppName, formatDateNumeric, formatPercent } from '../../../utils/formatters';import MemoryTimeline from './MemoryTimeline';// Lazy: MemoryGraph pulls the three.js stack; load it only when rendered.const MemoryGraph = lazy(() => import('./MemoryGraph'));@@ -271,7 +271,7 @@ export default function MemoryTab({ apps = [] }) {</span><span className="text-xs text-gray-500">{memory.category}</span><span className="text-xs text-yellow-400">- {((memory.confidence || 0) * 100).toFixed(0)}% confidence+ {formatPercent((memory.confidence || 0) * 100, { decimals: 0 })} confidence</span></div><p className="text-white text-sm whitespace-pre-wrap">{memory.summary || memory.content}</p>@@ -412,7 +412,7 @@ export default function MemoryTab({ apps = [] }) {</span>)}{memory.similarity && (- <span className="text-xs text-port-accent">{(memory.similarity * 100).toFixed(0)}% match</span>+ <span className="text-xs text-port-accent">{formatPercent(memory.similarity * 100, { decimals: 0 })} match</span>)}</div><p className="text-white text-sm whitespace-pre-wrap">{memory.summary || memory.content}</p>@@ -428,7 +428,7 @@ export default function MemoryTab({ apps = [] }) {<div className="text-xs text-gray-500 mt-2 flex flex-wrap items-center gap-2"><span>{formatDateNumeric(memory.createdAt)}</span><span>*</span>- <span>importance: {((memory.importance || 0.5) * 100).toFixed(0)}%</span>+ <span>importance: {formatPercent((memory.importance || 0.5) * 100, { decimals: 0 })}</span>{getAppName(memory.sourceAppId, apps) && (<><span>*</span>diff --git a/client/src/components/meatspace/tabs/CalendarTab.jsx b/client/src/components/meatspace/tabs/CalendarTab.jsxindex 185e737b89..e0bc0f1825 100644--- a/client/src/components/meatspace/tabs/CalendarTab.jsx+++ b/client/src/components/meatspace/tabs/CalendarTab.jsx@@ -10,7 +10,7 @@ import LifeGrid from './calendar/LifeGrid';import TimeStats from './calendar/TimeStats';import AddActivityForm from './calendar/AddActivityForm';import LifeEventsPanel from './calendar/LifeEventsPanel';-import { formatCount } from '../../../utils/formatters';+import { formatCount, formatPercent } from '../../../utils/formatters';export default function CalendarTab() {const [data, setData] = useState(null);@@ -120,7 +120,7 @@ export default function CalendarTab() {<div className="flex-1 min-w-[140px] max-w-[300px]"><div className="flex justify-between text-xs text-gray-500 mb-1"><span>Life Progress</span>- <span className={pctColor}>{pctSpent.toFixed(1)}%</span>+ <span className={pctColor}>{formatPercent(pctSpent)}</span></div><div className="h-2 bg-port-bg rounded-full overflow-hidden"><divdiff --git a/client/src/components/media/RigPanel.jsx b/client/src/components/media/RigPanel.jsxindex c5aa75a214..6bf1385109 100644--- a/client/src/components/media/RigPanel.jsx+++ b/client/src/components/media/RigPanel.jsx@@ -4,7 +4,7 @@ import { getRiggingReadiness, rigImageTo3dModel, listRiggingClips, retargetImageimport { riggingReasonLabel } from '../../lib/riggingReasons.js';import useMounted from '../../hooks/useMounted';import { useInstanceFeatures } from '../../hooks/useInstanceFeatures';-import { formatBytes, formatCount } from '../../utils/formatters';+import { formatBytes, formatCount, formatPercent } from '../../utils/formatters';import toast from '../ui/Toast';/**@@ -157,8 +157,8 @@ export default function RigPanel({ record, onRecordChange }) {</p><p>Automatic weighting left{' '}- {`${((rig.summary?.unweightedFractionAfterHeat ?? 0) * 100).toFixed(1)}%`} unweighted- {' '}(ceiling {`${((rig.summary?.unweightedCeiling ?? 0) * 100).toFixed(1)}%`}); the nearest-bone pass+ {formatPercent((rig.summary?.unweightedFractionAfterHeat ?? 0) * 100)} unweighted+ {' '}(ceiling {formatPercent((rig.summary?.unweightedCeiling ?? 0) * 100)}); the nearest-bone passcompleted {rig.summary?.nearestBoneCompleted ?? 0}.</p><adiff --git a/client/src/components/models/UntrustedContentPolicyPanel.jsx b/client/src/components/models/UntrustedContentPolicyPanel.jsxindex 78d82ac926..35f9b5ad5b 100644--- a/client/src/components/models/UntrustedContentPolicyPanel.jsx+++ b/client/src/components/models/UntrustedContentPolicyPanel.jsx@@ -3,6 +3,7 @@ import { getSettings, updateSettings } from '../../services/api';import useProviderModels from '../../hooks/useProviderModels';import ProviderModelSelector from '../ProviderModelSelector';import toast from '../ui/Toast';+import { isLocalEndpoint } from '../../utils/providerEndpoints';import {PRIVATE_UNTRUSTED_CONTENT_SOURCES,UNTRUSTED_CONTENT_SOURCES,@@ -15,12 +16,7 @@ const SOURCES = [];const PRIVATE_SOURCES = PRIVATE_UNTRUSTED_CONTENT_SOURCES;const apiProvider = provider => provider.type === 'api';-const localApiProvider = provider => {- if (!apiProvider(provider) || !URL.canParse(provider.endpoint)) return false;- const endpoint = new URL(provider.endpoint);- return ['http:', 'https:'].includes(endpoint.protocol) && !endpoint.username && !endpoint.password- && ['localhost', '127.0.0.1', '[::1]'].includes(endpoint.hostname.toLowerCase());-};+const localApiProvider = provider => apiProvider(provider) && isLocalEndpoint(provider.endpoint);const INPUT_CLASS = 'w-full min-w-0 px-3 py-2 bg-port-bg border border-port-border rounded-lg text-sm text-white';export default function UntrustedContentPolicyPanel() {diff --git a/client/src/components/musicVideo/MusicVideoProjectCard.jsx b/client/src/components/musicVideo/MusicVideoProjectCard.jsxindex fb6bd5b9b4..8d75765e42 100644--- a/client/src/components/musicVideo/MusicVideoProjectCard.jsx+++ b/client/src/components/musicVideo/MusicVideoProjectCard.jsx@@ -3,6 +3,7 @@ import { Film, Play, Music, Wand2, Sparkles, Copy, Trash2, ArrowUpRight } from 'import MediaImage from '../MediaImage.jsx';import ScenePreview from '../creative-director/ScenePreview.jsx';import ConfirmButtonPair from '../ui/ConfirmButtonPair.jsx';+import { formatUsd } from '../../utils/formatters.js';import { selectMusicVideoPreview } from '../../lib/musicVideoPreview.js';import { useVideoFileSrc } from '../../hooks/useVideoFileSrc.js';import { deriveStages, projectSpend, projectShotSummary, MUSIC_VIDEO_STAGES } from '../../lib/musicVideoStages.js';@@ -259,7 +260,7 @@ export default function MusicVideoProjectCard({</span>{spend.capUsd != null || spend.spentUsd > 0 ? (<span className="font-mono text-port-text-muted">- ${spend.spentUsd.toFixed(2)}{spend.capUsd != null ? ` / $${spend.capUsd}` : ''}+ {formatUsd(spend.spentUsd)}{spend.capUsd != null ? ` / ${formatUsd(spend.capUsd, { trimWhole: true })}` : ''}</span>) : null}</div>diff --git a/client/src/lib/mindThinkingPresets.js b/client/src/lib/mindThinkingPresets.jsindex d3155a200a..f12261925c 100644--- a/client/src/lib/mindThinkingPresets.js+++ b/client/src/lib/mindThinkingPresets.js@@ -12,7 +12,7 @@* READ of the already-loaded provider record, not a capability call.*/-import { formatCount, formatRuntime } from '../utils/formatters.js';+import { formatCount, formatRuntime, formatUsd } from '../utils/formatters.js';import {credentialSource,isApiProvider,@@ -170,7 +170,7 @@ export function formatMindCallUsage(usage) {parts.push(`${formatCount(usage.inputTokens)} in`);}if (usage.costUsd !== null && usage.costUsd !== undefined) {- parts.push(`$${usage.costUsd.toFixed(4)}`);+ parts.push(formatUsd(usage.costUsd, { maximumFractionDigits: 4 }));}return parts.length > 0 ? parts.join(' · ') : 'Usage unknown';}diff --git a/client/src/lib/mindThinkingPresets.test.js b/client/src/lib/mindThinkingPresets.test.jsindex fffee1127d..87d75667f3 100644--- a/client/src/lib/mindThinkingPresets.test.js+++ b/client/src/lib/mindThinkingPresets.test.js@@ -60,7 +60,13 @@ describe('formatMindCallUsage', () => {it('renders a reported zero cost as a real measured value', () => {expect(formatMindCallUsage({state: 'reported', source: 'provider-reported', inputTokens: 10, outputTokens: 5, totalTokens: 15, costUsd: 0,- })).toBe('15 tokens · $0.0000');+ })).toBe('15 tokens · $0.00');+ });++ it('keeps sub-cent precision on a small reported cost', () => {+ expect(formatMindCallUsage({+ state: 'reported', source: 'provider-reported', inputTokens: 10, outputTokens: 5, totalTokens: 15, costUsd: 0.0123,+ })).toBe('15 tokens · $0.0123');});});diff --git a/client/src/numberFormattingConventions.test.js b/client/src/numberFormattingConventions.test.jsindex 2971471464..9ec270e93c 100644--- a/client/src/numberFormattingConventions.test.js+++ b/client/src/numberFormattingConventions.test.js@@ -24,6 +24,13 @@* The rule is therefore structural rather than per-site: any `.toLocaleString(`* call outside the allowlist fails this suite.*+ * Percent and USD have the same shape of drift (#9951): a hand-rolled+ * `` `${x.toFixed(1)}%` `` renders `%` for a missing value and keeps trailing+ * zeros, and `` `$${x.toFixed(2)}` `` drops thousands grouping and the sign+ * handling `formatUsd` owns. Both route through `formatPercent` / `formatUsd`;+ * a `toFixed(...)` whose next token is `%`, or whose result is the amount+ * after a `$`, fails this suite. `formatters.js` is exempt (it implements them).+ ** ## Allowlist** - `src/utils/formatters.js` — it IS the canonical implementation (`formatCount`@@ -77,6 +84,31 @@ export function findRawToLocaleString(src) {return [...stripComments(src).matchAll(RAW_TO_LOCALE_STRING)].map((m) => m[0].trim());}+/**+ * `toFixed(n)` immediately followed by a `%` — in a template (`${x.toFixed(1)}%`),+ * in JSX text (`{x.toFixed(1)}%`), or concatenated (`x.toFixed(1) + '%'`).+ */+const HAND_ROLLED_PERCENT = /\.toFixed\s*\([^)]*\)\s*(?:\}|\+\s*['"`])\s*%/g;++/**+ * `toFixed(n)` rendered as a dollar amount: `$${x.toFixed(2)}` in a template, or+ * JSX text `${x.toFixed(2)}` (a `$` right before the expression container). The+ * JSX form is only read on a line with no backtick before it, because inside a+ * template literal a bare `${x.toFixed(2)}` is ordinary interpolation.+ */+const TEMPLATE_USD = /\$\$\{[^}]*\.toFixed\s*\(/g;+const JSX_USD = /^[^`]*\$\{[^}]*\.toFixed\s*\(/;++/** Hand-rolled `toFixed` percent / USD renders in `src`, as matched snippets. */+export function findHandRolledPercentOrUsd(src) {+ const code = stripComments(src);+ const hits = [...code.matchAll(HAND_ROLLED_PERCENT), ...code.matchAll(TEMPLATE_USD)].map((m) => m[0].trim());+ for (const line of code.split('\n')) {+ if (JSX_USD.test(line)) hits.push(line.trim());+ }+ return hits;+}+describe('Number/date formatting goes through utils/formatters', () => {it('has no raw .toLocaleString( calls outside the wrapper and its allowlist', () => {const files = trackedSourceFiles(CLIENT_ROOT);@@ -102,6 +134,43 @@ describe('Number/date formatting goes through utils/formatters', () => {).toEqual([]);});+ it('has no hand-rolled toFixed percent or USD outside utils/formatters', () => {+ const files = trackedSourceFiles(CLIENT_ROOT);+ expect(files.length).toBeGreaterThan(100);++ const violations = [];+ for (const file of files) {+ if (file === WRAPPER_FILE) continue;+ const src = readFileSync(join(CLIENT_ROOT, file), 'utf8');+ for (const hit of findHandRolledPercentOrUsd(src)) violations.push(`${file}: ${hit}`);+ }++ expect(+ violations,+ 'These files format a percentage or dollar amount with `toFixed`. Use '+ + '`formatPercent(value, { decimals })` (value already 0–100; multiply a fraction by 100 first) '+ + 'or `formatUsd(value)` from `utils/formatters` — they render a missing value as `—`, '+ + 'drop float noise, and group thousands.\n'+ + `Offenders:\n ${violations.join('\n ')}`,+ ).toEqual([]);+ });++ it('flags a hand-rolled percent or USD shape and accepts the formatters', () => {+ expect(findHandRolledPercentOrUsd('const s = `${x.toFixed(1)}%`;')).toHaveLength(1);+ expect(findHandRolledPercentOrUsd('<span>{p.cpu?.toFixed(0)}% CPU</span>')).toHaveLength(1);+ expect(findHandRolledPercentOrUsd("const s = x.toFixed(1) + '%';")).toHaveLength(1);+ expect(findHandRolledPercentOrUsd('parts.push(`$${usage.costUsd.toFixed(4)}`);')).toHaveLength(1);+ expect(findHandRolledPercentOrUsd('<b>${spend.spentUsd.toFixed(2)}</b>')).toHaveLength(1);++ expect(findHandRolledPercentOrUsd('formatPercent(x * 100, { decimals: 0 })')).toEqual([]);+ expect(findHandRolledPercentOrUsd('formatUsd(spend.spentUsd)')).toEqual([]);+ // Non-percent / non-currency `toFixed` uses stay legal: seconds, SVG coordinates,+ // and a plain template interpolation of a number.+ expect(findHandRolledPercentOrUsd('`${t.toFixed(2)}s / ${d.toFixed(1)}s`')).toEqual([]);+ expect(findHandRolledPercentOrUsd('`${x.toFixed(1)},${y.toFixed(1)}`')).toEqual([]);+ expect(findHandRolledPercentOrUsd('// shows `${x.toFixed(1)}%` today')).toEqual([]);+ });+// Guards the guard: if the detector stops recognizing the call, the scan// above goes vacuously green and the bug class walks straight back in.it('flags every call shape and ignores prose that merely names the method', () => {diff --git a/client/src/pages/AgentsPage.jsx b/client/src/pages/AgentsPage.jsxindex 8659271c09..447dbc9bf5 100644--- a/client/src/pages/AgentsPage.jsx+++ b/client/src/pages/AgentsPage.jsx@@ -4,7 +4,7 @@ import * as api from '../services/api';import { useSocketResource } from '../hooks/useSocketResource';import socket from '../services/socket';import useMounted from '../hooks/useMounted';-import { formatCount, formatDateTime } from '../utils/formatters';+import { formatCount, formatDateTime, formatPercent } from '../utils/formatters';import PageSkeleton from '../components/ui/PageSkeleton';const AGENT_EVENTS = [];@@ -84,14 +84,14 @@ export function AgentsPage() {<div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm:p-5 flex items-center justify-between"><div><div className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">CPU</div>- <div className="text-lg sm:text-3xl font-bold text-white font-mono">{totalCpu.toFixed(1)}%</div>+ <div className="text-lg sm:text-3xl font-bold text-white font-mono">{formatPercent(totalCpu)}</div></div><Cpu size={20} className="sm:w-8 sm:h-8 text-port-accent" /></div><div className="bg-port-card border border-port-border rounded-lg sm:rounded-xl p-2 sm:p-5 flex items-center justify-between"><div><div className="text-gray-400 text-[10px] sm:text-sm mb-0.5 sm:mb-1">Memory</div>- <div className="text-lg sm:text-3xl font-bold text-white font-mono">{totalMemory.toFixed(1)}%</div>+ <div className="text-lg sm:text-3xl font-bold text-white font-mono">{formatPercent(totalMemory)}</div></div><MemoryStick size={20} className="sm:w-8 sm:h-8 text-port-success" /></div>@@ -130,11 +130,11 @@ export function AgentsPage() {<div className="flex items-center gap-4 text-xs"><div className="flex items-center gap-1"><span className="text-gray-500">CPU</span>- <span className="font-mono text-port-success">{agent.cpu?.toFixed(1)}%</span>+ <span className="font-mono text-port-success">{formatPercent(agent.cpu)}</span></div><div className="flex items-center gap-1"><span className="text-gray-500">Mem</span>- <span className="font-mono text-port-accent">{agent.memory?.toFixed(1)}%</span>+ <span className="font-mono text-port-accent">{formatPercent(agent.memory)}</span></div></div><button@@ -219,8 +219,8 @@ export function AgentsPage() {</td><td className="px-4 py-4 font-mono text-white">{agent.pid}</td><td className="px-4 py-4 font-mono text-port-accent">{agent.runtimeFormatted}</td>- <td className="px-4 py-4 font-mono text-port-success">{agent.cpu?.toFixed(1)}%</td>- <td className="px-4 py-4 font-mono text-port-accent">{agent.memory?.toFixed(1)}%</td>+ <td className="px-4 py-4 font-mono text-port-success">{formatPercent(agent.cpu)}</td>+ <td className="px-4 py-4 font-mono text-port-accent">{formatPercent(agent.memory)}</td><td className="px-4 py-4 font-mono text-gray-300">{agent.agentName.toLowerCase()}{agent.source === 'cos' && (@@ -320,7 +320,7 @@ export function AgentsPage() {<div><div className="flex items-center justify-between text-xs mb-1"><span className="text-gray-500 uppercase tracking-wide">CPU Usage</span>- <span className="text-port-success font-mono">{agent.cpu?.toFixed(1)}%</span>+ <span className="text-port-success font-mono">{formatPercent(agent.cpu)}</span></div><div className="h-2 bg-port-border rounded-full overflow-hidden"><div@@ -332,7 +332,7 @@ export function AgentsPage() {<div><div className="flex items-center justify-between text-xs mb-1"><span className="text-gray-500 uppercase tracking-wide">Memory Usage</span>- <span className="text-port-accent font-mono">{agent.memory?.toFixed(1)}%</span>+ <span className="text-port-accent font-mono">{formatPercent(agent.memory)}</span></div><div className="h-2 bg-port-border rounded-full overflow-hidden"><divdiff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsxindex a17211fc90..27e6cd6273 100644--- a/client/src/pages/SystemHealthPage.jsx+++ b/client/src/pages/SystemHealthPage.jsx@@ -3,6 +3,7 @@ import { Link, Navigate, useParams } from 'react-router';import { Activity, AlertTriangle, HardDrive, Cpu, Database, ListOrdered, RefreshCw, ServerCog, X, Zap } from 'lucide-react';import * as api from '../services/api';import toast from '../components/ui/Toast';+import { formatPercent } from '../utils/formatters';import PageSkeleton from '../components/ui/PageSkeleton';import Banner from '../components/ui/Banner';import { useSocketResource } from '../hooks/useSocketResource';@@ -312,7 +313,7 @@ function SystemHealthOverview() {<div key={p.name} className="flex items-center gap-3 px-3 py-2 rounded-lg bg-port-bg/40 hover:bg-port-bg/60 text-sm"><span className={`w-2 h-2 rounded-full ${p.status === 'online' ? 'bg-port-success' : p.status === 'errored' ? 'bg-port-error' : 'bg-gray-500'}`} /><span className="flex-1 text-gray-200 font-mono text-xs truncate">{p.name}</span>- <span className="text-gray-400 tabular-nums">{p.cpu.toFixed(0)}% CPU</span>+ <span className="text-gray-400 tabular-nums">{formatPercent(p.cpu, { decimals: 0 })} CPU</span><span className="text-gray-100 tabular-nums w-24 text-right">{p.memoryFormatted}</span>{p.unstableRestarts > 0 && (<span className="text-port-warning text-xs">{p.unstableRestarts} crash-loop</span>diff --git a/client/src/pages/VideoTimelineEditor.jsx b/client/src/pages/VideoTimelineEditor.jsxindex 6adcadc9b1..bfb9fdeaa6 100644--- a/client/src/pages/VideoTimelineEditor.jsx+++ b/client/src/pages/VideoTimelineEditor.jsx@@ -21,7 +21,7 @@ import {} from 'lucide-react';import toast from '../components/ui/Toast';import * as api from '../services/api';-import { formatTimecode, clamp } from '../utils/formatters';+import { formatTimecode, clamp, formatPercent } from '../utils/formatters';import { useSseProgress, isTerminalSseFrame } from '../hooks/useSseProgress';import {TimelineBlock, FloatingLane, LibraryTile, StillTile, AudioRow, BedAudio,@@ -921,7 +921,7 @@ function TimelineProjectEditor({ projectId }) {className="flex items-center gap-2 px-3 py-1.5 bg-port-success hover:bg-port-success/80 disabled:opacity-40 disabled:cursor-not-allowed text-white text-sm rounded-md">{renderJobId ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}- {renderJobId ? `Rendering ${(renderProgress * 100).toFixed(0)}%` : 'Render'}+ {renderJobId ? `Rendering ${formatPercent(renderProgress * 100, { decimals: 0 })}` : 'Render'}</button></div></div>diff --git a/server/lib/aiToolkit/internal/providerCatalogService.js b/server/lib/aiToolkit/internal/providerCatalogService.jsindex 914bdad455..2886db7265 100644--- a/server/lib/aiToolkit/internal/providerCatalogService.js+++ b/server/lib/aiToolkit/internal/providerCatalogService.js@@ -144,7 +144,7 @@ export function createProviderCatalogService({}fetched = await this._withCachedCheckpoints(provider, probe);} catch (error) {- console.error(`Failed to refresh models for ${provider.name}:`, error.message);+ console.error(`❌ Failed to refresh models for ${provider.name}:`, error.message);error.status = error.status || 502;throw error;}diff --git a/server/lib/jsonIo.js b/server/lib/jsonIo.jsindex 9eb04e2a79..7d563c637b 100644--- a/server/lib/jsonIo.js+++ b/server/lib/jsonIo.js@@ -70,7 +70,7 @@ export function safeJSONParse(str, defaultValue = null, { allowArray = true, logif (!str || !str.trim()) {if (logError && str) {- console.warn(`Invalid JSON${context ? ` in ${context}` : ''}: empty or malformed content`);+ console.warn(`⚠️ Invalid JSON${context ? ` in ${context}` : ''}: empty or malformed content`);}return defaultValue;}@@ -79,14 +79,14 @@ export function safeJSONParse(str, defaultValue = null, { allowArray = true, logconst parsed = JSON.parse(str);if (!allowArray && Array.isArray(parsed)) {if (logError) {- console.warn(`Invalid JSON${context ? ` in ${context}` : ''}: array not allowed`);+ console.warn(`⚠️ Invalid JSON${context ? ` in ${context}` : ''}: array not allowed`);}return defaultValue;}return parsed;} catch (err) {if (logError) {- console.warn(`Failed to parse JSON${context ? ` in ${context}` : ''}: ${err.message}`);+ console.warn(`⚠️ Failed to parse JSON${context ? ` in ${context}` : ''}: ${err.message}`);}return defaultValue;}@@ -328,7 +328,7 @@ export async function readJSONFileStrict(filePath, defaultValue = null, { allowAreturn { ok: true, value: defaultValue };}if (logError) {- console.warn(`Failed to read file ${filePath}: ${err.message}`);+ console.warn(`⚠️ Failed to read file ${filePath}: ${err.message}`);}return { ok: false, value: defaultValue };}@@ -360,7 +360,7 @@ export async function readJSONFileStrict(filePath, defaultValue = null, { allowA// a strict caller must refuse to count a shape it cannot count.if (allowArray && Array.isArray(defaultValue) && !Array.isArray(parsed)) {if (logError) {- console.warn(`Expected a JSON array in ${filePath}, got ${parsed === null ? 'null' : typeof parsed}`);+ console.warn(`⚠️ Expected a JSON array in ${filePath}, got ${parsed === null ? 'null' : typeof parsed}`);}return { ok: false, value: defaultValue };}@@ -476,7 +476,7 @@ export async function readJSONLFile(filePath, { logErrors = false } = {}) {}// Log other I/O errors if requestedif (logErrors) {- console.warn(`Failed to read file ${filePath}: ${err.message}`);+ console.warn(`⚠️ Failed to read file ${filePath}: ${err.message}`);}return [];}diff --git a/server/logLevelConventions.test.js b/server/logLevelConventions.test.jsindex 2c0dbc862d..d0e7f22132 100644--- a/server/logLevelConventions.test.js+++ b/server/logLevelConventions.test.js@@ -1,6 +1,7 @@/*** Long-running Node process guard: a failure line may not be logged through- * `console.log`.+ * `console.log`, and every log line carries a leading marker emoji and never a+ * bare error object (#9951).** ## The bug class*@@ -32,9 +33,30 @@* version-refusal notice in `services/sharing/importer.js`, for one), and* re-leveling those is per-domain judgment, not a tree-wide rule.*+ * ## Marker and error-object rule (#9951)+ *+ * The single-line-logging convention (root `AGENTS.md`) is an emoji prefix plus+ * string interpolation, and the stream rule above only works because the marker+ * is there to read. Two further shapes defeat it:+ *+ * - A `console.log|warn|error|info|debug` whose first argument is a literal+ * with NO leading marker emoji — it cannot be grepped by marker and the+ * failure-level scan never sees it.+ * - A bare error object as an argument (`console.error('❌ …', err)`) — it+ * prints a multi-line stack and every enumerable property, breaking+ * one-line-per-event. Interpolate `${err.message}` instead.+ *+ * Judged only where the text is visible to a lexer: a literal whose body starts+ * with `${` (the marker may live in an interpolated `LOG_PREFIX` / icon+ * variable) and an indented continuation line (body starts with two spaces,+ * the follow-on lines of a multi-line notice) are accepted, and a first+ * argument that is not a literal is never judged. `server/scripts/` (one-shot+ * operator CLIs whose output is human-formatted, not a log stream) and+ * `server/test/` (fixtures) are exempt from this second rule.+ ** ## Allowlist*- * There is none, on purpose. Every site in the tree passes; a new violation is+ * There is none for the failure-stream rule, on purpose. Every site in the tree passes; a new violation is* a bug to fix, not an entry to add. If you are reading this because the scan* just failed, change `console.log` to `console.error` (or `console.warn` for a* refusal) on the named line.@@ -117,11 +139,75 @@ export function findMislabeledFailureLogs(src) {.map(({ line, args }) => `line ${line}: ${args.replace(/\s+/g, ' ').trim().slice(0, 120)}`);}+const CONSOLE_CALL_OPEN = /\bconsole\s*\.\s*(log|warn|error|info|debug)\s*\(/g;+const BARE_ERROR_ARG = /^(?:err|error|e|ex|reason)$/;+// Shown to the reader of a failing marker scan — only literals whose first+// character a lexer can see are judged (see the rule above).+const LEADING_MARKER = /^\p{Extended_Pictographic}/u;++/**+ * Every `console.<level>(…)` call as `{ line, method, args }`, where `args` is the+ * top-level argument list with comment bodies blanked and literal text kept.+ * Argument boundaries come from the fully blanked copy, so a comma inside a+ * string or template cannot split an argument.+ */+export function consoleCalls(src) {+ const blanked = blankLiterals(src);+ const codeOnly = blankCommentBodies(src);+ const calls = [];+ for (const match of blanked.matchAll(CONSOLE_CALL_OPEN)) {+ const open = blanked.indexOf('(', match.index);+ const close = matchBracket(blanked, open);+ if (close === -1) continue;+ const end = close - 1;+ const args = [];+ let depth = 0;+ let start = open + 1;+ for (let i = open + 1; i < end; i++) {+ const c = blanked[i];+ if ('([{'.includes(c)) depth++;+ else if (')]}'.includes(c)) depth--;+ else if (c === ',' && depth === 0) {+ args.push(codeOnly.slice(start, i).trim());+ start = i + 1;+ }+ }+ const last = codeOnly.slice(start, end).trim();+ if (last) args.push(last);+ calls.push({ line: src.slice(0, match.index).split('\n').length, method: match[1], args });+ }+ return calls;+}++/** `line N: <excerpt>` for every console call whose literal message has no leading marker emoji. */+export function findMarkerlessLogs(src) {+ const hits = [];+ for (const { line, args } of consoleCalls(src)) {+ const literal = (args[0] ?? '').match(/^(['"`])([\s\S]*)/);+ if (!literal) continue;+ // `\n` / `\r` escapes lead a spaced-out block; they are not part of the message.+ const body = literal[2].replace(/^(?:\\[nr])+/, '');+ if (body.startsWith('${') || body.startsWith(' ')) continue;+ if (!LEADING_MARKER.test(body.trimStart())) hits.push(`line ${line}: ${args[0].slice(0, 80)}`);+ }+ return hits;+}++/** `line N: <excerpt>` for every console call passing a bare error identifier as an argument. */+export function findBareErrorArguments(src) {+ return consoleCalls(src)+ .filter(({ args }) => args.some((arg) => BARE_ERROR_ARG.test(arg)))+ .map(({ line, args }) => `line ${line}: ${args.join(', ').slice(0, 80)}`);+}+// Every module extension the covered process trees actually ship, not just// `.js`. The repository root is important: using `server/` as cwd silently// excludes the sibling `autofixer/` daemon.const REPO_ROOT = dirname(SERVER_ROOT);const PROCESS_ROOTS = ['server/', 'autofixer/'];+// One-shot operator CLIs print human-formatted output, and fixtures stub other+// code; neither is a log stream a marker grep or stderr monitor reads.+const LINE_SHAPE_EXEMPT_PREFIXES = ['server/scripts/', 'server/test/'];const trackedServerSources = () => execFileSync('git', ['ls-files', '*.js', '*.mjs', '*.cjs'], {cwd: REPO_ROOT,encoding: 'utf8',@@ -178,6 +264,59 @@ describe('failure lines log at error level (#7945)', () => {});});+describe('log lines carry a marker and no bare error object (#9951)', () => {+ const scanned = () => trackedServerSources()+ .filter((file) => !LINE_SHAPE_EXEMPT_PREFIXES.some((prefix) => file.startsWith(prefix)))+ .map((file) => ({ file, src: readFileSync(join(REPO_ROOT, file), 'utf8') }))+ .filter(({ src }) => /\bconsole\s*\.\s*(?:log|warn|error|info|debug)\s*\(/.test(src));++ it('has no console call whose message lacks a leading marker emoji', () => {+ const violations = scanned().flatMap(({ file, src }) => findMarkerlessLogs(src).map((hit) => `${file} ${hit}`));+ expect(+ violations,+ 'These log lines have no leading marker emoji (root `AGENTS.md` single-line logging: '+ + '`console.log(`🚀 …`)`, `❌` failure, `⚠️` refusal). Add the marker; the stream picks the level.\n'+ + `Offenders:\n ${violations.join('\n ')}`,+ ).toEqual([]);+ });++ it('passes no bare error object to a console call', () => {+ const violations = scanned().flatMap(({ file, src }) => findBareErrorArguments(src).map((hit) => `${file} ${hit}`));+ expect(+ violations,+ 'These calls hand a whole error object to console, which prints a multi-line stack. '+ + 'Interpolate it: `console.error(`❌ … ${err.message}`)`.\n'+ + `Offenders:\n ${violations.join('\n ')}`,+ ).toEqual([]);+ });++ it('flags a marker-less literal and accepts the shapes it cannot judge', () => {+ expect(findMarkerlessLogs("console.warn(`Failed to read ${p}`);")).toHaveLength(1);+ expect(findMarkerlessLogs("console.log('server started');")).toHaveLength(1);+ expect(findMarkerlessLogs('console.error(`[Tag] failed`);')).toHaveLength(1);++ expect(findMarkerlessLogs(`console.log(\`\\n${String.fromCodePoint(0x1f6d1)} stopping\`);`)).toEqual([]);+ expect(findMarkerlessLogs("console.warn(`⚠️ refused`);")).toEqual([]);+ // The marker may live in an interpolated prefix the scan cannot see.+ expect(findMarkerlessLogs('console.log(`${LOG_PREFIX}: armed`);')).toEqual([]);+ // Indented follow-on line of a multi-line notice.+ expect(findMarkerlessLogs("console.error(' Set up the database with: npm run setup:db');")).toEqual([]);+ // A non-literal first argument is never judged.+ expect(findMarkerlessLogs('console.error(logMsg, stack);')).toEqual([]);+ expect(findMarkerlessLogs("// console.log('no marker in a comment')")).toEqual([]);+ });++ it('flags a bare error argument and accepts interpolated or property access', () => {+ expect(findBareErrorArguments("console.error('❌ failed', err);")).toHaveLength(1);+ expect(findBareErrorArguments("console.error('❌ failed:', error);")).toHaveLength(1);++ expect(findBareErrorArguments('console.error(`❌ failed: ${err.message}`);')).toEqual([]);+ expect(findBareErrorArguments('console.error(err.stack);')).toEqual([]);+ // A comma inside a template must not split off a fake bare argument.+ expect(findBareErrorArguments('console.error(`❌ a, err, b`);')).toEqual([]);+ });+});+// Guards the guard: if the recognizer stops seeing the broken shape, the scan// above goes green and the bug class walks straight back in.describe('the failure-log recognizer', () => {diff --git a/server/services/browserService.js b/server/services/browserService.jsindex 185e31e05e..ea98825dae 100644--- a/server/services/browserService.js+++ b/server/services/browserService.js@@ -8,6 +8,7 @@ import { readdir, stat, unlink } from 'fs/promises';import { join, basename, dirname, resolve, extname } from 'path';import { EventEmitter } from 'events';import { ensureDir, safeJSONParse, PATHS, tryReadFile, atomicWrite, sleep } from '../lib/fileUtils.js';+import { PORTS } from '../lib/ports.js';import { normalizeBrowserConfig } from '../lib/browserConfig.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { readResponseJson } from '../lib/readResponseJson.js';@@ -32,9 +33,9 @@ const DEFAULT_PROFILE_DIR = PATHS.browserProfile;const DEFAULT_DOWNLOAD_DIR = PATHS.browserDownloads;const DEFAULT_CONFIG = {- cdpPort: 5556,+ cdpPort: PORTS.CDP,cdpHost: process.env.CDP_HOST || '127.0.0.1',- healthPort: 5557,+ healthPort: PORTS.CDP_HEALTH,autoConnect: true,// Default HEADED — the managed CDP browser is meant to be visible (see// browser/server.js, which already launches headed unless `headless === true`).diff --git a/server/services/fableLoom/hostedSession.js b/server/services/fableLoom/hostedSession.jsindex ec4271254d..bdbf05fa19 100644--- a/server/services/fableLoom/hostedSession.js+++ b/server/services/fableLoom/hostedSession.js@@ -705,7 +705,7 @@ export async function processHostedUtterance(sessionId, {// A torn-down turn aborts this signal. That is a cancellation, not a// successful empty transcription, and must not fall through as one.if (turn.abortController.signal.aborted) return null;- console.warn(`[HostedPlay] STT transcription failed: ${err.message}`);+ console.warn(`⚠️ [HostedPlay] STT transcription failed: ${err.message}`);return { text: '' };});if (!sttResult || !isLive()) return abandonTurn('transcription');@@ -756,7 +756,7 @@ export async function processHostedUtterance(sessionId, {// A cancelled turn has no one left to narrate to — the authored fallback// would only produce a reply for a room that already saw `ended`.if (!isLive()) return abandonTurn('story turn');- console.warn(`[HostedPlay] LLM turn error, using authored fallback: ${err?.message}`);+ console.warn(`⚠️ [HostedPlay] LLM turn error, using authored fallback: ${err?.message}`);playResult = {action: 'stay',narration: node?.prose?.slice(0, 200) || "I hear you. Let's see what happens next.",@@ -811,14 +811,14 @@ export async function processHostedUtterance(sessionId, {voice: voice || undefined,}).catch((err) => {if (turn.abortController.signal.aborted) return null;- console.warn(`[HostedPlay] Protagonist TTS synthesis failed: ${err.message}`);+ console.warn(`⚠️ [HostedPlay] Protagonist TTS synthesis failed: ${err.message}`);return null;});if (synth?.wav) {ttsAudio = synth.wav;}} catch (err) {- console.warn(`[HostedPlay] Protagonist TTS synthesis failed: ${err.message}`);+ console.warn(`⚠️ [HostedPlay] Protagonist TTS synthesis failed: ${err.message}`);}if (!isLive()) return abandonTurn('speech synthesis');@@ -860,7 +860,7 @@ export async function processHostedUtterance(sessionId, {// already emitted its terminal frame, so log and swallow rather than// emitting `hosted:error` behind it.if (!isLive()) {- console.warn(`[HostedPlay] Hosted turn ${turn.id} failed after teardown: ${err?.message || err}`);+ console.warn(`⚠️ [HostedPlay] Hosted turn ${turn.id} failed after teardown: ${err?.message || err}`);return abandonedResult;}// Emit BEFORE clearing `activeTurn` — clearing it first makes the turndiff --git a/server/services/googleAuth.js b/server/services/googleAuth.jsindex cb14f9ec96..0cd846c522 100644--- a/server/services/googleAuth.js+++ b/server/services/googleAuth.js@@ -2,6 +2,7 @@ import { auth } from '@googleapis/calendar';import { join } from 'path';import { atomicWrite, ensureDir, PATHS, tryReadFile } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';+import { PORTS } from '../lib/ports.js';const { OAuth2: OAuth2Client } = auth;const AUTH_DIR = join(PATHS.calendar, 'google-auth');@@ -11,7 +12,7 @@ const SCOPES = ['https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/gmail.modify'];-export const OAUTH_REDIRECT_URI = `http://${process.env.PUBLIC_HOST || 'localhost'}:${process.env.PORT || 5555}/api/calendar/google/oauth/callback`;+export const OAUTH_REDIRECT_URI = `http://${process.env.PUBLIC_HOST || 'localhost'}:${process.env.PORT || PORTS.API}/api/calendar/google/oauth/callback`;let oAuth2Client = null;diff --git a/server/services/htmlComposition/encode.musicVideo.memory-check.mjs b/server/services/htmlComposition/encode.musicVideo.memory-check.mjsindex bb5ab6f8de..6eec2d7030 100644--- a/server/services/htmlComposition/encode.musicVideo.memory-check.mjs+++ b/server/services/htmlComposition/encode.musicVideo.memory-check.mjs@@ -5,7 +5,7 @@ import { EventEmitter } from 'node:events';import { encodeComposition } from './encode.js';if (typeof global.gc !== 'function') {- console.error('forced GC is required');+ console.error('❌ forced GC is required');process.exit(2);}@@ -45,7 +45,7 @@ await encodeComposition(page, { fps: 12, durationSec: 600, width: 1280, height:const delta = samples.length === 2 ? samples[1] - samples[0] : Number.POSITIVE_INFINITY;if (!(bytes > 0) || samples.length !== 2 || delta >= 12 * 1024 * 1024) {- console.error(`retained-heap delta=${delta} bytes=${bytes} samples=${samples.length}`);+ console.error(`❌ retained-heap delta=${delta} bytes=${bytes} samples=${samples.length}`);process.exit(1);}-console.log(`retained-heap delta=${delta}`);+console.log(`✅ retained-heap delta=${delta}`);diff --git a/server/services/pipeline/migrateSeriesCanon.js b/server/services/pipeline/migrateSeriesCanon.jsindex 32cd08264e..b896d5a9e7 100644--- a/server/services/pipeline/migrateSeriesCanon.js+++ b/server/services/pipeline/migrateSeriesCanon.js@@ -228,5 +228,5 @@ if (isDirectlyInvoked(import.meta.url)) {const dryRun = process.argv.includes('--dry-run');migrateSeriesCanon({ dryRun }).then(() => process.exit(0))- .catch((err) => { console.error('❌ Migration failed:', err); process.exit(1); });+ .catch((err) => { console.error(`❌ Migration failed: ${err.message}`); process.exit(1); });}diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.jsindex 998870f55c..c59492d5cc 100644--- a/server/services/sharing/peerSyncAssets.js+++ b/server/services/sharing/peerSyncAssets.js@@ -295,7 +295,7 @@ const ASSET_KIND_EXTENSIONS = {function hasAllowedAssetExtension(kind, filename) {if (ASSET_KIND_EXTENSIONS[kind]?.has(extname(filename).toLowerCase())) return true;// Do not echo a peer-controlled filename into the log (it can contain CR/LF).- console.warn(`peerSync: skipped unsupported ${kind} asset extension`);+ console.warn(`⚠️ peerSync: skipped unsupported ${kind} asset extension`);return false;}diff --git a/server/services/spotifyAuth.js b/server/services/spotifyAuth.jsindex 49b3efbbfd..ea02c3802e 100644--- a/server/services/spotifyAuth.js+++ b/server/services/spotifyAuth.js@@ -26,6 +26,7 @@ import { ServerError } from '../lib/errorHandler.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { getSelfHost } from '../lib/peerSelfHost.js';import { getHttpsEnabledAtBoot } from '../lib/httpsState.js';+import { PORTS } from '../lib/ports.js';// Cap on each token-endpoint round-trip so a hung accounts.spotify.com can't// stall an OAuth callback or a history-sync refresh indefinitely.@@ -60,7 +61,7 @@ const ACCOUNTS_BASE = 'https://accounts.spotify.com';*/export function getRedirectUri({ origin } = {}) {if (process.env.SPOTIFY_REDIRECT_URI) return process.env.SPOTIFY_REDIRECT_URI;- const port = process.env.PORT || 5555;+ const port = process.env.PORT || PORTS.API;if (origin) return `${origin.replace(/\/$/, '')}/api/spotify/oauth/callback`;if (process.env.PUBLIC_HOST) {return `http://${process.env.PUBLIC_HOST}:${port}/api/spotify/oauth/callback`;diff --git a/server/services/systemHealthSnapshot.js b/server/services/systemHealthSnapshot.jsindex 8b8303d9b6..310c27ec7e 100644--- a/server/services/systemHealthSnapshot.js+++ b/server/services/systemHealthSnapshot.js@@ -95,7 +95,7 @@ export async function getSystemHealthSnapshot() {return failedProbe;}),cos.getStatus().catch((error) => {- console.error('Chief of Staff health probe failed', error);+ console.error(`❌ Chief of Staff health probe failed: ${error.message}`);return failedProbe;}),// Queue depth is read here rather than taken off `getStatus()`, which has no@@ -114,7 +114,7 @@ export async function getSystemHealthSnapshot() {checkHealth().catch(() => ({ connected: false, hasSchema: false, error: 'Health check failed' })),getCurrentVersion().catch(() => null),statfs('/').catch((error) => {- console.error('Root filesystem health probe failed', error);+ console.error(`❌ Root filesystem health probe failed: ${error.message}`);return failedProbe;}),getMemoryStats(),