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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
surface Ollama out-of-date state + one-click update on Local LLMs page
[._.]/ Adam Eivy5374a25b1164
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9fc879a2d2..7370c8a6a8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -38,6 +38,7 @@## Local model stack+- **The Local LLMs page now tells you when Ollama is out of date and lets you update it in one click.** The backend card previously showed only the installed Ollama version with no indication that a newer release existed — so an install could quietly fall behind (and a model pull would fail with a cryptic "requires a newer version of Ollama" before the auto-upgrade flow kicked in). The card now compares the running version against the latest published Ollama release (looked up from GitHub, cached 6h so the steady-state UI never hits the network) and, when newer, shows a "v{latest} available" hint plus a green **Update to v{latest}** button that drives the existing in-place updater (direct `.app` download + relaunch on macOS, Homebrew or the official script elsewhere) with live progress. On platforms PortOS can't auto-update, it links to the download page instead. (`server/services/localLlm.js`, `client/src/components/settings/LocalLlmTab.jsx`)- **[issue-1320] LoRA captioning now keeps a subject's signature look out of the captions, so the trigger word learns it — and training won't silently start when identity is still leaking.** A LoRA binds whatever the captions *don't* describe to the trigger word, so naming a character's always-present cloak/crown/armor in every caption taught the model those phrases instead of the trigger — the bare trigger then rendered a generic subject. Two changes close the loop: (1) the vision captioner is now told to describe **only what changes shot-to-shot** (pose, framing, expression, lighting, setting) and to omit fixed identity — and when the bible knows the subject's signature wardrobe/props/palette, those are passed in by name as an explicit do-not-mention list, so they're omitted even when the model would have phrased them differently each shot (the case the post-hoc shared-fragment strip misses, since it only matches exact repeated phrasing). (2) Launching a training run now **re-checks for caption identity-leak and blocks** (409 `CAPTION_IDENTITY_LEAK`, listing the offending fragments) instead of training silently — the panel offers "Strip identity & queue" or "Train anyway," and resume skips the gate. This is the dataset-quality groundwork before the #1321 base-tier fidelity bench. (`server/services/loraDatasetCaption.js`, `server/services/loraDatasetGenerate.js`, `server/services/loraTraining/dataset.js`, `client/src/components/loraTraining/TrainingPanel.jsx`)- **[issue-1329] Pinned a validated mlx/mlx-metal trio for LoRA training so the GPU-watchdog stack can't silently drift back to the known-bad build.** The three M5 Max kernel panics during FLUX.2 LoRA training all happened on mlx/mlx-metal 0.30.6, but `setup-image-video.sh` installed `mflux>=0.17` as a *floor* and let pip resolve mlx under mflux's `mlx<0.32` cap — so a reinstall could land back on a panicking build. The setup script now pins the bisect-validated trio **mflux 0.17.5 · mlx 0.31.2 · mlx-metal 0.31.2**, proven by run `d36562a0` completing a full LoRA training to adapter extraction (flux2-klein-4b, bf16, 768px, segmentation on) on the panicking M5 Max with no panic or reboot. The runtime-fingerprint half shipped earlier (#1406). (`scripts/setup-image-video.sh`, `docs/research/2026-06-13-mflux-training-watchdog-panic.md`)- **[issue-1329] Applied the upstream-confirmed fix for the LoRA-training GPU watchdog panic.** A search of the MLX tracker turned up the root cause: [mlx #3267](https://github.com/ml-explore/mlx/issues/3267) — the Metal GPU watchdog kills sustained LoRA training whose command buffers compete with active-display compositing (escalating to a `watchdogd` kernel panic + hard reboot on M5-class silicon). The MLX maintainer's confirmed workaround is the `AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1` env var, which PortOS now sets automatically in the trainer (it propagates to the `mflux-train` child; set it to `0` to disable). The trainer logs `STATUS:watchdog mitigation · AGX_RELAX_CDM_CTXSTORE_TIMEOUT=…` so a paniclog records whether it was active. Notably, per #3267 the kill is at the IOGPU layer *above* the process boundary — so process-teardown segmentation alone does not prevent it, and the strongest user-side mitigation is to keep the display off (SSH headless or `pmset displaysleepnow`) for heavy sustained runs. Our data points were posted to #3267 rather than filed as a duplicate. (`scripts/train_mflux_lora.py`, `docs/TROUBLESHOOTING.md`, `docs/research/2026-06-13-mflux-training-watchdog-panic.md`)diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 1873882d46..22d95ced29 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { Link, useNavigate } from 'react-router-dom';-import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle, FlaskConical, Music } from 'lucide-react';+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle, FlaskConical, Music, ArrowUpCircle } from 'lucide-react';import toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import BrailleSpinner from '../BrailleSpinner';@@ -116,6 +116,11 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAc<div className="text-xs text-gray-400">{data?.modelCount ?? 0} model{(data?.modelCount ?? 0) === 1 ? '' : 's'} installed{data?.version && <> · v{data.version}</>}+ {backend.id === 'ollama' && data?.updateAvailable && data?.latestVersion && (+ <span className="text-port-warning" title={`Ollama v${data.latestVersion} is available (you have v${data.version})`}>+ {' · '}v{data.latestVersion} available+ </span>+ )}{startupService?.supported && <> · {runsAtStartup ? 'runs at login' : 'startup off'}</>}</div>@@ -168,6 +173,34 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAc{data.available ? 'Stop' : 'Start'} Ollama</button>)}+ {backend.id === 'ollama' && data?.updateAvailable && (+ data?.canUpgrade ? (+ <button+ onClick={() => runAction(+ 'upgrade-ollama',+ () => upgradeLocalLlmBackend('ollama'),+ (r) => r?.note ? `Ollama updated — ${r.note}` : `Ollama updated to v${data.latestVersion}`+ )}+ disabled={busy}+ className={`${btnClass} bg-port-success/20 hover:bg-port-success/30 text-port-success`}+ title={`Update Ollama from v${data.version} to v${data.latestVersion} in place (downloads the latest release and restarts it)`}+ >+ {actionInProgress === 'upgrade-ollama' ? <BrailleSpinner /> : <ArrowUpCircle size={12} />}+ Update to v{data.latestVersion}+ </button>+ ) : (+ <a+ href={data.downloadUrl}+ target="_blank"+ rel="noreferrer"+ className={`${btnClass} bg-port-warning/20 hover:bg-port-warning/30 text-port-warning no-underline`}+ title={`Ollama v${data.latestVersion} is available — automatic updates aren't supported on this platform`}+ >+ <ArrowUpCircle size={12} />+ Update available+ </a>+ )+ )}{backend.id === 'ollama' && startupService?.supported && (<buttononClick={() => runAction(diff --git a/server/lib/README.md b/server/lib/README.mdindex d94fa18e30..b8163183f0 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -236,6 +236,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. || `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). || `uuid.js` | `v4()` thin wrapper over `crypto.randomUUID()`. |+| `versionUtils.js` | `compareSemver(a, b)` — semver ordering (-1/0/1) with pre-release precedence and build-metadata stripping. Shared by the self-update checker (`updateChecker.js`) and the local-LLM Ollama update detector (`localLlm.js`). Inputs must be `v`-stripped. || `workTracker.js` | `WORK_TRACKERS`/`CONCRETE_WORK_TRACKERS`/`DEFAULT_WORK_TRACKER`, `workTrackerLabel`, `hostToWorkTracker`, `forgeCliForTracker`, `trackerToClaimTaskType`, `hostFromOriginUrl` (subgroup-tolerant host parse), pure `resolveWorkTracker({configured,host})`, async `resolveAppWorkTracker(app)` — resolves a managed app's autonomous work source (PLAN.md / GitHub / GitLab / JIRA), defaulting `'auto'` to the git origin host. Consumed by the `claim-work` router in `cosTaskGenerator.js` and `routes/apps.js`. || `workspaceRoots.js` | Shared allow-list for routes that take a caller-supplied filesystem path. `ALLOWED_WORKSPACE_ROOTS` (defaults + `PORTOS_WORKSPACE_ROOTS`, symlink-resolved), `isWithinRoot(resolvedPath, root)` (separator-safe containment), `isWithinAllowedRoots(realPath)`, and `WORKSPACE_ROOTS_CONFIGURED` (true when the operator set the env var — lets a permissive-by-default route like `routes/detect.js` opt into confinement). Used by `routes/commands.js` (always scoped) and `routes/detect.js` (scoped only when configured). || `zodCompat.js` | Zod 4 compatibility helpers. `partialWithoutDefaults(objectSchema)` — like `.partial()` but strips inner field defaults first, so a PATCH/update schema doesn't inject (and clobber) the stored values of fields the caller didn't send. Use for any update schema derived from a defaulted base. |diff --git a/server/lib/index.js b/server/lib/index.jsindex e147bb1a6b..31c4ece8b7 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -206,6 +206,7 @@ export * from './singleFlight.js';export * from './streamBackpressure.js';export * from './sseUtils.js';export * from './uuid.js';+export * from './versionUtils.js';export * from './workTracker.js';export * from './workspaceRoots.js';export * from './zodCompat.js';diff --git a/server/lib/versionUtils.js b/server/lib/versionUtils.jsnew file mode 100644index 0000000000..3c4df7fdd5--- /dev/null+++ b/server/lib/versionUtils.js@@ -0,0 +1,62 @@+/**+ * Version-string comparison shared across PortOS — the self-update checker+ * (upstream PortOS releases) and the local-LLM backend update detector (Ollama+ * GitHub releases) both need the same semver ordering, so it lives here rather+ * than being re-implemented per consumer.+ */++/**+ * Compare two semver strings. Returns:+ * -1 if a < b, 0 if equal, 1 if a > b+ *+ * Handles the three-segment core plus pre-release precedence (`1.0.0` >+ * `1.0.0-rc.1`, numeric pre-release identifiers sort before string ones) and+ * ignores build metadata (`+build`). Inputs must NOT carry a leading `v` — strip+ * it at the call site (a `v` makes the leading numeric segment NaN→0).+ */+export function compareSemver(a, b) {+ const extractParts = (v) => {+ const noBuild = v.split('+')[0];+ const hyphenIdx = noBuild.indexOf('-');+ const core = hyphenIdx === -1 ? noBuild : noBuild.slice(0, hyphenIdx);+ const pre = hyphenIdx === -1 ? null : noBuild.slice(hyphenIdx + 1);+ return { nums: core.split('.').map(Number), pre: pre || null };+ };+ const comparePreRelease = (preA, preB) => {+ const segsA = preA.split('.');+ const segsB = preB.split('.');+ const len = Math.max(segsA.length, segsB.length);+ for (let i = 0; i < len; i++) {+ if (i >= segsA.length) return -1; // fewer segments = lower precedence+ if (i >= segsB.length) return 1;+ const numA = /^\d+$/.test(segsA[i]) ? Number(segsA[i]) : null;+ const numB = /^\d+$/.test(segsB[i]) ? Number(segsB[i]) : null;+ // Numeric identifiers sort before string identifiers+ if (numA !== null && numB !== null) {+ if (numA < numB) return -1;+ if (numA > numB) return 1;+ } else if (numA !== null) {+ return -1;+ } else if (numB !== null) {+ return 1;+ } else {+ if (segsA[i] < segsB[i]) return -1;+ if (segsA[i] > segsB[i]) return 1;+ }+ }+ return 0;+ };+ const pa = extractParts(a);+ const pb = extractParts(b);+ for (let i = 0; i < 3; i++) {+ const na = pa.nums[i] || 0;+ const nb = pb.nums[i] || 0;+ if (na < nb) return -1;+ if (na > nb) return 1;+ }+ // Equal core versions: no pre-release > pre-release (1.0.0 > 1.0.0-rc.1)+ if (!pa.pre && pb.pre) return 1;+ if (pa.pre && !pb.pre) return -1;+ if (pa.pre && pb.pre) return comparePreRelease(pa.pre, pb.pre);+ return 0;+}diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 191bd99ee8..b74354a1eb 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -29,6 +29,7 @@ import { tmpdir } from 'os'import { pipeline } from 'stream/promises'import { Readable } from 'stream'import { PATHS, atomicWrite } from '../lib/fileUtils.js'+import { compareSemver } from '../lib/versionUtils.js'import { isBackend, mapModelToBackend } from '../lib/localLlmCatalog.js'import { sanitizeOllamaName } from '../lib/localLlmDisk.js'import { recommendEditorialModel, isVisionModel, isVisionCapableCliProvider } from '../lib/localModelHeuristics.js'@@ -60,6 +61,16 @@ function canAutoInstall(backend) {return false}+// Which (platform, backend) pairs PortOS can UPGRADE in place. This is NOT the+// same as canAutoInstall: LM Studio installs via the Homebrew cask on macOS but+// self-updates through Sparkle, which PortOS can't drive (upgradeBackend returns+// manualUpdateRequired for it). Only Ollama has a PortOS-driven upgrade path+// (direct .app download on macOS, brew formula / official script otherwise).+function canAutoUpgrade(backend) {+ if (backend !== 'ollama') return false+ return process.platform === 'darwin' || process.platform === 'linux'+}+// aiToolkit provider id that pairs with each backend.const PROVIDER_ID = { ollama: 'ollama', lmstudio: 'lmstudio' }@@ -349,6 +360,45 @@ export async function installBackend(backend, onProgress = () => {}) {}}+/**+ * Fetch the latest Ollama GitHub release object (or null on any failure). The+ * full object carries both the tag and the downloadable assets — getStatus's+ * cached version lookup reads `tag_name`, the macOS upgrader reads `assets`.+ */+async function fetchLatestOllamaRelease(timeoutMs = 8000) {+ return fetch('https://api.github.com/repos/ollama/ollama/releases/latest', {+ headers: { 'User-Agent': 'PortOS', Accept: 'application/vnd.github+json' },+ signal: AbortSignal.timeout(timeoutMs),+ }).then((r) => (r.ok ? r.json() : null)).catch(() => null)+}++// Cache the latest Ollama release tag. GitHub's release API is slow and+// unauthenticated-rate-limited, and getStatus() runs on every Local LLMs tab+// load / refresh / action — so a steady-state UI must not hit GitHub each time.+// `version: null` is the not-fetched sentinel (distinct from a cached value); a+// successful fetch holds for LATEST_VERSION_TTL_MS, a failed one backs off for+// the shorter error TTL instead of poisoning the cache forever or hammering.+let latestOllamaCache = { version: null, fetchedAt: 0 }+const LATEST_VERSION_TTL_MS = 6 * 60 * 60 * 1000+const LATEST_VERSION_ERROR_TTL_MS = 10 * 60 * 1000++/**+ * Latest published Ollama version (no leading `v`), or null if it can't be+ * determined. Cached — see the TTL notes above. Used by getStatus to surface an+ * "update available" affordance in the UI without a per-call network round-trip.+ */+export async function getLatestOllamaVersion() {+ const age = Date.now() - latestOllamaCache.fetchedAt+ if (latestOllamaCache.version && age < LATEST_VERSION_TTL_MS) return latestOllamaCache.version+ // Recent failed lookup — back off rather than refetch on every status call.+ if (!latestOllamaCache.version && latestOllamaCache.fetchedAt && age < LATEST_VERSION_ERROR_TTL_MS) return null++ const release = await fetchLatestOllamaRelease(8000)+ const version = release?.tag_name ? String(release.tag_name).replace(/^v/, '') : null+ latestOllamaCache = { version, fetchedAt: Date.now() }+ return version+}+/*** Pre-upgrade Ollama version (best-effort — returns null if Ollama isn't running* or isn't responding). Used to verify an upgrade actually moved the version.@@ -388,10 +438,9 @@ async function upgradeOllamaMacApp(emit) {const appPath = '/Applications/Ollama.app'emit('Looking up the latest Ollama release on GitHub…')- const release = await fetch('https://api.github.com/repos/ollama/ollama/releases/latest', {- headers: { 'User-Agent': 'PortOS', Accept: 'application/vnd.github+json' },- signal: AbortSignal.timeout(15000),- }).then((r) => (r.ok ? r.json() : null)).catch(() => null)+ // Uncached on purpose — an explicit upgrade needs the live release (and its+ // download assets), not the status-path's 6h-cached tag.+ const release = await fetchLatestOllamaRelease(15000)if (!release) return { success: false, error: 'Could not reach GitHub to look up the latest Ollama release.' }const asset = (release.assets || []).find((a) => a.name === 'Ollama-darwin.zip')@@ -614,23 +663,35 @@ export async function listModels(backend, forceRefresh = false) {* Combined status for both backends plus the active marker.*/export async function getStatus() {- const [ollamaStatus, ollamaCli, lmStudioStatus, lmsCli, lmStudioModels] = await Promise.all([+ const [ollamaStatus, ollamaCli, lmStudioStatus, lmsCli, lmStudioModels, latestOllamaVersion] = await Promise.all([ollamaManager.getStatus(true),commandExists('ollama', ['--version']),lmStudioManager.getStatus(),commandExists('lms', ['version']),// forceRefresh: status/refresh path bypasses the list cache.- listModels('lmstudio', true).catch(() => [])+ listModels('lmstudio', true).catch(() => []),+ // Cached (6h) — never blocks the steady-state UI on a GitHub round-trip.+ getLatestOllamaVersion().catch(() => null)])const ollamaModels = normalizeModels('ollama', ollamaStatus.models)const lmStudioRecommendation = recommendEditorialModel(lmStudioModels)+ // An update is "available" only when we know BOTH the installed version (Ollama+ // must be running for /api/version to answer) and the latest, and latest is+ // newer. canUpgrade (canAutoUpgrade) gates the in-app updater to the platforms+ // where upgradeBackend can actually drive an Ollama upgrade.+ const ollamaUpdateAvailable = Boolean(+ ollamaStatus.version && latestOllamaVersion && compareSemver(latestOllamaVersion, ollamaStatus.version) > 0+ )return {backend: getBackend(),ollama: {installed: ollamaCli || ollamaStatus.available,available: ollamaStatus.available,version: ollamaStatus.version,+ latestVersion: latestOllamaVersion,+ updateAvailable: ollamaUpdateAvailable,+ canUpgrade: canAutoUpgrade('ollama'),baseUrl: ollamaStatus.baseUrl,modelCount: ollamaStatus.modelCount,models: ollamaModels,diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex b960174888..f9baa5ae93 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -423,4 +423,55 @@ describe('localLlm', () => {]);});});++ describe('getLatestOllamaVersion', () => {+ afterEach(() => vi.unstubAllGlobals());++ it('fetches the latest release, strips the leading v, and caches it', async () => {+ const fetchMock = vi.fn(async () => ({ ok: true, json: async () => ({ tag_name: 'v0.5.7' }) }));+ vi.stubGlobal('fetch', fetchMock);+ expect(await svc.getLatestOllamaVersion()).toBe('0.5.7');+ // Second call within the TTL reuses the cache — no extra network hit.+ expect(await svc.getLatestOllamaVersion()).toBe('0.5.7');+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('returns null on a failed lookup and backs off instead of refetching every call', async () => {+ const fetchMock = vi.fn(async () => { throw new Error('network down'); });+ vi.stubGlobal('fetch', fetchMock);+ expect(await svc.getLatestOllamaVersion()).toBeNull();+ expect(await svc.getLatestOllamaVersion()).toBeNull();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+ });++ describe('getStatus update detection', () => {+ afterEach(() => vi.unstubAllGlobals());++ const stubLatest = (tag) => vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, json: async () => ({ tag_name: tag }) })));++ it('flags updateAvailable when the latest release is newer than the running version', async () => {+ mocks.ollama.getStatus.mockResolvedValueOnce({ available: true, baseUrl: 'x', version: '0.5.4', modelCount: 0, models: [] });+ stubLatest('v0.5.7');+ const s = await svc.getStatus();+ expect(s.ollama.version).toBe('0.5.4');+ expect(s.ollama.latestVersion).toBe('0.5.7');+ expect(s.ollama.updateAvailable).toBe(true);+ });++ it('does not flag an update when already on the latest version', async () => {+ mocks.ollama.getStatus.mockResolvedValueOnce({ available: true, baseUrl: 'x', version: '0.5.7', modelCount: 0, models: [] });+ stubLatest('v0.5.7');+ const s = await svc.getStatus();+ expect(s.ollama.updateAvailable).toBe(false);+ });++ it('cannot flag an update when Ollama is stopped (no running version to compare)', async () => {+ mocks.ollama.getStatus.mockResolvedValueOnce({ available: false, baseUrl: 'x', version: null, modelCount: 0, models: [] });+ stubLatest('v0.5.7');+ const s = await svc.getStatus();+ expect(s.ollama.latestVersion).toBe('0.5.7');+ expect(s.ollama.updateAvailable).toBe(false);+ });+ });});diff --git a/server/services/updateChecker.js b/server/services/updateChecker.jsindex 08fe67604d..974d898d5d 100644--- a/server/services/updateChecker.js+++ b/server/services/updateChecker.js@@ -4,8 +4,14 @@ import { readJSONFile, PATHS, ensureDir, atomicWrite } from '../lib/fileUtils.jsimport { createMutex } from '../lib/asyncMutex.js';import { isPlainObject } from '../lib/objects.js';import { getOriginInfo, UPSTREAM_OWNER, UPSTREAM_REPO, UPSTREAM_FULL_NAME } from '../lib/gitRemote.js';+import { compareSemver } from '../lib/versionUtils.js';import { execGh } from './github.js';+// Re-exported for back-compat: callers/tests historically import compareSemver+// from this module. The implementation now lives in lib/versionUtils.js so the+// local-LLM update detector can share it.+export { compareSemver };+const UPDATE_FILE = join(PATHS.data, 'update.json');const CHECK_INTERVAL_MS = 30 * 60 * 1000; // 30 minutesconst STARTUP_DELAY_MS = 10 * 1000; // 10 seconds@@ -46,57 +52,6 @@ export async function getCurrentVersion() {return version;}-/**- * Compare two semver strings. Returns:- * -1 if a < b, 0 if equal, 1 if a > b- */-export function compareSemver(a, b) {- const extractParts = (v) => {- const noBuild = v.split('+')[0];- const hyphenIdx = noBuild.indexOf('-');- const core = hyphenIdx === -1 ? noBuild : noBuild.slice(0, hyphenIdx);- const pre = hyphenIdx === -1 ? null : noBuild.slice(hyphenIdx + 1);- return { nums: core.split('.').map(Number), pre: pre || null };- };- const comparePreRelease = (preA, preB) => {- const segsA = preA.split('.');- const segsB = preB.split('.');- const len = Math.max(segsA.length, segsB.length);- for (let i = 0; i < len; i++) {- if (i >= segsA.length) return -1; // fewer segments = lower precedence- if (i >= segsB.length) return 1;- const numA = /^\d+$/.test(segsA[i]) ? Number(segsA[i]) : null;- const numB = /^\d+$/.test(segsB[i]) ? Number(segsB[i]) : null;- // Numeric identifiers sort before string identifiers- if (numA !== null && numB !== null) {- if (numA < numB) return -1;- if (numA > numB) return 1;- } else if (numA !== null) {- return -1;- } else if (numB !== null) {- return 1;- } else {- if (segsA[i] < segsB[i]) return -1;- if (segsA[i] > segsB[i]) return 1;- }- }- return 0;- };- const pa = extractParts(a);- const pb = extractParts(b);- for (let i = 0; i < 3; i++) {- const na = pa.nums[i] || 0;- const nb = pb.nums[i] || 0;- if (na < nb) return -1;- if (na > nb) return 1;- }- // Equal core versions: no pre-release > pre-release (1.0.0 > 1.0.0-rc.1)- if (!pa.pre && pb.pre) return 1;- if (pa.pre && !pb.pre) return -1;- if (pa.pre && pb.pre) return comparePreRelease(pa.pre, pb.pre);- return 0;-}-async function loadState() {await ensureDir(PATHS.data);const raw = await readJSONFile(UPDATE_FILE, defaultState(), { allowArray: false });