Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: share array fallback handling across server features (#7871)
[._.]/ Adam Eivyeed461e949f5
diff --git a/server/lib/README.md b/server/lib/README.mdindex 27472e2ea8..404bbf7035 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -605,7 +605,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `sourceScan.js` | Lexer-assisted primitives shared by the whole-tree source-scan guard suites, so the timer rule and the socket rule cannot drift on what "owns its rejection" means. `blankLiterals(src)` blanks comment/string/template/regex CONTENT to spaces while preserving length, so a brace inside a literal cannot skew a bracket walk and a caller can still read a literal (a socket event name) out of the original string at the same offset; `matchBracket(src, open)` returns the index past the matching `)`/`]`/`}`; `parseCallbackAt(blanked, from, limit)` parses the function expression at `from` (`async`/`function`/either arrow spelling, skipping the parameter list as a unit so a `= {}` default is not mistaken for the body) and returns `{isAsync, start, text}`; `unguardedAwaits(body)` returns the awaited chains that neither sit inside a `try`/`catch` nor END in `.catch(…)`. `blankComments(src)` is the weaker LINE-based stripper the per-line `child_process` rule needs. Callers: `childProcess.guards.test.js`, `server/timerCallbackConventions.test.js`, `server/sockets/asyncHandlerGuard.test.js`, `server/process-safety-net.test.js`. || `apiOperationContracts.js` | Detailed operation metadata for intentionally public APIs. It consumes the canonical route Zod contracts and feeds both public and internal OpenAPI documents. || `apiRegistry.js` | Single source of truth for which PortOS services are externally-callable HTTP APIs (`voice`, `sdapi`). `API_REGISTRY` declares each API's `publicPrefixes` (read/compute-safe surface only) + defaults; `isRegistryPublic(settings, path)` tells `authGate` when an `exposed && !requireAuth` API re-opens its prefix; `resolveApiAccess(settings)` merges persisted `apiAccess` flags for the Settings UI + OpenAPI docs. |-| `arrayUtils.js` | `shuffle(arr, random?)` — Fisher-Yates shuffle (new array, never mutates). The canonical uniform shuffle — never `arr.sort(() => Math.random() - 0.5)`, which is biased. Shared by `meatspacePostCognitive.js` (Schulte table / mental rotation) and `meatspacePostMemory.js` (memory drill generators). `dedupeByKey(items, keyOf, pick?)` — one survivor per key, first-seen order. **Required before any multi-row `INSERT … ON CONFLICT (key) DO UPDATE`**: Postgres refuses the whole statement ("ON CONFLICT DO UPDATE command cannot affect row a second time") when its VALUES list names one conflict key twice, and the rows a batcher joins usually come from something that promises no uniqueness (a disk scan, a peer payload). `DO NOTHING` upserts are exempt. `pick(held, candidate)` defaults to last-seen-wins (what a sequential one-row upsert loop leaves); pass a comparator when the table's conflict rule isn't "latest write" — `memorySync.applyRemoteChanges` keeps the newest `updatedAt` so a peer's payload ordering can't flip a last-writer-wins outcome. Used by `services/mediaAssetIndex/db.js` and `services/memorySync.js`. |+| `arrayUtils.js` | `asArray(value)` — returns an array unchanged, or a fresh empty array for non-array inputs. `shuffle(arr, random?)` — Fisher-Yates shuffle (new array, never mutates). The canonical uniform shuffle — never `arr.sort(() => Math.random() - 0.5)`, which is biased. Shared by `meatspacePostCognitive.js` (Schulte table / mental rotation) and `meatspacePostMemory.js` (memory drill generators). `dedupeByKey(items, keyOf, pick?)` — one survivor per key, first-seen order. **Required before any multi-row `INSERT … ON CONFLICT (key) DO UPDATE`**: Postgres refuses the whole statement ("ON CONFLICT DO UPDATE command cannot affect row a second time") when its VALUES list names one conflict key twice, and the rows a batcher joins usually come from something that promises no uniqueness (a disk scan, a peer payload). `DO NOTHING` upserts are exempt. `pick(held, candidate)` defaults to last-seen-wins (what a sequential one-row upsert loop leaves); pass a comparator when the table's conflict rule isn't "latest write" — `memorySync.applyRemoteChanges` keeps the newest `updatedAt` so a peer's payload ordering can't flip a last-writer-wins outcome. Used by `services/mediaAssetIndex/db.js` and `services/memorySync.js`. || `assetRoutePrefixes.js` | Import-free leaf holding the URL prefixes the server owns: `ASSET_ROUTE_PREFIXES` (every `/data/**` static mount) and `SERVER_OWNED_PREFIXES` (what must never reach the SPA fallback, each with the exact `spaPaths` that ARE client routes). `scripts/dev-proxy-drift.test.js` checks the dev proxy's `^/data/` wildcard against the mounts, pins the route-registration order in `server/index.js` (a router added below the terminators is shadowed), and fails if a client route — from `NAV_COMMANDS` or `App.jsx`'s nested `<Route>` tree — is ever added under a server-owned prefix without being declared. || `asyncMutex.js` | Promise-based async mutex. || `concurrencyGate.js` | `createConcurrencyGate(limit)` → `run(fn)` — cap on simultaneous async work for ONE module-scoped budget, released FIFO. Sibling to `mapWithConcurrency.js`, which caps in-flight work *within one array map*; a gate is shared state, so several call sites fanning out at the same remote respect one budget instead of each respecting its own while the host sees the sum. `createMutex` (`asyncMutex.js`) is this with `limit` fixed at 1 — prefer it for mutual exclusion. Note the budget is per-MODULE, not per-host: two modules calling one host each get their own gate. Used by `huggingFaceMetadata.js` (4) and `ollamaRegistryCatalog.js` (16), whose cold catalog-enrichment bursts otherwise arrive at a free public API as a thundering herd — which the Hub answers with an HTTP/2 GOAWAY that surfaces as a bare `fetch failed`. |diff --git a/server/lib/arrayUtils.js b/server/lib/arrayUtils.jsindex 1afd908314..7bb9f07792 100644--- a/server/lib/arrayUtils.js+++ b/server/lib/arrayUtils.js@@ -2,6 +2,9 @@* Array utilities — pure, side-effect-free helpers shared across services.*/+/** Return array inputs unchanged, or a fresh empty array for anything else. */+export const asArray = (value) => (Array.isArray(value) ? value : []);+/*** Fisher-Yates shuffle. Returns a new array in randomized order; never* mutates the input. Use this everywhere an array needs a uniform randomdiff --git a/server/lib/arrayUtils.test.js b/server/lib/arrayUtils.test.jsindex 9553f23d66..fa5782de70 100644--- a/server/lib/arrayUtils.test.js+++ b/server/lib/arrayUtils.test.js@@ -1,5 +1,22 @@import { describe, it, expect, vi } from 'vitest';-import { shuffle, dedupeByKey } from './arrayUtils.js';+import { asArray, shuffle, dedupeByKey } from './arrayUtils.js';++describe('asArray', () => {+ it('preserves array identity and contents, including empty arrays', () => {+ for (const input of [[], [null, 0, false, '']]) {+ Object.freeze(input);+ expect(asArray(input)).toBe(input);+ }+ });++ it('rejects non-arrays without sharing mutable fallback state', () => {+ asArray(null).push('previous fallback');+ const inputs = [undefined, null, false, 0, 'value', {}, { 0: 'value', length: 1 }, new Set(['value']), new Uint8Array([1])];+ for (const input of inputs) {+ expect(asArray(input)).toEqual([]);+ }+ });+});describe('shuffle', () => {it('returns a new array — never mutates the input', () => {diff --git a/server/lib/characterEvolutionCoverage.js b/server/lib/characterEvolutionCoverage.jsindex d95d0af292..52a8890947 100644--- a/server/lib/characterEvolutionCoverage.js+++ b/server/lib/characterEvolutionCoverage.js@@ -43,13 +43,12 @@* than being judged against a second, non-playable graph.*/+import { asArray } from './arrayUtils.js';import { EVOLUTION_STAGES, EVOLUTION_STAGE_LABELS, isDeclaredEvolution } from './characterEvolution.js';import { computeTopologicalNodeOrder } from './fableLoomProduction.js';import { enumerateEpisodePlaythroughs } from './fableLoomPlaytest.js';import { isNonBlankStr } from './textUtils.js';-const asArray = (value) => (Array.isArray(value) ? value : []);-/*** Per-lens and whole-report coverage. Mirrors `CHARACTER_REVIEW_STATUSES` in* `characterIntegrityVocabulary.js` on purpose — the two answer the same shaped questiondiff --git a/server/lib/eidoverseObservation.js b/server/lib/eidoverseObservation.jsindex 9d9f23efd5..5c2ccc8b5a 100644--- a/server/lib/eidoverseObservation.js+++ b/server/lib/eidoverseObservation.js@@ -36,6 +36,7 @@* digest), and nothing here reads a record body.*/+import { asArray } from './arrayUtils.js';import {EIDOVERSE_SCALAR_SOURCE_KEYS,EIDOVERSE_WORLD_DESIGN_V3,@@ -60,7 +61,6 @@ const MAX_CHANGE_ENTRIES = 20;// which degrades to reporting them as new once, not to a broken file.const MAX_MARKER_FOUNDATION_IDS = 2000;-const asArray = (value) => (Array.isArray(value) ? value : []);const sortedUnique = (values) => [...new Set(asArray(values).filter(Boolean))].sort();/**diff --git a/server/lib/fableLoomGraph.js b/server/lib/fableLoomGraph.jsindex 552e96fbed..1e2d521b66 100644--- a/server/lib/fableLoomGraph.js+++ b/server/lib/fableLoomGraph.js@@ -13,8 +13,8 @@* blocks on.*/+import { asArray } from './arrayUtils.js';import { isNonBlankStr } from './textUtils.js';-const asArray = (v) => (Array.isArray(v) ? v : []);export const GRAPH_ISSUE_CODES = Object.freeze({MISSING_START: 'MISSING_START',diff --git a/server/lib/fableLoomOutline.js b/server/lib/fableLoomOutline.jsindex 52f36fd420..7cdfa4889b 100644--- a/server/lib/fableLoomOutline.js+++ b/server/lib/fableLoomOutline.js@@ -8,11 +8,11 @@* before an outline is expanded and whenever an author edits it by hand.*/+import { asArray } from './arrayUtils.js';import { LOOM_LIMITS } from './fableLoomLimits.js';import { FABLELOOM_PROTAGONIST_PRESENCE } from './fableLoomPlayback.js';import { trimTo, isNonBlankStr } from './textUtils.js';-const asArray = (value) => (Array.isArray(value) ? value : []);const isObject = (value) => value && typeof value === 'object';export const OUTLINE_ISSUE_CODES = Object.freeze({diff --git a/server/lib/fableLoomPlaytest.js b/server/lib/fableLoomPlaytest.jsindex 13d23f0de9..6ba5dc0178 100644--- a/server/lib/fableLoomPlaytest.js+++ b/server/lib/fableLoomPlaytest.js@@ -7,11 +7,10 @@* the resulting narrative paths. The service layer owns that AI review.*/+import { asArray } from './arrayUtils.js';import { analyzeEpisodeGraph } from './fableLoomGraph.js';import { isNonBlankStr } from './textUtils.js';-const asArray = (value) => (Array.isArray(value) ? value : []);-export const FABLELOOM_PLAYTEST_LIMITS = Object.freeze({DEFAULT_MAX_PATHS: 96,MAX_PATHS: 256,diff --git a/server/services/fableLoom/editorial.js b/server/services/fableLoom/editorial.jsindex 1125e2dbb8..0ddf720e80 100644--- a/server/services/fableLoom/editorial.js+++ b/server/services/fableLoom/editorial.js@@ -8,6 +8,7 @@* edits land; the autopilot composes the two bounded operations.*/+import { asArray } from '../../lib/arrayUtils.js';import { ServerError } from '../../lib/errorHandler.js';import { analyzeEpisodeContinuity, CONTINUITY_CODES } from '../../lib/fableLoomContinuity.js';import { analyzeEpisodeGraph, describeGraphForPrompt } from '../../lib/fableLoomGraph.js';@@ -75,7 +76,6 @@ const INSTRUCTION_PLACEHOLDER_VALUES = new Set(['the signal shivers through the flooded tunnel walls.',]);-const asArray = (value) => (Array.isArray(value) ? value : []);const hasOwn = (value, key) => Object.hasOwn(value, key);const clampScore = (value) => (Number.isFinite(value)? Math.max(0, Math.min(10, Math.round(value * 10) / 10))diff --git a/server/services/portosProductMetrics.js b/server/services/portosProductMetrics.jsindex 80af851dd6..226f0c7301 100644--- a/server/services/portosProductMetrics.js+++ b/server/services/portosProductMetrics.js@@ -9,6 +9,7 @@* item needing attention.*/+import { asArray } from '../lib/arrayUtils.js';import { getPostSessions } from './meatspacePost.js';import { getAllTrainingEntries } from './postTrainingLogStore.js';import { listCommissions } from './creativeCommissions/store.js';@@ -25,7 +26,6 @@ const COMPLETED_PROJECT_STATUSES = new Set(['complete', 'completed']);const NON_REVIEWABLE_RUN_STATUSES = new Set(['failed', 'skipped', 'cancelled', 'canceled', 'error']);const isObject = (value) => value && typeof value === 'object' && !Array.isArray(value);-const asArray = (value) => (Array.isArray(value) ? value : []);function dateKey(value, timezone) {return recordDayKey(value, timezone);