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

Resolve federated media sync follow-ups

[._.]/ Adam Eivyb160dbd9729c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7e143ad31d..3b8ee98feb 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Changed
+- **[federated-media-sync-followups] Sync integrity, local LLM, voice, and service hardening.** Federated sync badges now distinguish offline peers from peers that need a PortOS update, series integrity checks include child-issue assets, and records with images missing prompt sidecars show a dedicated "Metadata missing" status. Tombstone pushes now bypass the schema-version cooldown so deletes converge immediately. Internal cleanup: the AI toolkit receives Ollama readiness through an injected hook, Linux Ollama startup uses persistent `systemctl enable --now` / `disable --now`, migration 037 streams history conversion instead of materializing the union in memory, Local LLM backend switching writes `.env` atomically, the Voice settings UI can pin a vision model, and the LTX2 negative-prompt patch only targets namespaced constants modules.
- **[catalog-tests + catalog-ddl-drift-test] Catalog stack now has unit-test coverage + a DDL parity guard.** Internal: pure unit tests for the catalog Zod validators, the peer-sync envelope apply path (per-kind dispatch, per-row isolation, schema-version gate, cursor normalization), and the extraction service (stage frames, isolation, light-shape sanitizer). A new structural parity test diffs the catalog DDL between `server/scripts/init-db.sql` (fresh-install path) and the `catalogDDL` array in `server/lib/db.js:ensureSchema()` (upgrade path) — table columns, indexes, trigger functions, triggers, the `type` CHECK list, and the `search_tsv` payload-field set must match in both files, so a future PR can't update one and forget the other.
- **[pythonsetup-arch-tests] Test coverage for the arch-aware Local Python detector.** Internal: locks in the macOS arm64-vs-x86_64 preference behavior and the `/setup/check` arch fields with mocked-platform unit tests, so future edits to interpreter detection can't silently regress mlx wheel loading. No user-visible behavior change.
- **[mediajobqueue-resolve-live-params] Media job dispatch internals.** Internal refactor: the live-settings re-resolution step that picks the current Python interpreter before each video / local-image render moves into its own helper, giving future live-resolved fields a single seam. No user-visible behavior change.
@@ -13,6 +14,7 @@
## Added
+- **[meatspace-workouts-read-path] Logged workouts are now visible in MeatSpace.** The server exposes `GET/POST /api/meatspace/workouts`, the client API wraps it, and the MeatSpace Health tab lists recent workouts that were logged by voice, palette, or API.
- **[catalog-extraction-idea-scene-concept] Catalog Ingest now extracts ideas, scenes, and concepts too.** Pasting prose into `/catalog/ingest` previously only surfaced characters / places / objects. A new LLM stage runs alongside the three existing bible passes and proposes idea, scene, and concept candidates from the same scrap — each rendered as its own review section with selectable / editable rows, then committed via the same path. One additional LLM call per ingest; failures isolate to that stage so the other three are unaffected.
- **[catalog-quick-idea-dashboard-widget] New "Quick Idea (Catalog)" dashboard widget.** Captures a creative ingredient directly into the catalog without the scrap+extract LLM round-trip — pick a type chip (character / place / object / idea / scene / concept), name it, optionally add primary text and tags, and submit. Lands in the Quick Capture row of the seeded "Everything" layout on fresh installs. Existing installs whose `data/dashboard-layouts.json` predates this PR keep their saved layout — the new widget appears in the Layout Picker's "Edit" sheet so you can toggle it on. The "Open" link in the success toast jumps straight to the new ingredient's detail page.
- **[catalog-extensibility-roadmap] PLAN.md: Creative Catalog extensibility roadmap.** Internal: 14 new tracked items covering type-registry consolidation, types table vs CHECK constraint, per-payload `schemaVersion` + upgraders, user-defined ingredient types, ingredient↔ingredient relations, canonical tag taxonomy, revision history, media attachments, bulk import + slice export, ⌘K/Ask/voice discovery hooks, URL/file/voice-memo source kinds, scrap chunking, and a dashboard Quick Idea (Catalog) widget under Quick Capture. No user-visible behavior change yet — scopes the work required to evolve the catalog beyond the v1 six hardcoded types.
diff --git a/PLAN.md b/PLAN.md
index 64c90081e1..c5dc0e14d5 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -129,23 +129,6 @@ Items here need a research / design pass, an explicit decision, or a preconditio
- [ ] [ref-watch-phosphene-long-clip-temporal-boost-12fps] **"Long Clip Temporal Boost" (render at 12fps, interpolate to 24fps).** From `reference-watch` review of phosphene (commit `53585fc`, 2026-05-22). Phosphene added a 12fps render path that uses ffmpeg's `minterpolate` / RIFE downstream to fill back to 24fps, doubling the effective clip length per memory budget. PortOS doesn't have an interpolation post-step in `server/services/videoGen/local.js` — adding one is a feature decision, not a bug fix. The math helpers (`_duration_to_8k_frames`, LTX `8k+1` frame-count snapping) are useful regardless; PortOS's `DEFAULT_NUM_FRAMES = 121` is already 8k+1-aligned but UI-side validation could borrow this pattern. **Decision needed:** is this worth a feature surface? No clear user pain motivating it today.
- [ ] [ref-watch-phosphene-t2v-standard-env-gated-two-stage] **Env-gated two-stage T2V perf experiment.** From `reference-watch` review of phosphene (commit `5004b40b`, 2026-05-28). PortOS's `scripts/generate_ltx2.py#run_text` already routes through `TwoStagePipeline` *when `cfg_scale` is set* (~line 221-222) — but the default no-CFG path uses single-stage `TextToVideoPipeline`. Phosphene's experiment routes T2V Standard through `pipe.generate_two_stage()` (half-res Stage 1 + 2× latent upsample + 3-step Stage 2 refine, the same recipe HQ + I2V Standard already use) even without CFG, gated on `PHOSPHENE_T2V_TWO_STAGE=1`. Predicted ~30-35 % wall-time reduction on T2V Standard (M4 Max 7:40 → 5:15 on a 5 s clip; math: 5.0 step-equivalents + ~30 s vs 8.0 step-equivalents native). Fix: in `run_text`, when `cfg_scale is None`, branch on a new `PORTOS_T2V_TWO_STAGE` env (or settings flag) to call `pipe.generate_two_stage(...)` with stage1_steps=8, stage2_steps=3, cfg_scale=1.0. **Decision needed:** worth the A/B knob, or just flip the default to two-stage T2V universally once we've validated quality? Scope: small.
-### Federated media sync — deferred follow-ups (2026-05-23)
-
-Surfaced during code review of the federated-media-collection-sync feature and consciously deferred (out of scope for that PR). Each is independently pickable.
-
-- [ ] [media-sync-integrity-unreachable-reason-ui] **Integrity: surface the `peer-unreachable` vs `peer-too-old` reason in the UI.** Server-side is done — `getPeerIntegrity` (`server/services/sharing/integrity.js`) now returns `reason: 'peer-unreachable'` for a network failure, `'peer-too-old'` for a 404, and `'fetch-failed'` for other non-OK statuses. The remaining gap is client-side: `useSyncIntegrity` only checks `available` and silently drops the `reason`, so the badge/drawer can't tell the user "peer is offline" vs "update the peer's PortOS." Thread `reason` through the hook's per-peer payload and render distinct messaging in `SyncBadge`/`SyncDetailDrawer`.
-- [ ] [media-sync-series-issue-assets-manifest] **Series integrity manifest omits child-issue assets (v1 limitation).** `assetShaListForRecord('series', …)` (`server/services/sharing/peerSync.js`) uses `buildAssetManifest(series)`, capturing only the series' own asset refs, not its issues' — so a series whose images all live in issues reports assets in-parity even when a peer is missing them. Extend to fold in child-issue asset hashes (mirror `buildAssetManifestForSeries`).
-- [ ] [media-sync-metadata-missing-status] **(Enhancement) `metadata-missing` integrity status.** Surface records whose images lack gen-params sidecars as a distinct status so the badge directly flags the "no prompts" condition (today repaired via the Unsorted "Pull missing prompts" action; byte-divergence shows as `assets-missing`). Requires the peer manifest to carry per-record sidecar-presence. `server/lib/syncIntegrity.js` + the manifest builder.
-- [ ] [media-sync-drawer-test-act-warning] **Test polish: `SyncDetailDrawer.test.jsx` act() warning.** The universe-kind "shows per-peer breakdown" test renders without awaiting the async record-name fetch, emitting a React `act()` warning (test still passes). Wrap the render/assertions in `waitFor`/`act`. Test-quality only.
-- [ ] [peer-sync-tombstone-cooldown-bypass] **Schema-block cooldown suppresses tombstone (delete) pushes for up to 5 min.** `pushRecordToPeer` (`server/services/sharing/peerSync.js` ~line 714) short-circuits on `sub.blockedBySchema && !options.bypassSchemaCooldown` BEFORE building the push payload, so a delete (tombstone) edit to a schema-blocked subscription is held off — even though the receiver-side gate (~line 1197) explicitly exempts tombstones (`record.deleted !== true`) so soft-deletes always converge. Delete still converges on the next `peer:online` (which passes `bypassSchemaCooldown: true`) or after the cooldown elapses, so this is eventual-consistency-correct but slow in the rare schema-mismatch + edit-triggered-delete window. Fix: resolve whether the pending push is a tombstone (load the record, or thread a `deleted` hint) before the cooldown gate and bypass the cooldown for tombstones, mirroring the receiver exemption. Surfaced during v2.8.0 release review (claude). Deferred: touches delicate push-gate ordering, no test coverage, low impact.
-- [ ] [aitoolkit-ollama-ready-hook-injection] **Vendored AI toolkit imports out to a PortOS service.** `server/lib/aiToolkit/runner.js:8` does `import { ensureProviderReady as ensureOllamaProviderReady } from '../../services/ollamaManager.js'` (added by the "Run Ollama as a startup service" work), used at ~line 313 in the API chat-completions path. This violates the documented self-containment rule ("Keep the directory self-contained — no imports out to other PortOS modules — so future upstream syncs don't fight local edits"). Fix: inject `ensureProviderReady` through the runner `config`/`hooks` (the factory already accepts `hooks = {}`) and wire it where PortOS constructs the toolkit, mirroring the `executeCliRun`/`stopRun` override pattern in `server/index.js`; the hook early-returns success for non-Ollama providers, so no behavior change. Surfaced during v2.8.0 release review (claude). Deferred: cross-file DI refactor of the toolkit boundary with no test coverage — maintainability/sync-hygiene only, no runtime impact today.
-- [ ] [ollama-linux-systemd-enable-not-start] **Linux "Run at Startup" only starts Ollama for the current boot.** The systemd controller in `getServiceController` (`server/services/ollamaManager.js:80-82`) uses `systemctl start`/`stop` and `getServiceStatus` (line 109-120) treats `is-active` as `runAtStartup`, so the UI claims the service will run at login even though it won't survive a reboot (macOS `brew services start` IS persistent, so the contract is platform-inconsistent). Fix: Linux start → `systemctl enable --now ollama`, stop → `systemctl disable --now ollama`, and split status into `is-enabled` (→ `runAtStartup`) vs `is-active` (→ `running`) as two queries. Surfaced during v2.8.0 release review (codex, P2). Deferred: Linux-only path, untestable on the macOS dev machine, zero existing test coverage, privileged systemctl semantics — land it where it can be exercised on a real systemd host.
-- [ ] [migration-037-history-streaming] **History JSON→JSONL migration loads the whole file into memory.** `scripts/migrations/037-history-json-to-jsonl.js` reads all of `history.json` (and any existing `.jsonl`) and stringifies the union — fine for typical history sizes, but a very large action-history file could spike heap at upgrade time. Convert to a streaming/append-only line-by-line rewrite if large histories become a problem. Surfaced during v2.8.0 release review (gemini, IMPROVEMENT). Deferred: one-shot migration, speculative for realistic sizes.
-- [ ] [localllm-env-atomic-write] **`.env` backend marker write is non-atomic.** `writeBackend` in `server/services/localLlm.js` (~line 94) uses `writeFileSync` to rewrite `.env`; a crash mid-write could corrupt it. `atomicWrite` (temp+rename, passes strings through unchanged) would make it crash-safe — but `writeBackend` is currently sync and the write is tiny/rare. Surfaced during v2.8.0 release review (gemini, IMPROVEMENT). Deferred: requires a sync→async ripple for a microsecond-wide crash window.
-- [ ] [meatspace-workouts-read-path] **`getWorkouts()` is a write-only feature today.** Voice (`meatspace_log_workout`) and the palette can *write* workouts via `addWorkout` (`server/services/meatspaceHealth.js:194`), and `getWorkouts()` (line 189) is exported, but it has zero consumers — no route, no UI, no test reads workouts back. Wire a `GET /api/meatspace/workouts` route + a MeatSpace tab section so logged workouts are visible. Surfaced during v2.9.0 release review (claude, NIT). Deferred: feature-completion follow-up; the write side works and is tested.
-- [ ] [voice-vision-model-settings-ui] **Wire a `cfg.llm.visionModel` field into the Voice settings UI.** The v2.9.0 release review decoupled `ui_describe_visually`'s vision model from the voice text model — `describeScreenshot` (`server/services/voice/pipeline.js`) now reads an optional `cfg.llm.visionModel` and otherwise falls back to the provider's vision-capable `defaultModel` (so a pinned text-only voice model no longer breaks vision). But nothing in the Voice settings UI sets `visionModel` yet, so it can only be configured by hand-editing settings (the read path is forward-compatible, mirroring `cfg.location` for `weather_now`). Add a Voice-settings field + a Zod slice so a user can pin a specific vision model. Small.
-- [ ] [ltx2-utils-constants-qualified] **LTX2 negative-prompt patch imports a generic top-level module.** `scripts/generate_ltx2.py:92` tries `("utils", "constants")` to override `DEFAULT_NEGATIVE_PROMPT`; `utils` is a very generic top-level package name in a shared venv and could be shadowed (the `hasattr(...)` guard makes a wrong-module *write* improbable, so this is defense-in-depth only). If the real module is namespaced under the ltx package, prefer the fully-qualified import path. Surfaced during v2.9.0 release review (claude, NIT). Deferred: guarded; cosmetic robustness.
-
### Duplicate resolution + conflict journal — deferred follow-ups (2026-05-25)
Surfaced while building the sync-hygiene feature (duplicate detection/merge, non-blocking conflict journal, Series→Universe hierarchy). Consciously scoped out of v1.
diff --git a/client/src/components/meatspace/tabs/HealthTab.jsx b/client/src/components/meatspace/tabs/HealthTab.jsx
index 973a20d7fc..e05383d4c7 100644
--- a/client/src/components/meatspace/tabs/HealthTab.jsx
+++ b/client/src/components/meatspace/tabs/HealthTab.jsx
@@ -26,6 +26,7 @@ export default function HealthTab() {
const [availableMetrics, setAvailableMetrics] = useState(new Set());
const [expandedSections, setExpandedSections] = useState(new Set());
const [correlationData, setCorrelationData] = useState(null);
+ const [workouts, setWorkouts] = useState([]);
const [initialized, setInitialized] = useState(false);
const sectionRefs = useRef({});
@@ -69,6 +70,12 @@ export default function HealthTab() {
.catch(() => setCorrelationData(null));
}, [from, to]);
+ useEffect(() => {
+ api.getWorkouts()
+ .then((data) => setWorkouts(data?.workouts || []))
+ .catch(() => setWorkouts([]));
+ }, []);
+
const setRange = useCallback((newRange) => {
const params = new URLSearchParams(searchParams);
params.set('range', newRange);
@@ -110,6 +117,33 @@ export default function HealthTab() {
))}
</div>
+ <section className="border border-port-border rounded-lg overflow-hidden">
+ <div className="px-4 py-3 border-b border-port-border bg-port-bg/40">
+ <h3 className="text-sm font-medium text-white">Workouts</h3>
+ </div>
+ {workouts.length === 0 ? (
+ <p className="px-4 py-3 text-sm text-gray-500">No workouts logged yet.</p>
+ ) : (
+ <div className="divide-y divide-port-border/70">
+ {workouts.slice(0, 8).map((workout, index) => (
+ <div key={`${workout.date}-${workout.type}-${index}`} className="px-4 py-3 flex items-center justify-between gap-4">
+ <div className="min-w-0">
+ <p className="text-sm text-white truncate">{workout.type}</p>
+ {workout.notes && <p className="text-xs text-gray-500 truncate">{workout.notes}</p>}
+ </div>
+ <div className="shrink-0 text-right text-xs text-gray-400">
+ <div>{workout.date}</div>
+ <div>
+ {workout.durationMinutes != null ? `${workout.durationMinutes} min` : 'Duration n/a'}
+ {workout.intensity ? ` · ${workout.intensity}` : ''}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+
{/* Category sections */}
{METRIC_CATEGORIES.map(category => (
<div key={category.id} ref={el => sectionRefs.current[category.id] = el}>
diff --git a/client/src/components/settings/VoiceTab.jsx b/client/src/components/settings/VoiceTab.jsx
index 9ef1fd67d7..72ba8eb627 100644
--- a/client/src/components/settings/VoiceTab.jsx
+++ b/client/src/components/settings/VoiceTab.jsx
@@ -242,10 +242,12 @@ export function VoiceTab() {
// the cached list) so the select never silently drops the user's choice.
const llmProvider = cfg.llm.provider || 'lmstudio';
const llmModel = cfg.llm.model || 'auto';
+ const llmVisionModel = cfg.llm.visionModel || 'auto';
const selectedProvider = apiProviders.find((p) => p.id === llmProvider);
const providerMissing = apiProviders.length > 0 && !selectedProvider;
const providerModels = selectedProvider?.models || [];
const modelMissing = llmModel !== 'auto' && !providerModels.includes(llmModel);
+ const visionModelMissing = llmVisionModel !== 'auto' && !providerModels.includes(llmVisionModel);
// Code-agent delegation picker. Empty provider/model = "system default" (the
// CoS spawner's activeProvider + selectModelForTask). The saved choice is
@@ -454,6 +456,7 @@ export function VoiceTab() {
// so we don't send a model the new provider doesn't have.
patch('llm.provider', e.target.value);
patch('llm.model', 'auto');
+ patch('llm.visionModel', 'auto');
}}
className={inputCls}
>
@@ -501,6 +504,35 @@ export function VoiceTab() {
</div>
</div>
+ <div className="space-y-1">
+ <label htmlFor="voice-vision-model" className="block text-sm text-gray-400">Vision model</label>
+ <p className="text-xs text-gray-500">'auto' uses the provider's vision-capable default for screen descriptions.</p>
+ <div className="flex items-center gap-2">
+ <select
+ id="voice-vision-model"
+ value={llmVisionModel}
+ onChange={(e) => patch('llm.visionModel', e.target.value)}
+ className={`${inputCls} flex-1`}
+ >
+ <option value="auto">auto</option>
+ {visionModelMissing && <option value={llmVisionModel}>{llmVisionModel} (current)</option>}
+ {providerModels.map((m) => (
+ <option key={m} value={m}>{m}</option>
+ ))}
+ </select>
+ <button
+ type="button"
+ onClick={() => handleRefreshModels(llmProvider)}
+ disabled={refreshingModels || providerMissing || apiProviders.length === 0}
+ aria-label="Refresh model list from the provider"
+ title="Refresh model list from the provider"
+ className="shrink-0 p-2 rounded-lg bg-port-border hover:bg-port-border/70 text-white disabled:opacity-50"
+ >
+ {refreshingModels ? <BrailleSpinner /> : <RefreshCw size={14} />}
+ </button>
+ </div>
+ </div>
+
<label className="flex items-start gap-3 cursor-pointer md:col-span-2">
<input
type="checkbox"
diff --git a/client/src/components/sync/SyncBadge.jsx b/client/src/components/sync/SyncBadge.jsx
index 2a34b962e0..3bdf200c32 100644
--- a/client/src/components/sync/SyncBadge.jsx
+++ b/client/src/components/sync/SyncBadge.jsx
@@ -2,8 +2,10 @@
* SyncBadge — presentational-only sync status badge.
*
* Props:
- * status — 'in-parity' | 'diverged' | 'assets-missing' | 'local-only' |
- * 'peer-only' | 'not-syncing' | 'unknown' | null | undefined
+ * status — 'in-parity' | 'diverged' | 'assets-missing' |
+ * 'metadata-missing' | 'local-only' | 'peer-only' |
+ * 'peer-unreachable' | 'peer-too-old' | 'fetch-failed' |
+ * 'not-syncing' | 'unknown' | null | undefined
* onClick — called when the badge button is clicked (e.g. open detail drawer)
*/
@@ -28,6 +30,12 @@ const STATUS_CONFIG = {
Icon: AlertTriangle,
title: 'Record present but associated files are missing on a peer',
},
+ 'metadata-missing': {
+ label: 'Metadata missing',
+ className: 'bg-port-warning/15 text-port-warning hover:bg-port-warning/25',
+ Icon: AlertTriangle,
+ title: 'One or more synced images is missing generation prompt metadata',
+ },
'local-only': {
label: 'Local only',
className: 'bg-port-warning/15 text-port-warning hover:bg-port-warning/25',
@@ -56,6 +64,24 @@ const STATUS_CONFIG = {
// errored, so we couldn't compute parity. Distinct from 'not-syncing'.
title: 'Sync status unavailable — peer offline, unreachable, or on an older PortOS',
},
+ 'peer-unreachable': {
+ label: 'Peer offline',
+ className: 'bg-gray-600/20 text-gray-400 hover:bg-gray-600/30',
+ Icon: WifiOff,
+ title: 'Sync status unavailable — peer is offline or unreachable',
+ },
+ 'peer-too-old': {
+ label: 'Peer update needed',
+ className: 'bg-gray-600/20 text-gray-400 hover:bg-gray-600/30',
+ Icon: HelpCircle,
+ title: 'Sync status unavailable — peer is running an older PortOS without integrity manifests',
+ },
+ 'fetch-failed': {
+ label: 'Sync check failed',
+ className: 'bg-gray-600/20 text-gray-400 hover:bg-gray-600/30',
+ Icon: HelpCircle,
+ title: 'Sync status unavailable — peer returned an error during integrity check',
+ },
};
export default function SyncBadge({ status, onClick }) {
diff --git a/client/src/components/sync/SyncBadge.test.jsx b/client/src/components/sync/SyncBadge.test.jsx
index cbd97fd62d..b4a1fa18e8 100644
--- a/client/src/components/sync/SyncBadge.test.jsx
+++ b/client/src/components/sync/SyncBadge.test.jsx
@@ -21,6 +21,12 @@ describe('SyncBadge', () => {
expect(screen.getByRole('button').className).toMatch(/port-warning/);
});
+ it('renders "Metadata missing" for metadata-missing status', () => {
+ render(<SyncBadge status="metadata-missing" onClick={() => {}} />);
+ expect(screen.getByText('Metadata missing')).toBeInTheDocument();
+ expect(screen.getByRole('button').className).toMatch(/port-warning/);
+ });
+
it('renders "Local only" for local-only status', () => {
render(<SyncBadge status="local-only" onClick={() => {}} />);
expect(screen.getByText('Local only')).toBeInTheDocument();
@@ -53,6 +59,16 @@ describe('SyncBadge', () => {
expect(btn.className).toMatch(/gray/);
});
+ it('renders peer-unreachable with distinct offline copy', () => {
+ render(<SyncBadge status="peer-unreachable" onClick={() => {}} />);
+ expect(screen.getByRole('button', { name: /peer offline/i })).toHaveAttribute('title', expect.stringMatching(/offline/i));
+ });
+
+ it('renders peer-too-old with update-needed copy', () => {
+ render(<SyncBadge status="peer-too-old" onClick={() => {}} />);
+ expect(screen.getByRole('button', { name: /peer update needed/i })).toHaveAttribute('title', expect.stringMatching(/older PortOS/i));
+ });
+
it('calls onClick when clicked', () => {
const onClick = vi.fn();
render(<SyncBadge status="in-parity" onClick={onClick} />);
diff --git a/client/src/components/sync/SyncDetailDrawer.jsx b/client/src/components/sync/SyncDetailDrawer.jsx
index 8c58a44104..0d2339573c 100644
--- a/client/src/components/sync/SyncDetailDrawer.jsx
+++ b/client/src/components/sync/SyncDetailDrawer.jsx
@@ -51,6 +51,11 @@ const STATUS_CONFIG = {
className: 'text-port-warning',
Icon: AlertTriangle,
},
+ 'metadata-missing': {
+ label: 'Metadata missing',
+ className: 'text-port-warning',
+ Icon: AlertTriangle,
+ },
'local-only': {
label: 'Local only',
className: 'text-port-warning',
@@ -63,6 +68,13 @@ const STATUS_CONFIG = {
},
};
+const UNAVAILABLE_REASON_LABELS = {
+ 'peer-unreachable': 'Peer offline or unreachable',
+ 'peer-too-old': 'Peer needs a PortOS update',
+ 'fetch-failed': 'Integrity check failed',
+ 'peer-not-found': 'Peer not found',
+};
+
function StatusPill({ status }) {
const config = STATUS_CONFIG[status];
if (!config) return <span className="text-gray-400 text-xs">{status ?? '—'}</span>;
@@ -157,12 +169,13 @@ const PULL_SKIP_LABELS = {
function PeerRow({ entry, kind, recordId, onRefresh }) {
const { peerId, peerName, status } = entry;
// Direction-aware actions. local-only → we have it, peer doesn't → PUSH.
- // peer-only → peer has it, we don't → PULL. diverged / assets-missing are
+ // peer-only → peer has it, we don't → PULL. diverged / assets-missing /
+ // metadata-missing are
// ambiguous (either side could be ahead) → offer BOTH so the fix is always
// reachable from the machine you're on. (Pre-fix, only push existed, which
// couldn't resolve a record the LOCAL side was behind on.)
- const canPush = ['local-only', 'diverged', 'assets-missing'].includes(status);
- const canPull = ['peer-only', 'diverged', 'assets-missing'].includes(status);
+ const canPush = ['local-only', 'diverged', 'assets-missing', 'metadata-missing'].includes(status);
+ const canPull = ['peer-only', 'diverged', 'assets-missing', 'metadata-missing'].includes(status);
const [syncToPeer, syncing] = useAsyncAction(async () => {
// The endpoint returns 200 even when nothing was pushed ({ pushed:false,
@@ -228,7 +241,7 @@ function PeerRow({ entry, kind, recordId, onRefresh }) {
// ── Main drawer ──────────────────────────────────────────────────────────────
export default function SyncDetailDrawer({ kind, recordId, onClose }) {
- const { byPeer, noSyncingPeers, integrityUnavailable, loading, error, refresh } = useSyncIntegrity(kind);
+ const { byPeer, unavailablePeers, noSyncingPeers, integrityUnavailable, loading, error, refresh } = useSyncIntegrity(kind);
const peerEntries = byPeer.get(recordId) ?? [];
// Record state is owned here (fetched once) so the preview and the
@@ -448,6 +461,19 @@ export default function SyncDetailDrawer({ kind, recordId, onClose }) {
</div>
)}
+ {!loading && !error && !noSyncingPeers && integrityUnavailable && unavailablePeers?.length > 0 && (
+ <div className="mt-2 rounded border border-port-border/70 divide-y divide-port-border/60">
+ {unavailablePeers.map((peer) => (
+ <div key={peer.peerId} className="flex items-center justify-between gap-3 px-2 py-1.5">
+ <span className="min-w-0 truncate text-sm text-white">{peer.peerName}</span>
+ <span className="shrink-0 text-xs text-gray-400">
+ {UNAVAILABLE_REASON_LABELS[peer.reason] ?? peer.reason ?? 'Unavailable'}
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+
{!loading && !error && !noSyncingPeers && !integrityUnavailable && peerEntries.length === 0 && (
<p className="text-gray-500 text-sm">No peer data for this record.</p>
)}
diff --git a/client/src/components/sync/SyncDetailDrawer.test.jsx b/client/src/components/sync/SyncDetailDrawer.test.jsx
index 332798d7a0..97e1d618ec 100644
--- a/client/src/components/sync/SyncDetailDrawer.test.jsx
+++ b/client/src/components/sync/SyncDetailDrawer.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { act, render, screen, fireEvent, waitFor } from '@testing-library/react';
// ── Mock useSyncIntegrity ────────────────────────────────────────────────────
const mockRefresh = vi.fn();
@@ -168,11 +168,13 @@ describe('SyncDetailDrawer', () => {
it('shows an "integrity unavailable" message (not "No peer data") when every peer is unreachable', async () => {
mockUseSyncIntegrity.mockReturnValue(defaultHookState({
byPeer: new Map(), // no peer contributed records
+ unavailablePeers: [{ peerId: 'peer-a', peerName: 'void', reason: 'peer-unreachable' }],
noSyncingPeers: false, // sync IS configured
integrityUnavailable: true, // …but no peer answered
}));
render(<SyncDetailDrawer kind="mediaCollection" recordId={RECORD_ID} onClose={() => {}} />);
expect(screen.getByText(/sync status unavailable/i)).toBeInTheDocument();
+ expect(screen.getByText(/peer offline or unreachable/i)).toBeInTheDocument();
expect(screen.queryByText(/no peer data for this record/i)).not.toBeInTheDocument();
});
@@ -243,7 +245,9 @@ describe('SyncDetailDrawer', () => {
try {
mockGetMediaCollection.mockImplementation(() => new Promise(() => {})); // never settles
render(<SyncDetailDrawer kind="mediaCollection" recordId={RECORD_ID} onClose={() => {}} />);
- await vi.advanceTimersByTimeAsync(12001);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(12001);
+ });
expect(screen.getByText(/couldn.t load this collection/i)).toBeInTheDocument();
} finally {
vi.useRealTimers();
@@ -263,8 +267,10 @@ describe('SyncDetailDrawer', () => {
// Now the stale col-A fetch settles — its cleanup must clear ONLY its own
// timer, NOT col-B's. If it cleared the ref blindly, col-B's hard timeout
// would be disabled and the drawer would hang on "Loading…" forever.
- resolveA();
- await vi.advanceTimersByTimeAsync(12001);
+ await act(async () => {
+ resolveA();
+ await vi.advanceTimersByTimeAsync(12001);
+ });
expect(screen.getByText(/couldn.t load this collection/i)).toBeInTheDocument();
} finally {
vi.useRealTimers();
@@ -387,6 +393,7 @@ describe('SyncDetailDrawer — kind="universe"', () => {
]);
return m;
})(),
+ unavailablePeers: [],
noSyncingPeers: false,
loading: false,
error: null,
@@ -406,6 +413,7 @@ describe('SyncDetailDrawer — kind="universe"', () => {
it('shows per-peer breakdown', async () => {
render(<SyncDetailDrawer kind="universe" recordId={UNIVERSE_ID} onClose={() => {}} />);
+ await waitFor(() => expect(screen.getByText('Iron Veil')).toBeInTheDocument());
expect(screen.getByText('void')).toBeInTheDocument();
expect(screen.getByText('null')).toBeInTheDocument();
expect(screen.getByText('Diverged')).toBeInTheDocument();
@@ -450,6 +458,7 @@ describe('SyncDetailDrawer — kind="series"', () => {
]);
return m;
})(),
+ unavailablePeers: [],
noSyncingPeers: false,
loading: false,
error: null,
diff --git a/client/src/hooks/useSyncIntegrity.js b/client/src/hooks/useSyncIntegrity.js
index bd3088ebe8..ed93a6a2d4 100644
--- a/client/src/hooks/useSyncIntegrity.js
+++ b/client/src/hooks/useSyncIntegrity.js
@@ -26,6 +26,7 @@ const STATUS_RANK = [
'diverged',
'peer-only',
'local-only',
+ 'metadata-missing',
'in-parity',
];
@@ -57,12 +58,15 @@ function worstStatus(a, b) {
* integrityUnavailable: boolean,
* statusById: Map<string, string>,
* byPeer: Map<string, Array<{peerId:string, peerName:string, status:string}>>,
+ * unavailablePeers: Array<{peerId:string, peerName:string, reason:string}>,
* refresh: () => void,
* }}
*
* `statusById` — Map<recordId, worst status across all queried peers>
* `byPeer` — Map<recordId, [{peerId, peerName, status}, …]> for drawer breakdowns
* `noSyncingPeers` — true when no online peer has the matching category enabled
+ * `unavailablePeers` — per-peer reasons for peers that could not report
+ * integrity, e.g. peer-unreachable vs peer-too-old.
* `integrityUnavailable` — true when eligible peers DO exist but none returned
* usable integrity data (all too-old / unreachable / fetch-failed). Distinct
* from `noSyncingPeers`; lets callers render a neutral "unknown" badge instead
@@ -83,9 +87,18 @@ function worstStatus(a, b) {
* @param {string} recordId
* @returns {string|undefined}
*/
+function unavailableBadgeStatus(unavailablePeers = []) {
+ const reasons = new Set(unavailablePeers.map((p) => p.reason).filter(Boolean));
+ if (reasons.size === 1 && reasons.has('peer-unreachable')) return 'peer-unreachable';
+ if (reasons.size === 1 && reasons.has('peer-too-old')) return 'peer-too-old';
+ if (reasons.size === 1 && reasons.has('fetch-failed')) return 'fetch-failed';
+ return 'unknown';
+}
+
export function syncBadgeStatus(sync, recordId) {
if (sync.noSyncingPeers) return 'not-syncing';
- return sync.statusById.get(recordId) ?? (sync.integrityUnavailable ? 'unknown' : undefined);
+ return sync.statusById.get(recordId)
+ ?? (sync.integrityUnavailable ? unavailableBadgeStatus(sync.unavailablePeers) : undefined);
}
export function useSyncIntegrity(kind, { peers: peersProp } = {}) {
@@ -95,6 +108,7 @@ export function useSyncIntegrity(kind, { peers: peersProp } = {}) {
const [integrityUnavailable, setIntegrityUnavailable] = useState(false);
const [statusById, setStatusById] = useState(() => new Map());
const [byPeer, setByPeer] = useState(() => new Map());
+ const [unavailablePeers, setUnavailablePeers] = useState([]);
// Generation counter to discard stale async responses (e.g. if `kind`
// changes while a fetch is in flight).
@@ -133,6 +147,7 @@ export function useSyncIntegrity(kind, { peers: peersProp } = {}) {
setIntegrityUnavailable(false);
setStatusById(new Map());
setByPeer(new Map());
+ setUnavailablePeers([]);
setLoading(false);
return;
}
@@ -148,7 +163,7 @@ export function useSyncIntegrity(kind, { peers: peersProp } = {}) {
const data = await fetchSyncIntegrity(peer.instanceId, kind);
return { peer, data };
} catch {
- return { peer, data: { available: false, records: [] } };
+ return { peer, data: { available: false, reason: 'fetch-failed', records: [] } };
}
}),
);
@@ -158,10 +173,18 @@ export function useSyncIntegrity(kind, { peers: peersProp } = {}) {
// Reduce to per-record worst-case status + per-peer breakdown.
const newStatusById = new Map();
const newByPeer = new Map();
+ const newUnavailablePeers = [];
let anyAvailable = false;
for (const { peer, data } of results) {
- if (!data?.available) continue;
+ if (!data?.available) {
+ newUnavailablePeers.push({
+ peerId: peer.instanceId,
+ peerName: peer.name ?? peer.instanceId,
+ reason: data?.reason ?? 'fetch-failed',
+ });
+ continue;
+ }
anyAvailable = true;
for (const rec of data.records ?? []) {
const existing = newStatusById.get(rec.id);
@@ -180,6 +203,7 @@ export function useSyncIntegrity(kind, { peers: peersProp } = {}) {
setIntegrityUnavailable(!anyAvailable);
setStatusById(newStatusById);
setByPeer(newByPeer);
+ setUnavailablePeers(newUnavailablePeers);
} catch (err) {
if (gen !== genRef.current) return;
setError(err);
@@ -192,5 +216,5 @@ export function useSyncIntegrity(kind, { peers: peersProp } = {}) {
run();
}, [run]);
- return { loading, error, noSyncingPeers, integrityUnavailable, statusById, byPeer, refresh: run };
+ return { loading, error, noSyncingPeers, integrityUnavailable, statusById, byPeer, unavailablePeers, refresh: run };
}
diff --git a/client/src/hooks/useSyncIntegrity.test.jsx b/client/src/hooks/useSyncIntegrity.test.jsx
index da463ec0ef..c6478dd25a 100644
--- a/client/src/hooks/useSyncIntegrity.test.jsx
+++ b/client/src/hooks/useSyncIntegrity.test.jsx
@@ -177,6 +177,24 @@ describe('useSyncIntegrity — worst-case status reduction', () => {
expect(result.current.statusById.get(recId)).toBe('assets-missing');
});
+ it('metadata-missing is worse than in-parity but does not outrank local-only', async () => {
+ const recId = 'rec-meta';
+ fetchSyncIntegrity
+ .mockResolvedValueOnce({
+ available: true,
+ records: [{ id: recId, name: 'R', status: 'metadata-missing' }],
+ })
+ .mockResolvedValueOnce({
+ available: true,
+ records: [{ id: recId, name: 'R', status: 'local-only' }],
+ });
+
+ const { result } = renderWithPeers('universe', [PEER_A, PEER_B]);
+ await waitFor(() => expect(result.current.loading).toBe(false));
+
+ expect(result.current.statusById.get(recId)).toBe('local-only');
+ });
+
it('excludes records from unavailable peers', async () => {
fetchSyncIntegrity
.mockResolvedValueOnce({ available: false, reason: 'peer-unreachable', records: [] })
@@ -255,6 +273,10 @@ describe('useSyncIntegrity — integrityUnavailable', () => {
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.integrityUnavailable).toBe(true);
+ expect(result.current.unavailablePeers).toEqual([
+ { peerId: 'peer-a', peerName: 'Peer Alpha', reason: 'peer-unreachable' },
+ { peerId: 'peer-b', peerName: 'Peer Beta', reason: 'peer-too-old' },
+ ]);
expect(result.current.noSyncingPeers).toBe(false); // distinct: peers ARE configured
expect(result.current.statusById.size).toBe(0);
});
@@ -314,7 +336,21 @@ describe('syncBadgeStatus — badge precedence helper', () => {
expect(syncBadgeStatus(make({ statusById: new Map([['r', 'diverged']]) }), 'r')).toBe('diverged');
});
- it('returns unknown when integrity was unavailable and the record has no status', () => {
+ it('returns the precise unavailable badge when all unavailable peers share a reason', () => {
+ expect(syncBadgeStatus(make({
+ integrityUnavailable: true,
+ unavailablePeers: [{ reason: 'peer-unreachable' }],
+ }), 'r')).toBe('peer-unreachable');
+ });
+
+ it('returns unknown when unavailable reasons are mixed and the record has no status', () => {
+ expect(syncBadgeStatus(make({
+ integrityUnavailable: true,
+ unavailablePeers: [{ reason: 'peer-unreachable' }, { reason: 'peer-too-old' }],
+ }), 'r')).toBe('unknown');
+ });
+
+ it('returns unknown when integrity was unavailable without peer details', () => {
expect(syncBadgeStatus(make({ integrityUnavailable: true }), 'r')).toBe('unknown');
});
diff --git a/client/src/services/apiMeatspace.js b/client/src/services/apiMeatspace.js
index efa3a280b4..ac3c6770f7 100644
--- a/client/src/services/apiMeatspace.js
+++ b/client/src/services/apiMeatspace.js
@@ -143,6 +143,11 @@ export const addBloodPressure = (data) => request('/meatspace/blood-pressure', {
method: 'POST',
body: JSON.stringify(data)
});
+export const getWorkouts = () => request('/meatspace/workouts');
+export const addWorkout = (data) => request('/meatspace/workouts', {
+ method: 'POST',
+ body: JSON.stringify(data)
+});
export const getEpigeneticTests = () => request('/meatspace/epigenetic');
export const addEpigeneticTest = (data) => request('/meatspace/epigenetic', {
method: 'POST',
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.py
index 9f08854710..93479b97b8 100644
--- a/scripts/generate_ltx2.py
+++ b/scripts/generate_ltx2.py
@@ -79,7 +79,8 @@ def configure_negative_prompt(negative_prompt: str) -> None:
constant lives in up to three places:
- ltx_pipelines_mlx.ti2vid_one_stage (T2V / I2V / A2V one-stage paths)
- ltx_pipelines_mlx._base (base class used by Q8/HQ paths)
- - utils.constants (two-stage / extend shared import)
+ - ltx_pipelines_mlx.utils.constants (two-stage / extend shared import)
+ - ltx_core_mlx.utils.constants (older upstream layouts)
We overwrite it on every module that already defines it (REPLACE semantics,
not append). Modules absent at the current LTX2 pin are skipped silently.
@@ -90,7 +91,8 @@ def configure_negative_prompt(negative_prompt: str) -> None:
_candidates = [
("ltx_pipelines_mlx", "ti2vid_one_stage"),
("ltx_pipelines_mlx", "_base"),
- ("utils", "constants"),
+ ("ltx_pipelines_mlx.utils", "constants"),
+ ("ltx_core_mlx.utils", "constants"),
]
patched = 0
for pkg, mod in _candidates:
diff --git a/scripts/migrations/037-history-json-to-jsonl.js b/scripts/migrations/037-history-json-to-jsonl.js
index 59edb7446f..a839f0ac24 100644
--- a/scripts/migrations/037-history-json-to-jsonl.js
+++ b/scripts/migrations/037-history-json-to-jsonl.js
@@ -12,9 +12,11 @@
* `history.json.bak-037` after conversion for manual recovery.
*/
-import { mkdir, readFile, rename, stat } from 'fs/promises';
+import { createReadStream, createWriteStream } from 'fs';
+import { mkdir, rename, rm, stat } from 'fs/promises';
+import { createInterface } from 'readline';
import { join, relative } from 'path';
-import { readJSONLFile, writeJSONLines } from '../../server/lib/fileUtils.js';
+import { writeJSONLines } from '../../server/lib/fileUtils.js';
const LEGACY_FILENAME = 'history.json';
const JSONL_FILENAME = 'history.jsonl';
@@ -25,14 +27,116 @@ const fileExists = (path) => stat(path).then(() => true, (err) => {
throw err;
});
-const readJsonTolerant = async (path) => {
- const raw = await readFile(path, 'utf-8').catch((err) => {
- if (err.code === 'ENOENT') return null;
- throw err;
+async function readExistingIds(jsonlPath) {
+ if (!await fileExists(jsonlPath)) return new Set();
+ const ids = new Set();
+ const rl = createInterface({ input: createReadStream(jsonlPath, { encoding: 'utf8' }), crlfDelay: Infinity });
+ for await (const line of rl) {
+ if (!line.trim()) continue;
+ try {
+ const entry = JSON.parse(line);
+ if (entry && typeof entry.id === 'string') ids.add(entry.id);
+ } catch { /* malformed legacy line: keep it in place, just cannot dedupe by id */ }
+ }
+ return ids;
+}
+
+async function streamLegacyEntries(legacyPath, onEntry) {
+ return new Promise((resolve, reject) => {
+ const stream = createReadStream(legacyPath, { encoding: 'utf8' });
+ let beforeArray = '';
+ let inArray = false;
+ let inObject = false;
+ let inString = false;
+ let escaped = false;
+ let depth = 0;
+ let buf = '';
+ let skippingPrimitive = false;
+ let sawEntries = false;
+ let done = false;
+ let invalid = 0;
+
+ const finish = () => {
+ if (!sawEntries) reject(new Error('missing entries array'));
+ else resolve({ skippedInvalid: invalid });
+ };
+
+ stream.on('error', reject);
+ stream.on('end', finish);
+ stream.on('data', async (chunk) => {
+ stream.pause();
+ try {
+ let i = 0;
+ if (!inArray) {
+ beforeArray += chunk;
+ const key = beforeArray.indexOf('"entries"');
+ const bracket = key === -1 ? -1 : beforeArray.indexOf('[', key);
+ if (bracket === -1) {
+ beforeArray = beforeArray.slice(-32);
+ stream.resume();
+ return;
+ }
+ sawEntries = true;
+ inArray = true;
+ chunk = beforeArray.slice(bracket + 1);
+ beforeArray = '';
+ }
+
+ for (; i < chunk.length && !done; i++) {
+ const ch = chunk[i];
+ if (!inObject) {
+ if (skippingPrimitive) {
+ if (ch === ',') skippingPrimitive = false;
+ else if (ch === ']') { done = true; stream.destroy(); break; }
+ continue;
+ }
+ if (ch === ']') { done = true; stream.destroy(); break; }
+ if (ch === '{') {
+ inObject = true;
+ inString = false;
+ escaped = false;
+ depth = 1;
+ buf = '{';
+ } else if (!/\s|,/.test(ch)) {
+ invalid += 1;
+ skippingPrimitive = true;
+ }
+ continue;
+ }
+
+ buf += ch;
+ if (escaped) { escaped = false; continue; }
+ if (ch === '\\') { escaped = true; continue; }
+ if (ch === '"') { inString = !inString; continue; }
+ if (inString) continue;
+ if (ch === '{') depth += 1;
+ else if (ch === '}') depth -= 1;
+
+ if (depth === 0) {
+ try {
+ await onEntry(JSON.parse(buf));
+ } catch {
+ invalid += 1;
+ }
+ inObject = false;
+ buf = '';
+ }
+ }
+ stream.resume();
+ } catch (err) {
+ reject(err);
+ }
+ });
+ stream.on('close', () => { if (done) finish(); });
});
- if (raw == null) return null;
- try { return JSON.parse(raw); } catch { return { __unreadable: true }; }
-};
+}
+
+function writeJsonlLine(out, entry) {
+ const line = `${JSON.stringify(entry)}\n`;
+ return new Promise((resolve, reject) => {
+ out.write(line, (err) => err ? reject(err) : resolve());
+ });
+}
export default {
async up({ rootDir }) {
@@ -56,42 +160,41 @@ export default {
return { ok: true, reason: 'already-jsonl' };
}
- const legacy = await readJsonTolerant(legacyPath);
- if (!legacy || typeof legacy !== 'object' || legacy.__unreadable || !Array.isArray(legacy.entries)) {
- console.warn(`⚠️ migration 037: ${legacyPath} unreadable or not { entries: [...] } — skipping. Resolve manually before next boot.`);
- return { ok: false, reason: 'unreadable' };
- }
+ const existingIds = await readExistingIds(jsonlPath);
+ if (!jsonlExists) await writeJSONLines(jsonlPath, []);
- const existing = await readJSONLFile(jsonlPath, { logErrors: true });
- const existingIds = new Set(existing.map((entry) => (
- entry && typeof entry.id === 'string' ? entry.id : null
- )).filter(Boolean));
-
- const converted = [];
+ const out = createWriteStream(jsonlPath, { flags: 'a' });
let skippedDuplicate = 0;
- let skippedInvalid = 0;
- for (const entry of legacy.entries) {
+ let converted = 0;
+ const { skippedInvalid } = await streamLegacyEntries(legacyPath, async (entry) => {
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
- skippedInvalid += 1;
- continue;
+ return;
}
if (typeof entry.id === 'string' && existingIds.has(entry.id)) {
skippedDuplicate += 1;
- continue;
+ return;
}
- converted.push(entry);
+ await writeJsonlLine(out, entry);
+ converted += 1;
if (typeof entry.id === 'string') existingIds.add(entry.id);
+ }).catch((err) => {
+ out.end();
+ console.warn(`⚠️ migration 037: ${legacyPath} unreadable or not { entries: [...] } — skipping. Resolve manually before next boot.`);
+ return { __error: err };
+ });
+ await new Promise((resolve, reject) => out.end((err) => err ? reject(err) : resolve()));
+ if (skippedInvalid == null) {
+ if (!jsonlExists) await rm(jsonlPath, { force: true });
+ return { ok: false, reason: 'unreadable' };
}
- await writeJSONLines(jsonlPath, [...existing, ...converted]);
-
const finalBackupPath = await fileExists(backupPath)
? `${backupPath}-${Date.now()}`
: backupPath;
await rename(legacyPath, finalBackupPath);
console.log(
- `📦 migration 037: converted ${converted.length} history entr${converted.length === 1 ? 'y' : 'ies'} ` +
+ `📦 migration 037: converted ${converted} history entr${converted === 1 ? 'y' : 'ies'} ` +
`to data/${JSONL_FILENAME} (${skippedDuplicate} duplicate, ${skippedInvalid} invalid); ` +
`legacy file backed up as ${relative(dataDir, finalBackupPath)}`,
);
@@ -99,7 +202,7 @@ export default {
return {
ok: true,
reason: 'converted',
- converted: converted.length,
+ converted,
skippedDuplicate,
skippedInvalid,
};
diff --git a/server/index.js b/server/index.js
index 9c52d86a7e..e4e3fe8653 100644
--- a/server/index.js
+++ b/server/index.js
@@ -73,7 +73,7 @@ import databaseRoutes from './routes/database.js';
import localLlmRoutes from './routes/localLlm.js';
import codeReviewRoutes from './routes/codeReview.js';
import { ensureBackendProvider, getBackend as getLocalLlmBackend } from './services/localLlm.js';
-import { ensureRunning as ensureOllamaRunning } from './services/ollamaManager.js';
+import { ensureProviderReady as ensureOllamaProviderReady, ensureRunning as ensureOllamaRunning } from './services/ollamaManager.js';
import searchRoutes from './routes/search.js';
import paletteRoutes from './routes/palette.js';
import dashboardLayoutsRoutes from './routes/dashboardLayouts.js';
@@ -215,6 +215,7 @@ await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), co
// Lifecycle hooks shared between AI Toolkit and PortOS runner shim
const aiToolkitHooks = {
+ ensureProviderReady: (provider) => ensureOllamaProviderReady(provider),
onRunCreated: (metadata) => {
recordSession(metadata.providerId, metadata.providerName, metadata.model).catch(err => {
console.error(`❌ Failed to record usage session: ${err.message}`);
diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.js
index 73b7d0f5af..fc1dc77d60 100644
--- a/server/lib/aiToolkit/runner.js
+++ b/server/lib/aiToolkit/runner.js
@@ -5,7 +5,6 @@ import { join, extname } from 'path';
import { spawn } from 'child_process';
import { randomUUID } from 'crypto';
import { analyzeError, analyzeHttpError, ERROR_CATEGORIES } from './errorDetection.js';
-import { ensureProviderReady as ensureOllamaProviderReady } from '../../services/ollamaManager.js';
export function createRunnerService(config = {}) {
const {
@@ -310,7 +309,8 @@ export function createRunnerService(config = {}) {
messageContent = prompt;
}
- const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));
+ const ensureProviderReady = hooks.ensureProviderReady || (async () => ({ success: true }));
+ const ready = await ensureProviderReady(provider).catch((err) => ({ success: false, error: err.message }));
const response = ready.success
? await fetch(`${provider.endpoint}/chat/completions`, {
method: 'POST',
diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.js
new file mode 100644
index 0000000000..f45824fb48
--- /dev/null
+++ b/server/lib/aiToolkit/runner.test.js
@@ -0,0 +1,65 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import { mkdtemp, rm, readFile } from 'fs/promises';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { createRunnerService } from './runner.js';
+
+describe('AI Toolkit runner service', () => {
+ const tempDirs = [];
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ for (const dir of tempDirs.splice(0)) {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+
+ it('checks provider readiness through the injected hook before API fetches', async () => {
+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));
+ tempDirs.push(dataDir);
+
+ const provider = {
+ id: 'ollama',
+ name: 'Ollama',
+ endpoint: 'http://localhost:11434/v1',
+ defaultModel: 'llama3'
+ };
+ const ensureProviderReady = vi.fn(async () => ({ success: false, error: 'service offline' }));
+ const onComplete = vi.fn();
+ const onRunFailed = vi.fn();
+ const fetch = vi.fn();
+ vi.stubGlobal('fetch', fetch);
+
+ const runner = createRunnerService({
+ dataDir,
+ hooks: {
+ ensureProviderReady,
+ onRunFailed
+ }
+ });
+
+ await runner.executeApiRun(
+ 'run-ready-hook',
+ provider,
+ null,
+ 'hello',
+ process.cwd(),
+ [],
+ undefined,
+ onComplete
+ );
+
+ expect(ensureProviderReady).toHaveBeenCalledWith(provider);
+ expect(fetch).not.toHaveBeenCalled();
+ expect(onRunFailed).toHaveBeenCalledTimes(1);
+ expect(onComplete).toHaveBeenCalledWith(expect.objectContaining({ success: false }));
+
+ const metadata = JSON.parse(
+ await readFile(join(dataDir, 'runs', 'run-ready-hook', 'metadata.json'), 'utf8')
+ );
+ expect(metadata).toMatchObject({
+ success: false,
+ errorCategory: 'unknown'
+ });
+ });
+});
diff --git a/server/lib/meatspaceValidation.js b/server/lib/meatspaceValidation.js
index 4c35c94857..d90842094a 100644
--- a/server/lib/meatspaceValidation.js
+++ b/server/lib/meatspaceValidation.js
@@ -149,6 +149,18 @@ export const bloodPressureSchema = z.object({
diastolic: z.number().min(20).max(200)
});
+// =============================================================================
+// WORKOUTS
+// =============================================================================
+
+export const workoutSchema = z.object({
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
+ type: z.string().min(1).max(100),
+ durationMinutes: z.number().min(0).max(1440).nullable().optional(),
+ intensity: z.string().max(50).nullable().optional(),
+ notes: z.string().max(1000).nullable().optional()
+});
+
// =============================================================================
// EPIGENETIC TESTS
// =============================================================================
diff --git a/server/lib/syncIntegrity.js b/server/lib/syncIntegrity.js
index 945b73441a..dacd85eeb9 100644
--- a/server/lib/syncIntegrity.js
+++ b/server/lib/syncIntegrity.js
@@ -12,6 +12,7 @@ export const INTEGRITY_STATUS = Object.freeze({
PEER_ONLY: 'peer-only',
DIVERGED: 'diverged',
ASSETS_MISSING: 'assets-missing',
+ METADATA_MISSING: 'metadata-missing',
});
const sortedHashes = (a) => [...(Array.isArray(a) ? a : [])].sort();
@@ -25,7 +26,8 @@ const hashesEqual = (a, b) => {
/**
* Pure diff of two manifest lists.
*
- * Each entry shape: `{ id, name?, updatedAt, deleted?, assetHashes }`.
+ * Each entry shape:
+ * `{ id, name?, updatedAt, deleted?, assetHashes, metadataMissing? }`.
*
* Tombstone handling: when BOTH sides are tombstoned (deleted === true) the
* pair is omitted from the output entirely — both agree the record is gone, so
@@ -69,6 +71,8 @@ export function computeRecordIntegrity(localList, remoteList) {
status = INTEGRITY_STATUS.DIVERGED;
} else if (!hashesEqual(local.assetHashes, remote.assetHashes)) {
status = INTEGRITY_STATUS.ASSETS_MISSING;
+ } else if (local.metadataMissing === true || remote.metadataMissing === true) {
+ status = INTEGRITY_STATUS.METADATA_MISSING;
} else {
status = INTEGRITY_STATUS.IN_PARITY;
}
diff --git a/server/lib/syncIntegrity.test.js b/server/lib/syncIntegrity.test.js
index 4f5b3981a9..093efff0f7 100644
--- a/server/lib/syncIntegrity.test.js
+++ b/server/lib/syncIntegrity.test.js
@@ -49,6 +49,15 @@ describe('computeRecordIntegrity', () => {
expect(result[0]).toMatchObject({ id: 'r1', status: INTEGRITY_STATUS.ASSETS_MISSING });
});
+ it('returns METADATA_MISSING when image hashes match but one side lacks sidecar metadata', () => {
+ const ts = '2026-05-23T00:00:00.000Z';
+ const local = makeRow({ updatedAt: ts, assetHashes: ['aaaa'], metadataMissing: true });
+ const remote = makeRow({ updatedAt: ts, assetHashes: ['aaaa'], metadataMissing: false });
+ const result = computeRecordIntegrity([local], [remote]);
+ expect(result).toHaveLength(1);
+ expect(result[0]).toMatchObject({ id: 'r1', status: INTEGRITY_STATUS.METADATA_MISSING });
+ });
+
it('treats hash order as irrelevant for IN_PARITY (sorts before compare)', () => {
const ts = '2026-05-23T00:00:00.000Z';
const local = makeRow({ updatedAt: ts, assetHashes: ['bbbb', 'aaaa'] });
diff --git a/server/routes/meatspace.js b/server/routes/meatspace.js
index 868399d081..ddc527fb0f 100644
--- a/server/routes/meatspace.js
+++ b/server/routes/meatspace.js
@@ -18,6 +18,7 @@ import {
bloodTestSchema,
bodyEntrySchema,
bloodPressureSchema,
+ workoutSchema,
epigeneticTestSchema,
eyeExamSchema,
eyeExamUpdateSchema,
@@ -452,6 +453,25 @@ router.post('/blood-pressure', asyncHandler(async (req, res) => {
res.status(201).json(reading);
}));
+/**
+ * GET /api/meatspace/workouts
+ * Workout entries logged via voice, palette, or API
+ */
+router.get('/workouts', asyncHandler(async (req, res) => {
+ const workouts = await healthService.getWorkouts();
+ res.json({ workouts });
+}));
+
+/**
+ * POST /api/meatspace/workouts
+ * Log a workout
+ */
+router.post('/workouts', asyncHandler(async (req, res) => {
+ const data = validateRequest(workoutSchema, req.body);
+ const workout = await healthService.addWorkout(data);
+ res.status(201).json(workout);
+}));
+
/**
* GET /api/meatspace/epigenetic
* Elysium results
diff --git a/server/routes/voice.js b/server/routes/voice.js
index 7f8e835cb3..a059175ed9 100644
--- a/server/routes/voice.js
+++ b/server/routes/voice.js
@@ -65,6 +65,7 @@ const voiceConfigPatchSchema = z.object({
// custom provider the voice picker happily lets the user select.
provider: z.string().max(80).optional(),
model: z.string().max(128).optional(),
+ visionModel: z.string().max(128).optional(),
systemPrompt: z.string().max(4000).optional(),
usePersonality: z.boolean().optional(),
personality: z.object({
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index 692a325991..863c10e7fe 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -22,13 +22,13 @@
import { execFile, spawn } from 'child_process'
import { promisify } from 'util'
-import { readFileSync, writeFileSync, createWriteStream } from 'fs'
+import { readFileSync, createWriteStream } from 'fs'
import { stat, mkdir, rm } from 'fs/promises'
import { join } from 'path'
import { tmpdir } from 'os'
import { pipeline } from 'stream/promises'
import { Readable } from 'stream'
-import { PATHS } from '../lib/fileUtils.js'
+import { PATHS, atomicWrite } from '../lib/fileUtils.js'
import { isBackend, mapModelToBackend } from '../lib/localLlmCatalog.js'
import { sanitizeOllamaName } from '../lib/localLlmDisk.js'
import * as ollamaManager from './ollamaManager.js'
@@ -145,7 +145,7 @@ export function getBackend() {
return DEFAULT_BACKEND
}
-function writeBackend(backend) {
+async function writeBackend(backend) {
let content = ''
try { content = readFileSync(ENV_PATH, 'utf8') } catch { /* no .env yet */ }
if (/^LLM_BACKEND=/m.test(content)) {
@@ -153,7 +153,7 @@ function writeBackend(backend) {
} else {
content = `LLM_BACKEND=${backend}\n${content}`
}
- writeFileSync(ENV_PATH, content)
+ await atomicWrite(ENV_PATH, content)
}
/**
@@ -651,7 +651,7 @@ export async function deleteModel(backend, modelId) {
*/
export async function switchBackend(to) {
if (!isBackend(to)) return { success: false, error: `Unknown backend: ${to}` }
- writeBackend(to)
+ await writeBackend(to)
await ensureBackendProvider(to)
console.log(`🔀 Active local LLM backend → ${to}`)
return { success: true, backend: to }
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index 0fb2d491a8..aa57a9277e 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -8,7 +8,13 @@ import fs from 'fs';
// service captures ENV_PATH = join(PATHS.root, '.env') at import time, so each
// test sets `state.root` to a fresh temp dir and re-imports under resetModules.
const state = vi.hoisted(() => ({ root: '' }));
-vi.mock('../lib/fileUtils.js', () => ({ PATHS: state }));
+vi.mock('../lib/fileUtils.js', async () => {
+ const fsMod = await import('fs');
+ return {
+ PATHS: state,
+ atomicWrite: async (file, data) => fsMod.writeFileSync(file, data),
+ };
+});
const mocks = vi.hoisted(() => ({
ollama: {
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index f1c72394c9..11ee0aeb52 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -84,9 +84,10 @@ async function getServiceController() {
return {
supported: true,
manager: 'systemd',
- start: ['systemctl', ['start', 'ollama']],
- stop: ['systemctl', ['stop', 'ollama']],
- list: ['systemctl', ['is-active', 'ollama']]
+ start: ['systemctl', ['enable', '--now', 'ollama']],
+ stop: ['systemctl', ['disable', '--now', 'ollama']],
+ active: ['systemctl', ['is-active', 'ollama']],
+ enabled: ['systemctl', ['is-enabled', 'ollama']]
}
}
return { supported: false, manager: null }
@@ -114,16 +115,23 @@ async function getServiceStatus() {
}
if (controller.manager === 'systemd') {
- const [cmd, args] = controller.list
- const { stdout } = await execFileAsync(cmd, args, { timeout: SERVICE_COMMAND_TIMEOUT_MS }).catch(() => ({ stdout: '' }))
- const serviceStatus = stdout.trim() || 'inactive'
- const running = serviceStatus === 'active'
+ const [activeCmd, activeArgs] = controller.active
+ const [enabledCmd, enabledArgs] = controller.enabled
+ const [{ stdout: activeOut }, { stdout: enabledOut }] = await Promise.all([
+ execFileAsync(activeCmd, activeArgs, { timeout: SERVICE_COMMAND_TIMEOUT_MS }).catch(() => ({ stdout: '' })),
+ execFileAsync(enabledCmd, enabledArgs, { timeout: SERVICE_COMMAND_TIMEOUT_MS }).catch(() => ({ stdout: '' })),
+ ])
+ const activeStatus = activeOut.trim() || 'inactive'
+ const enabledStatus = enabledOut.trim() || 'disabled'
+ const running = activeStatus === 'active'
+ const runAtStartup = enabledStatus === 'enabled'
return {
supported: true,
manager: 'systemd',
running,
- runAtStartup: running,
- status: serviceStatus
+ runAtStartup,
+ status: activeStatus,
+ enabledStatus
}
}
diff --git a/server/services/sharing/integrity.js b/server/services/sharing/integrity.js
index 332636d28e..39c8f5dcca 100644
--- a/server/services/sharing/integrity.js
+++ b/server/services/sharing/integrity.js
@@ -16,7 +16,7 @@ import { listCollections } from '../mediaCollections.js';
import { listUniverses } from '../universeBuilder.js';
import { listSeries } from '../pipeline/series.js';
import { getPeers } from '../instances.js';
-import { assetShaListForRecord } from './peerSync.js';
+import { assetIntegrityForRecord } from './peerSync.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
@@ -44,6 +44,9 @@ export async function buildLocalManifest(kind) {
const out = [];
for (const r of records) {
const deleted = r.deleted === true;
+ const assetIntegrity = deleted
+ ? { assetHashes: [], metadataMissing: false }
+ : await assetIntegrityForRecord(kind, r);
out.push({
id: r.id,
name: r.name,
@@ -53,7 +56,8 @@ export async function buildLocalManifest(kind) {
// compares assetHashes when BOTH sides are live (and drops
// deleted-vs-deleted pairs entirely). Hashing a deleted record's
// still-on-disk assets is pure wasted file I/O.
- assetHashes: deleted ? [] : await assetShaListForRecord(kind, r),
+ assetHashes: assetIntegrity.assetHashes,
+ metadataMissing: assetIntegrity.metadataMissing,
});
}
return out;
diff --git a/server/services/sharing/integrity.test.js b/server/services/sharing/integrity.test.js
index 2075ec844b..4498cf4fe1 100644
--- a/server/services/sharing/integrity.test.js
+++ b/server/services/sharing/integrity.test.js
@@ -20,6 +20,7 @@ vi.mock('../instances.js', async () => ({
// Mock peerSync.js — we test integrity.js logic, not asset hashing.
vi.mock('./peerSync.js', async () => ({
+ assetIntegrityForRecord: vi.fn().mockResolvedValue({ assetHashes: [], metadataMissing: false }),
assetShaListForRecord: vi.fn().mockResolvedValue([]),
PEER_SUBSCRIBABLE_KINDS: ['universe', 'series', 'mediaCollection'],
}));
@@ -37,7 +38,7 @@ vi.mock('../pipeline/series.js', async () => ({
import { peerFetch } from '../../lib/peerHttpClient.js';
import { getPeers } from '../instances.js';
-import { assetShaListForRecord } from './peerSync.js';
+import { assetIntegrityForRecord } from './peerSync.js';
import { listCollections } from '../mediaCollections.js';
import { listUniverses } from '../universeBuilder.js';
import { listSeries } from '../pipeline/series.js';
@@ -73,7 +74,7 @@ describe('buildLocalManifest', () => {
it('returns one row per collection with the correct shape', async () => {
const col = makeCollection();
vi.mocked(listCollections).mockResolvedValue([col]);
- vi.mocked(assetShaListForRecord).mockResolvedValue(['aabb', 'ccdd']);
+ vi.mocked(assetIntegrityForRecord).mockResolvedValue({ assetHashes: ['aabb', 'ccdd'], metadataMissing: true });
const result = await buildLocalManifest('mediaCollection');
expect(result).toHaveLength(1);
@@ -83,8 +84,9 @@ describe('buildLocalManifest', () => {
updatedAt: '2026-05-23T00:00:00.000Z',
deleted: false,
assetHashes: ['aabb', 'ccdd'],
+ metadataMissing: true,
});
- expect(assetShaListForRecord).toHaveBeenCalledWith('mediaCollection', col);
+ expect(assetIntegrityForRecord).toHaveBeenCalledWith('mediaCollection', col);
});
it('marks deleted collections as deleted:true and skips asset hashing for them', async () => {
@@ -96,7 +98,7 @@ describe('buildLocalManifest', () => {
// Tombstones are never hashed — computeRecordIntegrity ignores assets for
// deleted records, so the file I/O would be wasted.
expect(result[0].assetHashes).toEqual([]);
- expect(assetShaListForRecord).not.toHaveBeenCalled();
+ expect(assetIntegrityForRecord).not.toHaveBeenCalled();
});
it('passes includeDeleted:true so listCollections returns tombstones', async () => {
@@ -119,18 +121,19 @@ describe('buildLocalManifest', () => {
expect(result).toEqual([]);
});
- it('handles multiple collections and calls assetShaListForRecord for each', async () => {
+ it('handles multiple collections and calls assetIntegrityForRecord for each', async () => {
const col1 = makeCollection({ id: 'c1', name: 'C1' });
const col2 = makeCollection({ id: 'c2', name: 'C2' });
vi.mocked(listCollections).mockResolvedValue([col1, col2]);
- vi.mocked(assetShaListForRecord)
- .mockResolvedValueOnce(['hash-a'])
- .mockResolvedValueOnce(['hash-b']);
+ vi.mocked(assetIntegrityForRecord)
+ .mockResolvedValueOnce({ assetHashes: ['hash-a'], metadataMissing: false })
+ .mockResolvedValueOnce({ assetHashes: ['hash-b'], metadataMissing: true });
const result = await buildLocalManifest('mediaCollection');
expect(result).toHaveLength(2);
expect(result.find((r) => r.id === 'c1').assetHashes).toEqual(['hash-a']);
expect(result.find((r) => r.id === 'c2').assetHashes).toEqual(['hash-b']);
+ expect(result.find((r) => r.id === 'c2').metadataMissing).toBe(true);
});
});
@@ -175,7 +178,7 @@ describe('getPeerIntegrity', () => {
const ts = '2026-05-23T00:00:00.000Z';
const localCol = makeCollection({ id: 'col-1', updatedAt: ts });
vi.mocked(listCollections).mockResolvedValue([localCol]);
- vi.mocked(assetShaListForRecord).mockResolvedValue([]);
+ vi.mocked(assetIntegrityForRecord).mockResolvedValue({ assetHashes: [], metadataMissing: false });
const remoteRecords = [
{ id: 'col-1', name: 'My Collection', updatedAt: ts, deleted: false, assetHashes: [] },
@@ -200,7 +203,7 @@ describe('getPeerIntegrity', () => {
vi.mocked(getPeers).mockResolvedValue([peer]);
const ts = '2026-05-23T00:00:00.000Z';
vi.mocked(listCollections).mockResolvedValue([makeCollection({ id: 'col-1', updatedAt: ts })]);
- vi.mocked(assetShaListForRecord).mockResolvedValue([]);
+ vi.mocked(assetIntegrityForRecord).mockResolvedValue({ assetHashes: [], metadataMissing: false });
vi.mocked(peerFetch).mockResolvedValue({
ok: true,
status: 200,
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index be4146c5a0..46b09f7747 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -590,21 +590,51 @@ async function buildCollectionAssetManifest(collection) {
return out;
}
+function summarizeAssetManifest(manifest) {
+ const entries = Array.isArray(manifest) ? manifest : [];
+ return {
+ assetHashes: entries.map((e) => e.sha256).filter(Boolean).sort(),
+ metadataMissing: entries.some((e) => e?.kind === 'image' && !isNonEmptyStr(e.sidecarSha256)),
+ };
+}
+
+async function buildIntegrityAssetManifest(kind, record) {
+ if (kind === 'mediaCollection') return buildCollectionAssetManifest(record);
+ if (kind === 'series') {
+ const childIssues = await listIssues({ seriesId: record?.id, includeDeleted: true }).catch(() => []);
+ const manifestIssues = childIssues.filter(
+ (i) => i?.deleted !== true && i?.ephemeral !== true,
+ );
+ const linkedCollection = await findCollectionBySeriesId(record?.id).catch(() => null);
+ return buildAssetManifestForSeries(record, manifestIssues, linkedCollection);
+ }
+ return buildAssetManifest(record);
+}
+
/**
- * Returns sorted sha256 hashes for a record's own assets (used by the
- * integrity manifest builder). For `series` this captures the series' OWN
- * asset refs only — child-issue assets are not yet included (v1 limitation;
- * full issue-level integrity is deferred to a future pass).
+ * Returns the integrity-facing asset summary for a record: sorted file hashes
+ * plus whether any hashed image lacks a gen-params sidecar. `series` mirrors
+ * the push manifest path so child issue assets participate in integrity.
+ *
+ * @param {'universe'|'series'|'mediaCollection'} kind
+ * @param {object} record
+ * @returns {Promise<{assetHashes:string[], metadataMissing:boolean}>}
+ */
+export async function assetIntegrityForRecord(kind, record) {
+ const manifest = await buildIntegrityAssetManifest(kind, record);
+ return summarizeAssetManifest(manifest);
+}
+
+/**
+ * Back-compat helper for callers/tests that only need hashes.
*
* @param {'universe'|'series'|'mediaCollection'} kind
* @param {object} record
* @returns {Promise<string[]>} sorted sha256 strings (falsy hashes omitted)
*/
export async function assetShaListForRecord(kind, record) {
- const manifest = kind === 'mediaCollection'
- ? await buildCollectionAssetManifest(record)
- : await buildAssetManifest(record);
- return manifest.map((e) => e.sha256).filter(Boolean).sort();
+ const { assetHashes } = await assetIntegrityForRecord(kind, record);
+ return assetHashes;
}
async function hashImageForManifest(filename) {
@@ -758,6 +788,22 @@ function directoryForAssetKind(kind) {
// upgrade?" probe point.
const SCHEMA_BLOCK_RETRY_COOLDOWN_MS = 5 * 60_000;
+async function isSubscriptionRecordTombstone(sub) {
+ if (sub.recordKind === 'universe') {
+ const record = await getUniverse(sub.recordId, { includeDeleted: true }).catch(() => null);
+ return record?.deleted === true;
+ }
+ if (sub.recordKind === 'series') {
+ const record = await getSeries(sub.recordId, { includeDeleted: true }).catch(() => null);
+ return record?.deleted === true;
+ }
+ if (sub.recordKind === 'mediaCollection') {
+ const record = await getCollection(sub.recordId, { includeDeleted: true }).catch(() => null);
+ return record?.deleted === true;
+ }
+ return false;
+}
+
export async function pushRecordToPeer(sub, options = {}) {
if (
!isPlainObject(sub)
@@ -772,11 +818,14 @@ export async function pushRecordToPeer(sub, options = {}) {
// on the next `peer:online` (where `retryPendingPushesForPeer` passes
// `bypassSchemaCooldown: true`) or after the cooldown elapses.
if (sub.blockedBySchema && !options.bypassSchemaCooldown) {
- const detectedAtMs = Date.parse(sub.blockedBySchema.detectedAt || '');
- const stillCooling = Number.isFinite(detectedAtMs)
- && (Date.now() - detectedAtMs) < SCHEMA_BLOCK_RETRY_COOLDOWN_MS;
- if (stillCooling) {
- return { pushed: false, reason: 'peer-schema-behind-cooldown', blockedBySchema: true };
+ const tombstonePush = await isSubscriptionRecordTombstone(sub);
+ if (!tombstonePush) {
+ const detectedAtMs = Date.parse(sub.blockedBySchema.detectedAt || '');
+ const stillCooling = Number.isFinite(detectedAtMs)
+ && (Date.now() - detectedAtMs) < SCHEMA_BLOCK_RETRY_COOLDOWN_MS;
+ if (stillCooling) {
+ return { pushed: false, reason: 'peer-schema-behind-cooldown', blockedBySchema: true };
+ }
}
}
const peer = await findPeerById(sub.peerId);
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index d86ee80f5e..c6ad6cc1fb 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -65,6 +65,7 @@ import {
applyIncomingPush,
diffAssetManifestAgainstLocal,
buildAssetManifest,
+ assetIntegrityForRecord,
collectCollectionAssetReferences,
autoSubscribeRecordToAllPeers,
autoSubscribePeerToAllRecords,
@@ -937,6 +938,24 @@ describe('peerSync', () => {
expect(manifest).toHaveLength(1);
expect(manifest[0]).not.toHaveProperty('sidecarSha256');
});
+
+ it('summarizes missing image sidecars for integrity without another asset walk', async () => {
+ await writeFile(join(PATHS.images, 'missing-meta.png'), Buffer.from('image bytes'));
+ const record = { id: 'u1', characters: [{ imageRefs: ['missing-meta.png'] }] };
+ const summary = await assetIntegrityForRecord('universe', record);
+ expect(summary.assetHashes).toHaveLength(1);
+ expect(summary.metadataMissing).toBe(true);
+ });
+
+ it('includes live child issue assets in a series integrity summary', async () => {
+ await writeFile(join(PATHS.images, 'issue-panel.png'), Buffer.from('issue image bytes'));
+ vi.mocked(listIssues).mockResolvedValue([
+ { id: 'i1', seriesId: 's1', stages: { storyboards: { panels: [{ imageRefs: ['issue-panel.png'] }] } } },
+ ]);
+ const summary = await assetIntegrityForRecord('series', { id: 's1', name: 'Series' });
+ expect(summary.assetHashes).toHaveLength(1);
+ expect(summary.metadataMissing).toBe(true);
+ });
});
describe('diffAssetManifestAgainstLocal', () => {
@@ -2310,6 +2329,40 @@ describe('peerSync', () => {
expect(vi.mocked(peerFetch).mock.calls.length).toBe(fetchCallsAfterFirst);
});
+ it('bypasses the schema cooldown for tombstone pushes so deletes converge immediately', async () => {
+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });
+ vi.mocked(peerFetch).mockResolvedValueOnce({
+ ok: false,
+ status: 409,
+ json: async () => ({
+ code: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',
+ context: {
+ details: { ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }] },
+ },
+ }),
+ });
+ const sub = await subscribePeer({
+ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',
+ }, { adoptedFromReverse: true });
+ await pushRecordToPeer(sub);
+ const blocked = await findPeerSubscription('peer-a', 'universe', 'u1');
+ vi.mocked(getUniverse).mockResolvedValue({
+ id: 'u1',
+ name: 'Foo',
+ deleted: true,
+ deletedAt: '2026-05-23T00:00:00.000Z',
+ updatedAt: '2026-05-23T00:00:00.000Z',
+ });
+ vi.mocked(peerFetch).mockResolvedValueOnce({ ok: true, json: async () => ({ missingAssets: [] }) });
+
+ const result = await pushRecordToPeer(blocked);
+
+ expect(result.pushed).toBe(true);
+ const body = JSON.parse(vi.mocked(peerFetch).mock.calls.at(-1)[1].body);
+ expect(body.record.deleted).toBe(true);
+ expect(body.assetManifest).toEqual([]);
+ });
+
it('bypassSchemaCooldown=true re-probes regardless of recent block', async () => {
// Simulates the peer:online path: retryPendingPushesForPeer passes
// bypassSchemaCooldown so the next probe actually hits the wire even
diff --git a/server/services/voice/config.js b/server/services/voice/config.js
index 0a315e994d..275470e4b3 100644
--- a/server/services/voice/config.js
+++ b/server/services/voice/config.js
@@ -58,6 +58,7 @@ export const VOICE_DEFAULTS = Object.freeze({
llm: {
provider: 'lmstudio',
model: 'auto',
+ visionModel: 'auto',
// Legacy free-form system prompt. Overridden by `personality` + tool
// descriptions when `usePersonality` is true (default).
systemPrompt: 'You are the PortOS assistant. Your replies are spoken aloud — keep them short and use plain prose (no markdown or lists).',