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

fix([med-sharing-server-services-sharing-version-js]): retry idempotency + helper-throw stays pending

[._.]/ Adam Eivya6da12d45cda
diff --git a/PLAN.md b/PLAN.md
index 0f4a9da94f..e908398fc0 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -53,6 +53,8 @@ The 2026-04-25 CODEX 5.5 review's concrete bugs (Brain Feeds nav, Time Capsule n
### Deferred from better/2026-05-19
+- [ ] [universebuilder-collection-hook-flaky-batch-enrich] **[MED][TESTS]** `server/services/universeBuilderCollectionHook.test.js > "enriches every sidecar in a batch — all N images get tagged"` still fails intermittently when the full server suite runs in parallel, even after the 2026-05-19 fix that migrated `enrichSidecar` to `atomicWrite` (`[imagegen-local-defer-module-load-side-effects]` PR). Passes 100% in isolation (`vitest run services/universeBuilderCollectionHook.test.js` — 8/8). Suggests a cross-file race that survives the temp+rename atomicity — likely shared `PATHS.data` Proxy / mocked `mediaCollections` state colliding with a sibling test that drains the same hook queue concurrently. Reproduce by running the full server `vitest run` 10× and grepping for FAIL; instrument the batch enrich path to log timing and identify the contending writer. Surfaced 2026-05-20 during the legacy-series-canon import PR.
+
- [ ] [ansistrip-osc-alternative-unreachable] **[MED][TUI]** `server/lib/ansiStrip.js:14` — the OSC alternative in `ANSI_PATTERN` (`\][^\x07]*(?:\x07|\x1B\\)`) is dead code. Alternation order matches the single-byte alternative `[@-Z\\-_]` against `\x1B]` (0x5D is in 0x5C-0x5F) before the OSC alt is tried. Effect: only `\x1B]` is stripped from OSC sequences; the body+terminator leak into the cleaned stream (e.g. `\x1B]0;title\x07after` → `0;title\x07after`). Callers (`tuiPromptRunner.js:237`, `agentTuiSpawning.js:292`) consume the result without further filtering. Fix by either reordering alternatives (OSC before single-byte) or excluding `]` from the single-byte class (`[@-Z\\^_]` or similar). The new `ansiStrip.test.js` pins the current buggy behavior so a fix has an unambiguous before/after baseline. Surfaced 2026-05-20 during the test-coverage PR for med-tests-no-tests-for-server-lib-ansistrip-js; deferred to keep that PR scoped to tests.
- [ ] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index f24ed3f511..8b360b5095 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -444,26 +444,48 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
// to a universe that isn't in this manifest and isn't local), skip the
// sanitized-series insert for that record — otherwise the canon arrays
// get silently stripped by `sanitizeSeries` and the bug we just fixed
- // recurs. The bucket record stays untouched and `legacyCanonPendingUniverses`
+ // recurs. The bucket record stays untouched and the relevant pending list
// surfaces upward to the manifest-pending check, so the watcher retries
- // when the missing universe later arrives instead of cursor-advancing into
+ // when the underlying cause resolves instead of cursor-advancing into
// permanent skip.
const skipSeriesMerge = new Set();
const legacyCanonPendingUniverses = [];
+ const legacyCanonPendingFailures = [];
for (const s of records.series) {
const hasLegacyCanon = ['characters', 'settings', 'places', 'objects']
.some((field) => Array.isArray(s[field]) && s[field].length > 0);
if (!hasLegacyCanon) continue;
+
+ // Retry idempotency: when a local series record already exists from a
+ // prior pass (manifest is being retried because some OTHER pending
+ // condition held the cursor back), reuse its persisted universeId so
+ // we don't keep minting fresh "<name> (auto-migrated)" universes per
+ // retry. And if LWW would no-op the upcoming series merge, skip the
+ // helper entirely — re-merging stale remote canon over a locally-newer
+ // universe would just reset provenance.
+ const existing = await getSeries(s.id).catch(() => null);
+ if (existing) {
+ if (!remoteWins(existing.updatedAt, s.updatedAt)) continue;
+ if (!s.universeId && existing.universeId) s.universeId = existing.universeId;
+ }
+
const r = await applyLegacySeriesCanonToUniverse(s).catch((err) => {
console.log(`⚠️ sharing.importer: legacy series canon migration for ${s.id} failed: ${err.message}`);
return null;
});
- if (!r || r.skipped === 'missing-universe') {
- console.log(`⚠️ sharing.importer: skipping series ${s.id} merge — legacy canon could not be salvaged (${r?.skipped || 'helper failed'})`);
+ if (!r) {
+ // Helper threw — keep the manifest retryable so a transient I/O
+ // failure doesn't permanently lose this series. The failure id
+ // flows through `pendingLegacyCanonFailures` so processManifest
+ // leaves the cursor un-advanced.
skipSeriesMerge.add(s.id);
- if (r?.skipped === 'missing-universe' && r.universeId) {
- legacyCanonPendingUniverses.push(r.universeId);
- }
+ legacyCanonPendingFailures.push(s.id);
+ continue;
+ }
+ if (r.skipped === 'missing-universe') {
+ console.log(`⚠️ sharing.importer: skipping series ${s.id} merge — missing universe ${r.universeId}`);
+ skipSeriesMerge.add(s.id);
+ if (r.universeId) legacyCanonPendingUniverses.push(r.universeId);
continue;
}
// Stamp the freshly-created orphan universe id onto the in-memory record
@@ -537,6 +559,7 @@ async function applyAutoMerge(bucket, manifest, records, { availableAssetKeys =
collectionPendingUniverse,
collectionPendingSeries,
legacyCanonPendingUniverses: legacyCanonPendingUniverses.length > 0 ? legacyCanonPendingUniverses : null,
+ legacyCanonPendingFailures: legacyCanonPendingFailures.length > 0 ? legacyCanonPendingFailures : null,
adoptedSubscription: adoptedSubscription
? { id: adoptedSubscription.id, bucketId: adoptedSubscription.bucketId, recordKind: adoptedSubscription.recordKind, recordId: adoptedSubscription.recordId }
: null,
@@ -750,14 +773,16 @@ export async function processManifest(bucketId, manifestFilename) {
const collectionPendingUniverse = outcome?.collectionPendingUniverse || null;
const collectionPendingSeries = outcome?.collectionPendingSeries || null;
const legacyCanonPendingUniverses = outcome?.legacyCanonPendingUniverses || null;
- if (assetCopy.missing.length > 0 || missingRecords.length > 0 || collectionPendingUniverse || collectionPendingSeries || legacyCanonPendingUniverses) {
+ const legacyCanonPendingFailures = outcome?.legacyCanonPendingFailures || null;
+ if (assetCopy.missing.length > 0 || missingRecords.length > 0 || collectionPendingUniverse || collectionPendingSeries || legacyCanonPendingUniverses || legacyCanonPendingFailures) {
if (assetCopy.missing.length > 0) outcome.pendingAssets = assetCopy.missing;
if (missingRecords.length > 0) outcome.pendingRecords = missingRecords;
if (collectionPendingUniverse) outcome.pendingCollectionUniverse = collectionPendingUniverse;
if (collectionPendingSeries) outcome.pendingCollectionSeries = collectionPendingSeries;
if (legacyCanonPendingUniverses) outcome.pendingLegacyCanonUniverses = legacyCanonPendingUniverses;
+ if (legacyCanonPendingFailures) outcome.pendingLegacyCanonFailures = legacyCanonPendingFailures;
sharingEvents.emit('manifest-processed', { bucketId, manifestId: manifest.id, manifestFilename, outcome });
- console.log(`⏳ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} mode=${bucket.mode} waitingForAssets=${assetCopy.missing.length} waitingForRecords=${missingRecords.length}${collectionPendingUniverse ? ` waitingForUniverse=${collectionPendingUniverse}` : ''}${collectionPendingSeries ? ` waitingForSeries=${collectionPendingSeries}` : ''}${legacyCanonPendingUniverses ? ` waitingForLegacyCanonUniverses=${legacyCanonPendingUniverses.join(',')}` : ''}`);
+ console.log(`⏳ sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} mode=${bucket.mode} waitingForAssets=${assetCopy.missing.length} waitingForRecords=${missingRecords.length}${collectionPendingUniverse ? ` waitingForUniverse=${collectionPendingUniverse}` : ''}${collectionPendingSeries ? ` waitingForSeries=${collectionPendingSeries}` : ''}${legacyCanonPendingUniverses ? ` waitingForLegacyCanonUniverses=${legacyCanonPendingUniverses.join(',')}` : ''}${legacyCanonPendingFailures ? ` legacyCanonFailures=${legacyCanonPendingFailures.join(',')}` : ''}`);
return { processed: true, pending: true, manifest, outcome };
}
await markProcessed(bucketId, manifestFilename, manifest.id);
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 9b70fdbab1..070c62d932 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -1385,6 +1385,67 @@ describe('sharing round-trip', () => {
expect(orphanUni.characters.map((c) => c.name)).toContain('Solo');
});
+ it('reuses an existing local series.universeId on retry — no duplicate auto-migrated universes', async () => {
+ // When the same orphan-series manifest is processed twice (e.g. an
+ // unrelated pending condition held the cursor back the first time),
+ // the legacy-canon helper must reuse the persisted local universeId
+ // instead of minting a fresh "<name> (auto-migrated)" universe each pass.
+ const bucket = await buckets.createBucket({ name: 'OrphanIdempBucket', path: tempBucket, mode: 'auto-merge' });
+
+ const seriesId = 'ser-orphan-idemp';
+ const legacySeries = {
+ id: seriesId,
+ name: 'Orphan Idemp Series',
+ logline: 'will be reimported',
+ premise: 'idempotency test',
+ characters: [{ name: 'Echo', physicalDescription: 'on retry' }],
+ createdAt: '2026-05-01T00:00:00.000Z',
+ updatedAt: '2026-05-01T00:00:00.000Z',
+ };
+ mkdirSync(join(tempBucket, 'records', 'series'), { recursive: true });
+ writeFileSync(
+ join(tempBucket, 'records', 'series', `${seriesId}.json`),
+ JSON.stringify(legacySeries),
+ );
+ const manifest = {
+ id: 'mfst-orphan-idemp',
+ schemaVersion: 1,
+ sharingSchemaVersion: 1,
+ producedByVersion: '1.0.0',
+ createdAt: new Date().toISOString(),
+ kind: 'series',
+ senderInstanceId: 'orphan-idemp-peer',
+ source: 'Orphan Idemp Peer',
+ sourceBio: null,
+ bucketId: bucket.id,
+ bucketName: bucket.name,
+ recordIds: [seriesId],
+ assetRefs: [],
+ note: null,
+ };
+ const filename = `2026-05-01T00-00-00-000Z-orphan-idemp-peer-${manifest.id}.json`;
+ writeFileSync(join(tempBucket, 'manifests', filename), JSON.stringify(manifest));
+
+ // First pass — creates the orphan universe + inserts the series.
+ await importer.processManifest(bucket.id, filename);
+ const restoredFirst = await series.getSeries(seriesId);
+ const firstUniverseId = restoredFirst.universeId;
+ expect(firstUniverseId).toBeTruthy();
+
+ // Force a retry — simulate the cursor being un-advanced by forgetting the
+ // manifest, then re-process. Without idempotency the helper would mint a
+ // SECOND auto-migrated universe and `mergeOne` would no-op the series.
+ const { forgetProcessed } = await import('./manifest.js');
+ await forgetProcessed(bucket.id, filename);
+ await importer.processManifest(bucket.id, filename);
+
+ const restoredAfter = await series.getSeries(seriesId);
+ expect(restoredAfter.universeId).toBe(firstUniverseId);
+ const allUnis = await universeSvc.listUniverses();
+ const autoMigrated = allUnis.filter((u) => /Orphan Idemp Series/.test(u.name));
+ expect(autoMigrated).toHaveLength(1);
+ });
+
it('leaves the manifest pending and retries when the missing universe later arrives', async () => {
// Without this guard, the importer would fall through to insertSeriesWithId
// and `sanitizeSeries` would silently drop the legacy canon arrays — the