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([datasync-bundle]): migrate writes to atomicWrite + add mtime-keyed checksum cache

[._.]/ Adam Eivy61c18e8674e7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 0f369b75cc..fe20a49697 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Changed
+- **[datasync-bundle] `dataSync.js` write-pattern + checksum-cache cleanup (2 items).** (1) [datasync-migrate-categories-to-atomicwrite] Replace seven inlined `ensureDir + writeFile(JSON.stringify(...))` triples across the goals/character/digitalTwin/meatspace categories with single `atomicWrite(path, data)` calls — temp+rename atomicity protects readers from seeing a partial write, which matters for the larger pipeline/universe JSON files that other services write concurrently. Pre-loop `ensureDir` calls dropped because each `atomicWrite` ensures its own dirname. (2) [datasync-checksum-only-fast-path] Add a per-category mtime-keyed cache in front of `getChecksum()`. The orchestrator hits this every cycle and previously materialized the full snapshot just to discard `data`; now a `stat`-only path returns the cached checksum when no underlying file changed since the last computation, falling through to `getSnapshot()` on a cache miss. Same checksum value as before — pure optimization, no protocol break. Three new tests cover cache consistency across consecutive calls, invalidation after `applyRemote`, and invalidation on out-of-band file mutations (16/16 dataSync tests pass; 5973/5973 full server suite).
+
- **[med-ai-dispatch-server-services-aidetect-js-242] `aiDetect.js` migrated to `runPromptThroughProvider` — TUI providers now work on Settings → Detect App.** `server/services/aiDetect.js` had a legacy `if (provider.type === 'cli') … else if ('api') … else 'Unknown provider type'` dispatch that rejected TUI providers outright and duplicated spawn/fetch logic the central handler already covers. The two inline functions (`executeCliDetection`, `executeApiDetection`) and the local `spawn`/`fetch` machinery are gone; detection now flows through `runPromptThroughProvider` from `server/lib/promptRunner.js` with `source: 'ai-app-detect'`, `cwd: dirPath` (so a spawned CLI/TUI runs against the analyzed repo, not PortOS's own cwd), and a 60s default timeout. `parseAiResponse` also moved to the shared `extractJson` helper from `server/lib/jsonExtract.js`, which strips CLI banner text and repairs trailing-comma JSON — relevant for TUI providers that emit banner output around the JSON payload. New `server/services/aiDetect.test.js` locks in the dispatch behavior (regression test ensures TUI no longer fails with "Unknown provider type") plus directory + provider-disabled error paths and the banner-stripping JSON case.
- **[imagegen-autoclean-bundle] Image-gen auto-clean code-quality cleanup (4 items).** Bundled deferrals from the per-render auto-clean PR's `/simplify` pass. (1) [imagegen-autoclean-double-resolution] Extract `resolveAutoClean(body, settings, mode)` from `server/services/imageGen/index.js` and share it with `server/routes/imageGen.js` so the precedence resolution lives in one place — the route stamps the resolved value onto the request body and the dispatcher still resolves as a safety net for direct callers like `generateAvatar`. (2) [imagegentab-triplicate-autoclean-state-collapse] Collapse three `autoCleanCodex/Local/External` state vars in `client/src/components/settings/ImageGenTab.jsx` into one `autoCleanByMode` object with a curried `setAutoCleanFor(mode)` setter, dropping ~15 LOC of triplicated isDirty / saved-snapshot / patch / reload code. (3) [imagegen-savedautocleanbymode-derive] Drop the re-seed `useEffect` in `client/src/pages/ImageGen.jsx` and re-seed `autoClean` explicitly at the two mode-change points (`reloadBackends` + new `handleSelectMode`); `selectedModeRef` mirrors the latest value so `reloadBackends`'s `useCallback` stays stable. (4) [autoclean-sidecar-read-parallelize] Kick off the sidecar `tryReadFile` immediately after `cleanImageBuffer` returns so the disk read overlaps the PNG atomic-write window in `server/lib/imageClean.js#autoCleanGeneratedImage`. Added a `resolveAutoClean` shim to the imageGen-route test mock to mirror real precedence. All 5958 server + 163 client tests pass.
diff --git a/PLAN.md b/PLAN.md
index 83922f9248..0cafb28aaf 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -19,8 +19,6 @@ _Nothing currently parked — pick the next item from the Backlog._
- [ ] [extract-usependinglistrows-hook] **Extract `usePendingListRows({ persisted, requiredColumn, idPrefix, onChange }) → { merged, isPending, addRow, updateRow, removeRow }`.** Surfaced by /simplify during `[wardroberow-migrate-to-userowdraft]`. `WardrobeSection` in `client/src/components/pipeline/CanonCard.jsx:155-211` and `CharacterDetailEditor` list-section block in `client/src/components/universe/CharacterDetailEditor.jsx:202-278` now share substantial structure: pending rows held client-side until a required column fills, then promoted to `onChange`/`patchList`, with an index space that concatenates `[...persisted, ...pending]` and an `isPending(idx)` partition. Estimated ~70 LOC savings across both call sites. Two load-bearing details to preserve in the extraction: (1) `WardrobeSection` mints `wd-<uuid>` ids that round-trip verbatim; `CharacterDetailEditor` mints `pending-<key>-<uuid>` that get stripped at promotion — pass an `idPrefix` and a `stripIdOnPromote` flag (or unify both onto server-shaped ids and drop the strip); (2) hook is per-list (one instance per `LIST_SECTION` in `CharacterDetailEditor`, one in `WardrobeSection`), NOT per-component. Deferred to keep this PR focused on the `useRowDraft` migration; revisit when a third caller appears or the parallel divergence drifts.
- [ ] [client-tests-for-deep-routing-drag-smoke-tests-for] **Client tests for deep routing + drag.** Smoke tests for `goToWorld(id)` URL transitions and chip-reorder ordering (mock `useSortable`).
- [ ] [sweep-provider-type-tui-inline-checks-in-client] **Sweep `provider.type === 'tui'` inline checks in client.** New `isTuiProvider` helper in `client/src/utils/providers.js` not yet adopted in `client/src/pages/AIProviders.jsx` (3 remaining inline checks at lines 262, 396, 421 of CONFIG-style chips) and `client/src/components/cos/TaskAddForm.jsx`. Low priority — these are visual chip predicates, not behavioral.
-- [ ] [datasync-migrate-categories-to-atomicwrite] **Migrate all `dataSync.js` categories to `atomicWrite`.** Every category (`goals`, `character`, `digitalTwin`, `meatspace`, `universe`, `pipeline`) inlines `ensureDir + writeFile + JSON.stringify(..., null, 2)` — 6+ duplicate sites. `server/lib/fileUtils.js:124` exports `atomicWrite(path, data)` that handles all three steps as a temp+rename atomic write. One-line collapse per site + meaningful partial-write protection for the larger pipeline JSON files (which other services write concurrently). Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`; deferred to keep that PR focused on the new categories.
-- [ ] [datasync-checksum-only-fast-path] **Add a checksum-only fast path to `dataSync.js`.** `getChecksum(category)` currently calls the category's `getSnapshot` and discards `data` (`server/services/dataSync.js:451-456`) — every probe materializes the full payload. With pipeline/universe added the wasted work scales with the largest user-creative payload. Define per-category `getChecksum` shortcuts (e.g. hash file size+mtime, or hash raw bytes without parse) and dispatch via `CATEGORIES[cat].getChecksum`. The orchestrator hits the checksum endpoint every cycle — this is the hottest sync-side I/O. Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`.
- [ ] [consolidate-cert-path-constants] **Consolidate `CERT_DIR`/`CERT_PATH`/`KEY_PATH`/`META_PATH` constants.** Re-declared in `scripts/setup-cert.js`, `scripts/open-ui-in-browser.js`, `server/services/certProvisioner.js`, and `server/services/certRenewer.js` (4 sites). Surfaced by `/simplify` during the first-run HTTPS-auto-flip fix (2026-05-19); deferred to keep that PR scoped. Candidate home: `lib/certPaths.js` (alongside `lib/tailscale-https.js` so both runtime + bootstrap can import).
- [ ] [imagegen-local-defer-module-load-side-effects] **Defer module-load side effects in `server/services/imageGen/local.js`.** Line 32 runs `IMAGE_MODELS = Object.fromEntries(getImageModels().map(...))` at module evaluation — `getImageModels()` calls `lib/mediaModels.js#loadMediaModels` which `mkdirSync`s `dirname(REGISTRY_FILE)` and `writeFileSync`s a default registry if missing. Any importer that loads via a mocked `PATHS.data` (e.g. `routes/pipeline.test.js` → `routes/pipeline.js` → `routes/universeBuilder.js` → `services/universeBuilderCollectionHook.js` → `services/imageGen/local.js`) fails on `mkdirSync('/mock/data')`. Worked around in 2026-05-19 by lazy-importing `readImageSidecar` in `universeBuilderCollectionHook.js`; real fix is to convert `IMAGE_MODELS` + sibling top-level constants to lazy getters and audit callers. Affects every consumer of `local.js` exports today.
- [ ] [cleanplateprompt-migrate-to-rich-canon-fragments] **Migrate `client/src/lib/cleanPlatePrompt.js#composeCleanPlatePrompt` to `richCanonDescriptorFragments('place', setting)`.** Clean-plate prompt builder (Cluster A — A4 setting reference renders) hand-rolls `description + Palette + recurringDetails` extraction at `cleanPlatePrompt.js:26-30` and is missing `era` / `weather` for the same reason `[pipeline-visual-stages-setting-field-injection]` was missing them — both are visual prompts that benefit from period/atmosphere cues. Tightly scoped sibling change (one client file + one test file). Deferred from that PR because the PLAN item targeted storyboard+comic-panel specifically; clean plates are setting-reference renders, adjacent but distinct.
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index d674dc5234..7c871c4523 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -7,9 +7,9 @@
*/
import crypto from 'crypto';
-import { writeFile } from 'fs/promises';
+import { stat } from 'fs/promises';
import { join } from 'path';
-import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';
import { isPlainObject } from '../lib/objects.js';
import { mergeUniversesFromSync } from './universeBuilder.js';
import { mergeSeriesFromSync } from './pipeline/series.js';
@@ -177,8 +177,7 @@ async function applyGoalsRemote(remoteData) {
};
if (goalsChanged || remoteMaxTs > localMaxTs) {
- await ensureDir(PATHS.digitalTwin);
- await writeFile(GOALS_FILE, JSON.stringify(merged, null, 2));
+ await atomicWrite(GOALS_FILE, merged);
console.log(`🔄 Goals sync: merged ${mergedGoals.length} goals`);
return { applied: true, count: mergedGoals.length };
}
@@ -199,8 +198,7 @@ async function applyCharacterRemote(remoteData) {
const local = await readJSONFile(CHARACTER_FILE, null);
if (!local) {
// No local character — accept remote entirely
- await ensureDir(PATHS.data);
- await writeFile(CHARACTER_FILE, JSON.stringify(remoteData, null, 2));
+ await atomicWrite(CHARACTER_FILE, remoteData);
console.log(`🔄 Character sync: accepted remote character`);
return { applied: true, count: 1 };
}
@@ -241,8 +239,7 @@ async function applyCharacterRemote(remoteData) {
};
if (eventsChanged || remoteTs > localTs) {
- await ensureDir(PATHS.data);
- await writeFile(CHARACTER_FILE, JSON.stringify(merged, null, 2));
+ await atomicWrite(CHARACTER_FILE, merged);
console.log(`🔄 Character sync: merged ${mergedEvents.length} events`);
return { applied: true, count: mergedEvents.length };
}
@@ -268,7 +265,6 @@ async function getDigitalTwinSnapshot() {
async function applyDigitalTwinRemote(remoteData) {
if (!remoteData) return { applied: false, count: 0 };
- await ensureDir(PATHS.digitalTwin);
let totalApplied = 0;
for (const [key, { path, timestampField, merge }] of Object.entries(DIGITAL_TWIN_FILES)) {
@@ -279,7 +275,7 @@ async function applyDigitalTwinRemote(remoteData) {
const mergeFn = merge === 'deepUnion' ? mergeDeepUnion : mergeObjectLWW;
const { merged, changed } = mergeFn(local, remoteFile, timestampField);
if (changed) {
- await writeFile(path, JSON.stringify(merged, null, 2));
+ await atomicWrite(path, merged);
totalApplied++;
}
}
@@ -303,7 +299,6 @@ async function getMeatspaceSnapshot() {
async function applyMeatspaceRemote(remoteData) {
if (!remoteData) return { applied: false, count: 0 };
- await ensureDir(MEATSPACE_DIR);
let totalApplied = 0;
for (const [filename, config] of Object.entries(MEATSPACE_FILES)) {
@@ -316,7 +311,7 @@ async function applyMeatspaceRemote(remoteData) {
if (config.type === 'object-lww') {
const { merged, changed } = mergeObjectLWW(local, remoteFile, 'updatedAt');
if (changed) {
- await writeFile(filePath, JSON.stringify(merged, null, 2));
+ await atomicWrite(filePath, merged);
totalApplied++;
}
} else {
@@ -329,7 +324,7 @@ async function applyMeatspaceRemote(remoteData) {
// Sort by idField (usually date)
merged.sort((a, b) => (a[config.idField] || '').localeCompare(b[config.idField] || ''));
const mergedFile = { ...(local || {}), [config.arrayKey]: merged };
- await writeFile(filePath, JSON.stringify(mergedFile, null, 2));
+ await atomicWrite(filePath, mergedFile);
totalApplied++;
}
}
@@ -420,6 +415,20 @@ async function applyPipelineRemote(remoteData) {
// --- Public API ---
+// Files each category reads, used to keep the in-process checksum cache honest:
+// we skip the full snapshot on `getChecksum` when none of these files' mtimes
+// changed since the last computed checksum. mtime resolution is milliseconds,
+// which is fine for a single-user / single-writer system — every PortOS write
+// path goes through `atomicWrite` (temp+rename), which bumps mtime.
+const CHECKSUM_PATHS = {
+ goals: [GOALS_FILE],
+ character: [CHARACTER_FILE],
+ digitalTwin: Object.values(DIGITAL_TWIN_FILES).map((f) => f.path),
+ meatspace: Object.keys(MEATSPACE_FILES).map((f) => join(MEATSPACE_DIR, f)),
+ universe: [UNIVERSE_BUILDER_FILE],
+ pipeline: [PIPELINE_SERIES_FILE, PIPELINE_ISSUES_FILE],
+};
+
const CATEGORIES = {
goals: { getSnapshot: getGoalsSnapshot, applyRemote: applyGoalsRemote },
character: { getSnapshot: getCharacterSnapshot, applyRemote: applyCharacterRemote },
@@ -429,6 +438,27 @@ const CATEGORIES = {
pipeline: { getSnapshot: getPipelineSnapshot, applyRemote: applyPipelineRemote }
};
+// Per-category `{ mtimes, checksum }` cache. The orchestrator hits getChecksum
+// every cycle — by far the hottest sync-side I/O — so caching keyed on
+// underlying-file mtimes lets it stat-and-return when nothing has changed,
+// instead of re-materializing the full payload.
+const checksumCache = new Map();
+
+async function readMtimeMap(paths) {
+ const out = {};
+ await Promise.all(paths.map(async (p) => {
+ const s = await stat(p).catch(() => null);
+ out[p] = s ? s.mtimeMs : null;
+ }));
+ return out;
+}
+
+function mtimeMapsEqual(a, b) {
+ for (const p in a) if (a[p] !== b[p]) return false;
+ for (const p in b) if (a[p] !== b[p]) return false;
+ return true;
+}
+
export function getSupportedCategories() {
return Object.keys(CATEGORIES);
}
@@ -436,6 +466,17 @@ export function getSupportedCategories() {
export async function getChecksum(category) {
const cat = CATEGORIES[category];
if (!cat) return null;
+ const paths = CHECKSUM_PATHS[category];
+ if (paths) {
+ const mtimes = await readMtimeMap(paths);
+ const cached = checksumCache.get(category);
+ if (cached && mtimeMapsEqual(cached.mtimes, mtimes)) {
+ return { checksum: cached.checksum };
+ }
+ const snapshot = await cat.getSnapshot();
+ checksumCache.set(category, { mtimes, checksum: snapshot.checksum });
+ return { checksum: snapshot.checksum };
+ }
const snapshot = await cat.getSnapshot();
return { checksum: snapshot.checksum };
}
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 0826e9eb13..73a214af1b 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -224,3 +224,41 @@ describe('dataSync — pipeline category', () => {
expect(readJSON(ISSUES_PATH).issues).toHaveLength(1);
});
});
+
+describe('dataSync — getChecksum cache', () => {
+ it('returns the same checksum across consecutive calls and matches getSnapshot', async () => {
+ writeJSON(UNIVERSE_PATH, {
+ universes: [{ id: 'u1', name: 'A', updatedAt: '2026-05-17T10:00:00Z' }],
+ });
+ const c1 = await dataSync.getChecksum('universe');
+ const c2 = await dataSync.getChecksum('universe');
+ const snap = await dataSync.getSnapshot('universe');
+ expect(c1.checksum).toBe(c2.checksum);
+ expect(c1.checksum).toBe(snap.checksum);
+ });
+
+ it('invalidates the cache after applyRemote bumps the underlying file mtime', async () => {
+ writeJSON(UNIVERSE_PATH, {
+ universes: [{ id: 'u1', name: 'A', updatedAt: '2026-05-17T10:00:00Z' }],
+ });
+ const before = await dataSync.getChecksum('universe');
+ await dataSync.applyRemote('universe', {
+ universes: [{ id: 'u1', name: 'B', updatedAt: '2026-05-17T11:00:00Z' }],
+ });
+ const after = await dataSync.getChecksum('universe');
+ expect(after.checksum).not.toBe(before.checksum);
+ expect(after.checksum).toBe((await dataSync.getSnapshot('universe')).checksum);
+ });
+
+ it('reflects an out-of-band file mutation (pipeline series changes outside this service)', async () => {
+ writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', updatedAt: '2026-05-17T10:00:00Z' }] });
+ writeJSON(ISSUES_PATH, { issues: [] });
+ const before = await dataSync.getChecksum('pipeline');
+ // Force a different mtime — vitest can run faster than the FS's ms tick,
+ // so wait long enough that the mtime is guaranteed to advance.
+ await new Promise((r) => setTimeout(r, 5));
+ writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', updatedAt: '2026-05-17T11:00:00Z' }] });
+ const after = await dataSync.getChecksum('pipeline');
+ expect(after.checksum).not.toBe(before.checksum);
+ });
+});