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
address review (codex r2): verify nested manifest hash pins, scope verification to this run's copies, surface missing assets, isTestRunner backend gate
[._.]/ Adam Eivyab14fd99f4c8
diff --git a/server/services/sprites/importer.js b/server/services/sprites/importer.jsindex 01897ab0b4..423c2cc329 100644--- a/server/services/sprites/importer.js+++ b/server/services/sprites/importer.js@@ -77,21 +77,28 @@ async function copyTree(srcDir, destDir, shouldCopy = () => true) {}/**- * Verify copied files against the sha256 map a source manifest declares.- * `expectations` is [{ relPath, sha256 }] relative to destDir; missing files- * and hash mismatches land in the returned errors list.+ * Verify hash-pinned files against the sha256s the source manifests declare.+ * Only files copied by THIS run count — a stale copy left in the destination+ * by an earlier import must not vouch for a file the current source no+ * longer provides. Duplicate expectations (the same file pinned by more than+ * one manifest) collapse to one check per (path, hash).*/-async function verifyHashes(destDir, expectations, errors) {+async function verifyHashes(destDir, expectations, errors, copiedThisRun) {+ const seen = new Set();+ const unique = expectations.filter(({ relPath, sha256 }) => {+ if (typeof sha256 !== 'string' || !sha256) return false;+ const key = `${relPath}\n${sha256}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });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}` };- }),+ unique.map(async ({ relPath, sha256 }) => {+ if (!copiedThisRun.has(relPath)) return { error: `missing from source: ${relPath}` };+ return (await sha256File(join(destDir, relPath))) === 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;@@ -118,17 +125,44 @@ function relToCharacterDir(manifestPath, characterId) {// and packaged manifests — never raw/extracted intermediates or source video.const ASSET_REF = /\.(png|gif|json)$/i;const EXCLUDED_RUN_SEGMENTS = /(^|\/)(raw|frames|review)\//;+// Free-text log fields in run records can contain path-looking strings that+// were never assets — don't traverse them.+const NOISE_KEYS = /tail$|^stdout|^stderr|^log$/i;++function importableRel(value, characterId) {+ const rel = relToCharacterDir(value, characterId);+ return rel && ASSET_REF.test(rel) && !EXCLUDED_RUN_SEGMENTS.test(rel) ? rel : null;+}-// Recursively collect importable asset paths referenced anywhere in a-// manifest's JSON (string values that normalize into the character dir).-function collectManifestRefs(node, characterId, out) {+/**+ * Recursively collect importable asset paths referenced anywhere in a+ * manifest's JSON — and, when a manifest hash-pins a referenced file (a+ * `{ path, sha256 }` record, or the `<base>Path`/`<base>Sha256` sibling-key+ * convention), the expectation pair so the copied bytes get verified too.+ */+function collectManifestRefs(node, characterId, refs, expectations) {if (typeof node === 'string') {- const rel = relToCharacterDir(node, characterId);- if (rel && ASSET_REF.test(rel) && !EXCLUDED_RUN_SEGMENTS.test(rel)) out.add(rel);+ const rel = importableRel(node, characterId);+ if (rel) refs.add(rel);} else if (Array.isArray(node)) {- for (const v of node) collectManifestRefs(v, characterId, out);+ for (const v of node) collectManifestRefs(v, characterId, refs, expectations);} else if (node && typeof node === 'object') {- for (const v of Object.values(node)) collectManifestRefs(v, characterId, out);+ for (const [k, v] of Object.entries(node)) {+ if (NOISE_KEYS.test(k)) continue;+ collectManifestRefs(v, characterId, refs, expectations);+ }+ if (typeof node.sha256 === 'string' && typeof node.path === 'string') {+ const rel = importableRel(node.path, characterId);+ if (rel) expectations.push({ relPath: rel, sha256: node.sha256 });+ }+ for (const [k, v] of Object.entries(node)) {+ if (!k.endsWith('Sha256') || typeof v !== 'string') continue;+ const base = k.slice(0, -'Sha256'.length);+ const pathVal = node[base] ?? node[`${base}Path`];+ if (typeof pathVal !== 'string') continue;+ const rel = importableRel(pathVal, characterId);+ if (rel) expectations.push({ relPath: rel, sha256: v });+ }}}@@ -149,7 +183,7 @@ async function copyCharFile(srcCharDir, destDir, rel) {* strips at the version root, surrounded by unselected candidates that must* stay behind).*/-async function importApprovedDirection({ srcCharDir, destDir, characterId, direction, dir, result, hashExpectations }) {+async function importApprovedDirection({ srcCharDir, destDir, characterId, direction, dir, result, hashExpectations, copiedThisRun }) {const manifestRel = relToCharacterDir(dir.runManifest, characterId);if (!manifestRel) {result.errors.push(`walk set ${direction}: unsafe run path rejected: ${dir.runManifest || dir.runPath}`);@@ -160,22 +194,30 @@ async function importApprovedDirection({ srcCharDir, destDir, characterId, direcreturn;}result.files += 1;+ copiedThisRun.add(manifestRel);if (dir.runManifestSha256) hashExpectations.push({ relPath: manifestRel, sha256: dir.runManifestSha256 });const refs = new Set();- collectManifestRefs(await readJson(join(srcCharDir, manifestRel)), characterId, refs);+ collectManifestRefs(await readJson(join(srcCharDir, manifestRel)), characterId, refs, hashExpectations);const runRel = relToCharacterDir(dir.runPath, characterId);if (runRel && (await pathExists(join(srcCharDir, `${runRel}/generated/review-preview.json`)))) {refs.add(`${runRel}/generated/review-preview.json`);}// One extra expansion level: packaged manifests / previews the run record- // names in turn declare the strip files.+ // names in turn declare the strip files (and their hash pins).for (const rel of [...refs]) {- if (rel.endsWith('.json')) collectManifestRefs(await readJson(join(srcCharDir, rel)), characterId, refs);+ if (rel.endsWith('.json')) collectManifestRefs(await readJson(join(srcCharDir, rel)), characterId, refs, hashExpectations);}refs.delete(manifestRel);for (const rel of [...refs].sort()) {- if (await copyCharFile(srcCharDir, destDir, rel)) result.files += 1;+ if (await copyCharFile(srcCharDir, destDir, rel)) {+ result.files += 1;+ copiedThisRun.add(rel);+ } else {+ // A manifest-declared asset the source no longer has is a real gap —+ // an "imported" subject must not silently omit an approved artifact.+ result.errors.push(`walk set ${direction}: referenced asset missing: ${rel}`);+ }}}@@ -190,6 +232,10 @@ async function importCharacter({ sourceRoot, characterId, spec, specPath, selectresult.files += 1;const hashExpectations = [];+ // Every file THIS run copied (dest-relative). Verification is scoped to+ // this set so a stale destination copy can't vouch for a file the current+ // source no longer provides.+ const copiedThisRun = new Set(['character-spec.json']);// reference/ — locked main + anchors; candidates/ (unapproved) stay behind.if (await pathExists(join(srcCharDir, 'reference'))) {@@ -199,6 +245,7 @@ async function importCharacter({ sourceRoot, characterId, spec, specPath, select(rel, isDir) => !(isDir && basename(rel) === 'candidates') && !rel.includes('candidates/'),);result.files += copied.length;+ for (const rel of copied) copiedThisRun.add(`reference/${rel}`);for (const rel of copied) {if (!rel.endsWith('.json')) continue;const manifest = await readJson(join(destDir, 'reference', rel));@@ -216,6 +263,7 @@ async function importCharacter({ sourceRoot, characterId, spec, specPath, selectif (await pathExists(walkDir)) {const copied = await copyTree(walkDir, join(destDir, 'walk'));result.files += copied.length;+ for (const rel of copied) copiedThisRun.add(`walk/${rel}`);for (const rel of copied) {if (!rel.endsWith('.json')) continue;const walkSet = await readJson(join(destDir, 'walk', rel));@@ -225,7 +273,7 @@ async function importCharacter({ sourceRoot, characterId, spec, specPath, selectresult.errors.push(`walk set ${direction}: not approved (${dir?.status ?? 'missing'}) — skipped`);continue;}- await importApprovedDirection({ srcCharDir, destDir, characterId, direction, dir, result, hashExpectations });+ await importApprovedDirection({ srcCharDir, destDir, characterId, direction, dir, result, hashExpectations, copiedThisRun });}}}@@ -236,6 +284,7 @@ async function importCharacter({ sourceRoot, characterId, spec, specPath, selectif (await pathExists(join(srcCharDir, 'runtime'))) {const copied = await copyTree(join(srcCharDir, 'runtime'), join(destDir, 'runtime'));result.files += copied.length;+ for (const rel of copied) copiedThisRun.add(`runtime/${rel}`);}// Published-selection provenance: verify the immutable runtime atlas the@@ -245,10 +294,16 @@ async function importCharacter({ sourceRoot, characterId, spec, specPath, selectconst immRel = relToCharacterDir(imm?.path, characterId);if (immRel && imm?.sha256) hashExpectations.push({ relPath: immRel, sha256: imm.sha256 });const keyedRel = relToCharacterDir(selection.selected?.keyedSourcePath, characterId);- if (keyedRel && (await copyCharFile(srcCharDir, destDir, keyedRel))) result.files += 1;+ if (keyedRel && (await copyCharFile(srcCharDir, destDir, keyedRel))) {+ result.files += 1;+ copiedThisRun.add(keyedRel);+ if (selection.selected?.keyedSourceSha256) {+ hashExpectations.push({ relPath: keyedRel, sha256: selection.selected.keyedSourceSha256 });+ }+ }}- result.verified = await verifyHashes(destDir, hashExpectations, result.errors);+ result.verified = await verifyHashes(destDir, hashExpectations, result.errors, copiedThisRun);const record = await upsertImportedRecord(characterId, {kind: 'character',diff --git a/server/services/sprites/importer.test.js b/server/services/sprites/importer.test.jsindex f9313cd46d..b5ba3a555b 100644--- a/server/services/sprites/importer.test.js+++ b/server/services/sprites/importer.test.js@@ -50,6 +50,10 @@ const southPackagedManifest = JSON.stringify({kind: 'deterministically-packaged-grok-walk-video', direction: 'south',sourceVideoPath: 'art-source/sprites/hero/grok/run-1/generated/source-video.mp4',frames: [{ path: 'art-source/sprites/hero/grok/run-1/generated/frames/f0.png' }],+ // Hash-pinned asset record: the copied strip must verify against this.+ assets: [{ path: 'art-source/sprites/hero/grok/run-1/generated/south-strip.png', sha256: sha256('FAKE-STRIP') }],+ // Path-looking strings in log tails must be ignored, not imported.+ stdoutTail: 'wrote art-source/sprites/hero/grok/run-1/generated/raw/ghost.png',}, null, 2);const southReviewPreview = JSON.stringify({stripPath: 'art-source/sprites/hero/grok/run-1/generated/south-strip.png', frameCount: 8, fps: 12,@@ -59,6 +63,9 @@ const southReviewPreview = JSON.stringify({const eastManifest = JSON.stringify({kind: 'imagegen-redraw-manifest', direction: 'east',stripPath: 'art-source/sprites/hero/imagegen/v2/east-strip.png',+ // Declared but absent from the source — must surface as an error, not a+ // silent skip that still reports a fully-imported subject.+ overlayPath: 'art-source/sprites/hero/imagegen/v2/gone.png',}, null, 2);beforeAll(() => {@@ -168,9 +175,11 @@ describe('importFromSource', () => {const hero = results.find((r) => r.id === 'hero');expect(hero.kind).toBe('character');- // south anchor + south run record + east manifest + hash-pinned runtime atlas- expect(hero.verified).toBe(4);+ // south anchor + south run record + pinned south strip + east manifest+ // + hash-pinned runtime atlas+ expect(hero.verified).toBe(5);expect(hero.errors).toEqual([+ 'walk set east: referenced asset missing: imagegen/v2/gone.png','walk set west: not approved (pending) — skipped','walk set north: unsafe run path rejected: art-source/sprites/hero/../../../../tmp/sprite-escape/x.json','sha256 mismatch: reference/hero-anchor-east.png',@@ -213,7 +222,7 @@ describe('importFromSource', () => {expect(results.some((r) => r.id === 'character-schema-v1')).toBe(false);expect(totals.subjects).toBe(3); // hero + buddy characters, flora props- expect(totals.errors).toBe(3);+ expect(totals.errors).toBe(4);const record = await getRecord('hero');expect(record).toMatchObject({ kind: 'character', name: 'Hero', status: 'imported', chromaKey: '#FF00FF' });@@ -236,6 +245,15 @@ describe('importFromSource', () => {expect(record.chromaKey).toBe('#00FF00');});+ it('re-import errors when a hash-pinned file disappears from the source (stale dest copy must not vouch)', async () => {+ rmSync(join(SOURCE_ROOT, 'art-source/sprites/hero/reference/hero-anchor-south.png'));+ const { results } = await importFromSource({ sourceRoot: SOURCE_ROOT, characters: ['hero'], includeProps: false });+ const hero = results.find((r) => r.id === 'hero');+ expect(hero.errors).toContain('missing from source: reference/hero-anchor-south.png');+ // the destination still holds the earlier copy — it must not count as verified+ expect(existsSync(join(SPRITES_ROOT, 'hero/reference/hero-anchor-south.png'))).toBe(true);+ });+it('rejects a root that is not a sprite pipeline', async () => {const empty = mkdtempSync(join(tmpdir(), 'sprite-importer-empty-'));await expect(importFromSource({ sourceRoot: empty })).rejects.toMatchObject({ code: 'INVALID_SOURCE_ROOT' });diff --git a/server/services/sprites/records.js b/server/services/sprites/records.jsindex f4d3f18418..c110e7a138 100644--- a/server/services/sprites/records.js+++ b/server/services/sprites/records.js@@ -14,7 +14,7 @@* #2895's scope); the tombstone trio on the record keeps peer-sync additive.*/-import { checkHealth, ensureSchema } from '../../lib/db.js';+import { checkHealth, ensureSchema, isTestRunner } from '../../lib/db.js';import { listSpriteAssets } from './paths.js';let backend = null;@@ -22,8 +22,11 @@ let backend = null;async function selectBackend() {if (backend) return backend;+ // isTestRunner (NODE_ENV==='test' OR VITEST) is the repo's supported test+ // detection — a wrapper that drops NODE_ENV must still select the file+ // backend instead of hitting the real DB's test gate.const envBackend = process.env.MEMORY_BACKEND;- if (envBackend === 'file' || process.env.NODE_ENV === 'test') {+ if (envBackend === 'file' || isTestRunner()) {backend = await import('./recordsFile.js');return backend;}