Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Explain the package-lock churn, and add a reset-to-origin button

[._.]/ Adam Eivy8ed76133c5a1
diff --git a/README.md b/README.md
index b2b81c5dde..e3f5cd1b20 100644
--- a/README.md
+++ b/README.md
@@ -292,6 +292,7 @@ Track your biological self alongside your digital one.
### Requirements
- Node.js 22.12 or later (24 is what CI and `.nvmrc` use; Vite 8 requires ≥20.19). `npm run setup`, `npm start` and `npm run dev` check this first and stop immediately on an older Node — a bare `npm install` only warns, so use the commands below.
+- npm 12 or later (`npm install -g npm@latest`). Older npm installs fine, but its lockfile writer omits the `libc` fields npm 12 records, so every `npm install` rewrites `client/package-lock.json` and `server/package-lock.json` — and the next Dependabot PR puts those fields back. Every workspace declares `engines.npm`, so npm warns on any install path; `npm run setup`/`start`/`dev` also print what to do about it. These are warnings, never failures. No Node release bundles npm 12 yet (Node 24.10 ships 11.6.1), so this is a deliberate global upgrade — and worth checking `npm -v` matches, since an old global npm earlier on `PATH` shadows the one Node ships.
- Git
- PostgreSQL, either installed locally or available through Docker. PortOS requires a healthy database; the setup command provisions the supported local or Docker-backed instance.
diff --git a/autofixer/package.json b/autofixer/package.json
index 1f9ba97cc3..41ef4dd6d3 100644
--- a/autofixer/package.json
+++ b/autofixer/package.json
@@ -4,7 +4,8 @@
"private": true,
"type": "module",
"engines": {
- "node": ">=22.12.0"
+ "node": ">=22.12.0",
+ "npm": ">=12.0.0"
},
"dependencies": {
"express": "5.2.1"
diff --git a/client/package.json b/client/package.json
index bde1232a7b..2bbd98f7bc 100644
--- a/client/package.json
+++ b/client/package.json
@@ -4,7 +4,8 @@
"private": true,
"type": "module",
"engines": {
- "node": ">=22.12.0"
+ "node": ">=22.12.0",
+ "npm": ">=12.0.0"
},
"scripts": {
"dev": "vite --host 0.0.0.0 --port 5554",
diff --git a/client/src/components/apps/tabs/GitTab.jsx b/client/src/components/apps/tabs/GitTab.jsx
index 9c42f29921..6050494588 100644
--- a/client/src/components/apps/tabs/GitTab.jsx
+++ b/client/src/components/apps/tabs/GitTab.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect, useCallback } from 'react';
-import { GitBranch, Plus, Minus, FileText, RefreshCw, Download, Rocket, Upload, ArrowUpDown, Check, Trash2, GitMerge, Globe } from 'lucide-react';
+import { GitBranch, Plus, Minus, FileText, RefreshCw, Download, Rocket, Upload, ArrowUpDown, Check, Trash2, GitMerge, Globe, RotateCcw } from 'lucide-react';
import toast from '../../ui/Toast';
import Modal from '../../ui/Modal';
import BrailleSpinner from '../../BrailleSpinner';
@@ -81,6 +81,55 @@ ${mergeStep}. **Merge**: Once approved and CI passes, merge with \`gh pr merge -
const iconBtnCls = 'p-1.5 min-h-[40px] min-w-[40px] flex items-center justify-center';
const touchBtnCls = 'min-h-[40px]';
+/**
+ * The confirm-dialog chrome this tab uses for its consequential actions — the
+ * release PR and the reset-to-origin. Extracted at the third copy of the same
+ * `Modal` props + header/body/footer markup, because the parts that drift when
+ * it is pasted again are the accessibility ones (`aria-labelledby` wiring, the
+ * 44px close target) rather than anything visible.
+ *
+ * `tone` picks the confirm button's colour: 'accent' for a normal action,
+ * 'error' for one that destroys work.
+ */
+function ConfirmModal({ open, onClose, titleId, icon, title, tone = 'accent', confirmLabel, onConfirm, busy = false, children }) {
+ const confirmCls = tone === 'error'
+ ? 'bg-port-error hover:bg-port-error/80'
+ : 'bg-port-accent hover:bg-port-accent/80';
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ size="md"
+ align="none"
+ backdropClassName="bg-black/50"
+ panelClassName="bg-port-card border border-port-border rounded-xl overflow-hidden"
+ ariaLabelledBy={titleId}
+ >
+ <div className="flex items-center justify-between p-4 border-b border-port-border">
+ <h3 id={titleId} className="font-medium text-white flex items-center gap-2">
+ {icon}
+ {title}
+ </h3>
+ <button onClick={onClose} aria-label="Close" className="text-gray-400 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center">×</button>
+ </div>
+ <div className="p-4 space-y-3">{children}</div>
+ <div className="flex justify-end gap-3 p-4 border-t border-port-border">
+ <button onClick={onClose} className="px-4 py-2 text-sm text-gray-400 hover:text-white">
+ Cancel
+ </button>
+ <button
+ onClick={onConfirm}
+ disabled={busy}
+ className={`flex items-center gap-2 px-4 py-2 ${confirmCls} text-white rounded-lg text-sm disabled:opacity-50`}
+ >
+ {icon}
+ {confirmLabel}
+ </button>
+ </div>
+ </Modal>
+ );
+}
+
export default function GitTab({ appId: _appId, appName, repoPath }) {
const [gitInfo, setGitInfo] = useState(null);
const [diff, setDiff] = useState('');
@@ -107,6 +156,8 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {
const [checkingOutRemote, setCheckingOutRemote] = useState(null);
const [cleaningUp, setCleaningUp] = useState(false);
const [cleanupConfirm, setCleanupConfirm] = useState(false);
+ const [resetting, setResetting] = useState(false);
+ const [resetConfirm, setResetConfirm] = useState(false);
const loadGitData = useCallback(async (opts = {}) => {
if (!repoPath) return;
@@ -379,6 +430,36 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {
}
};
+ // Destructive: throws away tracked edits and local commits on the default
+ // branch. The pre-reset sha comes back in the result and is surfaced in the
+ // toast, so a mistake is still recoverable with `git reset --hard <sha>`.
+ const handleResetToDefault = async () => {
+ if (!repoPath || resetting) return;
+ setResetting(true);
+ setResetConfirm(false);
+ const result = await api.resetToDefaultBranch(repoPath, { silent: true }).catch((err) => {
+ toast.error(`Reset failed: ${err.message}`);
+ return null;
+ });
+ setResetting(false);
+ if (result?.success) {
+ // The server's counts, not the pre-click snapshot the dialog previewed.
+ const from = result.previousBranch && result.previousBranch !== result.branch
+ ? ` from ${result.previousBranch}`
+ : '';
+ toast.success(`Reset to origin/${result.branch}${from} — discarded ${result.discardedFiles} file change${result.discardedFiles === 1 ? '' : 's'}`);
+ if (result.previousHead) {
+ toast(`Previous state was ${result.previousHead.slice(0, 7)} — git reset --hard ${result.previousHead.slice(0, 7)} to undo`, { icon: '↩️' });
+ }
+ if (!result.fetched) {
+ toast('Could not reach origin — reset to the last fetched state', { icon: '⚠️' });
+ }
+ await loadGitData({ includeRemote: true });
+ }
+ };
+
+ const dirtyCount = gitInfo?.status?.files?.length || 0;
+
const getStatusIcon = (file) => {
if (file.added) return <Plus size={14} className="text-port-success" />;
if (file.deleted) return <Minus size={14} className="text-port-error" />;
@@ -395,9 +476,10 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {
return (
<div className="space-y-6">
- <div className="flex items-center justify-between">
+ {/* Wraps rather than overflows: three actions no longer fit one phone row. */}
+ <div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-semibold text-white">Git Status</h2>
- <div className="flex items-center gap-2">
+ <div className="flex flex-wrap items-center gap-2">
{branches.some(b => b.tracking && b.ahead > 0) && (
<button
onClick={handlePushAll}
@@ -416,6 +498,20 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {
<Download size={16} className={updating ? 'animate-bounce' : ''} />
{updating ? 'Updating...' : 'Update'}
</button>
+ <button
+ onClick={() => {
+ setResetConfirm(true);
+ // The dialog names how many files it is about to destroy, so it
+ // reads fresh state rather than whatever the last poll left.
+ loadGitInfo();
+ }}
+ disabled={resetting}
+ title="Discard local changes and match origin's default branch"
+ className="flex items-center gap-1.5 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm text-gray-300 hover:text-white hover:border-port-error disabled:opacity-50"
+ >
+ <RotateCcw size={16} className={resetting ? 'animate-spin' : ''} />
+ {resetting ? 'Resetting...' : 'Reset to origin'}
+ </button>
</div>
</div>
@@ -900,54 +996,55 @@ export default function GitTab({ appId: _appId, appName, repoPath }) {
</pre>
</Modal>
- {/* Release Confirmation Dialog */}
- <Modal
+ <ConfirmModal
open={showReleaseConfirm}
onClose={() => setShowReleaseConfirm(false)}
- size="md"
- align="none"
- backdropClassName="bg-black/50"
- panelClassName="bg-port-card border border-port-border rounded-xl overflow-hidden"
- ariaLabelledBy="git-release-modal-title"
+ titleId="git-release-modal-title"
+ icon={<Rocket size={18} className="text-port-accent" />}
+ title={`Create Release PR for ${appName}`}
+ confirmLabel="Start Release"
+ onConfirm={handleReleasePR}
>
- <div className="flex items-center justify-between p-4 border-b border-port-border">
- <h3 id="git-release-modal-title" className="font-medium text-white flex items-center gap-2">
- <Rocket size={18} className="text-port-accent" />
- Create Release PR for {appName}
- </h3>
- <button onClick={() => setShowReleaseConfirm(false)} aria-label="Close" className="text-gray-400 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center">×</button>
- </div>
- <div className="p-4 space-y-3">
- <p className="text-sm text-gray-300">
- This will create a CoS agent task to automate the full release workflow:
- </p>
- <ul className="text-sm text-gray-400 space-y-1.5 ml-4 list-disc">
- <li>Push local commits to origin/{gitInfo?.devBranch || 'dev'}</li>
- {gitInfo?.hasChangelog && <li>Check and update the changelog</li>}
- <li>Create PR from {gitInfo?.devBranch || 'dev'} to {gitInfo?.baseBranch || 'main'}</li>
- <li>Wait for Copilot review and address feedback</li>
- <li>Merge when approved and CI passes</li>
- </ul>
- <p className="text-xs text-gray-500">
- {branchComparison?.ahead || 0} commits will be included in this release.
- </p>
- </div>
- <div className="flex justify-end gap-3 p-4 border-t border-port-border">
- <button
- onClick={() => setShowReleaseConfirm(false)}
- className="px-4 py-2 text-sm text-gray-400 hover:text-white"
- >
- Cancel
- </button>
- <button
- onClick={handleReleasePR}
- className="flex items-center gap-2 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg text-sm"
- >
- <Rocket size={16} />
- Start Release
- </button>
- </div>
- </Modal>
+ <p className="text-sm text-gray-300">
+ This will create a CoS agent task to automate the full release workflow:
+ </p>
+ <ul className="text-sm text-gray-400 space-y-1.5 ml-4 list-disc">
+ <li>Push local commits to origin/{gitInfo?.devBranch || 'dev'}</li>
+ {gitInfo?.hasChangelog && <li>Check and update the changelog</li>}
+ <li>Create PR from {gitInfo?.devBranch || 'dev'} to {gitInfo?.baseBranch || 'main'}</li>
+ <li>Wait for Copilot review and address feedback</li>
+ <li>Merge when approved and CI passes</li>
+ </ul>
+ <p className="text-xs text-gray-500">
+ {branchComparison?.ahead || 0} commits will be included in this release.
+ </p>
+ </ConfirmModal>
+
+ {/* Destructive, so it spells out what goes and what survives rather than
+ asking "are you sure?". */}
+ <ConfirmModal
+ open={resetConfirm}
+ onClose={() => setResetConfirm(false)}
+ titleId="git-reset-modal-title"
+ icon={<RotateCcw size={18} className="text-port-error" />}
+ title={`Reset ${appName} to origin/${gitInfo?.baseBranch || 'main'}`}
+ tone="error"
+ confirmLabel={resetting ? 'Resetting...' : 'Discard and reset'}
+ onConfirm={handleResetToDefault}
+ busy={resetting}
+ >
+ <p className="text-sm text-gray-300">
+ Fetches origin, switches to the default branch, and hard-resets it to the remote.
+ </p>
+ <ul className="text-sm text-gray-400 space-y-1.5 ml-4 list-disc">
+ <li>Discards {dirtyCount} uncommitted file change{dirtyCount === 1 ? '' : 's'}</li>
+ <li>Discards any local commits on {gitInfo?.baseBranch || 'main'} that origin does not have</li>
+ <li>Keeps untracked files and every other local branch</li>
+ </ul>
+ <p className="text-xs text-gray-500">
+ The commit you are on now is reported after the reset, so <code>git reset --hard &lt;sha&gt;</code> can undo this.
+ </p>
+ </ConfirmModal>
</div>
);
}
diff --git a/client/src/components/apps/tabs/GitTab.test.jsx b/client/src/components/apps/tabs/GitTab.test.jsx
index a109ae9537..f3f6a404f5 100644
--- a/client/src/components/apps/tabs/GitTab.test.jsx
+++ b/client/src/components/apps/tabs/GitTab.test.jsx
@@ -9,6 +9,7 @@ vi.mock('../../../services/api', () => ({
getRemoteBranches: vi.fn(),
getGitDiff: vi.fn(),
cleanupMergedBranches: vi.fn(),
+ resetToDefaultBranch: vi.fn(),
}));
import * as api from '../../../services/api';
@@ -36,6 +37,7 @@ beforeEach(() => {
api.getRemoteBranches.mockResolvedValue({ branches: [], defaultBranch: 'main' });
api.getGitDiff.mockResolvedValue({ diff: '@@ -1 +1 @@\n-old\n+new' });
api.cleanupMergedBranches.mockResolvedValue({ deleted: [], skipped: [] });
+ api.resetToDefaultBranch.mockResolvedValue({ success: true, branch: 'main', previousBranch: 'main', previousHead: 'b'.repeat(40), head: 'a'.repeat(40), discardedFiles: 1, fetched: true });
});
afterEach(() => {
@@ -149,3 +151,56 @@ describe('GitTab merged branches checked out in worktrees', () => {
expect(screen.getAllByText('worktree')).toHaveLength(2);
});
});
+
+describe('GitTab reset to origin', () => {
+ it('confirms before resetting, and names what is discarded and what survives', async () => {
+ render(<GitTab appId="x" appName="App" repoPath="/repo" />);
+
+ fireEvent.click(await screen.findByText('Reset to origin'));
+
+ const dialog = await screen.findByRole('dialog');
+ expect(dialog).toHaveAttribute('aria-labelledby', 'git-reset-modal-title');
+ expect(document.getElementById('git-reset-modal-title')).toHaveTextContent('Reset App to origin/main');
+ // Scope is stated, not implied: one dirty file in GIT_INFO, untracked kept.
+ expect(dialog).toHaveTextContent('Discards 1 uncommitted file change');
+ expect(dialog).toHaveTextContent('Keeps untracked files');
+ // Opening the dialog alone must not touch the repo.
+ expect(api.resetToDefaultBranch).not.toHaveBeenCalled();
+ });
+
+ it('does not reset when the confirmation is cancelled', async () => {
+ render(<GitTab appId="x" appName="App" repoPath="/repo" />);
+
+ fireEvent.click(await screen.findByText('Reset to origin'));
+ fireEvent.click(await screen.findByText('Cancel'));
+
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+ expect(api.resetToDefaultBranch).not.toHaveBeenCalled();
+ });
+
+ it('refreshes the dirty-file count when the dialog opens', async () => {
+ render(<GitTab appId="x" appName="App" repoPath="/repo" />);
+ await screen.findByText('Reset to origin');
+ const onMount = api.getGitInfo.mock.calls.length;
+
+ fireEvent.click(screen.getByText('Reset to origin'));
+
+ // The dialog names how many files it will destroy, so it must not quote a
+ // count from whenever the tab last polled.
+ await waitFor(() => expect(api.getGitInfo.mock.calls.length).toBeGreaterThan(onMount));
+ });
+
+ it('resets on confirm and reloads git state', async () => {
+ render(<GitTab appId="x" appName="App" repoPath="/repo" />);
+
+ fireEvent.click(await screen.findByText('Reset to origin'));
+ await screen.findByRole('dialog');
+ const beforeConfirm = api.getGitInfo.mock.calls.length;
+
+ fireEvent.click(screen.getByText('Discard and reset'));
+
+ await waitFor(() => expect(api.resetToDefaultBranch).toHaveBeenCalledWith('/repo', { silent: true }));
+ // The tab re-reads git state rather than trusting its pre-reset snapshot.
+ await waitFor(() => expect(api.getGitInfo.mock.calls.length).toBeGreaterThan(beforeConfirm));
+ });
+});
diff --git a/client/src/services/apiGit.js b/client/src/services/apiGit.js
index 2b2c9bd90b..6157d5fc16 100644
--- a/client/src/services/apiGit.js
+++ b/client/src/services/apiGit.js
@@ -73,6 +73,14 @@ export const deleteBranch = (path, branch, { local = false, remote = false } = {
body: JSON.stringify({ path, branch, local, remote }),
...options
});
+// Destructive: discards tracked changes and local commits on the default
+// branch. Resolves with `previousHead` — the pre-reset sha, so the caller can
+// show a recovery handle.
+export const resetToDefaultBranch = (path, options = {}) => request('/git/reset-to-default', {
+ method: 'POST',
+ body: JSON.stringify({ path }),
+ ...options
+});
export const cleanupMergedBranches = (path, options = {}) => request('/git/cleanup-merged', {
method: 'POST',
body: JSON.stringify({ path }),
diff --git a/package.json b/package.json
index 2df5c4e408..4d7b70d134 100644
--- a/package.json
+++ b/package.json
@@ -7,14 +7,15 @@
"license": "MIT",
"type": "module",
"engines": {
- "node": ">=22.12.0"
+ "node": ">=22.12.0",
+ "npm": ">=12.0.0"
},
"scripts": {
- "dev": "node scripts/checkNodeVersion.js && node scripts/dev-start.js",
+ "dev": "node scripts/checkNodeVersion.js && node scripts/checkNpmVersion.js && node scripts/dev-start.js",
"dev:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs",
"eval:agent-context": "node scripts/agent-context-eval.js",
"build": "npm run build --prefix client",
- "start": "node scripts/checkNodeVersion.js && node scripts/ensure-deps.js && npm run build && node scripts/setup-db.js && node scripts/setup-cert.js && (node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent || echo pm2 delete skipped) && node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs && node ./node_modules/pm2/bin/pm2 save",
+ "start": "node scripts/checkNodeVersion.js && node scripts/checkNpmVersion.js && node scripts/ensure-deps.js && npm run build && node scripts/setup-db.js && node scripts/setup-cert.js && (node ./node_modules/pm2/bin/pm2 delete ecosystem.config.cjs --silent || echo pm2 delete skipped) && node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs && node ./node_modules/pm2/bin/pm2 save",
"pm2:start": "node ./node_modules/pm2/bin/pm2 start ecosystem.config.cjs",
"pm2:stop": "node ./node_modules/pm2/bin/pm2 stop ecosystem.config.cjs",
"pm2:restart": "node ./node_modules/pm2/bin/pm2 restart ecosystem.config.cjs",
@@ -24,7 +25,7 @@
"pm2:startup": "node ./node_modules/pm2/bin/pm2 startup",
"install:all": "npm run setup",
"migrations": "node scripts/run-migrations.js",
- "setup": "node scripts/checkNodeVersion.js && git submodule update --init --recursive && npm install && npm install --prefix client && npm install --prefix server && npm install --prefix autofixer && node scripts/trusted-rebuilds.js server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-llm.js && node scripts/setup-browser.js",
+ "setup": "node scripts/checkNodeVersion.js && node scripts/checkNpmVersion.js && git submodule update --init --recursive && npm install && npm install --prefix client && npm install --prefix server && npm install --prefix autofixer && node scripts/trusted-rebuilds.js server && node scripts/setup-data.js && node scripts/setup-db.js && node scripts/setup-llm.js && node scripts/setup-browser.js",
"setup:data": "node scripts/setup-data.js",
"setup:db": "node scripts/setup-db.js",
"setup:db:test": "npm run setup:db:test --prefix server",
diff --git a/scripts/checkNodeVersion.js b/scripts/checkNodeVersion.js
index ac57c3b9f6..4f94545ef6 100644
--- a/scripts/checkNodeVersion.js
+++ b/scripts/checkNodeVersion.js
@@ -23,8 +23,7 @@
* and is asserted to be >= this floor, not equal to it.
*/
-import { realpathSync } from 'fs';
-import { fileURLToPath } from 'url';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
/** The hard floor. Changing the version means changing exactly this string. */
export const MIN_NODE = '22.12.0';
@@ -77,30 +76,8 @@ export function assertNodeVersion({
return false;
}
-// Runnable directly: `node scripts/checkNodeVersion.js`.
-//
-// Both sides are realpath'd before comparing. Node's ESM loader resolves
-// symlinks when it builds `import.meta.url`, but `process.argv[1]` is whatever
-// the caller typed — so a repo reached through a symlinked parent (a checkout
-// under a symlinked home, /tmp → /private/tmp on macOS, a symlinked worktree)
-// makes the two spellings differ and the gate would silently no-op, exiting 0
-// on an unsupported Node. fileURLToPath/realpathSync also handle paths with
-// spaces or non-ASCII characters, which a `file://` string template does not.
-const invokedPath = process.argv[1];
-if (invokedPath) {
- const resolve = (p) => {
- try {
- return realpathSync(p);
- } catch {
- return p;
- }
- };
- // Case-fold on the case-insensitive filesystems (APFS, NTFS): there the two
- // spellings can differ only in case and still name the same file, and a
- // strict comparison would silently skip the check.
- const caseFold = process.platform === 'win32' || process.platform === 'darwin';
- const normalize = (p) => (caseFold ? resolve(p).toLowerCase() : resolve(p));
- if (normalize(fileURLToPath(import.meta.url)) === normalize(invokedPath)) {
- assertNodeVersion();
- }
+// Runnable directly: `node scripts/checkNodeVersion.js` — see lib/directInvocation.js
+// for why this comparison is not a plain string equality.
+if (isDirectlyInvoked(import.meta.url)) {
+ assertNodeVersion();
}
diff --git a/scripts/checkNpmVersion.js b/scripts/checkNpmVersion.js
new file mode 100644
index 0000000000..4017f0b3d0
--- /dev/null
+++ b/scripts/checkNpmVersion.js
@@ -0,0 +1,139 @@
+/**
+ * npm floor advisory — the reason the lockfiles keep showing up modified.
+ *
+ * Symptom: `client/package-lock.json` (and `server/`'s) appears in `git status`
+ * after every local `npm install`, deleting entries nobody edited — most
+ * visibly the `libc` arrays on the Linux-only Rollup/esbuild optional deps
+ * (`+0 / -66`, one file changed, over and over).
+ *
+ * Cause: npm's lockfile writer copies a fixed list of manifest fields into each
+ * entry — `pkgMetaKeys` in `@npmcli/arborist`'s `lib/shrinkwrap.js`. `libc` was
+ * only added to that list in arborist 10, which ships in npm 12. Dependabot
+ * runs a current npm, so every lockfile it opens a PR against carries `libc`;
+ * any install on npm 11 or older then rewrites the file without those fields,
+ * and the next Dependabot PR puts them back. Neither side is wrong — the two
+ * npm versions disagree about the schema, so the file ping-pongs forever. The
+ * same skew drops `peer: true` markers that npm 12 records.
+ *
+ * Why this warns instead of failing: no Node release bundles npm 12 yet (Node
+ * 24.10 ships npm 11.6.1), so gating `npm start` on it would break working
+ * installs over a file-formatting difference. An install on an older npm is
+ * correct — it just churns the lockfile. `npm install -g npm@latest` ends it.
+ *
+ * This advisory is the explainer, not the whole floor. The four `engines.npm`
+ * fields are the declarative half, and they are what covers the install paths
+ * this script never sees — `cd client && npm install`, `npm i <pkg>`, `npm ci`
+ * — because npm checks them itself and prints EBADENGINE. `engine-strict` stays
+ * off (see the .npmrc note: it would make one dependency's narrow range break
+ * every install), so those stay warnings too.
+ *
+ * The advisory also names the case that makes this confusing to diagnose: a
+ * stale global npm earlier on PATH than the one Node bundles, so `npm -v`
+ * reports a version far older than the Node in use would suggest.
+ */
+
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+
+import { compareVersions } from './checkNodeVersion.js';
+import { isDirectlyInvoked } from './lib/directInvocation.js';
+
+/**
+ * The first npm whose lockfile writer records `libc`. Changing this means
+ * changing exactly this string — scripts/checkNpmVersion.test.js pins the
+ * arborist/npm reasoning above to it.
+ */
+export const MIN_NPM = '12.0.0';
+
+/**
+ * Read the npm version out of the `npm_config_user_agent` npm exports to its
+ * run-scripts (`npm/9.6.0 node/v24.10.0 win32 x64 workspaces/false`). This is
+ * the npm actually running the install in the same script chain, which a
+ * `which npm` lookup is not guaranteed to be.
+ * @returns {string|null} - The version, or null when not running under npm
+ */
+export function parseNpmUserAgent(userAgent = process.env.npm_config_user_agent) {
+ const match = /(?:^|\s)npm\/(\d+(?:\.\d+)*)/.exec(String(userAgent));
+ return match ? match[1] : null;
+}
+
+/**
+ * The version of the npm that ships inside the running Node, so the advisory
+ * can tell "your npm is old" apart from "your npm is old *and* it isn't even
+ * the one Node gave you". Handles both install layouts: `<dir>/node_modules`
+ * next to the binary (Windows, and npm's own installer) and the POSIX
+ * `<prefix>/lib/node_modules` one.
+ * @returns {string|null} - The version, or null when it can't be read
+ */
+export function readBundledNpmVersion(execPath = process.execPath) {
+ const base = dirname(execPath);
+ const candidates = [
+ join(base, 'node_modules', 'npm', 'package.json'),
+ join(base, '..', 'lib', 'node_modules', 'npm', 'package.json')
+ ];
+ for (const candidate of candidates) {
+ try {
+ const { version } = JSON.parse(readFileSync(candidate, 'utf8'));
+ if (typeof version === 'string' && version) return version;
+ } catch {
+ // Not this layout (or an unreadable/corrupt manifest) — try the next.
+ }
+ }
+ return null;
+}
+
+/**
+ * The advisory lines for a given toolchain, or `[]` when nothing is wrong.
+ * Pure and injectable so the test can exercise every branch without an npm.
+ * @param {object} options
+ * @param {string|null} options.npmVersion - npm running the install
+ * @param {string|null} options.bundledNpmVersion - npm shipped with `nodeVersion`
+ * @param {string} options.nodeVersion - the running Node
+ * @returns {string[]} - Single-line messages, ready to print in order
+ */
+export function npmAdvisory({
+ npmVersion,
+ bundledNpmVersion = null,
+ nodeVersion = process.versions.node
+} = {}) {
+ // Not running under npm (a bare `node scripts/checkNpmVersion.js`, or a
+ // wrapper that stripped the env) — there is no install to warn about.
+ if (!npmVersion) return [];
+ if (compareVersions(npmVersion, MIN_NPM) >= 0) return [];
+
+ const lines = [
+ `⚠️ npm ${npmVersion} is below ${MIN_NPM} — installs will rewrite package-lock.json`,
+ 'ℹ️ Older npm drops the `libc` fields npm 12 records, so the lockfiles churn on every install and ping-pong with Dependabot'
+ ];
+
+ // The confusing case: PATH is resolving an older global npm ahead of the one
+ // Node bundles, so `npm -v` looks stuck in the past no matter which Node runs.
+ if (bundledNpmVersion && compareVersions(npmVersion, bundledNpmVersion) < 0) {
+ lines.push(
+ `ℹ️ Node v${String(nodeVersion).replace(/^v/, '')} bundles npm ${bundledNpmVersion}, but PATH resolves npm ${npmVersion} — an older global install is shadowing it`
+ );
+ }
+
+ lines.push('🔧 Fix: npm install -g npm@latest');
+ return lines;
+}
+
+/**
+ * Print the advisory. Always resolves to whether anything was reported — this
+ * never exits non-zero, so it is safe to chain ahead of a real install.
+ * @returns {boolean} - True when an advisory was printed
+ */
+export function warnOnOutdatedNpm({
+ npmVersion = parseNpmUserAgent(),
+ bundledNpmVersion = readBundledNpmVersion(),
+ warn = console.warn
+} = {}) {
+ const lines = npmAdvisory({ npmVersion, bundledNpmVersion });
+ for (const line of lines) warn(line);
+ return lines.length > 0;
+}
+
+// Runnable directly: `node scripts/checkNpmVersion.js`.
+if (isDirectlyInvoked(import.meta.url)) {
+ warnOnOutdatedNpm();
+}
diff --git a/scripts/checkNpmVersion.test.js b/scripts/checkNpmVersion.test.js
new file mode 100644
index 0000000000..fa02591f84
--- /dev/null
+++ b/scripts/checkNpmVersion.test.js
@@ -0,0 +1,170 @@
+/**
+ * Unit tests for the npm floor advisory.
+ *
+ * The gate exists because a lockfile written by npm 12 and re-written by npm 11
+ * or older differ by the `libc` fields, so `client/package-lock.json` shows up
+ * modified after every install. These tests pin the three things that make the
+ * advisory useful: it fires only below the floor, it never turns into a hard
+ * failure, and it names the shadowed-global-npm case that makes the version
+ * skew hard to spot.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { existsSync, readFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+import {
+ MIN_NPM,
+ npmAdvisory,
+ parseNpmUserAgent,
+ readBundledNpmVersion,
+ warnOnOutdatedNpm,
+} from './checkNpmVersion.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const readJson = (rel) => JSON.parse(readFileSync(join(REPO_ROOT, rel), 'utf8'));
+
+describe('MIN_NPM', () => {
+ it('is the npm major whose lockfile writer records `libc`', () => {
+ // arborist 10 added 'libc' to pkgMetaKeys and ships in npm 12; arborist 9
+ // (npm 11.6.1, bundled with Node 24.10) strips it. Anything below 12 churns
+ // the lockfile, so the floor is a whole major and has no patch nuance.
+ expect(MIN_NPM).toBe('12.0.0');
+ });
+});
+
+describe('parseNpmUserAgent', () => {
+ it('reads the version out of the user agent npm exports to run-scripts', () => {
+ expect(parseNpmUserAgent('npm/9.6.0 node/v24.10.0 win32 x64 workspaces/false')).toBe('9.6.0');
+ expect(parseNpmUserAgent('npm/12.0.2 node/v24.10.0 darwin arm64 workspaces/false')).toBe('12.0.2');
+ });
+
+ it('is not fooled by a lookalike earlier in the string', () => {
+ // `pnpm/9.0.0` ends in "npm/9.0.0"; only a token boundary counts.
+ expect(parseNpmUserAgent('pnpm/9.0.0 node/v24.10.0 linux x64')).toBeNull();
+ expect(parseNpmUserAgent('yarn/4.1.0 npm/? node/v24.10.0 linux x64')).toBeNull();
+ });
+
+ it('returns null when not running under npm', () => {
+ expect(parseNpmUserAgent(undefined)).toBeNull();
+ expect(parseNpmUserAgent('')).toBeNull();
+ expect(parseNpmUserAgent(null)).toBeNull();
+ });
+});
+
+describe('readBundledNpmVersion', () => {
+ it('returns null instead of throwing when no npm sits beside the binary', () => {
+ expect(readBundledNpmVersion(join(REPO_ROOT, 'no', 'such', 'node'))).toBeNull();
+ });
+
+ it('reads the running Node’s own bundled npm', () => {
+ // Every supported Node ships an npm; a null here means the layout probe
+ // stopped matching reality, which would silently drop the shadowing hint.
+ expect(readBundledNpmVersion()).toMatch(/^\d+\.\d+\.\d+/);
+ });
+});
+
+describe('npmAdvisory', () => {
+ it('says nothing on npm at or above the floor', () => {
+ expect(npmAdvisory({ npmVersion: MIN_NPM, bundledNpmVersion: '11.6.1' })).toEqual([]);
+ expect(npmAdvisory({ npmVersion: '12.4.0', bundledNpmVersion: '11.6.1' })).toEqual([]);
+ });
+
+ it('says nothing when there is no npm to warn about', () => {
+ // A bare `node scripts/checkNpmVersion.js` isn't running an install.
+ expect(npmAdvisory({ npmVersion: null })).toEqual([]);
+ expect(npmAdvisory({})).toEqual([]);
+ });
+
+ it('names the version, the floor, the symptom, and the fix below the floor', () => {
+ const lines = npmAdvisory({ npmVersion: '11.6.1', bundledNpmVersion: '11.6.1' });
+ const text = lines.join('\n');
+ expect(text).toContain('11.6.1');
+ expect(text).toContain(MIN_NPM);
+ expect(text).toContain('package-lock.json');
+ expect(text).toContain('libc');
+ expect(text).toContain('npm install -g npm@latest');
+ });
+
+ it('flags a stale global npm shadowing the one Node bundles', () => {
+ const lines = npmAdvisory({
+ npmVersion: '9.6.0',
+ bundledNpmVersion: '11.6.1',
+ nodeVersion: 'v24.10.0',
+ });
+ const shadow = lines.find((line) => line.includes('shadowing'));
+ expect(shadow).toBeTruthy();
+ expect(shadow).toContain('24.10.0');
+ expect(shadow).toContain('11.6.1');
+ expect(shadow).toContain('9.6.0');
+ // The `v` is supplied by the message, not doubled up from the input.
+ expect(shadow).not.toContain('vv');
+ });
+
+ it('omits the shadowing line when npm is the bundled one, or newer', () => {
+ const bundled = npmAdvisory({ npmVersion: '11.6.1', bundledNpmVersion: '11.6.1' });
+ expect(bundled.some((line) => line.includes('shadowing'))).toBe(false);
+ const newer = npmAdvisory({ npmVersion: '11.9.0', bundledNpmVersion: '11.6.1' });
+ expect(newer.some((line) => line.includes('shadowing'))).toBe(false);
+ });
+
+ it('omits the shadowing line when the bundled npm cannot be read', () => {
+ const lines = npmAdvisory({ npmVersion: '9.6.0', bundledNpmVersion: null });
+ expect(lines.some((line) => line.includes('shadowing'))).toBe(false);
+ expect(lines.join('\n')).toContain('npm install -g npm@latest');
+ });
+});
+
+describe('warnOnOutdatedNpm', () => {
+ it('prints each advisory line and reports that it warned', () => {
+ const warn = vi.fn();
+ const warned = warnOnOutdatedNpm({ npmVersion: '9.6.0', bundledNpmVersion: '11.6.1', warn });
+ expect(warned).toBe(true);
+ expect(warn.mock.calls.length).toBeGreaterThan(0);
+ // Single-line logging: no multi-line blobs, no JSON dumps.
+ for (const [line] of warn.mock.calls) expect(line).not.toContain('\n');
+ });
+
+ it('stays silent — and non-fatal — on a current npm', () => {
+ const warn = vi.fn();
+ expect(warnOnOutdatedNpm({ npmVersion: '12.0.2', bundledNpmVersion: '11.6.1', warn })).toBe(false);
+ expect(warn).not.toHaveBeenCalled();
+ });
+});
+
+describe('the advisory is actually reachable', () => {
+ it.each(['setup', 'start', 'dev'])('the root `%s` script runs it before installing', (name) => {
+ const script = readJson('package.json').scripts[name];
+ expect(script).toContain('node scripts/checkNpmVersion.js &&');
+ // After the Node gate (which is fatal) and before anything that installs.
+ expect(script.indexOf('checkNodeVersion.js')).toBeLessThan(script.indexOf('checkNpmVersion.js'));
+ });
+});
+
+describe('the floor is declared where npm itself reads it', () => {
+ // The three scripts above cover `npm run setup|start|dev` and nothing else.
+ // `cd client && npm install`, `npm i <pkg>` and `npm ci` are how the lockfile
+ // churn actually gets introduced, and only `engines.npm` reaches those.
+ const MANIFESTS = ['package.json', 'client/package.json', 'server/package.json', 'autofixer/package.json'];
+
+ it.each(MANIFESTS)('%s declares engines.npm = the floor', (rel) => {
+ expect(readJson(rel).engines?.npm).toBe(`>=${MIN_NPM}`);
+ });
+
+ it.each(MANIFESTS)('%s ships a lockfile that the floor protects', (rel) => {
+ // If a workspace stops carrying a lockfile, its engines.npm entry is just
+ // noise — this is what would say so.
+ const lockfile = join(REPO_ROOT, rel.replace(/package\.json$/, 'package-lock.json'));
+ expect(existsSync(lockfile), `${rel} declares engines.npm but ships no lockfile`).toBe(true);
+ });
+
+ it.each(['.npmrc', 'client/.npmrc', 'server/.npmrc', 'autofixer/.npmrc'])(
+ '%s leaves engine-strict off so the npm floor stays a warning',
+ (rel) => {
+ // engine-strict would turn EBADENGINE fatal for dependencies too, which is
+ // the trap the node floor already documents. A churned lockfile is not
+ // worth a broken install.
+ expect(readFileSync(join(REPO_ROOT, rel), 'utf8')).not.toMatch(/^\s*engine-strict\s*=\s*true/m);
+ }
+ );
+});
diff --git a/scripts/lib/directInvocation.js b/scripts/lib/directInvocation.js
new file mode 100644
index 0000000000..847a2a92c5
--- /dev/null
+++ b/scripts/lib/directInvocation.js
@@ -0,0 +1,41 @@
+/**
+ * "Was this module run directly, or imported?" — shared by the toolchain gates
+ * in scripts/ so each one can expose pure helpers to its test while still
+ * acting when invoked as `node scripts/<gate>.js`.
+ *
+ * The naive `import.meta.url === pathToFileURL(process.argv[1]).href` breaks in
+ * ways that matter here, because a gate that silently no-ops is worse than no
+ * gate at all:
+ * - Node's ESM loader resolves symlinks when it builds `import.meta.url`,
+ * while `process.argv[1]` is whatever the caller typed. A repo reached
+ * through a symlinked parent (a checkout under a symlinked home,
+ * /tmp → /private/tmp on macOS, a symlinked worktree) makes the two
+ * spellings differ, so both sides are realpath'd first.
+ * - APFS and NTFS are case-insensitive: two spellings can differ only in case
+ * and still name the same file, so those platforms compare case-folded.
+ * - fileURLToPath (rather than a `file://` string template) is what handles
+ * paths containing spaces or non-ASCII characters.
+ */
+
+import { realpathSync } from 'fs';
+import { fileURLToPath } from 'url';
+
+const resolve = (path) => {
+ try {
+ return realpathSync(path);
+ } catch {
+ return path;
+ }
+};
+
+/**
+ * True when `moduleUrl` names the script node was asked to run.
+ * @param {string} moduleUrl - The module's own `import.meta.url`
+ * @param {string} [invokedPath] - Defaults to `process.argv[1]`
+ */
+export function isDirectlyInvoked(moduleUrl, invokedPath = process.argv[1]) {
+ if (!invokedPath) return false;
+ const caseFold = process.platform === 'win32' || process.platform === 'darwin';
+ const normalize = (path) => (caseFold ? resolve(path).toLowerCase() : resolve(path));
+ return normalize(fileURLToPath(moduleUrl)) === normalize(invokedPath);
+}
diff --git a/server/package.json b/server/package.json
index 419d99aa6f..b01e635568 100644
--- a/server/package.json
+++ b/server/package.json
@@ -4,7 +4,8 @@
"private": true,
"type": "module",
"engines": {
- "node": ">=22.12.0"
+ "node": ">=22.12.0",
+ "npm": ">=12.0.0"
},
"scripts": {
"dev": "node --watch index.js",
diff --git a/server/routes/git.js b/server/routes/git.js
index f8b228b997..a712ddabb5 100644
--- a/server/routes/git.js
+++ b/server/routes/git.js
@@ -249,6 +249,17 @@ router.post('/checkout-remote', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/git/reset-to-default - Discard local changes and match origin's
+// default branch. Destructive on tracked files; untracked ones are kept, and
+// the response carries the pre-reset HEAD so the caller can offer a recovery
+// sha. See git.resetToDefaultBranch for the full contract.
+router.post('/reset-to-default', asyncHandler(async (req, res) => {
+ const { path } = req.body;
+ assertAllowedWorkspace(path);
+ const result = await git.resetToDefaultBranch(path);
+ res.json(result);
+}));
+
// POST /api/git/cleanup-merged - Delete all merged branches (local + remote)
router.post('/cleanup-merged', asyncHandler(async (req, res) => {
const { path } = req.body;
diff --git a/server/services/git.js b/server/services/git.js
index 37bc68031a..5cc884f55a 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -1,6 +1,6 @@
import { spawn } from '../lib/childProcess.js';
import { existsSync } from 'fs';
-import { join } from 'path';
+import { join, resolve } from 'path';
import { safeJSONParse, PATHS, sleep } from '../lib/fileUtils.js';
import { isGitLockError, listWorktrees } from './worktreeManager.js';
import { execGit } from '../lib/execGit.js';
@@ -1163,6 +1163,122 @@ export async function checkoutRemoteBranch(dir, branchName) {
return { success: true, branch: branchName };
}
+/**
+ * The id of a running CoS agent whose workspace IS `dir`, or null when none is.
+ * Paths are compared after `resolve` so a trailing slash or a `..` segment on
+ * either side doesn't let a live run slip past the check.
+ *
+ * Imported lazily: `services/git.js` is on the boot path and the agent
+ * lifecycle module is not, so a static import would drag agent state into
+ * every consumer of a git helper.
+ * @param {string} dir - Repo root to check
+ * @returns {Promise<string|null>} - Agent id, or null
+ */
+async function findActiveAgentInWorkspace(dir) {
+ const { getAgents } = await import('./cosAgentLifecycle.js').catch(() => ({ getAgents: null }));
+ if (!getAgents) return null;
+ const agents = await getAgents().catch(() => []);
+ const target = resolve(dir);
+ const busy = agents.find(agent =>
+ agent.status === 'running'
+ && agent.metadata?.workspacePath
+ && resolve(agent.metadata.workspacePath) === target
+ );
+ return busy?.id || null;
+}
+
+/**
+ * Throw away every local change and put the checkout back on origin's default
+ * branch, exactly as the remote has it. The escape hatch for a checkout that
+ * has drifted — a lockfile a local toolchain keeps rewriting, a half-finished
+ * edit, a branch left behind by an interrupted operation.
+ *
+ * Deliberately narrower than "make it look like a fresh clone":
+ * - Tracked modifications and local commits on the default branch go away;
+ * `previousHead` comes back in the result so `git reset --hard <sha>`
+ * recovers them (the commits stay in the reflog for git's gc window).
+ * - Untracked files stay. There is no `git clean` here: a checkout's
+ * untracked set is where `.env` files, build output, and scratch work live,
+ * and losing those is not recoverable from a reflog.
+ * - Other local branches are untouched — this moves the default branch only.
+ *
+ * A fetch failure is not fatal: the reset falls back to the cached
+ * `origin/<default>` ref so an offline machine can still get back to a known
+ * state, and `fetched: false` says the target may be behind the remote.
+ *
+ * @param {string} dir - Working directory (a repo root, not a linked worktree)
+ * @returns {Promise<{success: boolean, branch: string, previousBranch: string|null,
+ * previousHead: string|null, discardedFiles: number, fetched: boolean}>}
+ */
+export async function resetToDefaultBranch(dir) {
+ // A linked worktree cannot check out the default branch — the main checkout
+ // already holds it — and hard-resetting one would discard an agent's
+ // in-flight work on a branch that is not the default anyway. Fail with a
+ // reason instead of surfacing git's "already checked out" further down. The
+ // two dirs differ only in a linked worktree, and rev-parse answers both flags
+ // in one spawn, one value per line.
+ const dirs = await execGitSafe(['rev-parse', '--git-dir', '--git-common-dir'], dir);
+ const [gitDir, commonDir] = dirs.stdout.trim().split('\n').map(line => line.trim());
+ if (gitDir && commonDir && gitDir !== commonDir) {
+ throw new ServerError('cannot reset a linked worktree — run this on the main checkout', {
+ status: 400,
+ code: 'WORKTREE_RESET_REFUSED'
+ });
+ }
+
+ // A CoS agent without a worktree works directly in the checkout it was given
+ // (agentWorkspacePrep only isolates when the task asks for it), so resetting
+ // under a running one destroys tracked edits it is still producing and moves
+ // HEAD beneath a live process. primaryCheckoutGuard.js already treats
+ // `reset --hard` on the primary checkout as a decision a human makes
+ // deliberately — this keeps that decision from landing on top of a run.
+ const busyAgent = await findActiveAgentInWorkspace(dir);
+ if (busyAgent) {
+ throw new ServerError(
+ `a CoS agent (${busyAgent}) is running in this checkout — stop it before resetting`,
+ { status: 409, code: 'AGENT_RUNNING' }
+ );
+ }
+
+ const fetched = await fetchOrigin(dir).then(() => true).catch(() => false);
+
+ // A failed fetch already told us the remote is unreachable, so skip
+ // getDefaultBranch's `remote set-head` probe rather than stall on its timeout.
+ const branch = await getDefaultBranch(dir, { allowRemote: fetched });
+ if (!branch) {
+ throw new ServerError('could not determine the default branch', { status: 400, code: 'NO_DEFAULT_BRANCH' });
+ }
+
+ const target = `origin/${branch}`;
+ const targetRef = await execGitSafe(['rev-parse', '--verify', `refs/remotes/${target}`], dir);
+ if (targetRef.exitCode !== 0 || !targetRef.stdout.trim()) {
+ throw new ServerError(`no ${target} ref to reset to`, { status: 400, code: 'NO_REMOTE_REF' });
+ }
+
+ // `rev-parse` takes both spellings of HEAD in one spawn: the sha, then the
+ // branch name. `getStatusPorcelain` is the cheap half of `getStatus` — a
+ // line count is all the caller needs, not a parsed per-file breakdown.
+ const [headBefore, dirty] = await Promise.all([
+ execGitSafe(['rev-parse', 'HEAD', '--abbrev-ref', 'HEAD'], dir),
+ getStatusPorcelain(dir).catch(() => '')
+ ]);
+ const [previousHead = null, previousBranch = null] = headBefore.stdout.trim().split('\n').map(line => line.trim());
+
+ // `checkout --force -B` is the whole operation: `-B` repoints the local branch
+ // at the remote ref and `--force` resets index AND working tree to it, so a
+ // trailing `reset --hard` would re-walk every tracked file to change nothing.
+ await execGit(['checkout', '--force', '-B', branch, target], dir);
+
+ return {
+ success: true,
+ branch,
+ previousBranch,
+ previousHead,
+ discardedFiles: dirty ? dirty.split('\n').filter(Boolean).length : 0,
+ fetched
+ };
+}
+
/**
* Delete all merged branches (local and remote) in one operation.
* Skips the `PROTECTED_BRANCHES` set (see `../lib/gitArgs.js`), the current branch,
diff --git a/server/services/git.resetToDefault.test.js b/server/services/git.resetToDefault.test.js
new file mode 100644
index 0000000000..b79dc9a70c
--- /dev/null
+++ b/server/services/git.resetToDefault.test.js
@@ -0,0 +1,179 @@
+/**
+ * Tests for the "reset to origin's default branch" escape hatch behind the
+ * Apps → Git tab button.
+ *
+ * The whole point of the operation is that it destroys work, so the things
+ * worth pinning are its guard rails: it refuses to run in a linked worktree or
+ * under a live CoS agent, it reports the pre-reset sha so the destruction is
+ * undoable, it never runs `git clean` (untracked files survive), and an
+ * unreachable origin degrades to the cached ref instead of failing.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const execGitMock = vi.hoisted(() => vi.fn());
+const getAgentsMock = vi.hoisted(() => vi.fn());
+
+vi.mock('../lib/execGit.js', () => ({
+ execGit: execGitMock
+}));
+
+vi.mock('./cosAgentLifecycle.js', () => ({
+ getAgents: getAgentsMock
+}));
+
+import { resetToDefaultBranch, clearFetchCache } from './git.js';
+
+const ok = (stdout = '') => ({ stdout, stderr: '', exitCode: 0 });
+
+/** Args a call was made with, joined for readable matching. */
+const key = (args) => args.join(' ');
+
+/**
+ * Drive execGit from a table of `'joined args' -> result`, so each test states
+ * only the responses it cares about. Unlisted commands resolve empty, which is
+ * what the optional probes in getDefaultBranch expect.
+ */
+function routeGit(table) {
+ execGitMock.mockImplementation((args) => {
+ const entry = table[key(args)];
+ if (entry instanceof Error) return Promise.reject(entry);
+ return Promise.resolve(entry ?? ok());
+ });
+}
+
+const HAPPY_PATH = {
+ // rev-parse prints one line per flag, so both dirs come back in one spawn.
+ 'rev-parse --git-dir --git-common-dir': ok('.git\n.git'),
+ 'fetch origin': ok(),
+ 'symbolic-ref --short refs/remotes/origin/HEAD': ok('origin/main'),
+ 'rev-parse --verify refs/remotes/origin/main': ok('a'.repeat(40)),
+ // Same trick for HEAD: the sha, then the branch name it is on.
+ 'rev-parse HEAD --abbrev-ref HEAD': ok(`${'b'.repeat(40)}\nfeature/wip`),
+ 'status --porcelain': ok(' M client/package-lock.json\n M server/index.js'),
+ 'checkout --force -B main origin/main': ok()
+};
+
+/** Every command the run issued, joined — for "did it / didn't it" assertions. */
+const calledCommands = () => execGitMock.mock.calls.map(([args]) => key(args));
+
+beforeEach(() => {
+ execGitMock.mockReset();
+ getAgentsMock.mockReset();
+ getAgentsMock.mockResolvedValue([]);
+ clearFetchCache();
+});
+
+describe('resetToDefaultBranch', () => {
+ it('fetches, then points the default branch at origin and checks it out', async () => {
+ routeGit(HAPPY_PATH);
+
+ const result = await resetToDefaultBranch('/repo');
+
+ expect(result.success).toBe(true);
+ expect(result.branch).toBe('main');
+ expect(result.fetched).toBe(true);
+ expect(calledCommands()).toEqual(
+ expect.arrayContaining(['fetch origin', 'checkout --force -B main origin/main'])
+ );
+ });
+
+ it('does not follow the forced checkout with a redundant reset --hard', async () => {
+ // `checkout --force -B` already resets index AND working tree to the target
+ // (verified against real git with staged adds, modifications and deletes),
+ // so a trailing `reset --hard` re-walks every tracked file to change nothing.
+ routeGit(HAPPY_PATH);
+
+ await resetToDefaultBranch('/repo');
+
+ expect(calledCommands().some((cmd) => cmd.startsWith('reset --hard'))).toBe(false);
+ });
+
+ it('reports the pre-reset branch, sha, and dirty-file count so the reset is undoable', async () => {
+ routeGit(HAPPY_PATH);
+
+ const result = await resetToDefaultBranch('/repo');
+
+ expect(result.previousBranch).toBe('feature/wip');
+ expect(result.previousHead).toBe('b'.repeat(40));
+ expect(result.discardedFiles).toBe(2);
+ });
+
+ it('never runs git clean — untracked files are not recoverable from a reflog', async () => {
+ routeGit(HAPPY_PATH);
+
+ await resetToDefaultBranch('/repo');
+
+ expect(calledCommands().some((cmd) => cmd.startsWith('clean'))).toBe(false);
+ });
+
+ it('refuses to reset a linked worktree', async () => {
+ routeGit({
+ ...HAPPY_PATH,
+ 'rev-parse --git-dir --git-common-dir': ok('/repo/.git/worktrees/agent-1\n/repo/.git')
+ });
+
+ await expect(resetToDefaultBranch('/repo/wt')).rejects.toThrow(/linked worktree/);
+ // Refused before anything touched the working tree.
+ expect(calledCommands().some((cmd) => cmd.startsWith('checkout'))).toBe(false);
+ });
+
+ it('refuses while a CoS agent is running in the same checkout', async () => {
+ // Agents spawned without a worktree work directly in the checkout, so a
+ // reset would discard edits a live run is still writing.
+ routeGit(HAPPY_PATH);
+ getAgentsMock.mockResolvedValue([
+ { id: 'agent-live', status: 'running', metadata: { workspacePath: '/repo/' } }
+ ]);
+
+ await expect(resetToDefaultBranch('/repo')).rejects.toThrow(/agent-live/);
+ expect(calledCommands().some((cmd) => cmd.startsWith('checkout'))).toBe(false);
+ });
+
+ it('ignores agents that finished, or that are running somewhere else', async () => {
+ routeGit(HAPPY_PATH);
+ getAgentsMock.mockResolvedValue([
+ { id: 'agent-done', status: 'completed', metadata: { workspacePath: '/repo' } },
+ { id: 'agent-elsewhere', status: 'running', metadata: { workspacePath: '/other-repo' } },
+ { id: 'agent-worktree', status: 'running', metadata: { workspacePath: '/repo/wt' } }
+ ]);
+
+ await expect(resetToDefaultBranch('/repo')).resolves.toMatchObject({ success: true });
+ });
+
+ it('falls back to the cached ref when origin is unreachable', async () => {
+ routeGit({
+ ...HAPPY_PATH,
+ 'fetch origin': new Error('fatal: unable to access origin: Could not resolve host')
+ });
+
+ const result = await resetToDefaultBranch('/repo');
+
+ expect(result.fetched).toBe(false);
+ expect(result.success).toBe(true);
+ expect(calledCommands()).toContain('checkout --force -B main origin/main');
+ });
+
+ it('refuses when the default branch cannot be determined', async () => {
+ routeGit({
+ 'rev-parse --git-dir --git-common-dir': ok('.git\n.git'),
+ 'fetch origin': ok(),
+ // No origin/HEAD, no local branches, and a detached HEAD leave nothing to
+ // resolve — every getDefaultBranch fallback comes back empty.
+ 'rev-parse --abbrev-ref HEAD': ok('HEAD')
+ });
+
+ await expect(resetToDefaultBranch('/repo')).rejects.toThrow(/default branch/);
+ });
+
+ it('refuses when there is no origin ref to reset to', async () => {
+ routeGit({
+ ...HAPPY_PATH,
+ // origin/HEAD names a branch whose remote-tracking ref is gone.
+ 'rev-parse --verify refs/remotes/origin/main': { stdout: '', stderr: 'fatal: Needed a single revision', exitCode: 1 },
+ 'branch --list': ok('* main')
+ });
+
+ await expect(resetToDefaultBranch('/repo')).rejects.toThrow(/origin\/main/);
+ expect(calledCommands().some((cmd) => cmd.startsWith('checkout'))).toBe(false);
+ });
+});