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: stamp the running build's git commit so a stale server or stale dist is detectable (#4694)
[._.]/ Adam Eivyca98f929e590
diff --git a/client/biome.jsonc b/client/biome.jsoncindex 24772d5cf8..3b90ca78dd 100644--- a/client/biome.jsonc+++ b/client/biome.jsonc@@ -18,11 +18,13 @@// __dirname/__filename/require/module/exports are deliberately absent — they// are not valid in the ESM browser bundles this client ships.//- // `__APP_VERSION__` is a Vite build-time define (see vite.config.js). ESLint- // picked it up from a `/* global __APP_VERSION__ */` comment in Layout.jsx;- // Biome does not honour those comments, so it is declared here instead.+ // `__APP_VERSION__` and `__BUILD_STAMP__` are Vite build-time defines (see+ // vite.config.js). ESLint picked `__APP_VERSION__` up from a+ // `/* global __APP_VERSION__ */` comment in Layout.jsx; Biome does not honour+ // those comments, so both are declared here instead."globals": ["__APP_VERSION__",+ "__BUILD_STAMP__","AbortController", "AbortSignal", "ArrayBuffer", "Audio", "AudioContext","AudioWorkletNode", "Blob", "BroadcastChannel", "Buffer", "CSS", "CustomEvent","DOMException", "DOMParser", "DataView", "DecompressionStream", "Element", "Event",diff --git a/client/src/components/system-resources/BuildStampPanel.jsx b/client/src/components/system-resources/BuildStampPanel.jsxnew file mode 100644index 0000000000..354cf922ee--- /dev/null+++ b/client/src/components/system-resources/BuildStampPanel.jsx@@ -0,0 +1,97 @@+import { AlertTriangle, GitCommitHorizontal } from 'lucide-react';+import Pill from '../ui/Pill';+import Banner from '../ui/Banner';+import { compareBuildStamps, describeBuild } from '../../lib/buildStamp.js';+import { timeAgo } from '../../utils/formatters';++// `__BUILD_STAMP__` is a Vite build-time define (see client/vite.config.js).+// It is genuinely absent under vitest and under any non-bundled consumer, so it+// is read through `typeof` rather than referenced bare — a bare reference throws+// a ReferenceError instead of degrading to the 'unknown' state.+function readBundleStamp() {+ return typeof __BUILD_STAMP__ === 'undefined' ? null : __BUILD_STAMP__;+}++/**+ * Which code is actually running — the git commit of the server process, and of+ * the bundle this browser loaded (#4694).+ *+ * `version` cannot answer this: by project rule package.json's version reflects+ * the last release and is identical across every development commit and every+ * worktree, so a server restarted from a stale checkout looks exactly like a+ * current one. The mismatch banner is the point of the panel — it turns "my+ * change isn't showing up" from a debugging session into a visible fact.+ */+export default function BuildStampPanel({ build }) {+ const bundle = readBundleStamp();+ const { state, bundleCommit, serverCommit } = compareBuildStamps(bundle, build);++ const serverLabel = describeBuild({+ commit: build?.shortCommit || build?.commit,+ branch: build?.branch,+ dirty: build?.dirty+ });+ const bundleLabel = describeBuild({ commit: bundle?.commit, branch: bundle?.branch });++ // Nothing to say at all — a tarball install with no git on either side. Render+ // the panel anyway rather than hiding it, so "we could not tell" is visible+ // instead of looking like the feature is missing.+ return (+ <section className="rounded-xl border border-port-border bg-port-card p-4">+ <h3 className="mb-3 flex items-center gap-2 text-sm font-semibold text-white">+ <GitCommitHorizontal size={16} />+ Running build+ </h3>++ {state === 'mismatch' && (+ <Banner tone="warning" size="md" icon={AlertTriangle} align="start" className="mb-3">+ <div>+ This page was built from <span className="font-mono">{bundleCommit}</span> but the API is+ running <span className="font-mono">{serverCommit}</span>. The UI is stale relative to the+ server it is calling — rebuild the client (<span className="font-mono">npm run build</span>)+ or restart the server from the checkout you are editing.+ </div>+ </Banner>+ )}++ <dl className="space-y-2 text-sm">+ <StampRow+ label="Server"+ value={serverLabel}+ hint={build?.builtAt ? `started ${timeAgo(build.builtAt)}` : null}+ />+ <StampRow+ label="This page"+ value={bundleLabel}+ hint={bundle?.builtAt ? `built ${timeAgo(bundle.builtAt)}` : null}+ />+ </dl>++ {state === 'match' && (+ <p className="mt-3 text-xs text-gray-500">+ Bundle and server agree — what you are looking at is the code that is running.+ </p>+ )}+ {state === 'unknown' && (+ <p className="mt-3 text-xs text-gray-500">+ Commit unknown on at least one side (no git metadata), so bundle/server drift cannot be+ checked here.+ </p>+ )}+ </section>+ );+}++function StampRow({ label, value, hint }) {+ return (+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <dt className="w-24 shrink-0 text-xs uppercase tracking-wide text-gray-500">{label}</dt>+ <dd className="flex flex-wrap items-center gap-2">+ {value+ ? <span className="font-mono text-xs text-gray-200">{value}</span>+ : <Pill tone="note" size="xs" bordered={false}>unknown</Pill>}+ {hint && <span className="text-[10px] text-gray-600">{hint}</span>}+ </dd>+ </div>+ );+}diff --git a/client/src/components/system-resources/BuildStampPanel.test.jsx b/client/src/components/system-resources/BuildStampPanel.test.jsxnew file mode 100644index 0000000000..8549f47a70--- /dev/null+++ b/client/src/components/system-resources/BuildStampPanel.test.jsx@@ -0,0 +1,74 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { render, screen } from '@testing-library/react';+import BuildStampPanel from './BuildStampPanel.jsx';++const serverBuild = (overrides = {}) => ({+ commit: 'abc1234567890abcdef1234567890abcdef12345',+ shortCommit: 'abc1234',+ branch: 'main',+ dirty: false,+ builtAt: new Date().toISOString(),+ ...overrides,+});++afterEach(() => {+ vi.unstubAllGlobals();+});++describe('BuildStampPanel', () => {+ it('renders the server commit and branch', () => {+ render(<BuildStampPanel build={serverBuild()} />);++ expect(screen.getByText('abc1234 · main')).toBeInTheDocument();+ });++ it('flags a stale bundle when the page and the API were built from different commits', () => {+ vi.stubGlobal('__BUILD_STAMP__', { commit: 'def5678', branch: 'main', builtAt: new Date().toISOString() });++ render(<BuildStampPanel build={serverBuild()} />);++ expect(screen.getByText(/stale relative to the server/i)).toBeInTheDocument();+ expect(screen.getByText('def5678')).toBeInTheDocument();+ expect(screen.getByText('abc1234')).toBeInTheDocument();+ });++ it('confirms agreement when the bundle and the server share a commit', () => {+ vi.stubGlobal('__BUILD_STAMP__', { commit: 'abc1234', branch: 'main', builtAt: new Date().toISOString() });++ render(<BuildStampPanel build={serverBuild()} />);++ expect(screen.getByText(/bundle and server agree/i)).toBeInTheDocument();+ expect(screen.queryByText(/stale relative to the server/i)).not.toBeInTheDocument();+ });++ it('never claims agreement when the bundle stamp is unavailable', () => {+ // `__BUILD_STAMP__` is a Vite define — genuinely absent here, which is the+ // same shape a source-tarball build produces. Reading it must not throw a+ // ReferenceError, and must not report a match nobody verified.+ render(<BuildStampPanel build={serverBuild()} />);++ expect(screen.getByText(/commit unknown on at least one side/i)).toBeInTheDocument();+ expect(screen.queryByText(/bundle and server agree/i)).not.toBeInTheDocument();+ expect(screen.queryByText(/stale relative to the server/i)).not.toBeInTheDocument();+ });++ it('renders "unknown" rather than blank rows when the server has no git metadata', () => {+ render(<BuildStampPanel build={{ commit: null, shortCommit: null, branch: null, dirty: null }} />);++ expect(screen.getAllByText('unknown').length).toBeGreaterThan(0);+ });++ it('surfaces an uncommitted-changes server tree', () => {+ render(<BuildStampPanel build={serverBuild({ dirty: true })} />);++ expect(screen.getByText(/uncommitted changes/)).toBeInTheDocument();+ });++ it('survives a missing build block entirely (older server, no build field)', () => {+ // A newer client can talk to an older server whose /health/details predates+ // this field — the panel must degrade, not crash the whole overview.+ render(<BuildStampPanel build={undefined} />);++ expect(screen.getByText('Running build')).toBeInTheDocument();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 64bec19d68..69421643a8 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -97,6 +97,7 @@ grep -i "what you want to do" client/src/lib/README.md| `bareUrl.js` | `parseBareUrl(text)` — the normalized URL when a capture's entire text is a URL, else null. Client mirror of the authoritative `server/lib/bareUrl.js` (parity enforced by `server/lib/bareUrl.mirror.test.js`), so the brain capture boxes preview the exact filing decision the server will make. Use this — not the looser `utils/urlNormalize.js` `isUrl` — anywhere the answer must match the server. || `youtubeUrl.js` | `isYoutubeVideoUrl(text)` / `youtubeVideoId(url)` — single-video YouTube URL detection. Client mirror of `YOUTUBE_INGEST_URL_RE` in `server/services/youtubeIngest.js` (behavioral parity pinned by `server/lib/youtubeUrl.mirror.test.js`); deliberately excludes playlists and channels. Quick Capture uses it to swap to the ingest submit path and reveal the ingest options panel. Also `INGEST_OPTIONS` — the single table of the three ingest artifacts (`key` / `settingKey` / `fallback` / `label` / `hint`) — plus `defaultIngestOptions()` and `ingestOptionsFromSettings(settings)`. Everything that enumerates the switches derives from that table; add an artifact there, not at each call site. || `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. |+| `buildStamp.js` | `compareBuildStamps(bundle, server)` / `describeBuild({commit, branch, dirty})` — does the bundle this browser loaded come from the same git commit the API is running (#4694)? Returns `match` / `mismatch` / `unknown`, where absent-or-`unknown` on either side is always `unknown` (never a claimed match, never a false alarm). Answers the rebuild-and-restart drift the socket build-id check cannot see, since that compares bundle hashes rather than commits. Rendered by `components/system-resources/BuildStampPanel.jsx`. || `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup, dropping browser-extension errors (see `extensionErrors.js`) before either gate. Wired from `main.jsx`; never call directly from React components. || `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. || `quotaBurnPatch.js` | `mergeQuotaBurnPatch(base, patch)` — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's `jobs` array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. `applyQuotaBurnPreset(job, preset)` / `jobFromPreset(preset, { id, appId })` — copy a catalog prompt preset into a job, preserving the user's own step name and app choice. `quotaBurnJobIsSpent(job, ranAt)` — whether a `run once` step has had its one dispatch, gated on the optimistic config's own `runOnce` so a just-ticked checkbox reads as spent before the save round-trips (the client mirror of the server's `jobIsSpent`). `UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap(cap)` / `dispatchCapInput(value)` — the -1 "no dispatch cap" sentinel (the default), mirrored from the server. |diff --git a/client/src/lib/buildStamp.js b/client/src/lib/buildStamp.jsnew file mode 100644index 0000000000..e3bb2ed580--- /dev/null+++ b/client/src/lib/buildStamp.js@@ -0,0 +1,78 @@+/**+ * Pure comparison between the BUNDLE this browser loaded and the SERVER build it+ * is talking to (#4694).+ *+ * The failure this catches: the dashboard is served from a `client/dist` built+ * from one commit while `portos-server` was restarted from a different checkout+ * at a different commit. Both halves look perfectly healthy, so a UI change that+ * "isn't working" can be a UI that was never rebuilt — an entire debugging+ * session spent judging code that was not running.+ *+ * Distinct from the socket's build-id check (`server/lib/buildId.js`), which+ * compares the browser's loaded bundle against the bundle on disk RIGHT NOW.+ * That answers "should I reload?"; this answers "was this bundle built from the+ * same commit the API is running?" — a rebuild-and-restart mismatch the id hash+ * cannot see, because both sides agree on a `dist/` that is simply old.+ */++// `__BUILD_STAMP__` is a Vite define, so it is absent under vitest and in any+// consumer that renders these helpers without the bundler. Every unknown input+// resolves to `state: 'unknown'` — never to `'match'` (which would claim a+// verification we did not perform) and never to `'mismatch'` (which would cry+// wolf on every dev run).+const UNKNOWN = 'unknown';++function normalizeCommit(value) {+ if (typeof value !== 'string') return null;+ const trimmed = value.trim().toLowerCase();+ // '' and the literal 'unknown' placeholder both mean "not known". Collapsing+ // them to null keeps absent from ever comparing equal-or-unequal to a real+ // commit (root CLAUDE.md's absent-vs-empty rule).+ if (trimmed === '' || trimmed === UNKNOWN) return null;+ return trimmed;+}++/**+ * Compare a bundle stamp against the server's build identity.+ *+ * @param {{commit?: string, branch?: string, builtAt?: string}|null|undefined} bundle+ * The `__BUILD_STAMP__` define, or null/undefined when unavailable.+ * @param {{commit?: string|null, shortCommit?: string|null, branch?: string|null, dirty?: boolean|null}|null|undefined} server+ * The `build` block from GET /api/system/health/details.+ * @returns {{state: 'match'|'mismatch'|'unknown', bundleCommit: string|null, serverCommit: string|null}}+ * `bundleCommit` / `serverCommit` are the SHORT forms, for display.+ */+export function compareBuildStamps(bundle, server) {+ const bundleCommit = normalizeCommit(bundle?.commit);+ // The server sends both forms; the bundle only ever has the short one, so the+ // comparison is done on a common prefix rather than on full-vs-short (which+ // would never be equal).+ const serverCommit = normalizeCommit(server?.shortCommit) ?? normalizeCommit(server?.commit);++ if (!bundleCommit || !serverCommit) {+ return { state: UNKNOWN, bundleCommit, serverCommit };+ }++ const width = Math.min(bundleCommit.length, serverCommit.length);+ const same = bundleCommit.slice(0, width) === serverCommit.slice(0, width);+ return { state: same ? 'match' : 'mismatch', bundleCommit, serverCommit };+}++/**+ * One-line human summary of a build identity — `abc1234 · main · dirty`.+ * Returns null when there is nothing worth rendering, so a caller can drop the+ * row entirely instead of printing a line of em-dashes.+ */+export function describeBuild({ commit, branch, dirty } = {}) {+ const shortCommit = normalizeCommit(commit);+ const parts = [];+ if (shortCommit) parts.push(shortCommit.slice(0, 7));+ const cleanBranch = typeof branch === 'string' && branch.trim() && branch.trim().toLowerCase() !== UNKNOWN+ ? branch.trim()+ : null;+ if (cleanBranch) parts.push(cleanBranch);+ // Only `true` earns a badge: `null` means the check itself did not run, and+ // rendering that as "clean" would be a claim we cannot make.+ if (dirty === true) parts.push('uncommitted changes');+ return parts.length > 0 ? parts.join(' · ') : null;+}diff --git a/client/src/lib/buildStamp.test.js b/client/src/lib/buildStamp.test.jsnew file mode 100644index 0000000000..b4912cc934--- /dev/null+++ b/client/src/lib/buildStamp.test.js@@ -0,0 +1,80 @@+import { describe, it, expect } from 'vitest';+import { compareBuildStamps, describeBuild } from './buildStamp.js';++describe('compareBuildStamps', () => {+ it('matches a bundle short commit against the server short commit', () => {+ const result = compareBuildStamps({ commit: 'abc1234' }, { shortCommit: 'abc1234', commit: 'abc1234def' });+ expect(result.state).toBe('match');+ expect(result.bundleCommit).toBe('abc1234');+ expect(result.serverCommit).toBe('abc1234');+ });++ it('matches a short bundle commit against a full server commit on the common prefix', () => {+ // The server may send only the full sha; comparing full-vs-short verbatim+ // would report a permanent false mismatch.+ const result = compareBuildStamps(+ { commit: 'abc1234' },+ { shortCommit: null, commit: 'abc1234567890abcdef1234567890abcdef1234' }+ );+ expect(result.state).toBe('match');+ });++ it('flags a genuine mismatch — the stale-bundle case this exists for', () => {+ expect(compareBuildStamps({ commit: 'abc1234' }, { shortCommit: 'def5678' }).state).toBe('mismatch');+ });++ it('is case-insensitive and tolerates surrounding whitespace', () => {+ expect(compareBuildStamps({ commit: ' ABC1234 ' }, { shortCommit: 'abc1234' }).state).toBe('match');+ });++ it('reports unknown — never match — when either side is missing', () => {+ // Claiming 'match' here would assert a verification that never happened.+ for (const [bundle, server] of [+ [null, { shortCommit: 'abc1234' }],+ [{ commit: 'abc1234' }, null],+ [undefined, undefined],+ [{ commit: 'abc1234' }, { shortCommit: null, commit: null }],+ ]) {+ expect(compareBuildStamps(bundle, server).state).toBe('unknown');+ }+ });++ it('treats the empty string and the literal "unknown" placeholder as absent, not as a commit', () => {+ // A source-tarball build stamps 'unknown'; an empty string would otherwise+ // compare unequal to every real commit and cry wolf on every page load.+ expect(compareBuildStamps({ commit: '' }, { shortCommit: 'abc1234' }).state).toBe('unknown');+ expect(compareBuildStamps({ commit: 'unknown' }, { shortCommit: 'abc1234' }).state).toBe('unknown');+ expect(compareBuildStamps({ commit: 'abc1234' }, { shortCommit: 'unknown' }).state).toBe('unknown');+ expect(compareBuildStamps({ commit: 'unknown' }, { shortCommit: 'abc1234' }).bundleCommit).toBeNull();+ });++ it('ignores a non-string commit rather than coercing it', () => {+ expect(compareBuildStamps({ commit: 12345 }, { shortCommit: 'abc1234' }).state).toBe('unknown');+ });+});++describe('describeBuild', () => {+ it('renders commit, branch, and an uncommitted-changes badge', () => {+ expect(describeBuild({ commit: 'abc1234def', branch: 'main', dirty: true }))+ .toBe('abc1234 · main · uncommitted changes');+ expect(describeBuild({ commit: 'abc1234', branch: 'main', dirty: false }))+ .toBe('abc1234 · main');+ });++ it('omits a dirty badge when the check did not run', () => {+ // `null` is "we could not tell" — not "clean", and not "dirty".+ expect(describeBuild({ commit: 'abc1234', branch: 'main', dirty: null }))+ .toBe('abc1234 · main');+ });++ it('drops unknown/blank parts instead of printing placeholder text', () => {+ expect(describeBuild({ commit: 'abc1234', branch: 'unknown' })).toBe('abc1234');+ expect(describeBuild({ commit: 'abc1234', branch: ' ' })).toBe('abc1234');+ });++ it('returns null when there is nothing worth rendering', () => {+ expect(describeBuild({})).toBeNull();+ expect(describeBuild()).toBeNull();+ expect(describeBuild({ commit: 'unknown', branch: 'unknown', dirty: null })).toBeNull();+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex b5f1f83494..a683baef7f 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -70,6 +70,7 @@ export * from './applyManuscriptEdits.js';export * from './audioRecorder.js';export * from './bareUrl.js';export * from './boundedMap.js';+export * from './buildStamp.js';export * from './clientErrorReporter.js';export * from './clinicianReport.js';export * from './clipboard.js';diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsxindex 2cae5226bb..49895ebbe0 100644--- a/client/src/pages/SystemHealthPage.jsx+++ b/client/src/pages/SystemHealthPage.jsx@@ -10,6 +10,7 @@ import { useSystemResourceReport } from '../hooks/useSystemResourceReport.js';import StoragePanel from '../components/system-resources/StoragePanel.jsx';import QueuesPanel from '../components/system-resources/QueuesPanel.jsx';import MediaCapacityPanel from '../components/system-resources/MediaCapacityPanel.jsx';+import BuildStampPanel from '../components/system-resources/BuildStampPanel.jsx';const HEALTH_STYLE = {healthy: { color: 'text-port-success', bg: 'bg-port-success/10', icon: CheckCircle, label: 'Healthy' },@@ -273,6 +274,8 @@ function SystemHealthOverview() {<MediaCapacityPanel media={health.media} />+ <BuildStampPanel build={health.build} />+<section className="bg-port-card border border-port-border rounded-xl p-4"><h3 className="text-sm font-semibold text-white mb-3 flex items-center gap-2"><Activity size={16} />diff --git a/client/vite.config.js b/client/vite.config.jsindex 71e2ca300a..f66213c684 100644--- a/client/vite.config.js+++ b/client/vite.config.js@@ -2,6 +2,7 @@ import { defineConfig, loadEnv } from 'vite';import react from '@vitejs/plugin-react';import { visualizer } from 'rollup-plugin-visualizer';import { readFileSync, existsSync } from 'fs';+import { execFileSync } from 'child_process';import { resolve } from 'path';const ANALYZE_BUNDLE = process.env.ANALYZE === 'true';@@ -9,6 +10,44 @@ const CONFIG_DIR = import.meta.dirname;const rootPkg = JSON.parse(readFileSync(resolve(CONFIG_DIR, '../package.json'), 'utf-8'));+// Which commit this BUNDLE was built from (#4694). package.json's version cannot+// answer that — by project rule it reflects the last RELEASE and is identical+// across every development commit — so a dist/ built three days ago looks exactly+// like one built this minute. The client compares this against the server's+// /api/system/health/details `build.commit` and flags a mismatch, which is the+// "I spent an hour debugging a UI that was not talking to the code I edited"+// failure mode.+//+// Fail-soft: a source-tarball build has no .git and must still build, so every+// probe degrades to 'unknown' rather than throwing.+function gitStamp(args) {+ const out = execFileSync('git', args, {+ cwd: CONFIG_DIR,+ encoding: 'utf-8',+ stdio: ['ignore', 'pipe', 'ignore'],+ timeout: 5000+ });+ return out.trim() || 'unknown';+}++function buildStamp() {+ // 'unknown' rather than '' or null: this value is inlined into the bundle as a+ // literal, and an empty string would compare unequal to every real commit and+ // report a permanent false "stale bundle" (root CLAUDE.md's absent-vs-empty rule).+ let commit = 'unknown';+ let branch = 'unknown';+ try {+ commit = gitStamp(['rev-parse', '--short=7', 'HEAD']);+ const head = gitStamp(['rev-parse', '--abbrev-ref', 'HEAD']);+ branch = head === 'HEAD' ? 'unknown' : head;+ } catch {+ // No git, no repo, or a timeout — keep the 'unknown' defaults.+ }+ // Commit / branch / timestamp only. No paths (they embed the OS username), no+ // hostname — this string ships to every browser that loads the app.+ return { commit, branch, builtAt: new Date().toISOString() };+}+// Dev proxy target: probe for the self-signed/LE cert under data/certs/. If the// server is running HTTPS, the dev proxy must target HTTPS too (or requests// through Vite return "socket hang up"). `secure: false` accepts the cert@@ -23,7 +62,8 @@ export default defineConfig(({ mode }) => {return {define: {- __APP_VERSION__: JSON.stringify(rootPkg.version)+ __APP_VERSION__: JSON.stringify(rootPkg.version),+ __BUILD_STAMP__: JSON.stringify(buildStamp())},plugins: [react(),diff --git a/server/index.js b/server/index.jsindex 5ee0e9034a..cf0321beb2 100644--- a/server/index.js+++ b/server/index.js@@ -8,6 +8,7 @@ import { existsSync } from 'fs';import { createTailscaleServers } from '../lib/tailscale-https.js';import { certPaths } from '../lib/certPaths.js';import { getBuildId, getStampedIndexHtml } from './lib/buildId.js';+import { getBuildIdentity, formatBuildIdentity } from './lib/buildIdentity.js';import { PORTS } from './lib/ports.js';import alertsRoutes from './routes/alerts.js';@@ -442,6 +443,16 @@ app.use((req, res) => {// Error middleware (must be last)app.use(errorMiddleware);+// Which code is up. One PM2-managed portos-server serves :5555 for the whole+// machine while any number of worktrees hold different code, so `pm2 logs+// portos-server` should be able to answer "which commit is this?" without a+// request (#4694). Fire-and-forget: this is outside the request lifecycle, so+// it carries its own catch — an unhandled rejection here would take the process+// down over a diagnostic log line.+getBuildIdentity()+ .then((identity) => console.log(`🧬 Running build ${formatBuildIdentity(identity)}`))+ .catch((err) => console.error(`❌ Build identity probe failed: ${err.message}`));+// Post-route boot: background service inits + schedulers, then the ordered// instance/sync/media-queue/DB chain that ends in httpServer.listen(). Not// awaited — boot proceeds in the background and any fatal step exits thediff --git a/server/lib/README.md b/server/lib/README.mdindex c6918d62c4..577e5940ae 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -363,6 +363,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `tribeMatch.js` | Pure, deterministic matcher mapping a calendar attendee / message counterpart (`{ email, phone, name }`) to a tracked Tribe person for auto-logged touchpoints (#2033, #2151): `buildPersonMatchIndex(people)` → `{ byIdentifier, byPhone, byName }`, `matchPerson(identity, index)` (email/handle authoritative, then E.164 phone, then exact unique name fallback — no fuzzy matching), `matchPeople(identities, index)` → de-duplicated Set of personIds, `normalizeIdentifier(value)`, `normalizePhone(value)` (E.164 normalization for iMessage/Signal handles), `identityFromHandle(handle)` (classify a raw `chat.db` handle into email-or-phone). Consumed by `autoLogTouchpoints` in `services/tribe.js` from the calendar, message, and iMessage sync producers. || `viteAllowedHosts.js` | Detect and remediate a managed app's Vite `server.allowedHosts`. `findViteConfig(repoPath)` locates the config; `parseAllowedHosts(src)` / `hostIsAllowed(parsed, host)` decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); `rewriteAllowedHosts(src)` deterministically injects `allowedHosts: true` (or bails `ok:false` on ambiguous shapes so the caller can fall back to an LLM fix); `checkViteHost(repoPath, host)` is the one-shot status used by `GET /api/apps/:id/vite-host-check`. || `buildId.js` | Build-ID derived from the built client bundle. |+| `buildIdentity.js` | `getBuildIdentity()` / `formatBuildIdentity()` — which git commit the RUNNING server process was started from (#4694): `{ commit, shortCommit, branch, dirty, builtAt }`, cached once per process. Answers "is this the code I am testing?" on a machine where one PM2 server serves :5555 while many worktrees hold different code — `version` cannot, since package.json's version is identical across every development commit. Complements `buildId.js` (which compares the served BUNDLE hash, not the commit either side was built from). Non-throwing, every field independently nullable (no `.git` → `commit: null`, never `''`). Commit/branch/dirty/timestamp only — no paths, hostname, or username. |## General utilitiesdiff --git a/server/lib/buildIdentity.js b/server/lib/buildIdentity.jsnew file mode 100644index 0000000000..3aa6643b63--- /dev/null+++ b/server/lib/buildIdentity.js@@ -0,0 +1,125 @@+/**+ * Build identity of the RUNNING install — which git commit this process was+ * started from (#4694).+ *+ * The hazard this closes: one PM2-managed `portos-server` serves :5555 for the+ * whole machine while any number of worktrees (CoS agents, `/do:next` claims,+ * the primary checkout) hold different code. Anyone verifying a change by+ * hitting the running instance is, by default, observing whatever build PM2+ * last started, from whatever checkout, at whatever commit — and nothing in the+ * responses said so. `version` can't answer it: by project rule package.json's+ * version reflects the last RELEASE and is identical across every development+ * commit and every worktree.+ *+ * Distinct from `buildId.js`, which hashes `client/dist/index.html` to detect a+ * browser holding a stale BUNDLE relative to what is on disk right now. That+ * hash says nothing about which commit either side was built from: a `dist/`+ * built three days ago and one built this minute are both "current" to buildId+ * as long as the browser matches the file. This module answers the other half —+ * WHICH CODE is up — and the two are complementary, not redundant.+ *+ * Privacy: commit / branch / dirty / timestamp only. No absolute paths (they+ * embed the OS username), no hostname, no checkout directory — see the+ * Sensitive Data section of the root CLAUDE.md.+ */++import { execGit } from './execGit.js';+import { PATHS } from './fileUtils.js';++// `PATHS.root` is CODE_ROOT — the checkout this process's code was loaded+// from, which is exactly the question being asked. Deliberately NOT+// `installRoot`: under a worktree boot (PORTOS_DATA_ROOT, #1947) the data tree+// and the code tree diverge, and the commit that matters is the code's.+const CODE_ROOT = PATHS.root;++// Probe-shaped git calls, per the house convention (`gitCommitProbe.js`):+// `ignoreExitCode` so a non-repo resolves to a readable non-zero exit rather+// than rejecting, and a short `timeout` so a git wedged on a locked index or a+// slow network mount can't hold boot (or a health request) open for execGit's+// 30s default.+const GIT_TIMEOUT_MS = 5000;++/**+ * Run one probe-shaped git command and return its trimmed stdout, or null.+ * Every failure mode — missing `.git`, broken checkout, timeout, non-zero exit,+ * empty output — collapses to `null`, never `''`. An empty-string commit reads+ * downstream as "a commit whose value is blank" and would compare unequal to+ * every real commit, silently reporting a false mismatch; `null` says "not+ * known" (root CLAUDE.md's absent-vs-empty rule).+ */+async function gitProbe(args) {+ const result = await execGit(args, CODE_ROOT, {+ ignoreExitCode: true,+ timeout: GIT_TIMEOUT_MS+ }).catch(() => null);+ if (!result || result.exitCode !== 0) return null;+ const value = result.stdout.trim();+ return value === '' ? null : value;+}++let cached = null;++/**+ * Resolve the running build's git identity. Cached for the life of the process:+ * the code a running process loaded cannot change under it, so re-probing git+ * on every health request would spend three subprocesses to re-learn a constant.+ * (`dirty` CAN change on disk — but it describes the tree the process booted+ * from, and a mid-run edit is not code this process is executing.)+ *+ * Non-throwing. Every field is independently nullable: a tarball install with+ * no `.git`, a detached checkout, or a git timeout reports `commit: null`+ * rather than a fabricated or empty value.+ *+ * @returns {Promise<{commit: string|null, shortCommit: string|null, branch: string|null, dirty: boolean|null, builtAt: string}>}+ */+export async function getBuildIdentity() {+ if (cached) return cached;++ const [commit, branch, status] = await Promise.all([+ gitProbe(['rev-parse', 'HEAD']),+ // `--abbrev-ref HEAD` prints the literal string `HEAD` on a detached+ // checkout, which is not a branch name. Report that as null rather than+ // handing the UI a branch called "HEAD".+ gitProbe(['rev-parse', '--abbrev-ref', 'HEAD']),+ // `--porcelain` prints one line per changed path and NOTHING when clean —+ // so a clean tree trims to '' and `gitProbe` returns null, which is+ // indistinguishable from a failed probe. That ambiguity is why dirty is+ // resolved from the raw result below instead of through `gitProbe`.+ execGit(['status', '--porcelain'], CODE_ROOT, {+ ignoreExitCode: true,+ timeout: GIT_TIMEOUT_MS+ }).catch(() => null)+ ]);++ const dirty = status && status.exitCode === 0 ? status.stdout.trim() !== '' : null;++ cached = {+ commit,+ shortCommit: commit ? commit.slice(0, 7) : null,+ branch: branch === 'HEAD' ? null : branch,+ dirty,+ // When this process started — the honest reading of "how old is the code+ // that is answering me". Distinct from the client's `__BUILD_STAMP__`,+ // which is stamped when the bundle was built.+ builtAt: new Date(Date.now() - process.uptime() * 1000).toISOString()+ };+ return cached;+}++/**+ * Single-line, human-readable summary for the boot log — `abc1234 (main, dirty)`.+ * Falls back to `unknown` rather than printing an empty parenthetical when git+ * is unavailable.+ */+export function formatBuildIdentity(identity) {+ if (!identity?.shortCommit) return 'unknown (no git metadata)';+ const parts = [identity.branch || 'detached'];+ if (identity.dirty === true) parts.push('dirty');+ if (identity.dirty === null) parts.push('cleanliness unknown');+ return `${identity.shortCommit} (${parts.join(', ')})`;+}++/** Test-only: drop the process-lifetime cache. */+export function resetBuildIdentityCache() {+ cached = null;+}diff --git a/server/lib/buildIdentity.test.js b/server/lib/buildIdentity.test.jsnew file mode 100644index 0000000000..c4f10010e7--- /dev/null+++ b/server/lib/buildIdentity.test.js@@ -0,0 +1,171 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const mocks = vi.hoisted(() => ({ execGit: vi.fn() }));++vi.mock('./execGit.js', () => ({ execGit: mocks.execGit }));++const ok = (stdout) => ({ stdout, stderr: '', exitCode: 0 });+const fail = (stderr = 'not a git repository') => ({ stdout: '', stderr, exitCode: 128 });++// Route each probe by its git subcommand so a test can fail one call without+// caring what order the module fires them in.+function routeGit({ head, branch, status }) {+ mocks.execGit.mockImplementation(async (args) => {+ if (args[0] === 'status') return status;+ if (args.includes('--abbrev-ref')) return branch;+ return head;+ });+}++async function loadModule() {+ vi.resetModules();+ return import('./buildIdentity.js');+}++describe('buildIdentity', () => {+ beforeEach(() => {+ mocks.execGit.mockReset();+ });++ it('reports commit, short commit, branch, and a clean tree', async () => {+ routeGit({+ head: ok('1234567890abcdef1234567890abcdef12345678\n'),+ branch: ok('main\n'),+ status: ok('')+ });+ const { getBuildIdentity } = await loadModule();++ const identity = await getBuildIdentity();++ expect(identity.commit).toBe('1234567890abcdef1234567890abcdef12345678');+ expect(identity.shortCommit).toBe('1234567');+ expect(identity.branch).toBe('main');+ expect(identity.dirty).toBe(false);+ expect(Number.isNaN(Date.parse(identity.builtAt))).toBe(false);+ });++ it('detects a dirty working tree', async () => {+ routeGit({+ head: ok('abc1234\n'),+ branch: ok('feature\n'),+ status: ok(' M server/index.js\n?? scratch.txt\n')+ });+ const { getBuildIdentity } = await loadModule();++ expect((await getBuildIdentity()).dirty).toBe(true);+ });++ it('reports every git field null outside a repo, and never throws', async () => {+ routeGit({ head: fail(), branch: fail(), status: fail() });+ const { getBuildIdentity } = await loadModule();++ const identity = await getBuildIdentity();++ expect(identity.commit).toBeNull();+ expect(identity.shortCommit).toBeNull();+ expect(identity.branch).toBeNull();+ // `null`, not `false` — "we could not tell" must stay distinguishable from+ // "we checked and the tree is clean".+ expect(identity.dirty).toBeNull();+ expect(typeof identity.builtAt).toBe('string');+ });++ it('reports null (never an empty string) when git resolves but prints nothing', async () => {+ routeGit({ head: ok(' \n'), branch: ok(''), status: ok('') });+ const { getBuildIdentity } = await loadModule();++ const identity = await getBuildIdentity();++ // An empty-string commit would compare unequal to every real commit and+ // make the client's stale-bundle check report a permanent false mismatch.+ expect(identity.commit).toBeNull();+ expect(identity.shortCommit).toBeNull();+ expect(identity.branch).toBeNull();+ });++ it('survives a rejecting execGit (timeout / spawn failure) without throwing', async () => {+ mocks.execGit.mockRejectedValue(new Error('git command timed out after 5s'));+ const { getBuildIdentity } = await loadModule();++ const identity = await getBuildIdentity();++ expect(identity.commit).toBeNull();+ expect(identity.dirty).toBeNull();+ });++ it('maps a detached HEAD to a null branch rather than a branch named HEAD', async () => {+ routeGit({ head: ok('deadbeefdeadbeefdeadbeefdeadbeefdeadbeef\n'), branch: ok('HEAD\n'), status: ok('') });+ const { getBuildIdentity } = await loadModule();++ const identity = await getBuildIdentity();++ expect(identity.branch).toBeNull();+ expect(identity.commit).toBe('deadbeefdeadbeefdeadbeefdeadbeefdeadbeef');+ });++ it('caches for the life of the process instead of re-probing git per call', async () => {+ routeGit({ head: ok('abc1234\n'), branch: ok('main\n'), status: ok('') });+ const { getBuildIdentity, resetBuildIdentityCache } = await loadModule();++ const first = await getBuildIdentity();+ const callsAfterFirst = mocks.execGit.mock.calls.length;+ const second = await getBuildIdentity();++ expect(second).toBe(first);+ expect(mocks.execGit.mock.calls.length).toBe(callsAfterFirst);++ // And the cache is droppable, or no suite could exercise a second shape.+ resetBuildIdentityCache();+ await getBuildIdentity();+ expect(mocks.execGit.mock.calls.length).toBeGreaterThan(callsAfterFirst);+ });++ it('probes git with ignoreExitCode and a bounded timeout, never the 30s default', async () => {+ routeGit({ head: ok('abc1234\n'), branch: ok('main\n'), status: ok('') });+ const { getBuildIdentity } = await loadModule();++ await getBuildIdentity();++ expect(mocks.execGit.mock.calls.length).toBeGreaterThan(0);+ for (const [, cwd, options] of mocks.execGit.mock.calls) {+ expect(typeof cwd).toBe('string');+ expect(cwd.trim()).not.toBe('');+ expect(options.ignoreExitCode).toBe(true);+ expect(options.timeout).toBeLessThanOrEqual(10_000);+ }+ });++ it('never reports a path, hostname, or username field', async () => {+ routeGit({ head: ok('abc1234\n'), branch: ok('main\n'), status: ok('') });+ const { getBuildIdentity } = await loadModule();++ // Privacy contract: the payload rides an API response, so its shape is+ // pinned exactly rather than merely spot-checked for known-bad keys.+ expect(Object.keys(await getBuildIdentity()).sort()).toEqual(+ ['branch', 'builtAt', 'commit', 'dirty', 'shortCommit']+ );+ });+});++describe('formatBuildIdentity', () => {+ it('renders commit, branch, and dirty state on one line', async () => {+ const { formatBuildIdentity } = await loadModule();++ expect(formatBuildIdentity({ shortCommit: 'abc1234', branch: 'main', dirty: false }))+ .toBe('abc1234 (main)');+ expect(formatBuildIdentity({ shortCommit: 'abc1234', branch: 'main', dirty: true }))+ .toBe('abc1234 (main, dirty)');+ expect(formatBuildIdentity({ shortCommit: 'abc1234', branch: null, dirty: false }))+ .toBe('abc1234 (detached)');+ expect(formatBuildIdentity({ shortCommit: 'abc1234', branch: 'main', dirty: null }))+ .toBe('abc1234 (main, cleanliness unknown)');+ });++ it('says unknown rather than printing an empty parenthetical', async () => {+ const { formatBuildIdentity } = await loadModule();++ expect(formatBuildIdentity(null)).toBe('unknown (no git metadata)');+ expect(formatBuildIdentity({ shortCommit: null, branch: null, dirty: null }))+ .toBe('unknown (no git metadata)');+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex c28d34db7b..9d6c9cdf2d 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -330,6 +330,7 @@ export * from './vaultCrypto.js';// === Model & config ===export * from './browserConfig.js';export * from './buildId.js';+export * from './buildIdentity.js';export * from './condaEnv.js';export * from './cudaCapability.js';export * from './db.js';diff --git a/server/routes/health.test.js b/server/routes/health.test.jsindex 3b30beb54a..7fe65a05a2 100644--- a/server/routes/health.test.js+++ b/server/routes/health.test.js@@ -7,6 +7,7 @@ import { listProcesses } from '../services/pm2.js';import { getSelf } from '../services/instances.js';import { isAuthEnabled } from '../services/auth.js';import { checkGhHealth } from '../services/github.js';+import { getBuildIdentity } from '../lib/buildIdentity.js';vi.mock('../services/pm2.js', () => ({listProcesses: vi.fn().mockResolvedValue([])@@ -63,6 +64,19 @@ vi.mock('../lib/db.js', () => ({checkHealth: vi.fn().mockResolvedValue({ connected: false, hasSchema: false })}));+// The build stamp is read from the checkout the suite happens to run in, so+// mock it — otherwise every assertion below would depend on which worktree+// (and which commit) CI cloned.+vi.mock('../lib/buildIdentity.js', () => ({+ getBuildIdentity: vi.fn().mockResolvedValue({+ commit: 'abc1234567890abcdef1234567890abcdef12345',+ shortCommit: 'abc1234',+ branch: 'main',+ dirty: false,+ builtAt: '2026-01-01T00:00:00.000Z'+ })+}));+// The real probe spawns `gh` and hits the network — mock it, and default to a// healthy forge so the existing cases keep their warning counts.vi.mock('../services/github.js', () => ({@@ -133,6 +147,46 @@ describe('System Health Routes', () => {expect(response.body).toHaveProperty('overallHealth');});+ it('stamps the running build on health details (#4694)', async () => {+ const response = await request(app).get('/api/system/health/details');++ expect(response.status).toBe(200);+ expect(response.body.build).toEqual({+ commit: 'abc1234567890abcdef1234567890abcdef12345',+ shortCommit: 'abc1234',+ branch: 'main',+ dirty: false,+ builtAt: '2026-01-01T00:00:00.000Z'+ });+ });++ it('keeps the build stamp OFF the always-public /health payload', async () => {+ // /api/system/health is in PUBLIC_API_PATHS (lib/authGate.js) — a branch+ // name can carry an issue title, so the stamp stays behind the auth gate.+ const response = await request(app).get('/api/system/health');++ expect(response.status).toBe(200);+ expect(response.body).not.toHaveProperty('build');+ });++ it('degrades the build stamp to null instead of failing the whole health report', async () => {+ getBuildIdentity.mockRejectedValueOnce(new Error('git exploded'));++ const response = await request(app).get('/api/system/health/details');++ expect(response.status).toBe(200);+ expect(response.body.build).toBeNull();+ expect(response.body).toHaveProperty('overallHealth');+ });++ it('never leaks a path, hostname, or username through the build stamp', async () => {+ const response = await request(app).get('/api/system/health/details');++ expect(Object.keys(response.body.build).sort()).toEqual(+ ['branch', 'builtAt', 'commit', 'dirty', 'shortCommit']+ );+ });+it('does not warn on cumulative restart_time (developer-driven restarts)', async () => {listProcesses.mockResolvedValueOnce([{ name: 'portos', status: 'online', restarts: 97, unstableRestarts: 0, cpu: 0, memory: 0 }diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex 6c71a25a1a..f1fb84b371 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -16,6 +16,7 @@ import { isAuthEnabled } from '../services/auth.js';import { getHttpsEnabledAtBoot } from '../lib/httpsState.js';import { getActiveProcessing } from '../services/activeProcessing.js';import { getMediaCapacity } from '../services/mediaCapacity.js';+import { getBuildIdentity } from '../lib/buildIdentity.js';// Defaults are tuned for a real dev machine: memory routinely sits in the// 75-85% band on a host with a couple of LLMs loaded, and big SSDs commonly@@ -83,7 +84,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {const startTime = Date.now();// Gather data in parallel- const [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds, forgeHealth, mediaCapacity] = await Promise.all([+ const [pm2Processes, appStatusSummary, cosStatus, self, dbHealth, version, diskStats, memStats, thresholds, forgeHealth, mediaCapacity, build] = await Promise.all([listProcesses().catch(() => []),apps.getAppStatusSummary().catch(() => ({ total: 0, online: 0, stopped: 0, notStarted: 0, unknown: 0, degraded: false, unmanaged: 0 })),cos.getStatus().catch(() => null),@@ -96,7 +97,13 @@ router.get('/health/details', asyncHandler(async (req, res) => {checkGhHealth().catch(() => ({ status: 'error', ok: false, detail: 'Health check failed', remedy: null, checkedAt: null })),// Media-lane capacity never fails the health report: an unreadable GPU probe// degrades to `null`, which the UI renders as unknown rather than as idle.- getMediaCapacity().catch(() => null)+ getMediaCapacity().catch(() => null),+ // Which git commit THIS server process is running (#4694). Details-only:+ // /api/system/health is in the always-public set (lib/authGate.js), and a+ // branch name can carry an issue title, so the stamp stays behind the auth+ // gate. `getBuildIdentity` is non-throwing by contract; the catch keeps a+ // future change to it from being able to fail the whole health report.+ getBuildIdentity().catch(() => null)]);const memUsagePercent = Math.round((memStats.used / memStats.total) * 100);@@ -291,6 +298,7 @@ router.get('/health/details', asyncHandler(async (req, res) => {apps: appStats,cos: cosInfo,media: mediaCapacity,+ build,database: dbHealth,forge: forgeHealth,thresholds,