Skip to content

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

refactor([issue-2895]): apply /simplify pass — reuse shared fs helpers, parallelize asset walk, trim dead surface

[._.]/ Adam Eivyfbf4a0c8492d
diff --git a/client/src/pages/Sprites.jsx b/client/src/pages/Sprites.jsx
index d6c55b63a9..ffbd862fe1 100644
--- a/client/src/pages/Sprites.jsx
+++ b/client/src/pages/Sprites.jsx
@@ -1,4 +1,4 @@
-import { useEffect, useState, useCallback } from 'react';
+import { useEffect, useState, useCallback, useMemo } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { PersonStanding, Package, Download, FolderOpen, X, RefreshCw } from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -93,46 +93,46 @@ function ImportPanel({ onImported }) {
);
}
-function RecordList({ records, selectedId, onSelect }) {
- const characters = records.filter((r) => r.kind === 'character');
- const props = records.filter((r) => r.kind !== 'character');
- const Section = ({ title, icon: Icon, items }) => (
- items.length > 0 && (
- <div>
- <h3 className="flex items-center gap-1.5 text-xs uppercase tracking-wide text-gray-500 mb-1.5">
- <Icon className="w-3.5 h-3.5" /> {title}
- </h3>
- <ul className="space-y-1">
- {items.map((r) => (
- <li key={r.id}>
- <button
- onClick={() => onSelect(r.id)}
- className={`w-full text-left px-3 py-2 rounded text-sm ${selectedId === r.id ? 'bg-port-accent/20 text-white border border-port-accent' : 'bg-port-card text-gray-300 border border-port-border hover:border-gray-500'}`}
- >
- <span className="font-medium">{r.name}</span>
- <span className="block text-xs text-gray-500">{r.status}{r.chromaKey ? ` · key ${r.chromaKey}` : ''}</span>
- </button>
- </li>
- ))}
- </ul>
- </div>
- )
+function RecordSection({ title, icon: Icon, items, selectedId, onSelect }) {
+ if (items.length === 0) return null;
+ return (
+ <div>
+ <h3 className="flex items-center gap-1.5 text-xs uppercase tracking-wide text-gray-500 mb-1.5">
+ <Icon className="w-3.5 h-3.5" /> {title}
+ </h3>
+ <ul className="space-y-1">
+ {items.map((r) => (
+ <li key={r.id}>
+ <button
+ onClick={() => onSelect(r.id)}
+ className={`w-full text-left px-3 py-2 rounded text-sm ${selectedId === r.id ? 'bg-port-accent/20 text-white border border-port-accent' : 'bg-port-card text-gray-300 border border-port-border hover:border-gray-500'}`}
+ >
+ <span className="font-medium">{r.name}</span>
+ <span className="block text-xs text-gray-500">{r.status}{r.chromaKey ? ` · key ${r.chromaKey}` : ''}</span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
);
+}
+
+function RecordList({ records, selectedId, onSelect }) {
return (
<div className="space-y-4">
- <Section title="Characters" icon={PersonStanding} items={characters} />
- <Section title="Props" icon={Package} items={props} />
+ <RecordSection title="Characters" icon={PersonStanding} items={records.filter((r) => r.kind === 'character')} selectedId={selectedId} onSelect={onSelect} />
+ <RecordSection title="Props" icon={Package} items={records.filter((r) => r.kind !== 'character')} selectedId={selectedId} onSelect={onSelect} />
</div>
);
}
function AssetGroups({ recordId, assets }) {
const [preview, setPreview] = useState(null);
- const groups = assets.reduce((acc, a) => {
+ const groups = useMemo(() => assets.reduce((acc, a) => {
const g = topLevelGroup(a.path) || 'files';
(acc[g] ||= []).push(a);
return acc;
- }, {});
+ }, {}), [assets]);
return (
<div className="space-y-4">
{Object.entries(groups).map(([group, files]) => (
diff --git a/client/src/services/apiSprites.js b/client/src/services/apiSprites.js
index 244bb9900b..9c9f48d36b 100644
--- a/client/src/services/apiSprites.js
+++ b/client/src/services/apiSprites.js
@@ -7,12 +7,6 @@ import { request } from './apiCore.js';
export const listSpriteRecords = (options = {}) => request('/sprites', options);
export const getSpriteRecord = (id, options = {}) => request(`/sprites/${encodeURIComponent(id)}`, options);
-export const updateSpriteRecord = (id, patch, options = {}) => request(`/sprites/${encodeURIComponent(id)}`, {
- method: 'PATCH', body: JSON.stringify(patch), ...options,
-});
-export const deleteSpriteRecord = (id, options = {}) => request(`/sprites/${encodeURIComponent(id)}`, {
- method: 'DELETE', ...options,
-});
// Import approved production assets from a source pipeline checkout.
// Returns { results: [...perSubject], totals }.
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 276d283750..51105a2f2a 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -2,6 +2,7 @@ import { z } from 'zod';
import { ServerError } from './errorHandler.js';
import { partialWithoutDefaults, emptyToUndefined, emptyToNull } from './zodCompat.js';
import { WORK_TRACKERS } from './workTracker.js';
+import { SPRITE_ID_PATTERN } from '../services/sprites/recordsLogic.js';
// gpt-image-2 (codex backend) caps at 3840px per edge and 8,294,400 total
// pixels. Mirror the ceiling for every image-gen route. Local mflux can
@@ -940,10 +941,12 @@ export const videoDownloadSchema = z.object({
// Sprite Manager (issue #2895, phase 1). Import runs against a local
// filesystem path the user supplies (the source pipeline checkout); the
-// importer validates the tree shape server-side.
+// importer validates the tree shape server-side. The id pattern is owned by
+// recordsLogic.js (ids double as data/sprites/ directory names) — a pure,
+// dependency-free module, so importing it here can't disturb mocked suites.
export const spriteImportRequestSchema = z.object({
sourceRoot: z.string().min(1).max(1024),
- characters: z.array(z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/)).optional(),
+ characters: z.array(z.string().regex(SPRITE_ID_PATTERN)).optional(),
includeProps: z.boolean().optional(),
});
diff --git a/server/routes/sprites.js b/server/routes/sprites.js
index a30b8cb23b..76b126a366 100644
--- a/server/routes/sprites.js
+++ b/server/routes/sprites.js
@@ -15,8 +15,7 @@ import {
spriteImportRequestSchema,
spriteRecordUpdateSchema,
} from '../lib/validation.js';
-import { listRecords, getRecord, updateRecord, deleteRecord } from '../services/sprites/records.js';
-import { listSpriteAssets } from '../services/sprites/paths.js';
+import { listRecords, getRecordWithAssets, updateRecord, deleteRecord } from '../services/sprites/records.js';
import { importFromSource } from '../services/sprites/importer.js';
const router = Router();
@@ -34,10 +33,9 @@ router.post('/import', asyncHandler(async (req, res) => {
}));
router.get('/:id', asyncHandler(async (req, res) => {
- const record = await getRecord(req.params.id);
- if (!record) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });
- const assets = await listSpriteAssets(record.id);
- res.json({ record, assets });
+ const detail = await getRecordWithAssets(req.params.id);
+ if (!detail) throw new ServerError('Sprite record not found', { status: 404, code: 'NOT_FOUND' });
+ res.json(detail);
}));
router.patch('/:id', asyncHandler(async (req, res) => {
diff --git a/server/routes/sprites.test.js b/server/routes/sprites.test.js
index 768c1a6ebb..c117f8b843 100644
--- a/server/routes/sprites.test.js
+++ b/server/routes/sprites.test.js
@@ -4,21 +4,16 @@ import { request } from '../lib/testHelper.js';
vi.mock('../services/sprites/records.js', () => ({
listRecords: vi.fn(async () => [{ id: 'pioneer', kind: 'character', name: 'Pioneer' }]),
- getRecord: vi.fn(),
+ getRecordWithAssets: vi.fn(),
updateRecord: vi.fn(async (id, patch) => ({ id, ...patch })),
deleteRecord: vi.fn(async () => ({ ok: true })),
}));
-vi.mock('../services/sprites/paths.js', () => ({
- listSpriteAssets: vi.fn(async () => [{ path: 'reference/main.png', size: 10, mtime: 1 }]),
-}));
-
vi.mock('../services/sprites/importer.js', () => ({
importFromSource: vi.fn(async () => ({ results: [], totals: { subjects: 0, files: 0, verified: 0, errors: 0 } })),
}));
import * as records from '../services/sprites/records.js';
-import * as paths from '../services/sprites/paths.js';
import * as importer from '../services/sprites/importer.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import spriteRoutes from './sprites.js';
@@ -42,17 +37,19 @@ describe('sprites routes', () => {
});
it('GET /:id returns record + asset listing', async () => {
- records.getRecord.mockResolvedValueOnce({ id: 'pioneer', kind: 'character' });
+ records.getRecordWithAssets.mockResolvedValueOnce({
+ record: { id: 'pioneer', kind: 'character' },
+ assets: [{ path: 'reference/main.png', size: 10, mtime: 1 }],
+ });
const r = await request(app).get('/api/sprites/pioneer');
expect(r.status).toBe(200);
expect(r.body.record.id).toBe('pioneer');
expect(r.body.assets).toHaveLength(1);
- expect(records.getRecord).toHaveBeenCalledWith('pioneer');
- expect(paths.listSpriteAssets).toHaveBeenCalledWith('pioneer');
+ expect(records.getRecordWithAssets).toHaveBeenCalledWith('pioneer');
});
it('GET /:id 404s on an unknown record', async () => {
- records.getRecord.mockResolvedValueOnce(null);
+ records.getRecordWithAssets.mockResolvedValueOnce(null);
const r = await request(app).get('/api/sprites/ghost');
expect(r.status).toBe(404);
});
diff --git a/server/services/sprites/importer.js b/server/services/sprites/importer.js
index 5d6271f55f..94830b797c 100644
--- a/server/services/sprites/importer.js
+++ b/server/services/sprites/importer.js
@@ -22,8 +22,8 @@
*/
import { join, basename, dirname } from 'path';
-import { readdir, copyFile, stat } from 'fs/promises';
-import { PATHS, ensureDir, sha256File, tryReadFile, atomicWrite } from '../../lib/fileUtils.js';
+import { readdir, copyFile } from 'fs/promises';
+import { PATHS, ensureDir, sha256File, atomicWrite, pathExists, readJSONFile } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { upsertImportedRecord } from './records.js';
import { spriteDir } from './paths.js';
@@ -35,24 +35,9 @@ const LEGACY_CHROMA_KEY = '#FF00FF';
const PROP_FILE_EXTENSIONS = ['.png', '.md'];
-async function pathExists(p) {
- try {
- await stat(p);
- return true;
- } catch {
- return false;
- }
-}
-
-async function readJson(p) {
- const raw = await tryReadFile(p);
- if (raw === null) return null;
- try {
- return JSON.parse(raw);
- } catch {
- return null;
- }
-}
+// Absent-or-corrupt manifest reads collapse to null — the importer treats both
+// as "nothing to import from this manifest."
+const readJson = (p) => readJSONFile(p, null, { logError: false });
/**
* Recursively copy `srcDir` into `destDir`, filtering by `shouldCopy(relPath,
@@ -60,6 +45,7 @@ async function readJson(p) {
*/
async function copyTree(srcDir, destDir, shouldCopy = () => true) {
const copied = [];
+ const ensuredDirs = new Set();
async function walk(current, rel) {
let entries;
try {
@@ -76,7 +62,11 @@ async function copyTree(srcDir, destDir, shouldCopy = () => true) {
await walk(srcPath, entryRel);
} else if (entry.isFile()) {
const destPath = join(destDir, entryRel);
- await ensureDir(dirname(destPath));
+ const parent = dirname(destPath);
+ if (!ensuredDirs.has(parent)) {
+ await ensureDir(parent);
+ ensuredDirs.add(parent);
+ }
await copyFile(srcPath, destPath);
copied.push(entryRel);
}
@@ -92,19 +82,19 @@ async function copyTree(srcDir, destDir, shouldCopy = () => true) {
* and hash mismatches land in the returned errors list.
*/
async function verifyHashes(destDir, expectations, errors) {
- let verified = 0;
- for (const { relPath, sha256 } of expectations) {
- if (typeof sha256 !== 'string' || !sha256) continue;
- const abs = join(destDir, relPath);
- if (!(await pathExists(abs))) {
- errors.push(`missing after copy: ${relPath}`);
- continue;
- }
- const actual = await sha256File(abs);
- if (actual !== sha256) errors.push(`sha256 mismatch: ${relPath}`);
- else verified += 1;
- }
- return verified;
+ const outcomes = await Promise.all(
+ expectations
+ .filter(({ sha256 }) => typeof sha256 === 'string' && sha256)
+ .map(async ({ relPath, sha256 }) => {
+ const abs = join(destDir, relPath);
+ if (!(await pathExists(abs))) return { error: `missing after copy: ${relPath}` };
+ return (await sha256File(abs)) === sha256
+ ? { verified: true }
+ : { error: `sha256 mismatch: ${relPath}` };
+ }),
+ );
+ for (const o of outcomes) if (o.error) errors.push(o.error);
+ return outcomes.filter((o) => o.verified).length;
}
// Manifest paths reference files repo-relative (art-source/sprites/<id>/…) or
diff --git a/server/services/sprites/importer.test.js b/server/services/sprites/importer.test.js
index 02c455f9e4..273837ca08 100644
--- a/server/services/sprites/importer.test.js
+++ b/server/services/sprites/importer.test.js
@@ -22,7 +22,7 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {
});
const { importFromSource } = await import('./importer.js');
-const { getRecord, updateRecord } = await import('./records.js');
+const { getRecord, updateRecord, getRecordWithAssets } = await import('./records.js');
const { resolveSpriteAssetPath, listSpriteAssets } = await import('./paths.js');
const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
@@ -141,6 +141,13 @@ describe('paths confinement', () => {
expect(assets.some((a) => a.path === 'reference/hero-main.png')).toBe(true);
});
+ it('getRecordWithAssets pairs the record with its disk listing', async () => {
+ const detail = await getRecordWithAssets('hero');
+ expect(detail.record.id).toBe('hero');
+ expect(detail.assets.length).toBeGreaterThan(0);
+ expect(await getRecordWithAssets('nobody')).toBeNull();
+ });
+
it('refuses traversal and bad ids', () => {
expect(() => resolveSpriteAssetPath('hero', '../other/file.png')).toThrow(/escapes/);
expect(() => resolveSpriteAssetPath('hero', '/etc/passwd')).toThrow(/escapes/);
diff --git a/server/services/sprites/paths.js b/server/services/sprites/paths.js
index 83aef26ea6..fcfe3a0c60 100644
--- a/server/services/sprites/paths.js
+++ b/server/services/sprites/paths.js
@@ -3,23 +3,20 @@
*
* Binary sprite assets live under data/sprites/<recordId>/ mirroring the
* source pipeline's per-character tree (reference/, walk/, runs/<run-id>/,
- * runtime/vN/, atlas/ for props families). Every request-influenced path MUST
- * resolve through `resolveSpriteAssetPath` — the confinement gate that keeps a
- * crafted record id or relative path from escaping the sprites root (the port
- * of the source pipeline's pathsec gate). `safeUnder` in lib/ffmpeg.js is
- * single-segment-only, so this module carries the multi-segment equivalent.
+ * runtime/vN/, atlas/ for props families). `spriteDir` gates every record id
+ * (ids double as directory names) and `resolveSpriteAssetPath` is the
+ * multi-segment confinement gate for request-influenced relative paths — in
+ * phase 1 inline previews are served by express.static (which does its own
+ * traversal safety), so the resolver is the forward hook the phase-2+
+ * generation/publish paths route file access through.
*/
-import { join, resolve, sep } from 'path';
+import { join, resolve } from 'path';
import { readdir, stat } from 'fs/promises';
-import { PATHS } from '../../lib/fileUtils.js';
+import { PATHS, isPathInsideDir } from '../../lib/fileUtils.js';
import { ServerError } from '../../lib/errorHandler.js';
import { isValidSpriteId } from './recordsLogic.js';
-export function spritesRoot() {
- return PATHS.sprites;
-}
-
/** Asset directory for one sprite record. Throws on a non-slug id. */
export function spriteDir(recordId) {
if (!isValidSpriteId(recordId)) {
@@ -30,7 +27,7 @@ export function spriteDir(recordId) {
/**
* Resolve a relative asset path inside a record's directory, refusing any
- * path that escapes it (`..`, absolute paths, symlink-free lexical check).
+ * path that escapes it (`..`, absolute paths).
*/
export function resolveSpriteAssetPath(recordId, relPath) {
const dir = spriteDir(recordId);
@@ -38,16 +35,17 @@ export function resolveSpriteAssetPath(recordId, relPath) {
throw new ServerError('Missing asset path', { status: 400, code: 'INVALID_ASSET_PATH' });
}
const abs = resolve(dir, relPath);
- if (abs !== dir && !abs.startsWith(dir + sep)) {
+ if (abs !== dir && !isPathInsideDir(dir, abs)) {
throw new ServerError(`Asset path escapes sprite directory: ${relPath}`, { status: 400, code: 'INVALID_ASSET_PATH' });
}
return abs;
}
/**
- * Recursively list a record's on-disk assets as
- * `[{ path, size, mtime }]` with `path` relative (posix separators) to the
- * record dir. Dotfiles are skipped. A record with no directory yet returns [].
+ * Recursively list a record's on-disk assets as `[{ path, size, mtime }]`
+ * with `path` relative (posix separators) to the record dir. Dotfiles are
+ * skipped; per-directory stats and subdirectory descents run in parallel.
+ * A record with no directory yet returns [].
*/
export async function listSpriteAssets(recordId) {
const dir = spriteDir(recordId);
@@ -59,8 +57,8 @@ export async function listSpriteAssets(recordId) {
} catch {
return; // dir absent → no assets
}
- for (const entry of entries) {
- if (entry.name.startsWith('.')) continue;
+ await Promise.all(entries.map(async (entry) => {
+ if (entry.name.startsWith('.')) return;
const rel = relPrefix ? `${relPrefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await walk(join(current, entry.name), rel);
@@ -68,7 +66,7 @@ export async function listSpriteAssets(recordId) {
const s = await stat(join(current, entry.name));
out.push({ path: rel, size: s.size, mtime: s.mtimeMs });
}
- }
+ }));
}
await walk(dir, '');
out.sort((a, b) => a.path.localeCompare(b.path));
diff --git a/server/services/sprites/records.js b/server/services/sprites/records.js
index 0dc0058aab..f4d3f18418 100644
--- a/server/services/sprites/records.js
+++ b/server/services/sprites/records.js
@@ -15,9 +15,9 @@
*/
import { checkHealth, ensureSchema } from '../../lib/db.js';
+import { listSpriteAssets } from './paths.js';
let backend = null;
-let backendName = null;
async function selectBackend() {
if (backend) return backend;
@@ -25,7 +25,6 @@ async function selectBackend() {
const envBackend = process.env.MEMORY_BACKEND;
if (envBackend === 'file' || process.env.NODE_ENV === 'test') {
backend = await import('./recordsFile.js');
- backendName = 'file';
return backend;
}
@@ -35,15 +34,9 @@ async function selectBackend() {
}
await ensureSchema();
backend = await import('./recordsDB.js');
- backendName = 'postgres';
return backend;
}
-/** Name of the active backend, or null before first call (for diagnostics/tests). */
-export function getSpriteRecordsBackendName() {
- return backendName;
-}
-
export async function listRecords(options = {}) {
return (await selectBackend()).listRecords(options);
}
@@ -52,6 +45,15 @@ export async function getRecord(id, options = {}) {
return (await selectBackend()).getRecord(id, options);
}
+/**
+ * Detail view: the record plus its on-disk asset listing, fetched in
+ * parallel. Returns null for an unknown/tombstoned record.
+ */
+export async function getRecordWithAssets(id) {
+ const [record, assets] = await Promise.all([getRecord(id), listSpriteAssets(id)]);
+ return record ? { record, assets } : null;
+}
+
export async function createRecord(input, id) {
return (await selectBackend()).createRecord(input, id);
}