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
feat([issue-1779]): detect a half-updated install and offer one-click reconcile
[._.]/ Adam Eivyc1193bcd50a5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d524b0626f..ee9649207a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -61,6 +61,10 @@- **[issue-1329] Confirmed on the M5 Max what actually stops the watchdog panic: keeping the display off.** A clean A/B on the *same* 9B-bf16 segmentation-OFF config (the heaviest, most panic-prone) — both with `AGX_RELAX_CDM_CTXSTORE_TIMEOUT=1` set — settled it: with the **display active** the box hard-rebooted at step 0 within minutes (first telemetry-captured panic showed Nominal thermal pressure, i.e. a GPU **driver hang** not heat, with `WindowServer` the top-CPU thread); with the **display asleep** (`pmset displaysleepnow`) the identical run reached **step 302**, clearing the documented 150–300 panic window with no panic. So the env var is necessary but not sufficient for heavy runs — for a 9B/heavy bf16 job, drive the box over SSH or sleep the display, and keep segmentation on. `caffeinate -s` does not sleep the display, and closing the lid suspends the whole machine. TROUBLESHOOTING now documents the working recipe. (`docs/TROUBLESHOOTING.md`, `docs/research/2026-06-13-mflux-training-watchdog-panic.md`)- **[issue-1329] Fixed a bug that was *causing* the training GPU-watchdog crash, and made PortOS auto-sleep the Mac's display during training (then wake it after).** The trainer spawned `caffeinate -dis` to keep the machine awake — but the `-d` flag *forces the display to stay on*, the exact WindowServer-GPU-contention state that triggers the watchdog kernel panic. (The code comment even said "display can sleep"; the flag did the opposite.) The flag is now `-is` so the display can sleep, and on Apple Silicon PortOS proactively runs `pmset displaysleepnow` when a run starts and wakes the display (`caffeinate -u`) when it finishes — so a run you kick off and walk away from (or trigger remotely) protects the box automatically, and you see the result when it's done. On by default; opt out with `loraTraining.displaySleep: false` (e.g. headless). The training panel now explains the crash risk and recommends letting big runs go overnight. (`server/services/loraTraining/index.js`, `server/services/loraTraining/displayPower.js`, `server/lib/validation.js`, `client/src/components/loraTraining/TrainingPanel.jsx`)+## Self-update++- **[issue-1779] PortOS now warns when you've pulled new code but haven't reconciled the install — and reconciles in one click.** Running `git pull` by hand (without `./update.sh`) leaves a half-updated install: new source on disk, but old dependencies still installed, a stale client bundle still being served, the old server process still running, and any new data migrations unapplied. PortOS now detects this and surfaces it distinctly from the existing "a new release is available" notice — a persistent **Install out of sync** warning (toast + a panel on the Update tab) that spells out exactly what's stale: running older code than what's checked out, out-of-date dependencies (per workspace), an older client build, and the count of pending migrations. A **Reconcile Now** button runs the full `update.sh` (install · rebuild · migrate · restart) straight from the UI, fork-aware like the release-update flow, even when there's no newer release to move to. All four signals clear themselves automatically after a proper update, so existing installs get accurate detection with no migration or marker file. (`server/services/installState.js`, `server/services/updateChecker.js`, `server/routes/update.js`, `scripts/run-migrations.js`, `client/src/components/apps/tabs/UpdateTab.jsx`, `client/src/hooks/useUpdateChecker.jsx`)+## Mood boards- **Fix: Pinterest sync pulled 0 pins from boards that actually had images.** Two bugs compounded. (1) Linking a board *section* URL (`/user/board/section/`) stored a `/user/board/section.rss` feed, but Pinterest serves no per-section RSS — that path returns its HTML page with a 200, which parsed to zero pins. Section URLs now collapse to the parent board's feed (the best available, since Pinterest has no section feed), keeping the section URL for display; already-linked section boards self-heal on the next sync. (2) Pinterest entity-escapes each pin's description HTML (`<img src=…>`) rather than wrapping it in CDATA, so the `<img>` fallback never matched the live feed and every pin was skipped; the parser now decodes the description before probing for the image. (`server/lib/pinterestFeed.js`, `server/services/moodBoard/pinterest.js`)diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsxindex c0ad15daba..b1b4d55f52 100644--- a/client/src/components/apps/tabs/UpdateTab.jsx+++ b/client/src/components/apps/tabs/UpdateTab.jsx@@ -166,7 +166,16 @@ export default function UpdateTab() {const handleUpdateFromForkAsIs = () => runUpdate({ acknowledgeFork: true });- const handleSyncForkAndUpdate = async () => {+ // Reconcile a half-updated install (issue #1779) — same machinery as a normal+ // update, but `reconcile: true` lets the server run update.sh even with no+ // newer release. Fork-aware variants mirror the release-update buttons.+ const handleReconcile = () => runUpdate({ reconcile: true });++ const handleReconcileFromForkAsIs = () => runUpdate({ acknowledgeFork: true, reconcile: true });++ // Shared fork-sync-then-run: syncs the fork, then runs update/reconcile with+ // the freshly fetched status. `extraOpts` distinguishes update vs reconcile.+ const syncForkThenRun = async (extraOpts = {}) => {setSyncingFork(true);setForkSyncError(null);const synced = await api.syncPortosFork({}, { silent: true }).catch(err => {@@ -181,9 +190,13 @@ export default function UpdateTab() {toast.success(`Synced ${synced.fullName} from ${synced.source}`);}const fresh = await fetchStatus();- await runUpdate({}, fresh);+ await runUpdate(extraOpts, fresh);};+ const handleSyncForkAndUpdate = () => syncForkThenRun({});++ const handleSyncForkAndReconcile = () => syncForkThenRun({ reconcile: true });+const handleSyncForkOnly = async () => {setSyncingFork(true);setForkSyncError(null);@@ -233,6 +246,26 @@ export default function UpdateTab() {// re-implement the time math here.const forkSyncFresh = !!status?.forkSyncFresh;+ // Install-sync state (issue #1779) — surfaces a half-updated install (bare+ // `git pull`, no ./update.sh). Distinct from "a new release is available".+ const installState = status?.installState;+ const outOfSync = !!installState?.outOfSync;+ const installIssues = [];+ if (installState?.runningStaleCode) {+ installIssues.push('Running code is older than what’s checked out — a restart/update is required.');+ }+ if (installState?.staleDeps?.stale) {+ const ws = (installState.staleDeps.workspaces || []).filter(w => w.stale).map(w => w.name);+ installIssues.push(`Dependencies are out of date${ws.length ? ` (${ws.join(', ')})` : ''} — run update.sh to npm install.`);+ }+ if (installState?.staleBuild === true) {+ installIssues.push('The served client build is older than the UI source — a rebuild is needed.');+ }+ if (installState?.pendingMigrations?.count > 0) {+ const n = installState.pendingMigrations.count;+ installIssues.push(`${n} pending data migration${n === 1 ? '' : 's'} not yet applied.`);+ }+return (<div className="space-y-6">{/* Current Version + Check Button */}@@ -288,6 +321,62 @@ export default function UpdateTab() {</div>)}+ {/* Install out of sync (issue #1779) — distinct from "new release available" */}+ {outOfSync && (+ <div className="p-4 rounded-lg border border-port-warning/50 bg-port-warning/5">+ <div className="flex items-start gap-2">+ <AlertTriangle size={18} className="text-port-warning shrink-0 mt-0.5" />+ <div className="flex-1">+ <div className="text-sm text-white font-medium">Install out of sync</div>+ <div className="text-xs text-gray-400 mt-1">+ Your checked-out code is ahead of what’s running or installed — this happens after a+ manual <span className="font-mono">git pull</span> without <span className="font-mono">./update.sh</span>.+ Reconcile to finish the update (install dependencies, rebuild, run migrations, restart).+ </div>+ <ul className="text-xs text-gray-300 mt-2 space-y-1 list-disc list-inside">+ {installIssues.map((msg, i) => (+ <li key={i}>{msg}</li>+ ))}+ </ul>+ <div className="flex flex-wrap gap-2 mt-3">+ {isFork ? (+ <>+ <button+ onClick={handleSyncForkAndReconcile}+ disabled={updating || polling || syncingFork}+ className="px-4 py-2 bg-port-warning text-black rounded-lg text-sm flex items-center gap-2 hover:bg-port-warning/80 disabled:opacity-50"+ title={`Fast-forwards ${remote?.fullName} main from ${upstreamName}, then runs update.sh to reconcile the install.`}+ >+ <GitFork size={14} className={syncingFork ? 'animate-pulse' : ''} />+ {syncingFork ? 'Syncing fork...' : updating ? 'Reconciling...' : polling ? 'Restarting...' : 'Sync Fork & Reconcile'}+ </button>+ <button+ onClick={handleReconcileFromForkAsIs}+ disabled={updating || polling || syncingFork}+ className="px-4 py-2 bg-port-border text-gray-300 rounded-lg text-sm flex items-center gap-2 hover:bg-port-border/80 hover:text-white disabled:opacity-50"+ title="Skip the fork sync and reconcile from your fork's origin as-is."+ >+ <RefreshCw size={14} className={updating ? 'animate-spin' : ''} />+ Reconcile from Fork As-Is+ </button>+ </>+ ) : (+ <button+ onClick={handleReconcile}+ disabled={updating || polling || syncingFork}+ className="px-4 py-2 bg-port-warning text-black rounded-lg text-sm flex items-center gap-2 hover:bg-port-warning/80 disabled:opacity-50"+ title="Run update.sh to install dependencies, rebuild the client, run migrations, and restart."+ >+ <RefreshCw size={14} className={updating ? 'animate-spin' : ''} />+ {updating ? 'Reconciling...' : polling ? 'Restarting...' : 'Reconcile Now'}+ </button>+ )}+ </div>+ </div>+ </div>+ </div>+ )}+{/* Available Update */}{release && (<div className={`p-4 rounded-lg border ${hasUpdate ? 'border-port-accent/50 bg-port-accent/5' : 'border-port-border bg-port-card'}`}>diff --git a/client/src/hooks/useUpdateChecker.jsx b/client/src/hooks/useUpdateChecker.jsxindex 00145ea2a1..2a32720b60 100644--- a/client/src/hooks/useUpdateChecker.jsx+++ b/client/src/hooks/useUpdateChecker.jsx@@ -5,10 +5,13 @@ import socket from '../services/socket';import * as api from '../services/api';const TOAST_ID = 'portos-update-available';+const OUT_OF_SYNC_TOAST_ID = 'portos-install-out-of-sync';/*** Global hook that checks for PortOS updates and shows a persistent toast- * when a new version is available. Runs in Layout alongside useErrorNotifications.+ * when a new version is available, plus a distinct toast when the install is+ * out of sync (a bare `git pull` without ./update.sh — issue #1779). Runs in+ * Layout alongside useErrorNotifications.*/export function useUpdateChecker() {const navigate = useNavigate();@@ -53,6 +56,40 @@ export function useUpdateChecker() {);};+ const showOutOfSyncToast = () => {+ toast(+ (t) => (+ <div className="flex flex-col gap-2">+ <span className="text-sm">+ Install out of sync — you pulled new code but haven’t reconciled it.+ </span>+ <div className="flex gap-2">+ <button+ onClick={() => {+ toast.dismiss(t.id);+ navigateRef.current(`/apps/${api.PORTOS_APP_ID}/update`);+ }}+ className="px-2 py-1 bg-port-warning text-black text-xs rounded hover:bg-port-warning/80"+ >+ Reconcile+ </button>+ <button+ onClick={() => toast.dismiss(t.id)}+ className="px-2 py-1 bg-gray-600 text-white text-xs rounded hover:bg-gray-500"+ >+ Dismiss+ </button>+ </div>+ </div>+ ),+ {+ id: OUT_OF_SYNC_TOAST_ID,+ duration: Infinity,+ icon: '⚠️'+ }+ );+ };+// Check status on mountapi.getUpdateStatus().then(status => {if (status.updateAvailable && status.latestRelease) {@@ -61,6 +98,11 @@ export function useUpdateChecker() {latestVersion: status.latestRelease.version});}+ // Distinct from the release toast — a half-updated install needs a+ // reconcile (run update.sh), not a version bump.+ if (status.installState?.outOfSync) {+ showOutOfSyncToast();+ }}).catch(() => {});// Listen for real-time update available eventsdiff --git a/scripts/run-migrations.js b/scripts/run-migrations.jsindex c0ed43836c..b4cc29eb18 100644--- a/scripts/run-migrations.js+++ b/scripts/run-migrations.js@@ -7,55 +7,92 @@ const __dirname = dirname(fileURLToPath(import.meta.url));const DEFAULT_ROOT_DIR = join(__dirname, '..');const DEFAULT_MIGRATIONS_DIR = join(__dirname, 'migrations');-export async function runMigrations({- rootDir = DEFAULT_ROOT_DIR,- migrationsDir = DEFAULT_MIGRATIONS_DIR,-} = {}) {- const appliedFile = join(rootDir, 'data', 'migrations.applied.json');+const appliedFilePath = (rootDir) => join(rootDir, 'data', 'migrations.applied.json');- // Ensure data/ exists so we can persist applied state (migrationsDir- // ships in the repo and always exists).- await mkdir(dirname(appliedFile), { recursive: true });+/**+ * Scan for migration files (*.js, sorted by filename). Co-located vitest+ * files (*.test.js) are excluded — they don't export `up()` and would+ * throw the runner if imported as migrations. The vitest config picks+ * them up via its own scripts test glob in server/vitest.config.js.+ * `_`-prefixed files (e.g. `_lib.js`, `_testHelpers.js`) are shared+ * helpers consumed by migration files and their tests — they're never+ * migrations themselves.+ */+async function scanMigrationFiles(migrationsDir) {+ return (await readdir(migrationsDir))+ .filter(f => f.endsWith('.js') && !f.endsWith('.test.js') && !f.startsWith('_'))+ .sort();+}- // Load applied migrations list. Default to [] on missing/unreadable file.- // If the file is corrupt (mid-write truncation, bad JSON, wrong shape), rename- // it aside and rebuild from scratch — migrations are idempotent, so re-running- // is safe, and this prevents one bad write from bricking every subsequent boot.- let applied = [];+/**+ * Read the applied-migrations list. Default to [] on missing/unreadable file.+ *+ * When `repair` is true and the file is corrupt (mid-write truncation, bad+ * JSON, wrong shape), rename it aside and rebuild from scratch — migrations are+ * idempotent, so re-running is safe, and this prevents one bad write from+ * bricking every subsequent boot. When `repair` is false (read-only callers+ * like listPendingMigrations), a corrupt file is treated as `[]` WITHOUT+ * mutating anything on disk.+ */+async function readAppliedList(appliedFile, { repair = false } = {}) {const raw = await readFile(appliedFile, 'utf-8').catch(err => {- if (err.code !== 'ENOENT') {+ if (err.code !== 'ENOENT' && repair) {console.warn(`⚠️ Could not read ${appliedFile}: ${err.message}, defaulting to []`);}return null;});- if (raw !== null) {- let parsed;- let corruptReason = null;- try { parsed = JSON.parse(raw); } catch (err) {- corruptReason = `invalid JSON: ${err.message}`;- }- if (corruptReason === null && !Array.isArray(parsed)) {- corruptReason = `expected array, got ${typeof parsed}`;- }- if (corruptReason !== null) {+ if (raw === null) return [];++ let parsed;+ let corruptReason = null;+ try { parsed = JSON.parse(raw); } catch (err) {+ corruptReason = `invalid JSON: ${err.message}`;+ }+ if (corruptReason === null && !Array.isArray(parsed)) {+ corruptReason = `expected array, got ${typeof parsed}`;+ }+ if (corruptReason !== null) {+ if (repair) {const aside = `${appliedFile}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;await rename(appliedFile, aside);console.warn(`⚠️ Corrupt migrations file ${appliedFile} (${corruptReason}); renamed to ${aside} and rebuilding from scratch`);- } else {- applied = parsed;}+ return [];}+ return parsed;+}- // Scan for migration files (*.js, sorted by filename). Co-located vitest- // files (*.test.js) are excluded — they don't export `up()` and would- // throw the runner if imported as migrations. The vitest config picks- // them up via its own glob (`../scripts/**/*.test.js` in- // server/vitest.config.js). `_`-prefixed files (e.g. `_lib.js`,- // `_testHelpers.js`) are shared helpers consumed by migration files and- // their tests — they're never migrations themselves.- const files = (await readdir(migrationsDir))- .filter(f => f.endsWith('.js') && !f.endsWith('.test.js') && !f.startsWith('_'))- .sort();+/**+ * List migration files present on disk that are NOT yet in the applied-list —+ * i.e. migrations a boot would run. Pure read: never applies, renames, or+ * writes anything (so it's safe to call from a status endpoint). Returns the+ * pending filenames in sorted (apply) order.+ */+export async function listPendingMigrations({+ rootDir = DEFAULT_ROOT_DIR,+ migrationsDir = DEFAULT_MIGRATIONS_DIR,+} = {}) {+ const applied = await readAppliedList(appliedFilePath(rootDir), { repair: false });+ const appliedSet = new Set(applied);+ const files = await scanMigrationFiles(migrationsDir).catch(() => []);+ return files.filter(f => !appliedSet.has(f));+}++export async function runMigrations({+ rootDir = DEFAULT_ROOT_DIR,+ migrationsDir = DEFAULT_MIGRATIONS_DIR,+} = {}) {+ const appliedFile = appliedFilePath(rootDir);++ // Ensure data/ exists so we can persist applied state (migrationsDir+ // ships in the repo and always exists).+ await mkdir(dirname(appliedFile), { recursive: true });++ // Load applied migrations list (repairing a corrupt file aside — see+ // readAppliedList).+ const applied = await readAppliedList(appliedFile, { repair: true });++ const files = await scanMigrationFiles(migrationsDir);let ran = 0;for (const file of files) {diff --git a/scripts/run-migrations.test.js b/scripts/run-migrations.test.jsindex 1a525256d8..45ebd9955c 100644--- a/scripts/run-migrations.test.js+++ b/scripts/run-migrations.test.js@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, readdirSynimport { tmpdir } from 'os';import { join } from 'path';-import { runMigrations } from './run-migrations.js';+import { runMigrations, listPendingMigrations } from './run-migrations.js';describe('runMigrations corrupt applied-list recovery', () => {let rootDir;@@ -109,3 +109,60 @@ export const md5 = (s) => s;expect(JSON.parse(readFileSync(appliedFile, 'utf-8'))).toEqual(['001-fixture.js']);});});++describe('listPendingMigrations', () => {+ let rootDir;+ let dataDir;+ let migrationsDir;+ let appliedFile;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'list-pending-'));+ dataDir = join(rootDir, 'data');+ migrationsDir = join(rootDir, 'migrations');+ mkdirSync(dataDir, { recursive: true });+ mkdirSync(migrationsDir, { recursive: true });+ appliedFile = join(dataDir, 'migrations.applied.json');+ // Migration content is irrelevant — listPendingMigrations never imports them.+ writeFileSync(join(migrationsDir, '001-a.js'), 'export default { async up() {} };');+ writeFileSync(join(migrationsDir, '002-b.js'), 'export default { async up() {} };');+ writeFileSync(join(migrationsDir, '003-c.js'), 'export default { async up() {} };');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('returns all migrations as pending when the applied-list is missing', async () => {+ const pending = await listPendingMigrations({ rootDir, migrationsDir });+ expect(pending).toEqual(['001-a.js', '002-b.js', '003-c.js']);+ });++ it('returns only the migrations not in the applied-list, in sorted order', async () => {+ writeFileSync(appliedFile, JSON.stringify(['001-a.js']) + '\n');+ const pending = await listPendingMigrations({ rootDir, migrationsDir });+ expect(pending).toEqual(['002-b.js', '003-c.js']);+ });++ it('returns empty when every migration is applied', async () => {+ writeFileSync(appliedFile, JSON.stringify(['001-a.js', '002-b.js', '003-c.js']) + '\n');+ const pending = await listPendingMigrations({ rootDir, migrationsDir });+ expect(pending).toEqual([]);+ });++ it('excludes *.test.js and `_`-prefixed helper files', async () => {+ writeFileSync(join(migrationsDir, '001-a.test.js'), '// test');+ writeFileSync(join(migrationsDir, '_lib.js'), 'export const x = 1;');+ const pending = await listPendingMigrations({ rootDir, migrationsDir });+ expect(pending).toEqual(['001-a.js', '002-b.js', '003-c.js']);+ });++ it('treats a corrupt applied-list as empty WITHOUT mutating it (read-only)', async () => {+ writeFileSync(appliedFile, '{ not valid json');+ const pending = await listPendingMigrations({ rootDir, migrationsDir });+ expect(pending).toEqual(['001-a.js', '002-b.js', '003-c.js']);+ // Read-only: the corrupt file must NOT be renamed aside.+ expect(readdirSync(dataDir).some(f => f.includes('corrupt'))).toBe(false);+ expect(existsSync(appliedFile)).toBe(true);+ });+});diff --git a/server/index.js b/server/index.jsindex 5df49a65a1..3761c0d5cc 100644--- a/server/index.js+++ b/server/index.js@@ -165,6 +165,7 @@ import { getSettings as getInitSettings } from './services/settings.js';import { setUserCatalogTypes } from './lib/catalogTypes.js';import { readUserTypes as readUserTypeSlice } from './services/catalogUserTypes/store.js';import { startUpdateScheduler, recordUpdateResult, clearStaleUpdateInProgress, getCurrentVersion } from './services/updateChecker.js';+import { captureBootCommit } from './services/installState.js';import { restoreLoops } from './services/loops.js';import { startBrainScheduler } from './services/brainScheduler.js';import { recoverStuckClassifications } from './services/brain.js';@@ -676,6 +677,11 @@ const removeMarker = () => unlink(updateMarkerPath).catch(e => {// Clear stale updateInProgress if the server was killed mid-updateclearStaleUpdateInProgress().catch(err => console.error(`❌ Stale update recovery failed: ${err.message}`));+// Capture the commit this process booted at, so /api/update/status can detect+// a bare `git pull` that advanced on-disk HEAD without restarting (issue #1779).+// Best-effort — a tarball/non-git install just yields no boot commit.+captureBootCommit().catch(err => console.error(`❌ Boot commit capture failed: ${err.message}`));+// Start periodic update checker (checks GitHub releases every 30 min)startUpdateScheduler();diff --git a/server/routes/update.js b/server/routes/update.jsindex 4fd07407e7..bc5df938a9 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -17,7 +17,11 @@ const syncForkSchema = z.object({});const executeSchema = z.object({- acknowledgeFork: z.boolean().optional()+ acknowledgeFork: z.boolean().optional(),+ // Reconcile a half-updated install (issue #1779): run update.sh to pull ++ // install + build + restart even when there's no NEWER GitHub release — the+ // user did a bare `git pull` and just needs the rest of the update steps.+ reconcile: z.boolean().optional()});// GET /api/update/status — returns update state (also clears stale locks)@@ -104,12 +108,23 @@ router.post('/sync-fork', asyncHandler(async (req, res) => {// POST /api/update/execute — kicks off updaterouter.post('/execute', asyncHandler(async (req, res) => {- const { acknowledgeFork } = validateRequest(executeSchema, req.body || {});+ const { acknowledgeFork, reconcile } = validateRequest(executeSchema, req.body || {});const status = await updateChecker.getUpdateStatus();- if (!status.latestRelease?.tag) {- throw new ServerError('No release available to update to', { status: 400, code: 'NO_RELEASE' });++ // Normal path requires a known release tag to update TO. A reconcile request+ // (issue #1779) instead runs update.sh to finish a bare `git pull` even with+ // no newer release — so when no release tag is known, synthesize one from the+ // current version purely for logging (update.sh pulls main regardless of tag).+ // Guard reconcile on the install actually being out of sync so it can't be+ // used to force an unnecessary restart.+ let tag = status.latestRelease?.tag;+ if (!tag) {+ if (reconcile && status.installState?.outOfSync) {+ tag = `v${status.currentVersion}`;+ } else {+ throw new ServerError('No release available to update to', { status: 400, code: 'NO_RELEASE' });+ }}- const tag = status.latestRelease.tag;// Validate tag is a well-formed semver release (e.g. "v1.27.0" or "v1.27.0-rc.1") to prevent option injectionif (!/^v\d+\.\d+\.\d+(-[a-zA-Z0-9.]+)?$/.test(tag)) {diff --git a/server/services/installState.js b/server/services/installState.jsnew file mode 100644index 0000000000..a196f20844--- /dev/null+++ b/server/services/installState.js@@ -0,0 +1,216 @@+/**+ * Install-sync detection — answers "is the checked-out code ahead of what's+ * actually running / installed?" so the UI can tell a user who did a bare+ * `git pull` (without ./update.sh) that their install is half-updated.+ *+ * Four independent signals (issue #1779):+ * 1. running-stale-code — the server process booted at an older commit than+ * what's now on disk (a `git pull` advanced HEAD but nothing restarted).+ * 2. stale-deps — a workspace's package.json/lockfile is newer than+ * npm's install receipt (`node_modules/.package-lock.json`), or the+ * receipt is missing entirely (deps never installed). `update.sh` runs+ * `npm install`; a bare pull does not.+ * 3. stale-build — the served client bundle (`client/dist`) is older+ * than the client source (a pull touched the UI but it was never rebuilt).+ * 4. pending-migrations — migration files exist on disk that aren't in the+ * applied-list. (Boot normally applies these, so a non-zero count means a+ * pull landed new migrations and the server hasn't restarted yet.)+ *+ * All four self-clear after a proper `update.sh` cycle (install bumps the npm+ * receipt mtime, build bumps the dist mtime, boot applies migrations and+ * captures the new commit) — so no new on-disk marker format is introduced and+ * existing installs get accurate detection immediately, with no migration.+ *+ * Detection is deliberately mtime/receipt-based rather than reading a marker+ * `update.sh` would have to write: that keeps it backward-compatible with every+ * install that updated before this shipped.+ */++import { join } from 'path';+import { stat, readdir } from 'fs/promises';+import { PATHS } from '../lib/fileUtils.js';+import { execGit } from '../lib/execGit.js';+import { listPendingMigrations } from '../../scripts/run-migrations.js';++// The commit the running process was launched at. Captured once at boot (see+// captureBootCommit, called from server/index.js). null when not yet captured+// or when HEAD couldn't be read (tarball install / not a git repo).+let bootCommit = null;++// Workspaces `update.sh` installs (safe_install . client server autofixer).+// Order is cosmetic; '.' renders as 'root'.+const DEP_WORKSPACES = ['.', 'client', 'server', 'autofixer'];++// Directories never worth walking for client-source freshness.+const WALK_SKIP_DIRS = new Set(['node_modules', 'dist', '.git']);++/**+ * Capture the commit the process is running. Idempotent — only the first+ * successful read sticks, so a later on-disk `git pull` (which we WANT to+ * detect) can't overwrite the boot value. Call once from boot.+ */+export async function captureBootCommit({ rootDir = PATHS.root, getCommit = gitRevParseHead } = {}) {+ if (bootCommit) return bootCommit;+ const sha = await getCommit(rootDir).catch(() => null);+ if (sha) bootCommit = sha;+ return bootCommit;+}++/** Current boot commit (for inspection / tests). */+export function getBootCommit() {+ return bootCommit;+}++/** Test-only: override/reset the captured boot commit. */+export function __setBootCommitForTest(value) {+ bootCommit = value;+}++async function gitRevParseHead(rootDir) {+ const { stdout, exitCode } = await execGit(['rev-parse', 'HEAD'], rootDir, { ignoreExitCode: true });+ if (exitCode !== 0) return null;+ const sha = stdout.trim();+ return sha || null;+}++/**+ * Is `ancestor` an ancestor of `descendant`? Used to confirm the on-disk HEAD+ * is strictly AHEAD of the boot commit (a real pull-forward) rather than merely+ * different (e.g. the process booted on a feature branch and someone checked out+ * main) — which would otherwise produce a false "stale code" alarm in dev.+ */+async function gitIsAncestor(ancestor, descendant, rootDir) {+ const { exitCode } = await execGit(+ ['merge-base', '--is-ancestor', ancestor, descendant],+ rootDir,+ { ignoreExitCode: true }+ );+ return exitCode === 0;+}++/** mtime in ms for a path, or null when it doesn't exist / can't be stat'd. */+async function statMtimeMs(path) {+ const s = await stat(path).catch(() => null);+ return s ? s.mtimeMs : null;+}++/**+ * Walk client source looking for any file newer than `buildMtimeMs`,+ * short-circuiting on the first hit. Skips node_modules/dist/.git. Returns true+ * as soon as a newer source file is found, false if the build is current.+ */+async function isClientSourceNewer(rootDir, buildMtimeMs, { statMtime = statMtimeMs } = {}) {+ // Top-level client files that affect the build but live outside src/.+ const topLevel = ['client/index.html', 'client/package.json', 'client/vite.config.js'];+ for (const rel of topLevel) {+ const m = await statMtime(join(rootDir, rel));+ if (m != null && m > buildMtimeMs) return true;+ }++ const srcRoot = join(rootDir, 'client', 'src');+ const stack = [srcRoot];+ while (stack.length) {+ const dir = stack.pop();+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ if (entry.isDirectory()) {+ if (!WALK_SKIP_DIRS.has(entry.name)) stack.push(join(dir, entry.name));+ continue;+ }+ const m = await statMtime(join(dir, entry.name));+ if (m != null && m > buildMtimeMs) return true;+ }+ }+ return false;+}++/**+ * Classify each workspace's dependency freshness by comparing its manifest /+ * lockfile mtime against npm's install receipt (`node_modules/.package-lock.json`,+ * rewritten on every `npm install`). A workspace with no package.json is skipped+ * (not present in this install).+ */+async function detectStaleDeps(rootDir, { statMtime = statMtimeMs } = {}) {+ const workspaces = [];+ for (const ws of DEP_WORKSPACES) {+ const manifestMtime = await statMtime(join(rootDir, ws, 'package.json'));+ if (manifestMtime == null) continue; // workspace absent++ const receiptMtime = await statMtime(join(rootDir, ws, 'node_modules', '.package-lock.json'));+ const lockMtime = await statMtime(join(rootDir, ws, 'package-lock.json'));++ let stale = false;+ let reason = null;+ if (receiptMtime == null) {+ stale = true;+ reason = 'not-installed';+ } else if (manifestMtime > receiptMtime) {+ stale = true;+ reason = 'manifest-newer';+ } else if (lockMtime != null && lockMtime > receiptMtime) {+ stale = true;+ reason = 'lockfile-newer';+ }+ workspaces.push({ name: ws === '.' ? 'root' : ws, stale, reason });+ }+ return { stale: workspaces.some(w => w.stale), workspaces };+}++/**+ * Compute the full install-sync picture. Every external dependency is+ * injectable so the detection logic is unit-testable without touching real+ * git/fs. Returns a plain object safe to splice into /api/update/status.+ *+ * Best-effort by contract: callers wrap this in `.catch(() => null)` so a git+ * or fs hiccup never blocks the status response.+ */+export async function getInstallState({+ rootDir = PATHS.root,+ boot = bootCommit,+ getCurrentCommit = () => gitRevParseHead(rootDir),+ isAncestor = (a, b) => gitIsAncestor(a, b, rootDir),+ statMtime = statMtimeMs,+ clientSourceNewer = (buildMs) => isClientSourceNewer(rootDir, buildMs, { statMtime }),+ listPending = () => listPendingMigrations({ rootDir }),+} = {}) {+ const currentCommit = await getCurrentCommit().catch(() => null);++ // Running stale code only when the on-disk HEAD is strictly ahead of the+ // boot commit (boot is an ancestor of current). "Merely different" (branch+ // switch, rollback) is NOT flagged — it's not the half-updated state we warn+ // about, and flagging it would cry wolf on every dev branch checkout.+ let runningStaleCode = false;+ if (boot && currentCommit && boot !== currentCommit) {+ runningStaleCode = await isAncestor(boot, currentCommit).catch(() => false);+ }++ const staleDeps = await detectStaleDeps(rootDir, { statMtime });++ // Stale build: null (unknown) when there's no built bundle — that's dev mode+ // (`npm run dev` serves via Vite) or a never-built install, neither of which+ // should raise a false "rebuild needed" alarm.+ const buildMtime = await statMtime(join(rootDir, 'client', 'dist', 'index.html'));+ const staleBuild = buildMtime == null ? null : await clientSourceNewer(buildMtime).catch(() => null);++ const pendingFiles = await listPending().catch(() => []);+ const pendingMigrations = { count: pendingFiles.length, files: pendingFiles };++ const outOfSync =+ runningStaleCode ||+ staleDeps.stale ||+ staleBuild === true ||+ pendingMigrations.count > 0;++ return {+ bootCommit: boot || null,+ currentCommit: currentCommit || null,+ runningStaleCode,+ staleDeps,+ staleBuild,+ pendingMigrations,+ outOfSync+ };+}++// Exported for unit tests of the individual detectors.+export const __internal = { detectStaleDeps, isClientSourceNewer, gitRevParseHead, gitIsAncestor };diff --git a/server/services/installState.test.js b/server/services/installState.test.jsnew file mode 100644index 0000000000..3661bb4c65--- /dev/null+++ b/server/services/installState.test.js@@ -0,0 +1,233 @@+import { describe, it, expect, beforeEach } from 'vitest';+import {+ getInstallState,+ captureBootCommit,+ getBootCommit,+ __setBootCommitForTest,+ __internal+} from './installState.js';++// All external effects are injected, so these tests never touch real git/fs.++const ROOT = '/repo';++// Build a statMtime mock from a { pathSuffix: mtimeMs } map. A path not present+// in the map resolves to null (absent), mirroring the real helper.+function makeStat(map) {+ return async (path) => {+ for (const [suffix, mtime] of Object.entries(map)) {+ if (path.endsWith(suffix)) return mtime;+ }+ return null;+ };+}++// A fully in-sync baseline: every workspace installed (receipt newer than+// manifest), build current, no pending migrations, same commit.+function syncedOpts(overrides = {}) {+ return {+ rootDir: ROOT,+ boot: 'abc',+ getCurrentCommit: async () => 'abc',+ isAncestor: async () => false,+ statMtime: makeStat({+ 'package.json': 100,+ '.package-lock.json': 200,+ 'client/dist/index.html': 500+ }),+ clientSourceNewer: async () => false,+ listPending: async () => [],+ ...overrides+ };+}++describe('getInstallState — running stale code', () => {+ it('flags stale code when on-disk HEAD is strictly ahead of the boot commit', async () => {+ const state = await getInstallState(syncedOpts({+ boot: 'old',+ getCurrentCommit: async () => 'new',+ isAncestor: async () => true // boot is an ancestor of current → ahead+ }));+ expect(state.runningStaleCode).toBe(true);+ expect(state.outOfSync).toBe(true);+ expect(state.bootCommit).toBe('old');+ expect(state.currentCommit).toBe('new');+ });++ it('does NOT flag when commits differ but boot is not an ancestor (branch switch / rollback)', async () => {+ const state = await getInstallState(syncedOpts({+ boot: 'branchA',+ getCurrentCommit: async () => 'branchB',+ isAncestor: async () => false+ }));+ expect(state.runningStaleCode).toBe(false);+ expect(state.outOfSync).toBe(false);+ });++ it('does NOT flag when boot and current commit are identical', async () => {+ const state = await getInstallState(syncedOpts());+ expect(state.runningStaleCode).toBe(false);+ });++ it('does NOT flag when there is no boot commit (tarball / non-git install)', async () => {+ const state = await getInstallState(syncedOpts({ boot: null, isAncestor: async () => true }));+ expect(state.runningStaleCode).toBe(false);+ });+});++describe('getInstallState — stale deps', () => {+ it('flags a workspace whose manifest is newer than the npm install receipt', async () => {+ const state = await getInstallState(syncedOpts({+ statMtime: makeStat({+ 'package.json': 300, // manifest newer than receipt+ '.package-lock.json': 200,+ 'client/dist/index.html': 500+ })+ }));+ expect(state.staleDeps.stale).toBe(true);+ expect(state.staleDeps.workspaces.some(w => w.stale && w.reason === 'manifest-newer')).toBe(true);+ expect(state.outOfSync).toBe(true);+ });++ it('flags a workspace with no install receipt as not-installed', async () => {+ const state = await getInstallState(syncedOpts({+ statMtime: makeStat({+ 'package.json': 100,+ 'client/dist/index.html': 500+ // no .package-lock.json → receipt missing+ })+ }));+ expect(state.staleDeps.stale).toBe(true);+ expect(state.staleDeps.workspaces.every(w => w.reason === 'not-installed')).toBe(true);+ });++ it('flags a workspace whose lockfile is newer than the receipt', async () => {+ const state = await getInstallState(syncedOpts({+ statMtime: makeStat({+ 'package.json': 100,+ '.package-lock.json': 200,+ 'package-lock.json': 300, // lockfile newer than receipt+ 'client/dist/index.html': 500+ })+ }));+ expect(state.staleDeps.stale).toBe(true);+ expect(state.staleDeps.workspaces.some(w => w.reason === 'lockfile-newer')).toBe(true);+ });++ it('skips workspaces with no package.json (absent in this install)', async () => {+ const state = await getInstallState(syncedOpts({+ statMtime: makeStat({+ // Only the root manifest exists; others absent → skipped+ '/repo/package.json': 100,+ '/repo/node_modules/.package-lock.json': 200,+ 'client/dist/index.html': 500+ })+ }));+ expect(state.staleDeps.workspaces.map(w => w.name)).toEqual(['root']);+ expect(state.staleDeps.stale).toBe(false);+ });++ it('reports in-sync when every receipt is newer than its manifest', async () => {+ const state = await getInstallState(syncedOpts());+ expect(state.staleDeps.stale).toBe(false);+ });+});++describe('getInstallState — stale build', () => {+ it('flags when client source is newer than the built bundle', async () => {+ const state = await getInstallState(syncedOpts({ clientSourceNewer: async () => true }));+ expect(state.staleBuild).toBe(true);+ expect(state.outOfSync).toBe(true);+ });++ it('is null (unknown) when there is no built bundle — dev / never built', async () => {+ const state = await getInstallState(syncedOpts({+ statMtime: makeStat({ 'package.json': 100, '.package-lock.json': 200 }) // no dist/index.html+ }));+ expect(state.staleBuild).toBeNull();+ // null build must NOT count toward outOfSync+ expect(state.outOfSync).toBe(false);+ });++ it('is false when the build is current', async () => {+ const state = await getInstallState(syncedOpts());+ expect(state.staleBuild).toBe(false);+ });+});++describe('getInstallState — pending migrations', () => {+ it('surfaces pending migration files and count', async () => {+ const state = await getInstallState(syncedOpts({+ listPending: async () => ['099-foo.js', '100-bar.js']+ }));+ expect(state.pendingMigrations.count).toBe(2);+ expect(state.pendingMigrations.files).toEqual(['099-foo.js', '100-bar.js']);+ expect(state.outOfSync).toBe(true);+ });++ it('reports zero pending when the applied-list is current', async () => {+ const state = await getInstallState(syncedOpts());+ expect(state.pendingMigrations.count).toBe(0);+ expect(state.outOfSync).toBe(false);+ });+});++describe('getInstallState — resilience', () => {+ it('treats a thrown ancestry check as not-ahead', async () => {+ const state = await getInstallState(syncedOpts({+ boot: 'old',+ getCurrentCommit: async () => 'new',+ isAncestor: async () => { throw new Error('git boom'); }+ }));+ expect(state.runningStaleCode).toBe(false);+ });++ it('treats a thrown migration listing as zero pending', async () => {+ const state = await getInstallState(syncedOpts({+ listPending: async () => { throw new Error('fs boom'); }+ }));+ expect(state.pendingMigrations.count).toBe(0);+ });+});++describe('captureBootCommit', () => {+ beforeEach(() => __setBootCommitForTest(null));++ it('captures the HEAD commit once and is idempotent', async () => {+ let calls = 0;+ const getCommit = async () => { calls++; return calls === 1 ? 'first' : 'second'; };+ expect(await captureBootCommit({ getCommit })).toBe('first');+ // A later on-disk pull must not overwrite the captured boot commit.+ expect(await captureBootCommit({ getCommit })).toBe('first');+ expect(getBootCommit()).toBe('first');+ expect(calls).toBe(1);+ });++ it('leaves boot commit null when HEAD cannot be read', async () => {+ const getCommit = async () => null;+ expect(await captureBootCommit({ getCommit })).toBeNull();+ expect(getBootCommit()).toBeNull();+ });+});++describe('detectStaleDeps (direct)', () => {+ it('classifies each workspace independently', async () => {+ const statMtime = makeStat({+ '/repo/package.json': 100,+ '/repo/node_modules/.package-lock.json': 200, // root: fresh+ '/repo/client/package.json': 300,+ '/repo/client/node_modules/.package-lock.json': 200, // client: manifest-newer+ '/repo/server/package.json': 100,+ '/repo/server/node_modules/.package-lock.json': 200, // server: fresh+ '/repo/autofixer/package.json': 100+ // autofixer: no receipt → not-installed+ });+ const result = await __internal.detectStaleDeps(ROOT, { statMtime });+ const byName = Object.fromEntries(result.workspaces.map(w => [w.name, w]));+ expect(byName.root.stale).toBe(false);+ expect(byName.client.reason).toBe('manifest-newer');+ expect(byName.server.stale).toBe(false);+ expect(byName.autofixer.reason).toBe('not-installed');+ expect(result.stale).toBe(true);+ });+});diff --git a/server/services/updateChecker.js b/server/services/updateChecker.jsindex 974d898d5d..7b397caac3 100644--- a/server/services/updateChecker.js+++ b/server/services/updateChecker.js@@ -5,6 +5,7 @@ import { 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 { getInstallState } from './installState.js';import { execGh } from './github.js';// Re-exported for back-compat: callers/tests historically import compareSemver@@ -240,6 +241,11 @@ export async function getUpdateStatus() {(Date.now() - new Date(lastSync.syncedAt).getTime()) < FORK_SYNC_FRESHNESS_MS);+ // Install-sync state — "is the checked-out code ahead of what's running /+ // installed?" (issue #1779). Best-effort: a git/fs hiccup here must never+ // block the status response, so failures collapse to null.+ const installState = await getInstallState().catch(() => null);+return {currentVersion,...state,@@ -247,7 +253,8 @@ export async function getUpdateStatus() {remoteInfo,upstream: { owner: UPSTREAM_OWNER, repo: UPSTREAM_REPO, fullName: UPSTREAM_FULL_NAME },forkSyncFresh,- forkSyncWindowMs: FORK_SYNC_FRESHNESS_MS+ forkSyncWindowMs: FORK_SYNC_FRESHNESS_MS,+ installState};}diff --git a/server/services/updateChecker.test.js b/server/services/updateChecker.test.jsindex bc72494d35..e6156248d9 100644--- a/server/services/updateChecker.test.js+++ b/server/services/updateChecker.test.js@@ -27,6 +27,12 @@ vi.mock('../lib/gitRemote.js', () => ({UPSTREAM_FULL_NAME: 'atomantic/PortOS'}));+// Keep getUpdateStatus unit tests hermetic — install-sync detection has its own+// suite (installState.test.js); here it must not spawn real git/fs.+vi.mock('./installState.js', () => ({+ getInstallState: vi.fn().mockResolvedValue(null)+}));+import { readJSONFile, ensureDir, atomicWrite } from '../lib/fileUtils.js';import { execGh } from './github.js';import { getOriginInfo } from '../lib/gitRemote.js';