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([bucket-record-path-helper]): extract bucket record-file path helpers

[._.]/ Adam Eivy57baa88b08c8
diff --git a/server/services/sharing/buckets.js b/server/services/sharing/buckets.js
index f7d3fe0b5e..1ff04f4da8 100644
--- a/server/services/sharing/buckets.js
+++ b/server/services/sharing/buckets.js
@@ -106,6 +106,15 @@ export function bucketBlobSidecarPath(bucketPath, hash) {
export function bucketBlobIndexPath(bucketPath) { return join(bucketBlobsDir(bucketPath), '.index.json'); }
export function imageSidecarName(filename) { return filename.replace(IMAGE_EXT_RE, '') + '.metadata.json'; }
+// Per-bucket record store — series/issues/universes/media/reviews JSON live
+// under `records/<type>/<id>.json`. Unlike the blob helpers above, these do
+// NOT validate `id`: every callsite supplies an id that's either locally
+// authored (the exporter) or already screened by `isSafeRecordId` (the
+// importer) before it reaches the path. Keeping them as plain joins preserves
+// the prior hand-joined behavior exactly.
+export function bucketRecordsDir(bucketPath, type) { return join(bucketPath, 'records', type); }
+export function bucketRecordPath(bucketPath, type, id) { return join(bucketRecordsDir(bucketPath, type), `${id}.json`); }
+
/**
* Returns the filename if it's safe to use as a path segment under an asset
* directory, otherwise null. Rejects path separators, parent-directory
@@ -131,10 +140,11 @@ export async function ensureBucketLayout(bucket) {
const base = bucket.path;
await ensureDir(base);
await ensureDir(join(base, 'manifests'));
- await ensureDir(join(base, 'records', 'series'));
- await ensureDir(join(base, 'records', 'issues'));
- await ensureDir(join(base, 'records', 'universes'));
- await ensureDir(join(base, 'records', 'media'));
+ await ensureDir(bucketRecordsDir(base, 'series'));
+ await ensureDir(bucketRecordsDir(base, 'issues'));
+ await ensureDir(bucketRecordsDir(base, 'universes'));
+ await ensureDir(bucketRecordsDir(base, 'media'));
+ await ensureDir(bucketRecordsDir(base, 'reviews'));
await ensureDir(join(base, 'assets', 'images'));
await ensureDir(join(base, 'assets', 'videos'));
await ensureDir(join(base, 'assets', 'blobs'));
diff --git a/server/services/sharing/buckets.test.js b/server/services/sharing/buckets.test.js
index cf053939ee..21a0634ffe 100644
--- a/server/services/sharing/buckets.test.js
+++ b/server/services/sharing/buckets.test.js
@@ -43,6 +43,7 @@ describe('sharing/buckets', () => {
expect(fs.existsSync(join(bucketTargetDir, 'records', 'issues'))).toBe(true);
expect(fs.existsSync(join(bucketTargetDir, 'records', 'universes'))).toBe(true);
expect(fs.existsSync(join(bucketTargetDir, 'records', 'media'))).toBe(true);
+ expect(fs.existsSync(join(bucketTargetDir, 'records', 'reviews'))).toBe(true);
expect(fs.existsSync(join(bucketTargetDir, 'assets', 'images'))).toBe(true);
expect(fs.existsSync(join(bucketTargetDir, 'assets', 'videos'))).toBe(true);
expect(fs.existsSync(join(bucketTargetDir, 'assets', 'blobs'))).toBe(true);
@@ -98,6 +99,23 @@ describe('sharing/buckets', () => {
}
});
+ describe('bucketRecordsDir / bucketRecordPath', () => {
+ it('joins the per-type records directory under the bucket path', () => {
+ expect(buckets.bucketRecordsDir('/b', 'series')).toBe(join('/b', 'records', 'series'));
+ expect(buckets.bucketRecordsDir('/b', 'reviews')).toBe(join('/b', 'records', 'reviews'));
+ });
+
+ it('joins the per-record file path under its type directory', () => {
+ expect(buckets.bucketRecordPath('/b', 'series', 'ser-1')).toBe(join('/b', 'records', 'series', 'ser-1.json'));
+ expect(buckets.bucketRecordPath('/b', 'media', 'abc')).toBe(join('/b', 'records', 'media', 'abc.json'));
+ });
+
+ it('nests inside the matching records directory', () => {
+ expect(buckets.bucketRecordPath('/b', 'issues', 'iss-9'))
+ .toBe(join(buckets.bucketRecordsDir('/b', 'issues'), 'iss-9.json'));
+ });
+ });
+
describe('sanitizeAssetFilename', () => {
it('returns the name for a safe bare basename', () => {
expect(buckets.sanitizeAssetFilename('abc-123.png')).toBe('abc-123.png');
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index 61ef71f847..e2d794df51 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -21,7 +21,7 @@ import { existsSync } from 'fs';
import { PATHS, ensureDir, atomicWrite, readJSONFile, sha256File } from '../../lib/fileUtils.js';
import { getOrComputeImageSha256 } from '../../lib/assetHash.js';
import { isPlainObject } from '../../lib/objects.js';
-import { getBucket, ensureBucketLayout, bucketBlobsDir, bucketBlobPath, bucketBlobSidecarPath, bucketBlobIndexPath, imageSidecarName, isHexHash } from './buckets.js';
+import { getBucket, ensureBucketLayout, bucketBlobsDir, bucketBlobPath, bucketBlobSidecarPath, bucketBlobIndexPath, bucketRecordsDir, bucketRecordPath, imageSidecarName, isHexHash } from './buckets.js';
import { buildManifest, writeManifest, pruneBucketManifests } from './manifest.js';
import { listSeries, getSeries } from '../pipeline/series.js';
import { listIssues } from '../pipeline/issues.js';
@@ -227,7 +227,7 @@ async function exportMediaJobAndAsset(jobId, bucketPath, mediaRecordsDir, cache)
result: job.result,
};
await ensureDir(mediaRecordsDir);
- await atomicWrite(join(mediaRecordsDir, `${job.id}.json`), exported);
+ await atomicWrite(bucketRecordPath(bucketPath, 'media', job.id), exported);
// Copy the produced asset(s).
const assetKind = job.kind === 'video' ? 'video' : 'image';
const refs = [];
@@ -405,7 +405,7 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {
// Write records.
const recordIds = [series.id];
const stampedSeries = stampOrigin(series, { bucket, source, sourceBio, manifestId });
- await atomicWrite(join(bucket.path, 'records', 'series', `${series.id}.json`), stampedSeries);
+ await atomicWrite(bucketRecordPath(bucket.path, 'series', series.id), stampedSeries);
// Bundle the manuscript-review sibling doc (the "Finish the draft" comment
// set) so it travels with the series. It's keyed by seriesId — not a record
@@ -416,20 +416,20 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {
const review = await getReview(series.id).catch(() => null);
const reviewRefs = [];
if (review && Array.isArray(review.comments) && review.comments.length > 0) {
- await atomicWrite(join(bucket.path, 'records', 'reviews', `${series.id}.json`), review);
+ await atomicWrite(bucketRecordPath(bucket.path, 'reviews', series.id), review);
reviewRefs.push(series.id);
}
for (const issue of issues) {
recordIds.push(issue.id);
const stamped = stampOrigin(issue, { bucket, source, sourceBio, manifestId });
- await atomicWrite(join(bucket.path, 'records', 'issues', `${issue.id}.json`), stamped);
+ await atomicWrite(bucketRecordPath(bucket.path, 'issues', issue.id), stamped);
}
if (universe) {
recordIds.push(universe.id);
const stampedUni = stampOrigin(universe, { bucket, source, sourceBio, manifestId });
- await atomicWrite(join(bucket.path, 'records', 'universes', `${universe.id}.json`), stampedUni);
+ await atomicWrite(bucketRecordPath(bucket.path, 'universes', universe.id), stampedUni);
}
// Gather asset refs across every record, plus the universe's linked
@@ -455,7 +455,7 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {
}
// Copy media-job records + their assets — run all four groups in parallel.
- const mediaRecordsDir = join(bucket.path, 'records', 'media');
+ const mediaRecordsDir = bucketRecordsDir(bucket.path, 'media');
const assetRefs = await withAssetHashCache(bucket.path, async (cache) => {
const [jobRefGroups, imageRefs, videoRefs, imageRefRefs] = await Promise.all([
Promise.all([...allJobIds].map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir, cache))),
@@ -502,7 +502,7 @@ export async function exportUniverse(universeId, bucketId, opts = {}) {
const manifestId = manifestStub.id;
const stamped = stampOrigin(universe, { bucket, source, sourceBio, manifestId });
- await atomicWrite(join(bucket.path, 'records', 'universes', `${universe.id}.json`), stamped);
+ await atomicWrite(bucketRecordPath(bucket.path, 'universes', universe.id), stamped);
// Combine universe-record asset refs with the linked collection's assets
// so a single export pass pulls everything the universe needs.
@@ -518,7 +518,7 @@ export async function exportUniverse(universeId, bucketId, opts = {}) {
);
const allImageRefFiles = new Set(universeRefs.directImageRefFilenames);
- const mediaRecordsDir = join(bucket.path, 'records', 'media');
+ const mediaRecordsDir = bucketRecordsDir(bucket.path, 'media');
const assetRefs = await withAssetHashCache(bucket.path, async (cache) => {
const [jobRefGroups, imageRefs, videoRefs, imageRefRefs] = await Promise.all([
Promise.all([...allJobIds].map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir, cache))),
@@ -564,7 +564,7 @@ export async function exportMedia(items, bucketId) {
});
const manifestId = manifestStub.id;
- const mediaRecordsDir = join(bucket.path, 'records', 'media');
+ const mediaRecordsDir = bucketRecordsDir(bucket.path, 'media');
// Pre-resolve each item to a job (or null) so we know what to parallelize
// and what record ids to collect for the manifest.
const resolved = (items || []).flatMap((item) => {
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 8d589c8333..05ca8b39ce 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -27,7 +27,7 @@ import { existsSync } from 'fs';
import { EventEmitter } from 'events';
import { PATHS, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { isSafeRecordId } from '../../lib/validation.js';
-import { getBucket, bucketBlobPath, bucketBlobSidecarPath, imageSidecarName, isHexHash } from './buckets.js';
+import { getBucket, bucketBlobPath, bucketBlobSidecarPath, bucketRecordsDir, bucketRecordPath, imageSidecarName, isHexHash } from './buckets.js';
import { readManifest, markProcessed, readCursor, hasBeenProcessed, forgetProcessed } from './manifest.js';
import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';
import { PORTOS_SCHEMA_VERSIONS, RECORD_KIND_SCHEMA_CATEGORIES, compareSchemaVersions, scopeVersionDiff, formatVersionGap } from '../../lib/schemaVersions.js';
@@ -312,7 +312,7 @@ async function processAnnotationManifest(bucket, manifest) {
const recordId = (manifest.recordIds || [])[0] || manifest.senderInstanceId;
if (!recordId) return { applied: 0, missing: true, reason: 'no-record-id' };
if (!isSafeRecordId(recordId)) return { applied: 0, missing: true, reason: 'bad-record-id' };
- const recordPath = join(bucket.path, 'records', 'media-annotations', `${recordId}.json`);
+ const recordPath = bucketRecordPath(bucket.path, 'media-annotations', recordId);
const record = await readJSONFile(recordPath, null, { logError: false });
if (!record) return { applied: 0, missing: true, reason: 'record-not-synced' };
// record.instanceId is the source-of-truth for the author; fall back to the
@@ -331,14 +331,14 @@ async function processAnnotationManifest(bucket, manifest) {
/** Merge bucket-bundled media-job records into local data/media-jobs.json. */
async function mergeMediaJobRecords(bucketPath, recordIds) {
- const mediaDir = join(bucketPath, 'records', 'media');
+ const mediaDir = bucketRecordsDir(bucketPath, 'media');
if (!existsSync(mediaDir)) return;
const persistedPath = join(PATHS.data, 'media-jobs.json');
const [persisted, incoming] = await Promise.all([
readJSONFile(persistedPath, { jobs: [] }, { logError: false }),
Promise.all((recordIds || []).map(async (id) => {
if (!isSafeRecordId(id)) return null;
- const recordPath = join(mediaDir, `${id}.json`);
+ const recordPath = bucketRecordPath(bucketPath, 'media', id);
if (!existsSync(recordPath)) return null;
return readJSONFile(recordPath, null, { logError: false });
})),
@@ -372,7 +372,7 @@ async function mergeMediaJobRecords(bucketPath, recordIds) {
async function missingDeclaredReviews(bucketPath, manifest) {
const refs = (Array.isArray(manifest.reviewRefs) ? manifest.reviewRefs : []).filter(isSafeRecordId);
const checks = await Promise.all(refs.map(async (sid) => {
- const r = await readJSONFile(join(bucketPath, 'records', 'reviews', `${sid}.json`), null, { logError: false });
+ const r = await readJSONFile(bucketRecordPath(bucketPath, 'reviews', sid), null, { logError: false });
return r == null ? sid : null;
}));
return checks.filter(Boolean);
@@ -384,11 +384,11 @@ async function readReferencedRecords(bucketPath, manifest) {
const resolveOne = async (id) => {
if (!isSafeRecordId(id)) return { kind: 'missing', id };
if (id.startsWith('ser-')) {
- const r = await readJSONFile(join(bucketPath, 'records', 'series', `${id}.json`), null, { logError: false });
+ const r = await readJSONFile(bucketRecordPath(bucketPath, 'series', id), null, { logError: false });
return r ? { kind: 'series', record: r } : { kind: 'missing', id };
}
if (id.startsWith('iss-')) {
- const r = await readJSONFile(join(bucketPath, 'records', 'issues', `${id}.json`), null, { logError: false });
+ const r = await readJSONFile(bucketRecordPath(bucketPath, 'issues', id), null, { logError: false });
return r ? { kind: 'issues', record: r } : { kind: 'missing', id };
}
if (id.startsWith('chr-') || id.startsWith('set-') || id.startsWith('obj-')) {
@@ -396,9 +396,9 @@ async function readReferencedRecords(bucketPath, manifest) {
return { kind: 'skip' };
}
// UUID-only — could be a universe or a media job. Try both.
- const uni = await readJSONFile(join(bucketPath, 'records', 'universes', `${id}.json`), null, { logError: false });
+ const uni = await readJSONFile(bucketRecordPath(bucketPath, 'universes', id), null, { logError: false });
if (uni) return { kind: 'universes', record: uni };
- const med = await readJSONFile(join(bucketPath, 'records', 'media', `${id}.json`), null, { logError: false });
+ const med = await readJSONFile(bucketRecordPath(bucketPath, 'media', id), null, { logError: false });
if (med) return { kind: 'media', record: med };
return { kind: 'missing', id };
};
@@ -663,7 +663,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
const reviewMergeFailures = [];
for (const s of records.series) {
if (skipSeriesMerge.has(s.id) || !declaredReviews.has(s.id)) continue;
- const review = await readJSONFile(join(bucket.path, 'records', 'reviews', `${s.id}.json`), null, { logError: false });
+ const review = await readJSONFile(bucketRecordPath(bucket.path, 'reviews', s.id), null, { logError: false });
if (review) {
await mergeReviewFromSync(s.id, review).catch((err) => {
console.log(`⚠️ sharing.importer: manuscript-review merge for ${s.id} failed: ${err.message}`);