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: fork-aware update flow (#455)
[._.]/ Adam Eivyf2c57b77f989
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 91ba2fa15c..2b43c4b783 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -3,6 +3,7 @@## Added- `/work <task>` Claude Code slash command (`.claude/commands/work.md`) — slugifies the task, spins up a fresh git worktree under `.claude/worktrees/<slug>/` branched off local `main` (NOT current HEAD), `cd`s into it, carries out the work without disturbing the originating checkout's uncommitted edits / branch / HEAD, and on completion always chains `/simplify` → `/do:review --with codex,gemini` → `/do:pr --review-with copilot` so codex + gemini findings are addressed locally *before* the PR opens (otherwise Copilot kicks in immediately on unreviewed code and burns review cycles). Branch / dir collision auto-suffixes with `-2`, `-3`, etc. `.claude/worktrees/` is already gitignored.+- **Fork-aware update flow.** The PortOS update tab now detects whether the local clone's `origin` remote points at upstream `atomantic/PortOS` or at a personal fork (`server/lib/gitRemote.js` parses SCP-style + HTTPS + ssh:// remote URLs, case-insensitive owner/repo match). When running from a fork the Update tab swaps the "Update Now" button for three explicit choices: **Sync Fork & Update** (runs `gh repo sync <owner>/<fork> --source atomantic/PortOS --branch main` then proceeds with the local update — fast-forward only, so it refuses to clobber divergent fork commits), **Sync Fork Only** (sync without applying), and **Update from Fork As-Is** (skip sync, pull from your fork's origin — useful if you already merged upstream into your fork via your own workflow). The server `/api/update/execute` endpoint now gates fork runs behind either a fresh `lastForkSync` record (≤10 min, same fullName) or an explicit `acknowledgeFork: true` to avoid the silent "I clicked Update and nothing happened" failure mode when a fork's main is behind upstream. The release-check still polls `atomantic/PortOS` so fork users continue to see upstream version notifications. `POST /api/update/sync-fork` exposes the gh-sync action; a 409 with `FORK_DIVERGED` is returned when the fork's main has commits not on upstream, with guidance pointing the user at PRs / feature branches / the explicit `--force` escape hatch they can run from a terminal. `update.sh` / `update.ps1` now log the active origin URL so users can confirm in the update log which repo they actually pulled from.## Changeddiff --git a/CLAUDE.md b/CLAUDE.mdindex 5004a7f44b..4fb184a579 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -135,6 +135,14 @@ PortOS bundles [slashdo](https://github.com/atomantic/slashdo) as a git submodul- CoS agents can use `loadSlashdoCommand(name)` from `subAgentSpawner.js` to inline command content into prompts (resolves `!cat` lib includes automatically)- The `.claude/commands/do/` symlinks make all `/do:*` commands available as project-level Claude Code slash commands+### Self-update flow (`server/services/updateChecker.js` + `update.sh`)++- The release notification poll **always queries the upstream `atomantic/PortOS`** so users running from a personal fork still see new versions. Constants come from `server/lib/gitRemote.js` (`UPSTREAM_OWNER`, `UPSTREAM_REPO`, `UPSTREAM_FULL_NAME`) — don't re-hardcode `atomantic/PortOS` anywhere else.+- `getOriginInfo()` in `server/lib/gitRemote.js` classifies the local `origin` remote into `{ isUpstream, isFork, isGithub, owner, repo, fullName }`. `getUpdateStatus()` includes this as `remoteInfo` plus a fixed `upstream` block. New UI that says "running from PortOS" must read `remoteInfo.isUpstream` (NOT just `currentVersion`) — otherwise it lies to fork users.+- `update.sh` / `update.ps1` always `git pull --rebase --autostash` from **origin**, not upstream. Fork users who haven't merged upstream into their fork get a silent no-op pull. To prevent that confusion: `POST /api/update/execute` rejects fork runs with 412 `FORK_SYNC_REQUIRED` unless `acknowledgeFork: true` is set in the body OR `lastForkSync.fullName` matches `remoteInfo.fullName` within the last 10 minutes.+- Fork sync happens via `POST /api/update/sync-fork` → `gh repo sync <owner>/<fork> --source atomantic/PortOS --branch <branch>`. `gh` is fast-forward only by default, so a diverged fork main returns 409 `FORK_DIVERGED` — never add `--force` server-side. The error message points users at the explicit `--force` they can run from a terminal if they really want to discard fork commits.+- The UpdateTab UI swaps "Update Now" for three buttons when `isFork`: "Sync Fork & Update", "Sync Fork Only", "Update from Fork As-Is" (the last sends `acknowledgeFork: true`). Keep these three behaviors distinct — collapsing them strips user agency over what touches their GitHub fork.+## Module OrganizationPortOS has reached the size where re-implementing a helper is now cheaper to *start* than to find what already exists. To keep that pressure off, every directory that holds reusable code carries a catalog `README.md` and an enumerable `index.js` barrel. **Before writing a helper, grep the catalog.**diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsxindex b343207f57..4fc3fa34d0 100644--- a/client/src/components/apps/tabs/UpdateTab.jsx+++ b/client/src/components/apps/tabs/UpdateTab.jsx@@ -1,5 +1,5 @@import { useState, useEffect, useCallback, useRef } from 'react';-import { RefreshCw, Download, XCircle, Check, Loader, AlertTriangle, Trash2, ExternalLink, Tag } from 'lucide-react';+import { RefreshCw, Download, XCircle, Check, Loader, AlertTriangle, Trash2, ExternalLink, Tag, GitFork, GitBranch } from 'lucide-react';import toast from '../../ui/Toast';import BrailleSpinner from '../../BrailleSpinner';import MarkdownOutput from '../../cos/MarkdownOutput';@@ -35,6 +35,8 @@ export default function UpdateTab() {const [steps, setSteps] = useState([]);const [updateError, setUpdateError] = useState(null);const [polling, setPolling] = useState(false);+ const [syncingFork, setSyncingFork] = useState(false);+ const [forkSyncError, setForkSyncError] = useState(null);const attemptsRef = useRef(0);const targetVersionRef = useRef(null);const preUpdateVersionRef = useRef(null);@@ -43,6 +45,7 @@ export default function UpdateTab() {const data = await api.getUpdateStatus().catch(() => null);if (data) setStatus(data);setLoading(false);+ return data;}, []);useEffect(() => {@@ -133,25 +136,67 @@ export default function UpdateTab() {setChecking(false);};- const handleUpdate = async () => {- // Set target version BEFORE executing so it's available when the- // restarting step arrives via socket (which may beat the HTTP response)- if (status?.latestRelease?.version) {- targetVersionRef.current = status.latestRelease.version;+ // `fromStatus` lets callers (e.g. handleSyncForkAndUpdate) pass the freshly+ // fetched status object instead of relying on the closure capture — `setStatus`+ // only schedules a render and the awaited fetchStatus() return value is the+ // single source of truth for the just-loaded state.+ const runUpdate = useCallback(async (opts = {}, fromStatus = null) => {+ const s = fromStatus || status;+ if (s?.latestRelease?.version) {+ targetVersionRef.current = s.latestRelease.version;}- preUpdateVersionRef.current = status?.currentVersion || null;+ preUpdateVersionRef.current = s?.currentVersion || null;setUpdating(true);setSteps([]);setUpdateError(null);- const result = await api.executePortosUpdate().catch(err => {+ const result = await api.executePortosUpdate(opts).catch(err => {setUpdateError(err.message);setUpdating(false);return null;});- // Update from response if available (should match, but server is authoritative)if (result?.tag) {targetVersionRef.current = result.tag.replace(/^v/, '');}+ return result;+ }, [status]);++ const handleUpdate = () => runUpdate();++ const handleUpdateFromForkAsIs = () => runUpdate({ acknowledgeFork: true });++ const handleSyncForkAndUpdate = async () => {+ setSyncingFork(true);+ setForkSyncError(null);+ const synced = await api.syncPortosFork({}, { silent: true }).catch(err => {+ setForkSyncError(err.message);+ return null;+ });+ setSyncingFork(false);+ if (!synced) return;+ if (synced.alreadyUpToDate) {+ toast.success(`Fork already up to date with ${status?.upstream?.fullName || 'upstream'}`);+ } else {+ toast.success(`Synced ${synced.fullName} from ${synced.source}`);+ }+ const fresh = await fetchStatus();+ await runUpdate({}, fresh);+ };++ const handleSyncForkOnly = async () => {+ setSyncingFork(true);+ setForkSyncError(null);+ const synced = await api.syncPortosFork({}, { silent: true }).catch(err => {+ setForkSyncError(err.message);+ return null;+ });+ setSyncingFork(false);+ if (!synced) return;+ toast.success(+ synced.alreadyUpToDate+ ? `Fork already up to date with ${status?.upstream?.fullName || 'upstream'}`+ : `Synced ${synced.fullName} from ${synced.source}`+ );+ await fetchStatus();};const handleIgnore = async (version) => {@@ -178,6 +223,13 @@ export default function UpdateTab() {const release = status?.latestRelease;const hasUpdate = status?.updateAvailable;+ const remote = status?.remoteInfo;+ const upstreamName = status?.upstream?.fullName || 'atomantic/PortOS';+ const isFork = !!remote?.isFork;+ const lastForkSync = status?.lastForkSync;+ // Server is the source of truth for the freshness window — don't+ // re-implement the time math here.+ const forkSyncFresh = !!status?.forkSyncFresh;return (<div className="space-y-6">@@ -200,6 +252,40 @@ export default function UpdateTab() {</button></div>+ {/* Origin / Fork status */}+ {remote?.hasOrigin && (+ <div className={`p-3 rounded-lg border text-sm ${+ isFork+ ? 'border-port-warning/40 bg-port-warning/5'+ : remote.isUpstream+ ? 'border-port-border bg-port-card'+ : 'border-port-border bg-port-card'+ }`}>+ <div className="flex items-start gap-2">+ {isFork ? <GitFork size={16} className="text-port-warning shrink-0 mt-0.5" /> : <GitBranch size={16} className="text-gray-400 shrink-0 mt-0.5" />}+ <div className="flex-1">+ <div className="text-white">+ {remote.isUpstream && <>Running from upstream <span className="font-mono">{remote.fullName}</span></>}+ {isFork && <>Running from fork <span className="font-mono">{remote.fullName}</span></>}+ {!remote.isUpstream && !isFork && <>Origin: <span className="font-mono">{remote.fullName || remote.originUrl}</span></>}+ </div>+ {isFork && (+ <div className="text-xs text-gray-400 mt-1 space-y-1">+ <div>Updates pull from your fork's <span className="font-mono">main</span>. Sync it from <span className="font-mono">{upstreamName}</span> before updating, or apply upstream changes onto a working branch first to preserve customizations.</div>+ <div>Tip: PR shareable fixes upstream; keep private changes on a separate branch and rebase that branch onto <span className="font-mono">main</span> after each sync.</div>+ {forkSyncFresh && (+ <div className="text-port-success">✓ Fork synced {new Date(lastForkSync.syncedAt).toLocaleTimeString()} — ready to update.</div>+ )}+ </div>+ )}+ {forkSyncError && (+ <div className="mt-2 text-xs text-port-error whitespace-pre-wrap">{forkSyncError}</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'}`}>@@ -241,18 +327,50 @@ export default function UpdateTab() {{/* Update Actions */}{hasUpdate && (<div className="flex flex-wrap gap-2">- <button- onClick={handleUpdate}- disabled={updating || polling}- className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-accent/80 disabled:opacity-50"- >- <Download size={14} className={updating ? 'animate-bounce' : ''} />- {updating ? 'Updating...' : polling ? 'Restarting...' : 'Update Now'}- </button>+ {isFork ? (+ <>+ <button+ onClick={handleSyncForkAndUpdate}+ disabled={updating || polling || syncingFork}+ className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-accent/80 disabled:opacity-50"+ title={`Fast-forwards ${remote?.fullName} main from ${upstreamName} via gh repo sync, then runs the local update. Refuses to overwrite divergent fork commits.`}+ >+ <GitFork size={14} className={syncingFork ? 'animate-pulse' : ''} />+ {syncingFork ? 'Syncing fork...' : updating ? 'Updating...' : polling ? 'Restarting...' : 'Sync Fork & Update'}+ </button>+ <button+ onClick={handleSyncForkOnly}+ disabled={updating || polling || syncingFork}+ className="px-4 py-2 bg-port-border text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-border/80 disabled:opacity-50"+ title={`Run gh repo sync ${remote?.fullName} only — useful if you want to merge upstream into a feature branch yourself before applying.`}+ >+ <GitFork size={14} />+ Sync Fork Only+ </button>+ <button+ onClick={handleUpdateFromForkAsIs}+ disabled={updating || polling || syncingFork}+ className="px-4 py-2 bg-port-border text-gray-400 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 pull from your fork's origin as-is. Use this if you already merged upstream into your fork via your own workflow."+ >+ <Download size={14} className={updating ? 'animate-bounce' : ''} />+ Update from Fork As-Is+ </button>+ </>+ ) : (+ <button+ onClick={handleUpdate}+ disabled={updating || polling}+ className="px-4 py-2 bg-port-accent text-white rounded-lg text-sm flex items-center gap-2 hover:bg-port-accent/80 disabled:opacity-50"+ >+ <Download size={14} className={updating ? 'animate-bounce' : ''} />+ {updating ? 'Updating...' : polling ? 'Restarting...' : 'Update Now'}+ </button>+ )}{release && (<buttononClick={() => handleIgnore(release.version)}- disabled={updating}+ disabled={updating || syncingFork}className="px-4 py-2 bg-port-border text-gray-400 rounded-lg text-sm flex items-center gap-2 hover:bg-port-border/80 hover:text-white disabled:opacity-50"><XCircle size={14} />diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.jsindex 7225b6a801..7759fac9a8 100644--- a/client/src/services/apiSystem.js+++ b/client/src/services/apiSystem.js@@ -20,7 +20,15 @@ export const ignoreUpdateVersion = (version) => request('/update/ignore', {body: JSON.stringify({ version })});export const clearIgnoredVersions = () => request('/update/ignore', { method: 'DELETE' });-export const executePortosUpdate = () => request('/update/execute', { method: 'POST' });+export const executePortosUpdate = (opts) => {+ const body = opts && Object.keys(opts).length ? JSON.stringify(opts) : undefined;+ return request('/update/execute', body ? { method: 'POST', body } : { method: 'POST' });+};+export const syncPortosFork = (opts = {}, requestOpts = {}) => request('/update/sync-fork', {+ method: 'POST',+ body: JSON.stringify(opts),+ ...requestOpts+});// Settingsexport const getSettings = (options) => request('/settings', options);diff --git a/server/lib/README.md b/server/lib/README.mdindex 60f9a801ee..6b58c81b73 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -95,6 +95,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `commandSecurity.js` | Allowlist of safe shell commands. || `execGit.js` | `execGit` utility imported by `git.js` + worktree manager. || `ffmpeg.js` | Shared ffmpeg helpers (videoGen + videoTimeline). |+| `gitRemote.js` | `getOriginInfo`, `parseGitRemoteUrl`, `UPSTREAM_OWNER`/`UPSTREAM_REPO` — classifies the local `origin` remote vs the upstream atomantic/PortOS repo. Used by the update flow to detect forks. || `pythonSetup.js` | Python venv / runner setup helpers. |## Networkingdiff --git a/server/lib/gitRemote.js b/server/lib/gitRemote.jsnew file mode 100644index 0000000000..0517e229e6--- /dev/null+++ b/server/lib/gitRemote.js@@ -0,0 +1,162 @@+import { execGit } from './execGit.js';+import { PATHS } from './fileUtils.js';++export const UPSTREAM_OWNER = 'atomantic';+export const UPSTREAM_REPO = 'PortOS';+export const UPSTREAM_FULL_NAME = `${UPSTREAM_OWNER}/${UPSTREAM_REPO}`;++/**+ * Strip any `://user:token@` credentials from a URL so a PAT embedded in an+ * https remote can't leak into API responses, logs, or telemetry. SCP-style+ * remotes (`user@host:path`) carry only a username (no secret) so we leave+ * those alone — redacting them would corrupt the URL.+ */+export function redactRemoteUrlCredentials(url) {+ if (typeof url !== 'string') return url;+ return url.replace(/:\/\/[^@/\s]+@/, '://***@');+}++/**+ * Parse a git remote URL (SSH or HTTPS) into { host, owner, repo }.+ * Host-agnostic — accepts GitHub, GitLab, enterprise hosts, etc. Returns null+ * when the URL doesn't match an "owner/repo" shape (exactly two path segments+ * after the host). GitHub.com classification happens later in `getOriginInfo`.+ *+ * Handles:+ * [email protected]:owner/repo.git+ * [email protected]:443/owner/repo.git (SCP variant with leading port)+ * ssh://[email protected]/owner/repo.git+ * ssh://[email protected]:443/owner/repo.git (URL form with port)+ * https://github.com/owner/repo.git+ * https://github.com/owner/repo+ * [email protected]:org/repo.git+ *+ * The returned `host` is always normalized (no trailing `:port`) so callers+ * comparing against e.g. `github.com` don't have to special-case ports.+ * Rejects URLs with extra path segments (e.g. `git@host:owner/repo/extra`)+ * since those would produce a `fullName` like `owner/repo/extra` that breaks+ * `gh repo sync` and fork classification.+ */+export function parseGitRemoteUrl(url) {+ if (typeof url !== 'string' || !url.trim()) return null;+ // Strip a single trailing slash so `…/owner/repo/` parses, but+ // `…/owner/repo/extra` (extra path segment) still fails the regex.+ const trimmed = url.trim().replace(/\/$/, '');++ // Strip a trailing .git for both SSH and HTTPS variants+ const stripGit = (s) => s.replace(/\.git$/i, '');+ // Normalize host — strip an optional `:port` suffix so `github.com:443`+ // and `github.com` compare equal.+ const stripPort = (h) => h.replace(/:\d+$/, '');++ // SCP-style SSH: git@host:[port/]owner/repo(.git). repo segment cannot+ // contain '/'. The optional `(?:\d+\/)?` matches the GitHub-specific variant+ // `[email protected]:443/OWNER/REPO.git` where `443/` is a path-prefix+ // hop port.+ const scpMatch = trimmed.match(/^[a-zA-Z0-9._-]+@([^:]+):(?:\d+\/)?([^/]+)\/([^/]+)$/);+ if (scpMatch) {+ return { host: stripPort(scpMatch[1]), owner: scpMatch[2], repo: stripGit(scpMatch[3]) };+ }++ // URL-style: scheme://[user@]host(:port)/owner/repo(.git) — repo segment+ // cannot contain '/'.+ const urlMatch = trimmed.match(/^[a-zA-Z]+:\/\/(?:[^@/]+@)?([^/]+)\/([^/]+)\/([^/]+)$/);+ if (urlMatch) {+ return { host: stripPort(urlMatch[1]), owner: urlMatch[2], repo: stripGit(urlMatch[3]) };+ }++ return null;+}++/**+ * Read the current repo's `origin` remote URL. Returns null when the directory+ * isn't a git repo or has no `origin` remote (rare, e.g. a tarball install).+ */+export async function readOriginRemoteUrl(cwd = PATHS.root) {+ const result = await execGit(['remote', 'get-url', 'origin'], cwd, { ignoreExitCode: true });+ if (result.exitCode !== 0) return null;+ const url = result.stdout.trim();+ return url || null;+}++/**+ * Inspect the local git origin remote and classify it relative to the+ * upstream atomantic/PortOS repo.+ *+ * Returned shape:+ * {+ * hasOrigin: boolean,+ * originUrl: string | null,+ * host: string | null, // e.g. "github.com"+ * owner: string | null,+ * repo: string | null,+ * fullName: string | null, // "owner/repo"+ * isUpstream: boolean, // origin == atomantic/PortOS on github.com+ * isGithub: boolean,+ * isFork: boolean // a GitHub `<other>/PortOS` repo — strict+ * // fork candidate: same repo name (case-+ * // insensitive), different owner. A repo+ * // with a different name (e.g. someone+ * // forked-and-renamed) is NOT classified+ * // as a fork because `gh repo sync` would+ * // fail and the fork-aware UI would lie.+ * }+ *+ * Comparison is case-insensitive (GitHub treats owner/repo names as such).+ */+export async function getOriginInfo(cwd = PATHS.root) {+ const originUrl = await readOriginRemoteUrl(cwd);+ if (!originUrl) {+ return {+ hasOrigin: false,+ originUrl: null,+ host: null,+ owner: null,+ repo: null,+ fullName: null,+ isUpstream: false,+ isGithub: false,+ isFork: false+ };+ }++ // The URL surfaces to the client via getUpdateStatus(); scrub any embedded+ // PAT/basic-auth credentials so they don't leak into API responses or logs.+ const safeUrl = redactRemoteUrlCredentials(originUrl);++ const parsed = parseGitRemoteUrl(originUrl);+ if (!parsed) {+ return {+ hasOrigin: true,+ originUrl: safeUrl,+ host: null,+ owner: null,+ repo: null,+ fullName: null,+ isUpstream: false,+ isGithub: false,+ isFork: false+ };+ }++ const isGithub = /(^|\.)github\.com$/i.test(parsed.host);+ const ownerMatchesUpstream = parsed.owner.toLowerCase() === UPSTREAM_OWNER.toLowerCase();+ const repoMatchesUpstream = parsed.repo.toLowerCase() === UPSTREAM_REPO.toLowerCase();+ const isUpstream = isGithub && ownerMatchesUpstream && repoMatchesUpstream;+ // Strict fork: same repo name, different owner, on GitHub. A renamed+ // GitHub repo (different name) doesn't count — `gh repo sync` would fail+ // and the fork-aware UI would mislead the user.+ const isFork = isGithub && repoMatchesUpstream && !ownerMatchesUpstream;++ return {+ hasOrigin: true,+ originUrl: safeUrl,+ host: parsed.host,+ owner: parsed.owner,+ repo: parsed.repo,+ fullName: `${parsed.owner}/${parsed.repo}`,+ isUpstream,+ isGithub,+ isFork+ };+}diff --git a/server/lib/gitRemote.test.js b/server/lib/gitRemote.test.jsnew file mode 100644index 0000000000..ab1e273c40--- /dev/null+++ b/server/lib/gitRemote.test.js@@ -0,0 +1,292 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./execGit.js', () => ({+ execGit: vi.fn()+}));++vi.mock('./fileUtils.js', () => ({+ PATHS: { root: '/mock' }+}));++import { execGit } from './execGit.js';+import {+ parseGitRemoteUrl,+ getOriginInfo,+ readOriginRemoteUrl,+ redactRemoteUrlCredentials,+ UPSTREAM_OWNER,+ UPSTREAM_REPO,+ UPSTREAM_FULL_NAME+} from './gitRemote.js';++describe('parseGitRemoteUrl', () => {+ it('parses SCP-style SSH URLs', () => {+ expect(parseGitRemoteUrl('[email protected]:atomantic/PortOS.git')).toEqual({+ host: 'github.com', owner: 'atomantic', repo: 'PortOS'+ });+ expect(parseGitRemoteUrl('[email protected]:alice/my-fork')).toEqual({+ host: 'github.com', owner: 'alice', repo: 'my-fork'+ });+ });++ it('parses HTTPS URLs', () => {+ expect(parseGitRemoteUrl('https://github.com/atomantic/PortOS.git')).toEqual({+ host: 'github.com', owner: 'atomantic', repo: 'PortOS'+ });+ expect(parseGitRemoteUrl('https://github.com/alice/my-fork')).toEqual({+ host: 'github.com', owner: 'alice', repo: 'my-fork'+ });+ });++ it('parses HTTPS URLs with embedded credentials', () => {+ expect(parseGitRemoteUrl('https://user:[email protected]/alice/my-fork.git')).toEqual({+ host: 'github.com', owner: 'alice', repo: 'my-fork'+ });+ });++ it('parses ssh:// URLs', () => {+ expect(parseGitRemoteUrl('ssh://[email protected]/atomantic/PortOS.git')).toEqual({+ host: 'github.com', owner: 'atomantic', repo: 'PortOS'+ });+ });++ it('handles enterprise/non-github hosts', () => {+ expect(parseGitRemoteUrl('[email protected]:team/repo.git')).toEqual({+ host: 'git.example.com', owner: 'team', repo: 'repo'+ });+ expect(parseGitRemoteUrl('https://gitlab.com/group/proj.git')).toEqual({+ host: 'gitlab.com', owner: 'group', repo: 'proj'+ });+ });++ it('strips trailing slashes and .git suffix only', () => {+ expect(parseGitRemoteUrl('https://github.com/alice/PortOS/')).toEqual({+ host: 'github.com', owner: 'alice', repo: 'PortOS'+ });+ expect(parseGitRemoteUrl('https://github.com/alice/portos.git.backup')).toEqual({+ host: 'github.com', owner: 'alice', repo: 'portos.git.backup'+ });+ });++ it('returns null for invalid input', () => {+ expect(parseGitRemoteUrl('')).toBeNull();+ expect(parseGitRemoteUrl(null)).toBeNull();+ expect(parseGitRemoteUrl(undefined)).toBeNull();+ expect(parseGitRemoteUrl(123)).toBeNull();+ expect(parseGitRemoteUrl('not-a-url')).toBeNull();+ });++ it('rejects URLs with extra path segments beyond owner/repo', () => {+ // SCP-style with extra segment would otherwise produce repo="repo/extra"+ expect(parseGitRemoteUrl('[email protected]:owner/repo/extra')).toBeNull();+ expect(parseGitRemoteUrl('[email protected]:owner/repo/extra.git')).toBeNull();+ // HTTPS with extra path segment+ expect(parseGitRemoteUrl('https://github.com/owner/repo/extra')).toBeNull();+ expect(parseGitRemoteUrl('https://github.com/org/team/repo.git')).toBeNull();+ // ssh:// with extra+ expect(parseGitRemoteUrl('ssh://[email protected]/owner/repo/extra.git')).toBeNull();+ });++ it('strips ports from host so github.com:443 still classifies as GitHub', () => {+ // ssh:// with explicit port+ expect(parseGitRemoteUrl('ssh://[email protected]:443/atomantic/PortOS.git')).toEqual({+ host: 'github.com', owner: 'atomantic', repo: 'PortOS'+ });+ // HTTPS with explicit port+ expect(parseGitRemoteUrl('https://github.com:443/atomantic/PortOS.git')).toEqual({+ host: 'github.com', owner: 'atomantic', repo: 'PortOS'+ });+ });++ it('accepts the SCP `host:port/owner/repo` GitHub variant', () => {+ // GitHub publishes `[email protected]:443/owner/repo.git` for users+ // tunneling SSH over 443 — must classify the same as the standard form.+ expect(parseGitRemoteUrl('[email protected]:443/atomantic/PortOS.git')).toEqual({+ host: 'ssh.github.com', owner: 'atomantic', repo: 'PortOS'+ });+ });+});++describe('readOriginRemoteUrl', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('returns the trimmed URL on success', async () => {+ execGit.mockResolvedValue({ stdout: 'https://github.com/atomantic/PortOS.git\n', stderr: '', exitCode: 0 });+ const url = await readOriginRemoteUrl();+ expect(url).toBe('https://github.com/atomantic/PortOS.git');+ expect(execGit).toHaveBeenCalledWith(['remote', 'get-url', 'origin'], '/mock', { ignoreExitCode: true });+ });++ it('returns null when origin is missing (non-zero exit)', async () => {+ execGit.mockResolvedValue({ stdout: '', stderr: 'error: No such remote: origin', exitCode: 2 });+ const url = await readOriginRemoteUrl();+ expect(url).toBeNull();+ });++ it('returns null when stdout is empty', async () => {+ execGit.mockResolvedValue({ stdout: ' \n', stderr: '', exitCode: 0 });+ const url = await readOriginRemoteUrl();+ expect(url).toBeNull();+ });+});++describe('getOriginInfo', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('classifies upstream when origin == atomantic/PortOS', async () => {+ execGit.mockResolvedValue({ stdout: '[email protected]:atomantic/PortOS.git\n', stderr: '', exitCode: 0 });+ const info = await getOriginInfo();+ expect(info).toEqual({+ hasOrigin: true,+ originUrl: '[email protected]:atomantic/PortOS.git',+ host: 'github.com',+ owner: 'atomantic',+ repo: 'PortOS',+ fullName: 'atomantic/PortOS',+ isUpstream: true,+ isGithub: true,+ isFork: false+ });+ });++ it('is case-insensitive for upstream comparison', async () => {+ execGit.mockResolvedValue({ stdout: 'https://github.com/ATOMANTIC/portos.git\n', stderr: '', exitCode: 0 });+ const info = await getOriginInfo();+ expect(info.isUpstream).toBe(true);+ expect(info.isFork).toBe(false);+ });++ it('classifies fork when origin is another github user with the same repo name', async () => {+ execGit.mockResolvedValue({ stdout: '[email protected]:alice/PortOS.git\n', stderr: '', exitCode: 0 });+ const info = await getOriginInfo();+ expect(info.isFork).toBe(true);+ expect(info.isUpstream).toBe(false);+ expect(info.fullName).toBe('alice/PortOS');+ });++ it('does NOT classify as fork when the repo name differs (renamed/unrelated)', async () => {+ // Someone might fork-and-rename, or point origin at an unrelated GitHub+ // repo. Treating that as a fork would invoke `gh repo sync` and fail.+ execGit.mockResolvedValue({ stdout: '[email protected]:alice/MyCustomOS.git\n', stderr: '', exitCode: 0 });+ const info = await getOriginInfo();+ expect(info.isGithub).toBe(true);+ expect(info.isFork).toBe(false);+ expect(info.isUpstream).toBe(false);+ expect(info.fullName).toBe('alice/MyCustomOS');+ });++ it('classifies upstream even when origin URL carries a port', async () => {+ execGit.mockResolvedValue({ stdout: 'ssh://[email protected]:443/atomantic/PortOS.git\n', stderr: '', exitCode: 0 });+ const info = await getOriginInfo();+ expect(info.host).toBe('github.com');+ expect(info.isGithub).toBe(true);+ expect(info.isUpstream).toBe(true);+ });++ it('does not flag non-github remotes as fork even when owner/repo differ', async () => {+ execGit.mockResolvedValue({ stdout: '[email protected]:team/PortOS.git\n', stderr: '', exitCode: 0 });+ const info = await getOriginInfo();+ expect(info.isGithub).toBe(false);+ expect(info.isFork).toBe(false);+ expect(info.isUpstream).toBe(false);+ expect(info.fullName).toBe('team/PortOS');+ });++ it('returns hasOrigin=false when no origin remote exists', async () => {+ execGit.mockResolvedValue({ stdout: '', stderr: '', exitCode: 2 });+ const info = await getOriginInfo();+ expect(info.hasOrigin).toBe(false);+ expect(info.isFork).toBe(false);+ expect(info.isUpstream).toBe(false);+ expect(info.fullName).toBeNull();+ });++ it('returns hasOrigin=true but unparsed when URL is malformed', async () => {+ execGit.mockResolvedValue({ stdout: 'mumble-mumble', stderr: '', exitCode: 0 });+ const info = await getOriginInfo();+ expect(info.hasOrigin).toBe(true);+ expect(info.originUrl).toBe('mumble-mumble');+ expect(info.fullName).toBeNull();+ expect(info.isFork).toBe(false);+ expect(info.isUpstream).toBe(false);+ });+});++describe('redactRemoteUrlCredentials', () => {+ it('strips https://user:token@ prefix', () => {+ expect(redactRemoteUrlCredentials('https://user:[email protected]/alice/PortOS.git'))+ .toBe('https://***@github.com/alice/PortOS.git');+ });++ it('strips https://token@ prefix (no password)', () => {+ expect(redactRemoteUrlCredentials('https://[email protected]/alice/PortOS.git'))+ .toBe('https://***@github.com/alice/PortOS.git');+ });++ it('strips credentials from ssh:// URLs', () => {+ expect(redactRemoteUrlCredentials('ssh://git:[email protected]/alice/PortOS.git'))+ .toBe('ssh://***@github.com/alice/PortOS.git');+ });++ it('leaves SCP-style remotes untouched (no embedded secret)', () => {+ expect(redactRemoteUrlCredentials('[email protected]:alice/PortOS.git'))+ .toBe('[email protected]:alice/PortOS.git');+ });++ it('leaves URLs without credentials untouched', () => {+ expect(redactRemoteUrlCredentials('https://github.com/alice/PortOS.git'))+ .toBe('https://github.com/alice/PortOS.git');+ });++ it('returns non-string input unchanged', () => {+ expect(redactRemoteUrlCredentials(null)).toBeNull();+ expect(redactRemoteUrlCredentials(undefined)).toBeUndefined();+ });+});++describe('getOriginInfo credential leak regression', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('never returns credentials in originUrl when the remote embeds a PAT', async () => {+ execGit.mockResolvedValue({+ stdout: 'https://alice:[email protected]/alice/PortOS.git\n',+ stderr: '',+ exitCode: 0+ });+ const info = await getOriginInfo();+ expect(info.originUrl).toBe('https://***@github.com/alice/PortOS.git');+ // Belt-and-suspenders: the secret must not appear anywhere in the result+ const serialized = JSON.stringify(info);+ expect(serialized).not.toContain('ghp_secret_abc123');+ expect(serialized).not.toContain('alice:'); // user:pass prefix+ // Classification should still work — credentials don't break the parser+ expect(info.isGithub).toBe(true);+ expect(info.isFork).toBe(true);+ expect(info.fullName).toBe('alice/PortOS');+ });++ it('also redacts when the URL is unparseable', async () => {+ execGit.mockResolvedValue({+ stdout: 'https://user:tok@somethingweirdwithoutslash',+ stderr: '',+ exitCode: 0+ });+ const info = await getOriginInfo();+ expect(info.originUrl).not.toContain('tok');+ expect(info.originUrl).toContain('***@');+ });+});++describe('upstream constants', () => {+ it('exposes UPSTREAM_OWNER, UPSTREAM_REPO, UPSTREAM_FULL_NAME', () => {+ expect(UPSTREAM_OWNER).toBe('atomantic');+ expect(UPSTREAM_REPO).toBe('PortOS');+ expect(UPSTREAM_FULL_NAME).toBe('atomantic/PortOS');+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 06f446d84f..76cfcece2a 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -80,6 +80,7 @@ export * from './zipStream.js';export * from './commandSecurity.js';export * from './execGit.js';export * from './ffmpeg.js';+export * from './gitRemote.js';export * from './pythonSetup.js';// === Networking ===diff --git a/server/routes/update.js b/server/routes/update.jsindex f6eaf60d01..4fd07407e7 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -2,6 +2,7 @@ import { Router } from 'express';import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';+import { UPSTREAM_FULL_NAME } from '../lib/gitRemote.js';import * as updateChecker from '../services/updateChecker.js';import { executeUpdate } from '../services/updateExecutor.js';@@ -11,6 +12,14 @@ const ignoreSchema = z.object({version: z.string().min(1, 'version is required')});+const syncForkSchema = z.object({+ branch: z.string().min(1).max(255).regex(/^[A-Za-z0-9._/-]+$/, 'branch contains invalid characters').optional()+});++const executeSchema = z.object({+ acknowledgeFork: z.boolean().optional()+});+// GET /api/update/status — returns update state (also clears stale locks)router.get('/status', asyncHandler(async (req, res) => {await updateChecker.clearStaleUpdateInProgress();@@ -39,8 +48,63 @@ router.delete('/ignore', asyncHandler(async (req, res) => {res.json(status);}));+// POST /api/update/sync-fork — fast-forward the user's GitHub fork from upstream+// via `gh repo sync`. Non-destructive: gh refuses to overwrite divergent fork+// history without --force, so a 409 FORK_DIVERGED here means the fork's main has+// commits not on upstream (user customizations). Other failures (gh missing,+// network, etc.) bubble as 502 FORK_SYNC_FAILED.+router.post('/sync-fork', asyncHandler(async (req, res) => {+ const { branch } = validateRequest(syncForkSchema, req.body || {});+ // Surface git-binary/spawn failures as a structured 502 instead of an+ // unclassified 500 — the UI banner relies on err.message for guidance.+ const info = await updateChecker.getRemoteInfo().catch(err => {+ throw new ServerError(`Could not inspect git origin remote: ${err.message}`,+ { status: 502, code: 'GIT_UNAVAILABLE' });+ });+ if (!info?.hasOrigin) {+ throw new ServerError('No git origin remote found — fork sync requires a GitHub remote.',+ { status: 400, code: 'NO_ORIGIN' });+ }+ if (!info.isGithub) {+ throw new ServerError('Origin remote is not on GitHub — fork sync is GitHub-only.',+ { status: 400, code: 'NOT_GITHUB' });+ }+ if (info.isUpstream) {+ throw new ServerError(`Origin is already the upstream ${UPSTREAM_FULL_NAME} — nothing to sync.`,+ { status: 400, code: 'ALREADY_UPSTREAM' });+ }+ if (!info.isFork) {+ throw new ServerError(+ `Origin ${info.fullName} is not a fork of ${UPSTREAM_FULL_NAME} (repo name differs). ` ++ `Fork sync requires the origin to be a GitHub fork.`,+ { status: 400, code: 'NOT_A_FORK' }+ );+ }++ // Default mirrors syncFork()'s internal default so error messaging matches+ // the actual branch the gh call targeted.+ const targetBranch = branch || 'main';+ const result = await updateChecker.syncFork({ branch, remoteInfo: info }).catch(err => {+ const msg = err.message || 'Fork sync failed';+ // gh's "would not be a fast forward" / "diverged" error → 409 so client+ // can show the "you have local customizations" guidance+ if (/fast forward|diverge|non-fast/i.test(msg)) {+ throw new ServerError(+ `Fork sync would overwrite commits on ${info.fullName}'s ${targetBranch} branch (GitHub): ${msg}. ` ++ `Move customizations to a feature branch, PR them upstream, or run ` ++ `\`gh repo sync ${info.fullName} --branch ${targetBranch} --force\` from a terminal if you want to discard them.`,+ { status: 409, code: 'FORK_DIVERGED' }+ );+ }+ throw new ServerError(msg, { status: 502, code: 'FORK_SYNC_FAILED' });+ });++ res.json(result);+}));+// POST /api/update/execute — kicks off updaterouter.post('/execute', asyncHandler(async (req, res) => {+ const { acknowledgeFork } = 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' });@@ -52,6 +116,23 @@ router.post('/execute', asyncHandler(async (req, res) => {throw new ServerError('Invalid release tag format', { status: 400, code: 'INVALID_TAG' });}+ // Fork gate: update.sh pulls from origin, so running from an unsynced fork+ // would silently no-op (or pull a stale version). Require either a recent+ // fork sync of the upstream branch or an explicit acknowledgement that the+ // user knows they're updating from their own origin.+ const remote = status.remoteInfo;+ if (remote?.isFork && !acknowledgeFork) {+ // Reuse the freshness boolean the service already computed so the route+ // and `status.forkSyncFresh` agree by construction (no duplicate math).+ if (!status.forkSyncFresh) {+ throw new ServerError(+ `Running from a fork (${remote.fullName}). Sync your fork from ${status.upstream.fullName} ` ++ `first, or re-submit with acknowledgeFork: true to update from your fork's origin as-is.`,+ { status: 412, code: 'FORK_SYNC_REQUIRED' }+ );+ }+ }+// Atomic check-and-set: rejects if already in progress, preventing concurrent updatesconst acquired = await updateChecker.setUpdateInProgress(true);if (!acquired) {diff --git a/server/services/updateChecker.js b/server/services/updateChecker.jsindex fb90f36bab..08fe67604d 100644--- a/server/services/updateChecker.js+++ b/server/services/updateChecker.js@@ -3,12 +3,21 @@ import { EventEmitter } from 'events';import { readJSONFile, PATHS, ensureDir, atomicWrite } from '../lib/fileUtils.js';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 { execGh } from './github.js';const UPDATE_FILE = join(PATHS.data, 'update.json');const CHECK_INTERVAL_MS = 30 * 60 * 1000; // 30 minutesconst STARTUP_DELAY_MS = 10 * 1000; // 10 seconds+/**+ * How long a `lastForkSync` record counts as "fresh enough" to skip the+ * fork-sync gate on /api/update/execute. Exported so the route + UI agree on+ * a single number — the UI doesn't need to re-implement the time math; it+ * reads `status.forkSyncFresh` directly.+ */+export const FORK_SYNC_FRESHNESS_MS = 10 * 60 * 1000;+export const updateEvents = new EventEmitter();const withLock = createMutex();@@ -22,7 +31,8 @@ const defaultState = () => ({ignoredVersions: [],updateInProgress: false,updateStartedAt: null,- lastUpdateResult: null+ lastUpdateResult: null,+ lastForkSync: null});/**@@ -105,15 +115,101 @@ async function saveState(state) {await atomicWrite(UPDATE_FILE, JSON.stringify(state, null, 2) + '\n');}+/**+ * Inspect the local git origin remote and return its classification.+ * Pure read — never mutates state.+ */+export async function getRemoteInfo() {+ return getOriginInfo();+}++/**+ * Sync the user's GitHub fork from the upstream atomantic/PortOS repo via+ * `gh repo sync owner/fork`. Default fast-forward only — `gh` refuses to+ * overwrite divergent fork history unless `--force` is passed, so this is+ * non-destructive by design.+ *+ * Returns { synced, alreadyUpToDate, fullName, source, mergedBranch, message }.+ *+ * Error handling — by layer:+ * - This function throws plain `Error` for pre-flight refusals (no origin,+ * not GitHub, already upstream, not a fork).+ * - `execGh` rejections (gh CLI failure including the diverged-fork case)+ * bubble up unchanged.+ * - The /api/update/sync-fork route runs an upfront 400 gate against the+ * same conditions (NO_ORIGIN / NOT_GITHUB / ALREADY_UPSTREAM / NOT_A_FORK)+ * so the pre-flight throws above are defense-in-depth and would normally+ * be unreachable from the route. The route only string-matches `err.message`+ * to distinguish the gh diverged-fork case (409 FORK_DIVERGED) from other+ * gh failures (502 FORK_SYNC_FAILED).+ */+export async function syncFork({ branch, remoteInfo } = {}) {+ // Accept a pre-fetched remoteInfo from the route so we don't spawn `git+ // remote get-url origin` twice per /sync-fork call (and so a TOCTOU race+ // between the route's gate and ours can't surface as confusing messaging).+ const info = remoteInfo || await getRemoteInfo();+ if (!info.hasOrigin) {+ throw new Error('No git origin remote — cannot sync fork.');+ }+ if (!info.isGithub) {+ throw new Error(`Origin remote is not on GitHub (host: ${info.host || 'unknown'}). Fork sync is GitHub-only.`);+ }+ if (info.isUpstream) {+ throw new Error(`Origin is already the upstream ${UPSTREAM_FULL_NAME} — nothing to sync.`);+ }+ if (!info.isFork) {+ // Catches a GitHub remote that points at a repo with a different name+ // (e.g. someone forked-and-renamed). `gh repo sync` would fail with a+ // confusing 502; surface a clear refusal instead.+ throw new Error(+ `Origin ${info.fullName} is not a fork of ${UPSTREAM_FULL_NAME} ` ++ `(repo name differs). Fork sync requires the origin to be a GitHub fork named "${UPSTREAM_REPO}".`+ );+ }++ const targetBranch = branch || 'main';+ const args = ['repo', 'sync', info.fullName, '--source', UPSTREAM_FULL_NAME, '--branch', targetBranch];+ const stdout = await execGh(args);++ // `gh repo sync` prints e.g. "✓ Synced the "main" branch from atomantic/PortOS to owner/PortOS"+ // or "✓ Repository is up to date with atomantic/PortOS"+ const alreadyUpToDate = /up to date/i.test(stdout);++ await withLock(async () => {+ const state = await loadState();+ state.lastForkSync = {+ fullName: info.fullName,+ source: UPSTREAM_FULL_NAME,+ branch: targetBranch,+ alreadyUpToDate,+ syncedAt: new Date().toISOString(),+ message: stdout.trim()+ };+ await saveState(state);+ });++ return {+ synced: true,+ alreadyUpToDate,+ fullName: info.fullName,+ source: UPSTREAM_FULL_NAME,+ mergedBranch: targetBranch,+ message: stdout.trim()+ };+}+/*** Check GitHub for the latest release and compare to current version.+ * Always polls the upstream atomantic/PortOS releases so users running+ * from a fork still see upstream version availability. Pull/checkout+ * behavior is unchanged — update.sh still pulls from origin.*/export async function checkForUpdate() {return withLock(async () => {const state = await loadState();const currentVersion = await getCurrentVersion();- const raw = await execGh(['api', 'repos/atomantic/PortOS/releases/latest']);+ const raw = await execGh(['api', `repos/${UPSTREAM_OWNER}/${UPSTREAM_REPO}/releases/latest`]);let data;try { data = JSON.parse(raw); } catch { throw new Error(`Failed to parse GitHub release response: ${raw.slice(0, 200)}`); }const release = {@@ -156,6 +252,9 @@ export async function checkForUpdate() {/*** Get the current update status without checking GitHub.+ * Includes `remoteInfo` so the UI can render fork-aware messaging.+ * Remote inspection is best-effort — a failure (no git, no origin, etc.)+ * never blocks the status response.*/export async function getUpdateStatus() {const state = await loadState();@@ -170,11 +269,30 @@ export async function getUpdateStatus() {const isIgnored = latestVersion? state.ignoredVersions.includes(latestVersion): false;+ const remoteInfo = await getRemoteInfo().catch(() => null);++ // Single source of truth for the freshness check — the UI reads this+ // directly instead of re-implementing the time math + fullName match.+ // GitHub owner/repo names are case-insensitive, so the fullName match+ // must be too (otherwise a remote like `ALICE/PortOS` vs a stored+ // `alice/PortOS` falsely flips this to false).+ const lastSync = state.lastForkSync;+ const forkSyncFresh = !!(+ lastSync &&+ remoteInfo?.fullName &&+ typeof lastSync.fullName === 'string' &&+ lastSync.fullName.toLowerCase() === remoteInfo.fullName.toLowerCase() &&+ (Date.now() - new Date(lastSync.syncedAt).getTime()) < FORK_SYNC_FRESHNESS_MS+ );return {currentVersion,...state,- updateAvailable: isNewer && !isIgnored+ updateAvailable: isNewer && !isIgnored,+ remoteInfo,+ upstream: { owner: UPSTREAM_OWNER, repo: UPSTREAM_REPO, fullName: UPSTREAM_FULL_NAME },+ forkSyncFresh,+ forkSyncWindowMs: FORK_SYNC_FRESHNESS_MS};}diff --git a/server/services/updateChecker.test.js b/server/services/updateChecker.test.jsindex 1360c770c2..bc72494d35 100644--- a/server/services/updateChecker.test.js+++ b/server/services/updateChecker.test.js@@ -20,8 +20,16 @@ vi.mock('./github.js', () => ({execGh: vi.fn()}));+vi.mock('../lib/gitRemote.js', () => ({+ getOriginInfo: vi.fn(),+ UPSTREAM_OWNER: 'atomantic',+ UPSTREAM_REPO: 'PortOS',+ UPSTREAM_FULL_NAME: 'atomantic/PortOS'+}));+import { readJSONFile, ensureDir, atomicWrite } from '../lib/fileUtils.js';import { execGh } from './github.js';+import { getOriginInfo } from '../lib/gitRemote.js';import {compareSemver,getCurrentVersion,@@ -30,6 +38,8 @@ import {clearIgnored,checkForUpdate,clearStaleUpdateInProgress,+ getRemoteInfo,+ syncFork,updateEvents} from './updateChecker.js';@@ -81,6 +91,17 @@ describe('getCurrentVersion', () => {describe('getUpdateStatus', () => {beforeEach(() => {vi.clearAllMocks();+ getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ originUrl: '[email protected]:atomantic/PortOS.git',+ host: 'github.com',+ owner: 'atomantic',+ repo: 'PortOS',+ fullName: 'atomantic/PortOS',+ isUpstream: true,+ isGithub: true,+ isFork: false+ });});it('should report no update when latestRelease is null', async () => {@@ -401,3 +422,330 @@ describe('clearStaleUpdateInProgress', () => {expect(atomicWrite).not.toHaveBeenCalled();});});++describe('getRemoteInfo', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('proxies to getOriginInfo from lib/gitRemote', async () => {+ const mock = {+ hasOrigin: true,+ originUrl: '[email protected]:alice/PortOS.git',+ host: 'github.com',+ owner: 'alice',+ repo: 'PortOS',+ fullName: 'alice/PortOS',+ isUpstream: false,+ isGithub: true,+ isFork: true+ };+ getOriginInfo.mockResolvedValue(mock);+ await expect(getRemoteInfo()).resolves.toEqual(mock);+ });+});++describe('getUpdateStatus remoteInfo', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('includes remoteInfo and upstream metadata', async () => {+ const remote = {+ hasOrigin: true,+ originUrl: '[email protected]:alice/PortOS.git',+ host: 'github.com',+ owner: 'alice',+ repo: 'PortOS',+ fullName: 'alice/PortOS',+ isUpstream: false,+ isGithub: true,+ isFork: true+ };+ getOriginInfo.mockResolvedValue(remote);+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null,+ latestRelease: { version: '1.27.0' },+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.26.0' });++ const status = await getUpdateStatus();+ expect(status.remoteInfo).toEqual(remote);+ expect(status.upstream).toEqual({ owner: 'atomantic', repo: 'PortOS', fullName: 'atomantic/PortOS' });+ expect(status.updateAvailable).toBe(true);+ });++ it('returns remoteInfo=null when origin lookup throws', async () => {+ getOriginInfo.mockRejectedValue(new Error('not a git repo'));+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null,+ latestRelease: null,+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null+ })+ .mockResolvedValueOnce({ version: '1.26.0' });++ const status = await getUpdateStatus();+ expect(status.remoteInfo).toBeNull();+ expect(status.upstream.fullName).toBe('atomantic/PortOS');+ });++ it('forkSyncFresh is true within the freshness window for the same fork', async () => {+ const remote = {+ hasOrigin: true, originUrl: '[email protected]:alice/PortOS.git', host: 'github.com',+ owner: 'alice', repo: 'PortOS', fullName: 'alice/PortOS',+ isUpstream: false, isGithub: true, isFork: true+ };+ getOriginInfo.mockResolvedValue(remote);+ const recent = new Date(Date.now() - 2 * 60 * 1000).toISOString(); // 2 min ago+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null, latestRelease: null, ignoredVersions: [],+ updateInProgress: false, lastUpdateResult: null,+ lastForkSync: { fullName: 'alice/PortOS', syncedAt: recent }+ })+ .mockResolvedValueOnce({ version: '1.26.0' });++ const status = await getUpdateStatus();+ expect(status.forkSyncFresh).toBe(true);+ expect(status.forkSyncWindowMs).toBe(10 * 60 * 1000);+ });++ it('forkSyncFresh is false when lastForkSync is older than the window', async () => {+ const remote = {+ hasOrigin: true, originUrl: '[email protected]:alice/PortOS.git', host: 'github.com',+ owner: 'alice', repo: 'PortOS', fullName: 'alice/PortOS',+ isUpstream: false, isGithub: true, isFork: true+ };+ getOriginInfo.mockResolvedValue(remote);+ const stale = new Date(Date.now() - 30 * 60 * 1000).toISOString(); // 30 min ago+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null, latestRelease: null, ignoredVersions: [],+ updateInProgress: false, lastUpdateResult: null,+ lastForkSync: { fullName: 'alice/PortOS', syncedAt: stale }+ })+ .mockResolvedValueOnce({ version: '1.26.0' });++ const status = await getUpdateStatus();+ expect(status.forkSyncFresh).toBe(false);+ });++ it('forkSyncFresh is case-insensitive on fullName (matches GitHub semantics)', async () => {+ const remote = {+ hasOrigin: true, originUrl: '[email protected]:ALICE/PortOS.git', host: 'github.com',+ owner: 'ALICE', repo: 'PortOS', fullName: 'ALICE/PortOS',+ isUpstream: false, isGithub: true, isFork: true+ };+ getOriginInfo.mockResolvedValue(remote);+ const recent = new Date(Date.now() - 1 * 60 * 1000).toISOString();+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null, latestRelease: null, ignoredVersions: [],+ updateInProgress: false, lastUpdateResult: null,+ // Stored with lowercase variant — should still match the uppercase origin+ lastForkSync: { fullName: 'alice/portos', syncedAt: recent }+ })+ .mockResolvedValueOnce({ version: '1.26.0' });++ const status = await getUpdateStatus();+ expect(status.forkSyncFresh).toBe(true);+ });++ it('forkSyncFresh is false when lastForkSync.fullName mismatches the current origin', async () => {+ const remote = {+ hasOrigin: true, originUrl: '[email protected]:bob/PortOS.git', host: 'github.com',+ owner: 'bob', repo: 'PortOS', fullName: 'bob/PortOS',+ isUpstream: false, isGithub: true, isFork: true+ };+ getOriginInfo.mockResolvedValue(remote);+ const recent = new Date(Date.now() - 2 * 60 * 1000).toISOString();+ readJSONFile+ .mockResolvedValueOnce({+ lastCheck: null, latestRelease: null, ignoredVersions: [],+ updateInProgress: false, lastUpdateResult: null,+ lastForkSync: { fullName: 'alice/PortOS', syncedAt: recent }+ })+ .mockResolvedValueOnce({ version: '1.26.0' });++ const status = await getUpdateStatus();+ expect(status.forkSyncFresh).toBe(false);+ });+});++describe('syncFork', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ atomicWrite.mockResolvedValue(undefined);+ ensureDir.mockResolvedValue(undefined);+ readJSONFile.mockResolvedValue({+ lastCheck: null,+ latestRelease: null,+ ignoredVersions: [],+ updateInProgress: false,+ lastUpdateResult: null,+ lastForkSync: null+ });+ });++ it('runs gh repo sync against the user fork and the upstream source', async () => {+ getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ originUrl: '[email protected]:alice/PortOS.git',+ host: 'github.com',+ owner: 'alice',+ repo: 'PortOS',+ fullName: 'alice/PortOS',+ isUpstream: false,+ isGithub: true,+ isFork: true+ });+ execGh.mockResolvedValue('✓ Synced the "main" branch from atomantic/PortOS to alice/PortOS');++ const result = await syncFork();+ expect(execGh).toHaveBeenCalledWith([+ 'repo', 'sync', 'alice/PortOS', '--source', 'atomantic/PortOS', '--branch', 'main'+ ]);+ expect(result.synced).toBe(true);+ expect(result.fullName).toBe('alice/PortOS');+ expect(result.source).toBe('atomantic/PortOS');+ expect(result.mergedBranch).toBe('main');+ expect(result.alreadyUpToDate).toBe(false);+ });++ it('detects already-up-to-date response', async () => {+ getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ isGithub: true,+ isUpstream: false,+ isFork: true,+ fullName: 'alice/PortOS',+ owner: 'alice',+ repo: 'PortOS'+ });+ execGh.mockResolvedValue('✓ Repository is up to date with atomantic/PortOS');++ const result = await syncFork();+ expect(result.alreadyUpToDate).toBe(true);+ });++ it('respects an explicit branch argument', async () => {+ getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ isGithub: true,+ isUpstream: false,+ isFork: true,+ fullName: 'alice/PortOS',+ owner: 'alice',+ repo: 'PortOS'+ });+ execGh.mockResolvedValue('✓ Synced');++ await syncFork({ branch: 'release' });+ expect(execGh).toHaveBeenCalledWith([+ 'repo', 'sync', 'alice/PortOS', '--source', 'atomantic/PortOS', '--branch', 'release'+ ]);+ });++ it('refuses when there is no origin remote', async () => {+ getOriginInfo.mockResolvedValue({ hasOrigin: false, isGithub: false, isFork: false, isUpstream: false });+ await expect(syncFork()).rejects.toThrow(/no git origin/i);+ expect(execGh).not.toHaveBeenCalled();+ });++ it('refuses when origin is not on GitHub', async () => {+ getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ isGithub: false,+ isFork: false,+ isUpstream: false,+ host: 'gitlab.com',+ fullName: 'team/PortOS'+ });+ await expect(syncFork()).rejects.toThrow(/github-only/i);+ expect(execGh).not.toHaveBeenCalled();+ });++ it('refuses when origin is already the upstream', async () => {+ getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ isGithub: true,+ isUpstream: true,+ isFork: false,+ fullName: 'atomantic/PortOS'+ });+ await expect(syncFork()).rejects.toThrow(/already the upstream/i);+ expect(execGh).not.toHaveBeenCalled();+ });++ it('uses pre-fetched remoteInfo without re-spawning git', async () => {+ const remote = {+ hasOrigin: true, isGithub: true, isUpstream: false, isFork: true,+ fullName: 'alice/PortOS', owner: 'alice', repo: 'PortOS'+ };+ execGh.mockResolvedValue('✓ Synced');+ await syncFork({ remoteInfo: remote });+ expect(getOriginInfo).not.toHaveBeenCalled();+ expect(execGh).toHaveBeenCalledWith([+ 'repo', 'sync', 'alice/PortOS', '--source', 'atomantic/PortOS', '--branch', 'main'+ ]);+ });++ it('refuses when origin is a GitHub repo but not a fork (renamed/unrelated)', async () => {+ getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ isGithub: true,+ isUpstream: false,+ isFork: false,+ fullName: 'alice/MyCustomOS',+ owner: 'alice',+ repo: 'MyCustomOS'+ });+ await expect(syncFork()).rejects.toThrow(/not a fork of atomantic\/PortOS/i);+ expect(execGh).not.toHaveBeenCalled();+ });++ it('propagates gh CLI errors (diverged fork)', async () => {+ getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ isGithub: true,+ isUpstream: false,+ isFork: true,+ fullName: 'alice/PortOS',+ owner: 'alice',+ repo: 'PortOS'+ });+ execGh.mockRejectedValue(new Error('failed to sync: the destination repository would not be a fast forward'));+ await expect(syncFork()).rejects.toThrow(/fast forward/i);+ });++ it('persists lastForkSync metadata to state on success', async () => {+ getOriginInfo.mockResolvedValue({+ hasOrigin: true,+ isGithub: true,+ isUpstream: false,+ isFork: true,+ fullName: 'alice/PortOS',+ owner: 'alice',+ repo: 'PortOS'+ });+ execGh.mockResolvedValue('✓ Synced');++ await syncFork();+ expect(atomicWrite).toHaveBeenCalled();+ const saved = JSON.parse(atomicWrite.mock.calls[0][1]);+ expect(saved.lastForkSync).toEqual(expect.objectContaining({+ fullName: 'alice/PortOS',+ source: 'atomantic/PortOS',+ branch: 'main',+ alreadyUpToDate: false+ }));+ expect(saved.lastForkSync.syncedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ });+});diff --git a/update.ps1 b/update.ps1index 7812d548f1..b87300235d 100644--- a/update.ps1+++ b/update.ps1@@ -103,6 +103,16 @@ function Safe-Install {# the update completes (we don't auto-pop because the rest of the script# needs to keep running with main's contents).Step "git-pull" "running" "Pulling latest changes..."+$originUrl = git remote get-url origin 2>$null+if ($originUrl) {+ # Redact any embedded credentials (https://user:token@host/...) before logging+ # so PATs don't leak into data/update.log or the update UI step output.+ $originUrlSafe = $originUrl -replace '(://)[^@/]+@', '$1***@'+ Write-SafeHost "🌐 Pulling from origin: $originUrlSafe"+ # Also append directly to $UpdateLog — updateExecutor only forwards STEP:+ # lines, so Write-SafeHost above doesn't reach update.log on its own.+ Add-Content -Path $UpdateLog -Value "🌐 Pulling from origin: $originUrlSafe"+}$headRef = git symbolic-ref -q HEAD 2>$null$currentBranch = if ($headRef) { $headRef -replace "refs/heads/", "" } else { "" }$stashedForBranch = ""diff --git a/update.sh b/update.shindex e4bff6dba4..7bf13193b7 100755--- a/update.sh+++ b/update.sh@@ -68,6 +68,16 @@ safe_install() {# the update completes (we don't auto-pop because the rest of the script# needs to keep running with main's contents).step "git-pull" "running" "Pulling latest changes..."+origin_url=$(git remote get-url origin 2>/dev/null || echo "")+if [ -n "$origin_url" ]; then+ # Redact any embedded credentials (https://user:token@host/...) before logging+ # so PATs don't leak into data/update.log or the update UI step output.+ origin_url_safe=$(printf '%s' "$origin_url" | sed -E 's|://[^@/]+@|://***@|')+ log "🌐 Pulling from origin: $origin_url_safe"+ # Also append directly to $UPDATE_LOG — updateExecutor only forwards STEP:+ # lines, so the `log` above doesn't reach update.log on its own.+ echo "🌐 Pulling from origin: $origin_url_safe" >> "$UPDATE_LOG"+ficurrent_branch=$(git symbolic-ref -q --short HEAD 2>/dev/null || echo "")stashed_for_branch=""stashed_for_commit=""