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([unknown-instance-id-sentinel-extract]): promote UNKNOWN_INSTANCE_ID to instances.js export

[._.]/ Adam Eivy3ddf2a8e3d19
diff --git a/server/services/instances.js b/server/services/instances.js
index f597c4cc5e..6e267932a8 100644
--- a/server/services/instances.js
+++ b/server/services/instances.js
@@ -22,6 +22,14 @@ const PROBE_TIMEOUT_MS = 5000;
const POLL_INTERVAL_MS = 30000;
const INITIAL_PROBE_DELAY_MS = 2000;
+// Sentinel returned by getInstanceId() and stamped onto sender/peer fields when
+// the local identity hasn't been initialized yet. Every consumer that fans
+// instance-keyed state out to peers (sharing/annotationsSync.flushAll,
+// mediaAnnotations.mergePeerAnnotations, manifest builders) must refuse this
+// value — without that guard, every uninitialized peer would collide in the
+// same bucket and clobber each other on merge.
+export const UNKNOWN_INSTANCE_ID = 'unknown';
+
// Backoff tiers for consecutive probe failures (in ms)
// 30s → 1m → 5m → 15m → 1h → 24h
const BACKOFF_TIERS_MS = [
@@ -99,7 +107,7 @@ export async function getInstanceId() {
if (!cachedInstanceId) {
const id = (await getSelf())?.instanceId;
if (id) cachedInstanceId = id;
- return id ?? 'unknown';
+ return id ?? UNKNOWN_INSTANCE_ID;
}
return cachedInstanceId;
}
diff --git a/server/services/mediaAnnotations.js b/server/services/mediaAnnotations.js
index 9b3f6abf5d..8959b7428a 100644
--- a/server/services/mediaAnnotations.js
+++ b/server/services/mediaAnnotations.js
@@ -8,7 +8,7 @@
import { join } from 'path';
import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';
import { isValidKey } from '../lib/mediaItemKey.js';
-import { getInstanceId } from './instances.js';
+import { getInstanceId, UNKNOWN_INSTANCE_ID } from './instances.js';
import { resolveLocalAuthorName } from './sharing/annotationIdentity.js';
const STATE_PATH = join(PATHS.data, 'media-annotations.json');
@@ -80,19 +80,19 @@ async function readAll() {
// Resolve identity inputs ONCE for the whole file scan — every legacy entry
// would otherwise repeat both awaits below.
const [localInstanceId, defaultAuthorName] = await Promise.all([
- getInstanceId().catch(() => 'unknown'),
+ getInstanceId().catch(() => UNKNOWN_INSTANCE_ID),
resolveLocalAuthorName().catch(() => ''),
]);
const liftCtx = { localInstanceId, defaultAuthorName };
- // Heal-on-read: migration 014 wrote the literal `'unknown'` as an author key
+ // Heal-on-read: migration 014 wrote UNKNOWN_INSTANCE_ID as an author key
// when it ran before `ensureSelf()` had created the local identity. Re-key
// those entries to the real `localInstanceId` so they project as the user's
// own annotation and become exportable again (annotationsSync.flushAll
- // refuses to ship payloads with instanceId `'unknown'`). The heal is in-
+ // refuses to ship payloads with instanceId UNKNOWN_INSTANCE_ID). The heal is in-
// memory only — the first subsequent `setAnnotation` for the key persists
// the clean shape via the normal write path. Skip the heal when we still
// don't have a real local identity, otherwise we'd just rename the phantom.
- const healUnknownAuthor = localInstanceId && localInstanceId !== 'unknown';
+ const healUnknownAuthor = localInstanceId && localInstanceId !== UNKNOWN_INSTANCE_ID;
const out = {};
for (const [key, value] of Object.entries(annotations)) {
if (!isValidKey(key)) continue;
@@ -101,15 +101,15 @@ async function readAll() {
const authors = {};
for (const [instanceId, sub] of Object.entries(lifted.authors)) {
if (typeof instanceId !== 'string' || !instanceId) continue;
- if (instanceId === 'unknown' && healUnknownAuthor) continue; // re-keyed below
+ if (instanceId === UNKNOWN_INSTANCE_ID && healUnknownAuthor) continue; // re-keyed below
const sane = sanitizeAuthorEntry(sub);
if (sane) authors[instanceId] = sane;
}
- // Heal the phantom: re-key `unknown` → real local id. Skip when a real
+ // Heal the phantom: re-key UNKNOWN_INSTANCE_ID → real local id. Skip when a real
// local entry already exists for this key — that's the source of truth
// (a later setAnnotation already wrote there) and the phantom is dropped.
- if (healUnknownAuthor && lifted.authors.unknown && !authors[localInstanceId]) {
- const sane = sanitizeAuthorEntry(lifted.authors.unknown);
+ if (healUnknownAuthor && lifted.authors[UNKNOWN_INSTANCE_ID] && !authors[localInstanceId]) {
+ const sane = sanitizeAuthorEntry(lifted.authors[UNKNOWN_INSTANCE_ID]);
if (sane) {
authors[localInstanceId] = { ...sane, authorName: sane.authorName || defaultAuthorName };
}
@@ -132,7 +132,7 @@ function projectForLocal(authorsMap, localInstanceId) {
export async function listAnnotations() {
const [all, localInstanceId] = await Promise.all([
readAll(),
- getInstanceId().catch(() => 'unknown'),
+ getInstanceId().catch(() => UNKNOWN_INSTANCE_ID),
]);
const out = {};
for (const [key, { authors }] of Object.entries(all)) {
@@ -145,7 +145,7 @@ export async function listAnnotations() {
export async function listLocalAuthorAnnotations() {
const [all, localInstanceId] = await Promise.all([
readAll(),
- getInstanceId().catch(() => 'unknown'),
+ getInstanceId().catch(() => UNKNOWN_INSTANCE_ID),
]);
const out = {};
for (const [key, { authors }] of Object.entries(all)) {
@@ -166,12 +166,12 @@ export async function listLocalAuthorAnnotations() {
export async function mergePeerAnnotations(payload) {
if (!payload || typeof payload !== 'object') return { changed: [], projections: new Map() };
const peerInstanceId = typeof payload.instanceId === 'string' ? payload.instanceId : null;
- // Reject empty or sentinel `'unknown'` peer ids on import. The outgoing path
- // already guards (`annotationsSync.flushAll` early-returns on `'unknown'`)
+ // Reject empty or UNKNOWN_INSTANCE_ID peer ids on import. The outgoing path
+ // already guards (`annotationsSync.flushAll` early-returns on the sentinel)
// but a hand-crafted manifest or a peer in an inconsistent state could ship
// one — without this guard, every such peer would alias into the same
- // `'unknown'` bucket and clobber each other on every merge.
- if (!peerInstanceId || peerInstanceId === 'unknown') return { changed: [], projections: new Map() };
+ // sentinel bucket and clobber each other on every merge.
+ if (!peerInstanceId || peerInstanceId === UNKNOWN_INSTANCE_ID) return { changed: [], projections: new Map() };
const localInstanceId = await getInstanceId().catch(() => null);
if (peerInstanceId === localInstanceId) return { changed: [], projections: new Map() };
const incoming = payload.annotations && typeof payload.annotations === 'object'
@@ -262,7 +262,7 @@ export async function setAnnotation(key, patch) {
getInstanceId(),
resolveLocalAuthorName().catch(() => ''),
]);
- if (!localInstanceId || localInstanceId === 'unknown') {
+ if (!localInstanceId || localInstanceId === UNKNOWN_INSTANCE_ID) {
throw makeErr('Local instance identity not initialized', ERR_VALIDATION);
}
diff --git a/server/services/mediaAnnotations.test.js b/server/services/mediaAnnotations.test.js
index 2495f5a185..526216aeef 100644
--- a/server/services/mediaAnnotations.test.js
+++ b/server/services/mediaAnnotations.test.js
@@ -14,6 +14,7 @@ tryReadFile: vi.fn().mockResolvedValue(null),
const LOCAL_INSTANCE = 'local-instance-id';
vi.mock('./instances.js', () => ({
getInstanceId: vi.fn(async () => LOCAL_INSTANCE),
+ UNKNOWN_INSTANCE_ID: 'unknown',
}));
vi.mock('./sharing/annotationIdentity.js', () => ({
resolveLocalAuthorName: vi.fn(async () => 'Local User'),
diff --git a/server/services/sharing/annotationsSync.js b/server/services/sharing/annotationsSync.js
index 794964da56..0b287ec070 100644
--- a/server/services/sharing/annotationsSync.js
+++ b/server/services/sharing/annotationsSync.js
@@ -13,7 +13,7 @@ import { ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { listBuckets } from './buckets.js';
import { buildManifest, writeManifest, annotationManifestFilename, readManifest, listManifestFilenames } from './manifest.js';
import { getProducedByVersion } from './version.js';
-import { getInstanceId } from '../instances.js';
+import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';
import { resolveBucketSourceName } from './annotationIdentity.js';
import { onLocalAnnotationChange, listLocalAuthorAnnotations } from '../mediaAnnotations.js';
@@ -210,7 +210,7 @@ async function flushAll() {
getInstanceId().catch(() => null),
listLocalAuthorAnnotations().catch(() => ({})),
]);
- if (!senderInstanceId || senderInstanceId === 'unknown') return;
+ if (!senderInstanceId || senderInstanceId === UNKNOWN_INSTANCE_ID) return;
const autoMerge = buckets.filter((b) => b.mode === 'auto-merge');
if (autoMerge.length === 0) return;
await Promise.all(autoMerge.map(async (bucket) => {
diff --git a/server/services/sharing/annotationsSync.test.js b/server/services/sharing/annotationsSync.test.js
index a32b303f3b..cae2cc107f 100644
--- a/server/services/sharing/annotationsSync.test.js
+++ b/server/services/sharing/annotationsSync.test.js
@@ -32,6 +32,7 @@ vi.mock('./buckets.js', () => ({
vi.mock('../instances.js', () => ({
getInstanceId: vi.fn(async () => 'local-instance'),
+ UNKNOWN_INSTANCE_ID: 'unknown',
}));
vi.mock('./annotationIdentity.js', () => ({
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index 69fea82b64..aedf115a4b 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -34,12 +34,10 @@ import { insertIssueWithId, updateIssue, getIssue } from '../pipeline/issues.js'
import { insertUniverseWithId, updateUniverse, getUniverse } from '../universeBuilder.js';
import { findOrCreateUniverseCollection, findOrCreateSeriesCollection, addItem as addCollectionItem, ERR_DUPLICATE as COLLECTION_ERR_DUPLICATE } from '../mediaCollections.js';
import { adoptImportedSubscription, withReexportSuppressed } from './subscriptions.js';
-import { getInstanceId } from '../instances.js';
+import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';
import { mergePeerAnnotations } from '../mediaAnnotations.js';
import { isStr } from '../../lib/storyBible.js';
-const UNKNOWN_INSTANCE_ID = 'unknown';
-
function isSelfAuthored(senderInstanceId, localInstanceId) {
return !!localInstanceId
&& !!senderInstanceId
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 675e4f33b5..2778ba0c73 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -44,6 +44,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
vi.mock('../instances.js', () => ({
tryReadFile: vi.fn().mockResolvedValue(null),
getInstanceId: () => Promise.resolve('test-instance-id'),
+ UNKNOWN_INSTANCE_ID: 'unknown',
}));
// Stub mediaJobQueue.getJob — exporter uses it for full-fidelity gen
diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.js
index 0e172a3838..db79a449f5 100644
--- a/server/services/sharing/manifest.js
+++ b/server/services/sharing/manifest.js
@@ -21,6 +21,7 @@ import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils
import { SHARING_SCHEMA_VERSION, getProducedByVersion } from './version.js';
import { isStr } from '../../lib/storyBible.js';
import { universeCollectionNameFor, seriesCollectionNameFor } from '../mediaCollections.js';
+import { UNKNOWN_INSTANCE_ID } from '../instances.js';
export const MANIFEST_KIND = Object.freeze(['series', 'universe', 'media', 'media-annotations']);
@@ -28,7 +29,7 @@ export const MANIFEST_KIND = Object.freeze(['series', 'universe', 'media', 'medi
* One file per (bucket, instanceId) — re-exports overwrite in place so peers
* see updates via chokidar `change` events, same pattern as subscriptions. */
export function annotationManifestFilename(senderInstanceId) {
- const safeId = String(senderInstanceId || 'unknown').replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 80);
+ const safeId = String(senderInstanceId || UNKNOWN_INSTANCE_ID).replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 80);
return `annotations-${safeId}.json`;
}
@@ -156,7 +157,7 @@ export function buildManifest({
subscription: subscription && subscription.recordKind && subscription.recordId
? { recordKind: subscription.recordKind, recordId: subscription.recordId }
: null,
- senderInstanceId: senderInstanceId || 'unknown',
+ senderInstanceId: senderInstanceId || UNKNOWN_INSTANCE_ID,
source: source || 'unknown', // human display name
sourceBio: sourceBio || null,
bucketId,
@@ -194,14 +195,14 @@ export const SUBSCRIPTION_FILE_PREFIX = 'sub-';
/** Filename for a subscription manifest. Used by both the writer (exporter)
* and the reader (subscriptions service, watcher) so the formula stays in
* one place. The `senderInstanceId` segment keeps two peers' shares of the
- * same record from colliding; absent senderInstanceId falls back to
- * `'unknown'` so the filename is always valid. The sender segment is
- * sanitized with the same allowlist/length cap used by
+ * same record from colliding; absent senderInstanceId falls back to the
+ * UNKNOWN_INSTANCE_ID sentinel so the filename is always valid. The sender
+ * segment is sanitized with the same allowlist/length cap used by
* `annotationManifestFilename` so a malformed persisted instance id
* containing path separators can't escape the `manifests` directory. */
export function subscriptionFilename({ recordKind, recordId, senderInstanceId }) {
- const raw = (isStr(senderInstanceId) ? senderInstanceId.trim() : '') || 'unknown';
- const sender = raw.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 80) || 'unknown';
+ const raw = (isStr(senderInstanceId) ? senderInstanceId.trim() : '') || UNKNOWN_INSTANCE_ID;
+ const sender = raw.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 80) || UNKNOWN_INSTANCE_ID;
return `${SUBSCRIPTION_FILE_PREFIX}${recordKind}-${recordId}-${sender}.json`;
}
@@ -236,9 +237,9 @@ export function manifestFilename(manifest) {
});
}
const ts = manifest.createdAt.replace(/[:.]/g, '-');
- const senderSlug = (manifest.source || manifest.senderInstanceId || 'unknown')
+ const senderSlug = (manifest.source || manifest.senderInstanceId || UNKNOWN_INSTANCE_ID)
.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40)
- || 'unknown';
+ || UNKNOWN_INSTANCE_ID;
return `${ts}-${senderSlug}-${manifest.id}.json`;
}
@@ -323,15 +324,16 @@ const CLASSIFY_CONCURRENCY = 32;
* first by ISO-prefixed filename) into `<bucket>/.archive/manifests/`.
*
* Returns `{ archived, kept, ownedTotal, skippedForeign, skippedReason }`.
- * When `localInstanceId` is missing or 'unknown', returns a noop result with
- * `skippedReason` set — we never blanket-archive without an author check.
+ * When `localInstanceId` is missing or UNKNOWN_INSTANCE_ID, returns a noop
+ * result with `skippedReason` set — we never blanket-archive without an
+ * author check.
*/
export async function pruneBucketManifests(bucket, opts = {}) {
const maxManifests = Number.isFinite(opts.maxManifests)
? Math.max(0, opts.maxManifests)
: DEFAULT_MANIFEST_RETENTION;
const localInstanceId = opts.localInstanceId;
- if (!localInstanceId || localInstanceId === 'unknown') {
+ if (!localInstanceId || localInstanceId === UNKNOWN_INSTANCE_ID) {
return { archived: 0, kept: 0, ownedTotal: 0, skippedForeign: 0, skippedReason: 'no-local-instance-id' };
}
const manifestsDir = join(bucket.path, 'manifests');
diff --git a/server/services/sharing/manifest.test.js b/server/services/sharing/manifest.test.js
index 2bc3b44d85..b6e5475503 100644
--- a/server/services/sharing/manifest.test.js
+++ b/server/services/sharing/manifest.test.js
@@ -12,6 +12,12 @@ vi.mock('../../lib/fileUtils.js', async () => {
return makePathsProxy(actual, { dataRoot: () => tempRoot });
});
+// instances.js loads peerSelfHost.js at module top-level, which reads
+// PATHS.data via certPaths() — but `tempRoot` is allocated in beforeEach, not
+// at hoisted module load. Stub instances.js so the only export manifest.js
+// needs (UNKNOWN_INSTANCE_ID) is available without the side-effect chain.
+vi.mock('../instances.js', () => ({ UNKNOWN_INSTANCE_ID: 'unknown' }));
+
const manifest = await import('./manifest.js');
describe('sharing/manifest', () => {
diff --git a/server/services/sharing/subscriptions.test.js b/server/services/sharing/subscriptions.test.js
index 43aa3f7dd4..43b93a4804 100644
--- a/server/services/sharing/subscriptions.test.js
+++ b/server/services/sharing/subscriptions.test.js
@@ -23,7 +23,7 @@ vi.mock('../../lib/fileUtils.js', async () => {
});
});
vi.mock('../instances.js', () => ({
-tryReadFile: vi.fn().mockResolvedValue(null), getInstanceId: () => Promise.resolve('inst-test') }));
+tryReadFile: vi.fn().mockResolvedValue(null), getInstanceId: () => Promise.resolve('inst-test'), UNKNOWN_INSTANCE_ID: 'unknown' }));
vi.mock('../mediaJobQueue/index.js', () => ({ getJob: () => null }));
const buckets = await import('./buckets.js');