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
test: reset git test sandboxes in place instead of copy+delete per test (#6003)
Adam Eivy6ec4e7008ba1
diff --git a/server/lib/README.md b/server/lib/README.mdindex 22b80f4c0b..a0a7ec34f5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -510,7 +510,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| Module | Purpose ||---|---|| `dbTestGate.js` | `requireDbOrSkip(label, dbReady, reason)` keeps a missing local test database as a visible skipped suite, but throws when `PORTOS_REQUIRE_DB` is set so CI cannot pass after DB-backed suites disappear. |-| `gitTestRepo.js` | Shared real-git sandbox for integration tests (#4394): one initialized template (working tree + bare origin) per worker, then `fs.cp` into a fresh temp dir. `makeGitSandbox({ origin })`, `attachBareOrigin(scratch, repo)`, `materializeGitRepo(dest)`, `destroyGitSandbox`, plus `SKIP_HEAVY_INTEGRATION` (`VITEST_FAST=1`). Every entry point runs `assertTempPath` first, so a path outside `os.tmpdir()` throws instead of `git init`-ing or `rm -rf`-ing a real checkout (#4554). Still real git — just not rebuilt from `init`+`commit`+`push` in every `beforeEach`. |+| `gitTestRepo.js` | Shared real-git sandbox for integration tests (#4394): one initialized template (working tree + bare origin) per worker, then `fs.cp` into a fresh temp dir. `makeGitSandbox({ origin })`, `attachBareOrigin(scratch, repo)`, `materializeGitRepo(dest)`, `destroyGitSandbox`, plus `SKIP_HEAVY_INTEGRATION` (`VITEST_FAST=1`). `resetGitSandbox({ scratch, repo, initialHead })` / `resetGitWorktreeSandbox(repo, initialHead)` restore a sandbox in place (branches, worktrees, remote) so a `describe` can build one sandbox in `beforeAll` and reset between tests instead of paying the fs.cp/rm cycle per test (#5902). Every entry point runs `assertTempPath` first, so a path outside `os.tmpdir()` throws instead of `git init`-ing or `rm -rf`-ing a real checkout (#4554). Still real git — just not rebuilt from `init`+`commit`+`push` in every `beforeEach`. || `mirrorParity.js` | Source-comparison primitives for the `*.mirror.test.js` server↔client parity tests: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), `compareDeclaration(serverSrc, clientSrc, name)`, and `compareRegexDeclaration(serverSrc, clientSrc, serverName, clientName?)` / `regexAlternationSource(declText)` (for a regex spelled as a `new RegExp([…].join('|'), 'i')` array on one side and an inline `/…/i` literal on the other — compares what it matches, not how it is typeset, and returns `null` rather than a partial read on any shape it can't decode). Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. || `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` and no-peer record creation guards. || `settingsTestUtil.js` | `bindSettingsFile(dataRoot)` → `writeSettingsFile`/`mergeSettingsFile`: direct settings.json disk writes that also drop the `getSettings()` read cache (dynamic-import reset) so a stale cache can't survive a bypass-`save()` write. |diff --git a/server/lib/gitTestRepo.js b/server/lib/gitTestRepo.jsindex 6353c9b41e..c6f1b19574 100644--- a/server/lib/gitTestRepo.js+++ b/server/lib/gitTestRepo.js@@ -11,9 +11,9 @@* Pure-logic tests should not call these helpers at all.*/import { mkdtemp, rm, writeFile, cp, mkdir, readdir } from 'fs/promises';-import { rmSync } from 'fs';+import { rmSync, existsSync, readFileSync } from 'fs';import { tmpdir } from 'os';-import { join } from 'path';+import { join, basename } from 'path';import { execGit } from './execGit.js';import { assertTempPath } from './tempPathGuard.js';@@ -157,6 +157,85 @@ export async function materializeGitRepo(dest, { identity } = {}) {return dest;}+/**+ * Restore `repo` to a known-clean state in place — for suites that share one+ * sandbox across a whole `describe` (built once in `beforeAll`) instead of+ * paying `makeGitSandbox()`'s fs.cp + `destroyGitSandbox()`'s recursive+ * delete on every test. Discards working-tree changes, deletes every branch+ * but `main`, resets `main` back to `initialHead`, drops the `origin` remote,+ * and (when `scratch` is given) wipes any sibling directory a test created+ * under it — a bare `origin.git` from `attachBareOrigin()`, or a contributor+ * clone from a pull/push helper — so the next test starts from a bare repo+ * again. `initialHead` is the sha `repo` was at right after it was built+ * (capture it once with `execGit(['rev-parse', 'HEAD'], repo)` in `beforeAll`,+ * before any test has run).+ */+export async function resetGitSandbox({ scratch, repo, initialHead }) {+ assertTempPath(repo, 'git sandbox reset');+ // A test can delete `repo` itself (simulating a checkout that vanished+ // mid-run) — rebuild it from the template rather than handing every git+ // call below a cwd that no longer exists.+ if (!existsSync(repo)) {+ const template = await getTemplate();+ await copyTree(template.repo, repo);+ }+ const gitDir = join(repo, '.git');+ // Every git subprocess costs real wall time (spawn overhead alone runs+ // tens of ms, worse on Windows) — skip the ones our own tests never+ // actually need instead of always paying for a no-op `--abort`/`remove`.+ if (existsSync(join(gitDir, 'MERGE_HEAD'))) {+ await execGit(['merge', '--abort'], repo, { ignoreExitCode: true });+ }+ if (existsSync(join(gitDir, 'CHERRY_PICK_HEAD'))) {+ await execGit(['cherry-pick', '--abort'], repo, { ignoreExitCode: true });+ }+ if (existsSync(join(gitDir, 'rebase-merge')) || existsSync(join(gitDir, 'rebase-apply'))) {+ await execGit(['rebase', '--abort'], repo, { ignoreExitCode: true });+ }+ await execGit(['checkout', '-f', 'main'], repo, { ignoreExitCode: true });+ await execGit(['clean', '-fdx'], repo);+ const { stdout } = await execGit(['branch', '--format=%(refname:short)'], repo);+ const branches = stdout.split('\n').map((b) => b.trim()).filter((b) => b && b !== 'main');+ if (branches.length) await execGit(['branch', '-D', ...branches], repo, { ignoreExitCode: true });+ await execGit(['reset', '--hard', initialHead], repo);+ let hasOrigin = false;+ try {+ hasOrigin = /\[remote "origin"\]/.test(readFileSync(join(gitDir, 'config'), 'utf8'));+ } catch { /* no config to read — nothing to remove */ }+ if (hasOrigin) await execGit(['remote', 'remove', 'origin'], repo, { ignoreExitCode: true });+ if (scratch) {+ const keep = basename(repo);+ const entries = await readdir(scratch, { withFileTypes: true }).catch(() => []);+ await Promise.all(entries+ .filter((entry) => entry.name !== keep)+ .map((entry) => rm(join(scratch, entry.name), { recursive: true, force: true }).catch(() => {})));+ }+}++/**+ * Same contract as `resetGitSandbox()`, plus tearing down every real+ * `git worktree add` checkout `repo` has grown since the last reset+ * (including a locked one) — for suites whose tests exercise worktree+ * creation/removal directly rather than just branches and commits.+ */+export async function resetGitWorktreeSandbox(repo, initialHead) {+ assertTempPath(repo, 'git worktree sandbox reset');+ const { stdout } = await execGit(['worktree', 'list', '--porcelain'], repo);+ // Each block is `worktree <path>\n[HEAD ...\n][branch ...\n][locked[ <reason>]\n]`.+ // Skip the first block — it's always `repo` itself, never a grown worktree.+ const entries = stdout.split('\n\n').slice(1).map((block) => ({+ path: block.match(/^worktree (.+)$/m)?.[1],+ locked: /^locked\b/m.test(block),+ })).filter((entry) => entry.path);+ for (const { path, locked } of entries) {+ if (locked) await execGit(['worktree', 'unlock', path], repo, { ignoreExitCode: true });+ await execGit(['worktree', 'remove', '--force', path], repo, { ignoreExitCode: true });+ await rm(path, { recursive: true, force: true }).catch(() => {});+ }+ if (entries.length) await execGit(['worktree', 'prune'], repo, { ignoreExitCode: true });+ await resetGitSandbox({ repo, initialHead });+}+export async function destroyGitSandbox(scratch) {if (!scratch) return;assertTempPath(scratch, 'recursive sandbox delete');diff --git a/server/lib/gitTestRepo.test.js b/server/lib/gitTestRepo.test.jsindex 88d289faa5..6605661451 100644--- a/server/lib/gitTestRepo.test.js+++ b/server/lib/gitTestRepo.test.js@@ -1,5 +1,5 @@import { describe, it, expect, afterEach } from 'vitest';-import { mkdtemp, writeFile } from 'fs/promises';+import { mkdtemp, writeFile, readdir } from 'fs/promises';import { existsSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -9,6 +9,8 @@ import {attachBareOrigin,materializeGitRepo,destroyGitSandbox,+ resetGitSandbox,+ resetGitWorktreeSandbox,} from './gitTestRepo.js';describe('template exit hook', () => {@@ -89,3 +91,69 @@ describe('attachBareOrigin / materializeGitRepo', () => {expect((await execGit(['config', 'user.email'], dest)).stdout.trim()).toBe('[email protected]');});});++describe('resetGitSandbox', () => {+ it('discards branches, commits, the origin remote, and scratch siblings back to the initial state', async () => {+ const box = await makeGitSandbox({ prefix: 'portos-git-fx-reset-' });+ sandboxes.push(box.scratch);+ const initialHead = (await execGit(['rev-parse', 'HEAD'], box.repo)).stdout.trim();++ await attachBareOrigin(box.scratch, box.repo);+ await execGit(['checkout', '-b', 'feature'], box.repo);+ await writeFile(join(box.repo, 'work.txt'), 'wip');+ await execGit(['add', '-A'], box.repo);+ await execGit(['commit', '-m', 'feature work'], box.repo);+ await writeFile(join(box.repo, 'untracked.txt'), 'scratch');++ await resetGitSandbox({ scratch: box.scratch, repo: box.repo, initialHead });++ expect((await execGit(['rev-parse', 'HEAD'], box.repo)).stdout.trim()).toBe(initialHead);+ expect((await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], box.repo)).stdout.trim()).toBe('main');+ const branches = (await execGit(['branch', '--format=%(refname:short)'], box.repo)).stdout.trim();+ expect(branches).toBe('main');+ expect((await execGit(['remote'], box.repo)).stdout.trim()).toBe('');+ expect(existsSync(join(box.repo, 'untracked.txt'))).toBe(false);+ const scratchEntries = await readdir(box.scratch);+ expect(scratchEntries).toEqual(['primary']);+ });++ it('is safe to call on a plain repo with no scratch wrapper', async () => {+ const dest = await mkdtemp(join(tmpdir(), 'portos-git-fx-reset-plain-'));+ sandboxes.push(dest);+ await materializeGitRepo(dest);+ const initialHead = (await execGit(['rev-parse', 'HEAD'], dest)).stdout.trim();+ await execGit(['checkout', '-b', 'wip'], dest);+ await writeFile(join(dest, 'work.txt'), 'wip');+ await execGit(['add', '-A'], dest);+ await execGit(['commit', '-m', 'wip'], dest);++ await resetGitSandbox({ repo: dest, initialHead });++ expect((await execGit(['rev-parse', 'HEAD'], dest)).stdout.trim()).toBe(initialHead);+ expect((await execGit(['branch', '--format=%(refname:short)'], dest)).stdout.trim()).toBe('main');+ });+});++describe('resetGitWorktreeSandbox', () => {+ it('removes every worktree it grew, including a locked one, and restores main', async () => {+ const dest = await mkdtemp(join(tmpdir(), 'portos-git-fx-reset-wt-'));+ sandboxes.push(dest);+ await materializeGitRepo(dest);+ const initialHead = (await execGit(['rev-parse', 'HEAD'], dest)).stdout.trim();++ const wtA = await mkdtemp(join(tmpdir(), 'portos-git-fx-reset-wt-a-'));+ const wtB = await mkdtemp(join(tmpdir(), 'portos-git-fx-reset-wt-b-'));+ sandboxes.push(wtA, wtB);+ await execGit(['worktree', 'add', '-b', 'wt-a', wtA, 'main'], dest);+ await execGit(['worktree', 'add', '-b', 'wt-b', wtB, 'main'], dest);+ await execGit(['worktree', 'lock', wtB], dest);++ await resetGitWorktreeSandbox(dest, initialHead);++ const listing = (await execGit(['worktree', 'list', '--porcelain'], dest)).stdout;+ expect(listing).not.toContain('wt-a');+ expect(listing).not.toContain('wt-b');+ expect((await execGit(['branch', '--format=%(refname:short)'], dest)).stdout.trim()).toBe('main');+ expect((await execGit(['rev-parse', 'HEAD'], dest)).stdout.trim()).toBe(initialHead);+ });+});diff --git a/server/lib/primaryCheckoutGuard.test.js b/server/lib/primaryCheckoutGuard.test.jsindex acf6fad6f0..59750075f2 100644--- a/server/lib/primaryCheckoutGuard.test.js+++ b/server/lib/primaryCheckoutGuard.test.js@@ -10,7 +10,7 @@* `VITEST_FAST=1` skips the real-git describes and keeps the prose helpers.*/-import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';import { rm, writeFile } from 'fs/promises';import { join } from 'path';import { execGit } from './execGit.js';@@ -18,6 +18,7 @@ import {makeGitSandbox,attachBareOrigin,destroyGitSandbox,+ resetGitSandbox,SKIP_HEAVY_INTEGRATION,} from './gitTestRepo.js';import {@@ -76,12 +77,25 @@ async function pullFromOrigin(subject) {await execGit(['pull', '--ff-only'], repo);}+/**+ * One real sandbox per `describe`, reset in place between tests instead of+ * `fs.cp`-ing a fresh copy and recursively deleting it every time (#5902) —+ * the sandbox itself is already a cheap `cp` of a per-worker template+ * (`gitTestRepo.js`), so the remaining cost on a slow filesystem (Windows)+ * is that copy-and-delete cycle repeating once per test.+ */function useGitSandbox() {+ let sandbox;+ beforeAll(async () => {+ sandbox = await makeGitSandbox({ prefix: 'portos-branch-jack-' });+ sandbox.initialHead = (await execGit(['rev-parse', 'HEAD'], sandbox.repo)).stdout.trim();+ });beforeEach(async () => {- ({ scratch, repo } = await makeGitSandbox({ prefix: 'portos-branch-jack-' }));+ await resetGitSandbox(sandbox);+ ({ scratch, repo } = sandbox);});- afterEach(async () => {- await destroyGitSandbox(scratch);+ afterAll(async () => {+ await destroyGitSandbox(sandbox.scratch);});}diff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.jsindex ce1dd9321a..173104015f 100644--- a/server/services/worktreeReap.test.js+++ b/server/services/worktreeReap.test.js@@ -10,13 +10,18 @@* Repos are copied from the shared `gitTestRepo.js` template. The whole file* is excluded from `npm run test:fast` (`VITEST_FAST=1`).*/-import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';import { mkdtemp, rm, writeFile, mkdir } from 'fs/promises';import { existsSync, realpathSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { execGit } from '../lib/execGit.js';-import { materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';+import {+ materializeGitRepo,+ resetGitSandbox,+ resetGitWorktreeSandbox,+ SKIP_HEAVY_INTEGRATION,+} from '../lib/gitTestRepo.js';import { isBranchMergedInto } from './git.js';import { reapMergedWorktrees } from './worktreeManager.js';@@ -52,8 +57,17 @@ async function initRepo() {describe.skipIf(SKIP_HEAVY_INTEGRATION)('isBranchMergedInto', () => {let dir;- beforeEach(async () => { dir = await initRepo(); });- afterEach(async () => { await rm(dir, { recursive: true, force: true }); });+ let initialHead;+ // One real repo for the whole describe, reset in place between tests+ // instead of a fresh mkdtemp + materializeGitRepo (fs.cp) + rm per test+ // (#5902) — the slow part on a Windows filesystem is that copy/delete+ // cycle, not the handful of git commands each test runs.+ beforeAll(async () => {+ dir = await initRepo();+ initialHead = (await execGit(['rev-parse', 'HEAD'], dir)).stdout.trim();+ });+ beforeEach(async () => { await resetGitSandbox({ repo: dir, initialHead }); });+ afterAll(async () => { await rm(dir, { recursive: true, force: true }); });it('detects a normal (--no-ff) merge', async () => {await execGit(['checkout', '-b', 'feat'], dir);@@ -118,12 +132,21 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('reapMergedWorktrees', () => {// One root OUTSIDE the repo for the includeUnmanagedTrees cases, torn down// alongside the repo so a held tree can't leak out of the run.let externalRoot;-- beforeEach(async () => {+ let initialHead;++ // One real repo (and one external root) for the whole describe, reset in+ // place between tests via resetGitWorktreeSandbox() instead of a fresh+ // mkdtemp + materializeGitRepo (fs.cp) + rm per test (#5902) — the reset+ // tears down every `git worktree add` checkout a test grew (including a+ // locked one), wherever it lives, so externalRoot is naturally emptied+ // back out along with dir's own `.claude/worktrees` trees.+ beforeAll(async () => {dir = await initRepo();externalRoot = realpathSync(await mkdtemp(join(tmpdir(), 'portos-reap-ext-')));+ initialHead = (await execGit(['rev-parse', 'HEAD'], dir)).stdout.trim();});- afterEach(async () => {+ beforeEach(async () => { await resetGitWorktreeSandbox(dir, initialHead); });+ afterAll(async () => {await rm(dir, { recursive: true, force: true });await rm(externalRoot, { recursive: true, force: true });});