mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-11-29 23:37:41 +00:00
* docs(plans): add resumable analyze plan * perf(bench): measure resumable storage primitives * feat(embeddings): bound and persist work selection * feat(embeddings): persist resumable vector jobs Keep graph readers independent of vector writes. Acknowledge units only after complete chunk verification and a native checkpoint. * feat(embeddings): stream resumable job units * feat(storage): add generation publication Publish durable graph generations independently of vector jobs and gate readers on matching identities. Retain the legacy graph inode under a private name so older binaries cannot serve a stale canonical graph. Coordinator integration follows separately. Refs #3598 * feat(embeddings): coordinate durable jobs Join published graph selection, durable work, bounded native handles and vector publication behind one inactive controller. Limit optional HTTP response decoding within the job reservation and admit supported large inputs under larger budgets. Refs #3598 * feat(analyze): pass phase resource allocations Carry per-run worker heaps and native pools without changing legacy defaults. Hold parser reservations through safe native exit; refuse database reallocation after an unverified close. * feat(embeddings): reserve sidecar resources Pin each durable job to an admitted model heap and CPU config. Retain native allocations after caller cancellation until response or process exit, and reject phase handoff when release is unverified. * feat(status): separate graph and vector readiness Report embedding debt independently from graph content freshness. Read bounded durable progress without loading native runtimes, gate stale vector capability stamps, and allowlist additive phase counters on public SSE and ops payloads. * fix(embeddings): recover interrupted job setup Recover an owned empty native catalog after interrupted bootstrap, and rebuild damaged failure accounting without repeating completed provider work. Preserve foreign artifacts and propagate filesystem errors. * fix(resources): verify native pool release Keep failed and concurrent native closes tracked until release succeeds. Refuse another reserved allocation while cleanup is unverified, including failed connection construction. Let graph readers tear down after result-close errors. * fix(resources): drain graph before phase admission Wait for session work and verify the prior main graph pool has closed before parser or embedding admission. Recheck cancellation after the drain so cancelled jobs do not read or mutate job metadata. * docs(plans): revise resumable analyze seams * perf(bench): measure paired analyze runs * feat(index): publish logical graph generations Retain private database files across incremental generations and fence prepared publication against superseding writers. Exit-only producers must exit before publication; interrupted in-place writes remain explicitly dirty. * feat(index): guard graph process handoff Wait for actual process exit and reacquire the ordinary slot lock before publishing the prepared attempt. Recheck placement and the registered name, and retain graph discoverability after cancellation. Add a bounded nonterminal worker receipt without serializing the live graph. Production phase activation remains separate. * feat(cli): defer success across graph handoff Finish live-graph skill generation before the child hands off. Transfer only bounded counters, identity and the pre-run self-commit safety flags; wait for IPC delivery before returning for native process exit. Reject missing supervisors and mismatched prepared results before skill writes. Finalization, self-commit and success remain deferred until the production supervisor completes embedding; core activation follows the pending-artifact and resource contracts. Refs #3598 * feat(embeddings): rebase pending paid artifacts Separate graph job identity from mutable artifact ownership. Keep paid compatible groups across source edits using bounded revalidation and selection pruning; retain one sealed fallback for the active space. * feat(embeddings): preserve historical coverage * feat(embeddings): reuse verified legacy vectors Retain a directly referenced legacy source across pending-artifact rebases. Stream checkpoint exclusions and build a native metadata index without copying vectors or retaining corpus-sized JavaScript maps. Require recorded provider identity and provable complete input groups. Keep unknown provenance explicit, source artifacts immutable, compatible relocations free of provider calls, and new inputs in normal batches. The controller remains inactive until coordinated writer activation. Refs #3598 * feat(analyze): account for supervised phases Charge parent memory once per phase. Carry allowlisted progress through worker IPC and preserve counters across logs without completing the job. Refs #3598 * fix(storage): retain owned analysis generations Keep private generation files in place through shared-store preparation and publication. Retain prepared publications and pending embedding work across the unlocked process handoff, including work in branch slots. Refs #3598 * fix(embeddings): share pinned vector readers Share immutable vector file identities so sibling hard links retain one native reservation. Keep the handle alive until its final reader closes, including failed initialization and replacement of another reader's path. Refs #3598 * feat(storage): share completed vector artifacts Pin immutable vectors independently in checkout slots and shared graph snapshots. Keep mutable jobs with their owning checkout; resume interrupted adoption without overwriting unverified files. Refs #3598 * feat(analyze): retain caches across phase handoff Keep prepared staging during lock reacquisition and share cache publication between the graph writer and exit continuation. Bound the filesystem handoff to chunk keys; never copy live cache contents. Refs #3598 * fix(analyze): retain owned generation routing Keep prepared and pending work under its original slot lock during shared-store adoption. Preserve private generation filenames during incremental writes without copying the graph. Drain model and native resources only when graph work actually starts, including FTS repair. Leave the warm no-op path unchanged. Validated 158 tests, source build, test typecheck, formatting and lint. Complete graph gates cover 29 symbols in two files and the expected coordinator flow. End-to-end embedding activation and performance acceptance remain pending. * feat(analyze): wire resumable phase execution Publish verified graphs before embedding and hand off resource ownership across CLI, watch, auto-sync, and HTTP phases. Keep completed vectors readable while durable embedding units resume in a separate generation. Preserve legacy vector reuse, avoid graph rebuilds for dimension changes, and cover interruption boundaries with fresh-process restart tests. Refs #3598 * fix(analyze): close recovery and ownership gaps Retain interrupted private work, clear stale query widths, and keep native reservations until confirmed worker exit. Keep shared-member admission gates outside garbage-collected directories for flat and branch writers. Reject invalid routes and overlaps, and distinguish validation from uncertain writes. Make test imports work before build, isolate host-capacity assertions, and give legacy vector fixtures the production native pool allocation. Focused regressions, clean-build types, formatting and lint pass. Graph analysis maps 51 symbols across 21 paths. Two import-only test paths remain unmapped; direct review and integration tests cover them. The parent full suite passed 32,084 tests with five failures: two fixed legacy-vector fixture cases and three recovery cases awaiting isolation. Final full-suite and performance acceptance remain pending on the draft. Refs #3598 * perf(embeddings): batch reused vector writes Avoid a native transaction per reused node while retaining the byte budget and durable unit boundary. Cover mixed inputs, cancellation, and replay after read or committed-write failures. Native regression fails before the fix (65 commits for 64 nodes). 79 focused tests and all three former recovery timeouts pass. Fresh graph gate: 18 symbols, 2 files, 36 affected flows; complete mapping. Final whole-command performance acceptance remains pending. Refs #3598 * fix(analyze): honor explicit worker overrides Preserve the existing CPU oversubscription override while reserving memory for every requested worker. Automatic concurrency stays CPU-bounded. Validate on one- and four-CPU hosts: 81 tests pass; the override regressions fail before the fix. * fix(storage): validate opened artifact files Validate descriptors before reading bounded receipts and manifests. Use nonblocking opens to reject FIFO substitutions and verify directory entries when O_NOFOLLOW is unavailable. Preserve the metadata cache fast path and guard generation paths explicitly. Remove the redundant pending-node fallback. Add race, symlink, cleanup, and cache regressions to platform coverage. * fix(storage): guard the graph path directly Apply the containment check to the same path passed to lstat. The nested normalization guarded a different expression in CodeQL. path.relative already resolves its inputs, so remove the redundant normalization and retain relative-path behavior. * fix(embeddings): preserve AST inputs on resume Carry indexed source policy into bounded resumable jobs and preserve exact-input reuse across sibling edits. Include strategy and retention in job identity; admit source memory before reading. * chore: run checks for the rebased stack * refactor(embeddings): simplify reuse plumbing Name reuse-validation options and share the owned-directory loop. Preserve callback order, directory sync, and ownership checks. * test: fix recovery and Windows CI fixtures Distinguish legacy checkpoints without input provenance from verified source-aware chunks. Check the embed API at its shared-phase boundary and model pathname races without rename-over-open on Windows. * fix: close resource admission and CI gaps Keep live sidecars charged after a reap timeout. Let sync and HTTP jobs use automatic host budgets instead of overcommitting to default V8 limits. Explain the incompatible native zero-pool override, clean up failed HTTP fixtures, and run the native vector suites across platforms. * fix: preserve analysis resource ownership Pin admitted model settings and retain worker and supervisor reservations. Recheck canonical directory identity before receipt reads or writes. Canonicalize the native publication fixture for macOS and Windows. * test: distinguish parameterized CI cases * docs: remove implementation plan from PR * ci: gate resumable analyze performance * fix(analyze): close recovery and CI gaps Retain ownership receipts and paid vectors through interrupted work and cleanup. Restore automatic heap and parser-worker sizing, and cover publication, cancellation and capacity failures. Refs #3829, #3598 Note: pre-existing setup.test.ts and setup-skills.test.ts failures with inherited CODEX_HOME; all 62 tests pass with it unset for the test process. * fix(embeddings): normalize graph parent paths Bind the canonical job root to the same graph path on macOS temp aliases and Windows short paths. Keep graph identity and owned-directory checks. Canonicalize the retention fixture and show subprocess stderr on failure. Validation: 65 focused tests; 26 tests through an aliased TMPDIR; build, test typecheck, formatting and lint; graph change analysis (4 files). * fix(embeddings): batch writes and guard recovery Batch bounded vector and receipt writes to remove per-node native calls without changing validation, transactions, or durable checkpoints. Pin publication descriptors before entry validation. Preserve excluded vector coverage, reject malformed status paths, retry orphan sidecars, and complete shutdown after child spawn failures. Validation: 159 focused tests and 89 native/restart tests; build, test typecheck, lint and formatting. Refreshed graph analysis maps production changes; three test files remain unmapped. * ci: profile fresh analyze overhead Capture process and parser-worker CPU profiles in a separate CI-only run. Reject profiling with --check so diagnostic overhead never affects the acceptance gate. * perf(analyze): trim continuation startup work * fix(analyze): preserve recovery and storage bounds Keep automatic writer pools page-scaled and restore frontend heap caps. Adopt a generation recovered during handoff, reclaim sealed artifacts, and retire compatible legacy sources after migration completes. Report semantic degradation and omit provider causes from API logs. Enforce no paid replay in the CI resume benchmark. * perf(analyze): defer unused parser imports * fix(workers): retain failed shutdown reservations * perf: skip unused budget supervisor receipt * fix: bound rejection history and watch budgets * perf: batch provider vector writes within units * fix: harden cleanup and semantic availability * perf: avoid repeated analysis startup probes Skip unused automatic-heap parent provenance and reuse one npm version probe for runner selection and its warning. Keep child/watch identity capture and manual/test heap overrides. Refs #3829. * fix: normalize legacy export paths on Windows Cover Unicode export directories and restore the heap parser comment. Refs #3829. * test: restore watch resource mock contract Provide the supervisor reservation used by watch refresh admission. Refs #3829. * fix: retain watch budgets and bound lookahead Keep explicit heap reservations across refreshes and limit brace scans to the existing three-line window. Refs #3829. * fix: stop retries on shutdown and allow empty parse * refactor: simplify embedding setup and test lists * perf: batch vector completion hash updates Keep hash finalization inside the existing transaction and row bounds. Run embedding input-isolation tests in the serial native project. * fix: address PR #3829 recovery feedback Preserve terminal worker results, reclaim orphan attempt metadata, retain artifacts with unrecognized space ownership, and correct the cancellation comment. * perf: retain simple vector completion query * perf: skip redundant alias identity probes * perf: avoid Git probes for ordinary checkout roots * perf: avoid redundant vector transactions Standalone writes already execute in automatic transactions. Keep multi-query transactions and durable unit checkpoints unchanged. * docs: clarify cancellation grace period * fix: finish vector recovery and explicit drops Preserve paid peers through source-admission aborts and complete legacy retirement after interrupted publication. Explicit drops remove validated vector payloads before their ownership receipts so later runs regenerate them. Refs #3829 * fix: preserve storage errors during aborts Only unwrap aborts raised by source admission. A simultaneous native write failure must propagate instead of entering the provider-abort completion path. Refs #3829 * fix: validate retained analysis artifacts Reject malformed cache keys before shard writes and retain legacy work before shared-store adoption. Explicit drops validate legacy ownership and keep receipts until payload cleanup succeeds. Damaged registered graphs block stale local hook fallback. * fix: preserve legacy and preflight contracts Keep the native-default pool override, retain incomplete legacy seeds with their owner, and include resource preflight in the worker timeout. * fix: honor resource and preflight boundaries Release optional cache space before rejecting an admissible source read. Start server deadlines before preflight and reject null progress counts. Pass the native-default pool sentinel through the database opener. * test: align native and drop contracts Accept the documented native-default zero sentinel. Verify the rebuilt graph and empty vectors instead of an obsolete escalation log. Refs #3829 * perf: avoid redundant vector checkpoints Acknowledge verified WAL commits without rewriting the database per unit. Keep the final publication checkpoint and prove crash recovery from WAL. Give publication test cases distinct titles for the CI execution audit. Refs #3829 --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
1301 lines
55 KiB
TypeScript
1301 lines
55 KiB
TypeScript
/**
|
|
* Unit Tests: git utility helpers (storage/git.ts)
|
|
*
|
|
* Tests isGitRepo, getCurrentCommit, getGitRoot, and the newly added
|
|
* hasGitDir helper introduced for issue #384 (indexing non-git folders).
|
|
*/
|
|
import { describe, it, expect, vi } from 'vitest';
|
|
import path from 'path';
|
|
import os from 'os';
|
|
import fs from 'fs';
|
|
import { execFileSync, execSync } from 'child_process';
|
|
|
|
const gitExecutable = (() => {
|
|
if (process.platform !== 'win32') return 'git';
|
|
try {
|
|
return (
|
|
execFileSync('where.exe', ['git'], { encoding: 'utf8' }).split(/\r?\n/).find(Boolean) ?? 'git'
|
|
);
|
|
} catch {
|
|
return 'git';
|
|
}
|
|
})();
|
|
|
|
const isolatedTmpRoot = (() => {
|
|
const root =
|
|
process.platform === 'win32'
|
|
? path.join(path.parse(os.tmpdir()).root, 'gitnexus-outside-git')
|
|
: path.join(os.tmpdir(), 'gitnexus-outside-git');
|
|
fs.mkdirSync(root, { recursive: true });
|
|
return root;
|
|
})();
|
|
|
|
const makeIsolatedTempDir = (prefix = 'gitnexus-test-'): string =>
|
|
fs.mkdtempSync(path.join(isolatedTmpRoot, prefix));
|
|
|
|
// ─── hasGitDir ────────────────────────────────────────────────────────────
|
|
//
|
|
// hasGitDir is a synchronous fs.statSync check — we test it by actually
|
|
// creating temporary directories rather than mocking the fs module,
|
|
// because the implementation is a simple one-liner and real disk I/O is
|
|
// fast and deterministic for this purpose.
|
|
|
|
describe('hasGitDir', () => {
|
|
// Import after test setup to ensure module resolution is correct
|
|
const getHasGitDir = async () => {
|
|
const mod = await import('../../src/storage/git.js');
|
|
return mod.hasGitDir;
|
|
};
|
|
|
|
it('returns true when .git directory exists', async () => {
|
|
const hasGitDir = await getHasGitDir();
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-test-'));
|
|
try {
|
|
fs.mkdirSync(path.join(tmpDir, '.git'));
|
|
expect(hasGitDir(tmpDir)).toBe(true);
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns true when .git is a file (git worktree)', async () => {
|
|
const hasGitDir = await getHasGitDir();
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-test-'));
|
|
try {
|
|
fs.writeFileSync(path.join(tmpDir, '.git'), 'gitdir: /some/other/.git\n');
|
|
expect(hasGitDir(tmpDir)).toBe(true);
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns false when .git entry is absent', async () => {
|
|
const hasGitDir = await getHasGitDir();
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-test-'));
|
|
try {
|
|
// No .git here — plain directory
|
|
expect(hasGitDir(tmpDir)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns false for a non-existent path', async () => {
|
|
const hasGitDir = await getHasGitDir();
|
|
expect(hasGitDir('/tmp/__gitnexus_nonexistent_path__')).toBe(false);
|
|
});
|
|
});
|
|
|
|
// ─── isGitRepo ────────────────────────────────────────────────────────────
|
|
//
|
|
// isGitRepo shells out to `git rev-parse` — we verify it returns false
|
|
// for a plain temp directory without running git init.
|
|
|
|
describe('isGitRepo', () => {
|
|
it('returns false for a plain (non-git) directory', async () => {
|
|
const { isGitRepo } = await import('../../src/storage/git.js');
|
|
const tmpDir = makeIsolatedTempDir();
|
|
try {
|
|
expect(isGitRepo(tmpDir)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns false for a non-existent path', async () => {
|
|
const { isGitRepo } = await import('../../src/storage/git.js');
|
|
expect(isGitRepo('/tmp/__gitnexus_nonexistent__')).toBe(false);
|
|
});
|
|
});
|
|
|
|
// ─── getCurrentCommit ─────────────────────────────────────────────────────
|
|
|
|
describe('getCurrentCommit', () => {
|
|
it('returns empty string for a non-git directory', async () => {
|
|
const { getCurrentCommit } = await import('../../src/storage/git.js');
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-test-'));
|
|
try {
|
|
expect(getCurrentCommit(tmpDir)).toBe('');
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// Regression: #1172 — without explicit stdio on execSync, Node forwards
|
|
// the child's stderr to the parent process, printing "fatal: not a git
|
|
// repository" to the user's terminal even though the error is caught.
|
|
it('does not leak git stderr to process.stderr (#1172)', async () => {
|
|
const { getCurrentCommit } = await import('../../src/storage/git.js');
|
|
// git-init a dir without commits so `git rev-parse HEAD` fails with a
|
|
// "fatal:" message — the exact class of error that leaked before the fix.
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-test-'));
|
|
execSync('git init -q', { cwd: tmpDir, stdio: 'ignore' });
|
|
const spy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
|
try {
|
|
expect(getCurrentCommit(tmpDir)).toBe('');
|
|
const stderrOutput = spy.mock.calls.map((c) => String(c[0])).join('');
|
|
expect(stderrOutput).not.toContain('fatal');
|
|
} finally {
|
|
spy.mockRestore();
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─── getGitRoot ───────────────────────────────────────────────────────────
|
|
|
|
describe('getGitRoot', () => {
|
|
it('returns null for a plain temp directory', async () => {
|
|
const { getGitRoot } = await import('../../src/storage/git.js');
|
|
const tmpDir = makeIsolatedTempDir();
|
|
try {
|
|
expect(getGitRoot(tmpDir)).toBeNull();
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
// Regression: #1172 -- mirrors the getCurrentCommit stderr test above.
|
|
it('does not leak git stderr to process.stderr (#1172)', async () => {
|
|
const { getGitRoot } = await import('../../src/storage/git.js');
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-test-'));
|
|
const spy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
|
|
try {
|
|
getGitRoot(tmpDir);
|
|
const stderrOutput = spy.mock.calls.map((c) => String(c[0])).join('');
|
|
expect(stderrOutput).not.toContain('fatal');
|
|
} finally {
|
|
spy.mockRestore();
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('preserves a trailing-space repository directory name (#2190)', async () => {
|
|
const { getGitRoot } = await import('../../src/storage/git.js');
|
|
const parentDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-space-root-'));
|
|
const initDir = path.join(parentDir, 'repo-init');
|
|
const repoDir = path.join(parentDir, 'repo ');
|
|
try {
|
|
fs.mkdirSync(initDir);
|
|
execFileSync(gitExecutable, ['init', '-q'], { cwd: initDir, stdio: 'ignore' });
|
|
fs.renameSync(initDir, repoDir);
|
|
|
|
expect(getGitRoot(repoDir)).toBe(path.resolve(repoDir));
|
|
} finally {
|
|
fs.rmSync(parentDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─── getRemoteUrl ─────────────────────────────────────────────────────────
|
|
|
|
const setupRepoWithRemote = (remoteUrl: string): string => {
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-remote-'));
|
|
// Use real fs paths and shellouts — the helper itself shells out to
|
|
// `git config`, so we need a real git repo for the assertion to be
|
|
// meaningful.
|
|
execSync('git init -q', { cwd: tmpDir });
|
|
execSync(`git remote add origin ${remoteUrl}`, { cwd: tmpDir });
|
|
return tmpDir;
|
|
};
|
|
|
|
describe('getRemoteUrl', () => {
|
|
it('returns undefined for a non-git directory', async () => {
|
|
const { getRemoteUrl } = await import('../../src/storage/git.js');
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-test-'));
|
|
try {
|
|
expect(getRemoteUrl(tmpDir)).toBeUndefined();
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns undefined for a git repo with no origin remote', async () => {
|
|
const { getRemoteUrl } = await import('../../src/storage/git.js');
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-test-'));
|
|
try {
|
|
execSync('git init -q', { cwd: tmpDir });
|
|
expect(getRemoteUrl(tmpDir)).toBeUndefined();
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('strips trailing .git and lowercases host for HTTPS remotes', async () => {
|
|
const { getRemoteUrl } = await import('../../src/storage/git.js');
|
|
const tmpDir = setupRepoWithRemote('https://GitHub.COM/Foo/Bar.git');
|
|
try {
|
|
expect(getRemoteUrl(tmpDir)).toBe('https://github.com/Foo/Bar');
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('lowercases host for SCP-style SSH remotes and strips .git', async () => {
|
|
const { getRemoteUrl } = await import('../../src/storage/git.js');
|
|
const tmpDir = setupRepoWithRemote('git@GitHub.com:Foo/Bar.git');
|
|
try {
|
|
expect(getRemoteUrl(tmpDir)).toBe('git@github.com:Foo/Bar');
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns the same fingerprint for two clones of the same repo', async () => {
|
|
const { getRemoteUrl } = await import('../../src/storage/git.js');
|
|
const a = setupRepoWithRemote('https://example.com/foo/bar.git');
|
|
const b = setupRepoWithRemote('https://example.com/foo/bar');
|
|
try {
|
|
expect(getRemoteUrl(a)).toBe(getRemoteUrl(b));
|
|
expect(getRemoteUrl(a)).toBeTruthy();
|
|
} finally {
|
|
fs.rmSync(a, { recursive: true, force: true });
|
|
fs.rmSync(b, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─── credentials in remote URLs (#2914) ──────────────────────────────────
|
|
//
|
|
// `git config remote.origin.url` hands back whatever CI or a credential
|
|
// helper configured, including `https://x-access-token:<token>@host/…`.
|
|
// That value is persisted (registry.json, the per-repo meta) and echoed by
|
|
// MCP `list_repos`, so it must lose its userinfo at capture time. Every
|
|
// credential below is an obviously fake constant.
|
|
|
|
describe('remote URL credentials (#2914)', () => {
|
|
const FAKE_TOKEN = 'ExAmPle-FAKE-SECRET';
|
|
|
|
it('strips userinfo from an HTTPS remote before it can be persisted', async () => {
|
|
const { getRemoteUrl } = await import('../../src/storage/git.js');
|
|
const tmpDir = setupRepoWithRemote(
|
|
`https://x-access-token:${FAKE_TOKEN}@github.com/example/project.git`,
|
|
);
|
|
try {
|
|
expect(getRemoteUrl(tmpDir)).toBe('https://github.com/example/project');
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('strips a username-only HTTPS remote (the PAT-as-username form)', async () => {
|
|
const { getRemoteUrl } = await import('../../src/storage/git.js');
|
|
const tmpDir = setupRepoWithRemote(`https://${FAKE_TOKEN}@github.com/example/project.git`);
|
|
try {
|
|
expect(getRemoteUrl(tmpDir)).toBe('https://github.com/example/project');
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('leaves plain HTTPS, SSH-URL and SCP-like remotes untouched', async () => {
|
|
const { stripUrlCredentials } = await import('../../src/storage/git.js');
|
|
// The SSH forms carry a user NAME, not a secret, and are part of the
|
|
// remote's identity — rewriting them would repoint the #2054 fingerprint.
|
|
expect(stripUrlCredentials('https://github.com/example/project.git')).toBe(
|
|
'https://github.com/example/project.git',
|
|
);
|
|
expect(stripUrlCredentials('ssh://git@github.com/example/project.git')).toBe(
|
|
'ssh://git@github.com/example/project.git',
|
|
);
|
|
expect(stripUrlCredentials('git@github.com:example/project.git')).toBe(
|
|
'git@github.com:example/project.git',
|
|
);
|
|
// An `@` in the PATH is not userinfo — the authority ends at the first `/`.
|
|
expect(stripUrlCredentials('https://github.com/example/pro@ject')).toBe(
|
|
'https://github.com/example/pro@ject',
|
|
);
|
|
});
|
|
|
|
it('removes a password containing @ whole, leaving no tail behind', async () => {
|
|
const { stripUrlCredentials } = await import('../../src/storage/git.js');
|
|
expect(stripUrlCredentials(`https://user:pa@ss-${FAKE_TOKEN}@host.example/o/r`)).toBe(
|
|
'https://host.example/o/r',
|
|
);
|
|
});
|
|
|
|
it('keeps the same fingerprint for credentialed and clean clones of one repo', async () => {
|
|
const { getRemoteUrl } = await import('../../src/storage/git.js');
|
|
const withCreds = setupRepoWithRemote(
|
|
`https://x-access-token:${FAKE_TOKEN}@example.com/foo/bar.git`,
|
|
);
|
|
const clean = setupRepoWithRemote('https://example.com/foo/bar');
|
|
try {
|
|
expect(getRemoteUrl(withCreds)).toBe(getRemoteUrl(clean));
|
|
} finally {
|
|
fs.rmSync(withCreds, { recursive: true, force: true });
|
|
fs.rmSync(clean, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─── getCanonicalRepoRoot (#1259) ────────────────────────────────────────
|
|
//
|
|
// Critical for the worktree-naming bug: when `gitnexus analyze` runs from a
|
|
// linked worktree, deriving `repoName` from `path.basename(getGitRoot(cwd))`
|
|
// uses the worktree's directory slug instead of the canonical repo's
|
|
// basename. `getCanonicalRepoRoot` exists specifically to dereference
|
|
// worktrees via `git rev-parse --git-common-dir`.
|
|
|
|
describe('getCanonicalRepoRoot', () => {
|
|
it('returns null for a plain temp directory (not a git repo)', async () => {
|
|
const { getCanonicalRepoRoot } = await import('../../src/storage/git.js');
|
|
const tmpDir = makeIsolatedTempDir('gitnexus-canonical-');
|
|
try {
|
|
expect(getCanonicalRepoRoot(tmpDir)).toBeNull();
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns null for a non-existent path', async () => {
|
|
const { getCanonicalRepoRoot } = await import('../../src/storage/git.js');
|
|
expect(getCanonicalRepoRoot('/tmp/__gitnexus_canonical_nonexistent__')).toBeNull();
|
|
});
|
|
|
|
it('returns the repo root when called from a regular (non-worktree) checkout', async () => {
|
|
const { getCanonicalRepoRoot } = await import('../../src/storage/git.js');
|
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-canonical-main-'));
|
|
try {
|
|
execSync('git init -q', { cwd: tmpDir });
|
|
// Compare via `path.basename` instead of full-path string equality so
|
|
// the test is robust to platform path-format quirks (Windows 8.3 short
|
|
// names like `C:\Users\RUNNER~1\…` vs long form `C:\Users\runneradmin\…`,
|
|
// macOS `/var/folders/… ↔ /private/var/folders/…`). The basename is the
|
|
// only part that registry name derivation actually uses (#1259).
|
|
const result = getCanonicalRepoRoot(tmpDir);
|
|
expect(result).not.toBeNull();
|
|
expect(path.basename(result!)).toBe(path.basename(tmpDir));
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns the CANONICAL repo root when called from inside a linked worktree (#1259)', async () => {
|
|
const { getCanonicalRepoRoot, getGitRoot } = await import('../../src/storage/git.js');
|
|
const repoDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitnexus-canonical-wt-'));
|
|
try {
|
|
execFileSync(gitExecutable, ['init', '-q'], { cwd: repoDir, stdio: 'ignore' });
|
|
// `git worktree add` requires at least one commit on a real branch.
|
|
execSync('git config user.email "test@example.com"', { cwd: repoDir });
|
|
execSync('git config user.name "Test"', { cwd: repoDir });
|
|
execSync('git commit --allow-empty -q -m "initial"', { cwd: repoDir });
|
|
// Create a linked worktree on a new branch outside the main checkout.
|
|
const worktreeDir = path.join(repoDir, 'wt-feature');
|
|
execSync(`git worktree add -q -b feature "${worktreeDir}"`, { cwd: repoDir });
|
|
|
|
// Both calls go through the same git executable, so their path-format
|
|
// output is guaranteed consistent — equality between them is the
|
|
// stable cross-platform assertion. (Comparing against `realpathSync`
|
|
// breaks on Windows where 8.3 short names and long names diverge.)
|
|
const fromMain = getCanonicalRepoRoot(repoDir);
|
|
const fromWorktree = getCanonicalRepoRoot(worktreeDir);
|
|
|
|
expect(fromMain).not.toBeNull();
|
|
// From inside the worktree: canonical points BACK to the main repo's
|
|
// shared `.git`. This is the regression-guard for #1259 — the
|
|
// registry name derivation collapses across worktrees.
|
|
expect(fromWorktree).toBe(fromMain);
|
|
// Basename matches the canonical repo dir (NOT the worktree slug).
|
|
expect(path.basename(fromWorktree!)).toBe(path.basename(repoDir));
|
|
expect(path.basename(fromWorktree!)).not.toBe('wt-feature');
|
|
// Sanity: getGitRoot returns the worktree-local root (existing
|
|
// behavior unchanged). Compare basenames for the same path-format
|
|
// reason as above.
|
|
expect(path.basename(getGitRoot(worktreeDir)!)).toBe('wt-feature');
|
|
} finally {
|
|
// Best-effort cleanup; worktree teardown can leak open handles on
|
|
// Windows so use force.
|
|
try {
|
|
execSync('git worktree remove -f wt-feature', { cwd: repoDir });
|
|
} catch {
|
|
// ignore — fall through to recursive rm
|
|
}
|
|
fs.rmSync(repoDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('resolveRepoIdentityRoot', () => {
|
|
it.each(['ordinary', 'GIT_DIR', 'GIT_COMMON_DIR', 'commondir', 'symlink'] as const)(
|
|
'preserves Git identity for %s checkouts',
|
|
async (layout) => {
|
|
const { getCanonicalRepoRoot, resolveRepoIdentityRoot } =
|
|
await import('../../src/storage/git.js');
|
|
const root = fs.realpathSync.native(makeIsolatedTempDir('gitnexus-identity-'));
|
|
let repo = path.join(root, 'repo');
|
|
const other = path.join(root, 'other');
|
|
vi.stubEnv('GIT_DIR', undefined);
|
|
vi.stubEnv('GIT_COMMON_DIR', undefined);
|
|
try {
|
|
for (const directory of [repo, other]) {
|
|
fs.mkdirSync(directory);
|
|
execFileSync(gitExecutable, ['init', '-q'], { cwd: directory, stdio: 'pipe' });
|
|
}
|
|
if (layout === 'GIT_DIR' || layout === 'GIT_COMMON_DIR')
|
|
vi.stubEnv(layout, path.join(other, '.git'));
|
|
else if (layout === 'commondir')
|
|
fs.writeFileSync(path.join(repo, '.git', 'commondir'), path.join(other, '.git') + '\n');
|
|
else if (layout === 'symlink') {
|
|
const link = path.join(root, 'linked-name');
|
|
fs.symlinkSync(repo, link, 'junction');
|
|
repo = link;
|
|
}
|
|
const canonical = getCanonicalRepoRoot(repo);
|
|
expect(canonical).not.toBeNull();
|
|
expect(resolveRepoIdentityRoot(repo)).toBe(canonical);
|
|
const subdir = path.join(repo, 'subdir');
|
|
fs.mkdirSync(subdir);
|
|
expect(resolveRepoIdentityRoot(subdir)).toBe(path.resolve(subdir));
|
|
} finally {
|
|
vi.unstubAllEnvs();
|
|
fs.rmSync(root, { recursive: true, force: true });
|
|
}
|
|
},
|
|
);
|
|
});
|
|
|
|
// ─── selfCommitContextFiles (#2639) ────────────────────────────────────────
|
|
|
|
describe('selfCommitContextFiles', () => {
|
|
const initRepo = (): string => {
|
|
const repoDir = makeIsolatedTempDir('gitnexus-self-commit-');
|
|
execFileSync(gitExecutable, ['init', '-q'], { cwd: repoDir, stdio: 'ignore' });
|
|
execSync('git config user.email "test@example.com"', { cwd: repoDir });
|
|
execSync('git config user.name "Test"', { cwd: repoDir });
|
|
return repoDir;
|
|
};
|
|
|
|
const lastCommitMessage = (repoDir: string): string =>
|
|
execSync('git log -1 --format=%s', { cwd: repoDir, encoding: 'utf8' }).trim();
|
|
|
|
const commitCount = (repoDir: string): number =>
|
|
Number(execSync('git rev-list --count HEAD', { cwd: repoDir, encoding: 'utf8' }).trim());
|
|
|
|
const stagedFiles = (repoDir: string): string[] =>
|
|
execSync('git diff --cached --name-only', { cwd: repoDir, encoding: 'utf8' })
|
|
.split('\n')
|
|
.map((s) => s.trim())
|
|
.filter(Boolean);
|
|
|
|
// Most tests below aren't exercising snapshotSelfCommitSafety itself (that
|
|
// has its own describe block); they just need "everything is safe to
|
|
// commit," matching a normal run where nothing was dirty beforehand.
|
|
const allSafe = (names: string[]): Map<string, boolean> =>
|
|
new Map(names.map((name) => [name, true]));
|
|
|
|
it('commits only the changed candidate file, scoped by name (never git add -A)', async () => {
|
|
const { selfCommitContextFiles } = await import('../../src/storage/git.js');
|
|
const repoDir = initRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'v1\n');
|
|
execSync('git add AGENTS.md', { cwd: repoDir });
|
|
execSync('git commit -q -m "initial"', { cwd: repoDir });
|
|
|
|
// Dirty AGENTS.md (candidate) plus an unrelated untracked file that
|
|
// must never be swept in.
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'v2\n');
|
|
fs.writeFileSync(path.join(repoDir, 'unrelated.txt'), 'should stay untouched\n');
|
|
|
|
selfCommitContextFiles(
|
|
repoDir,
|
|
['AGENTS.md', 'CLAUDE.md'],
|
|
allSafe(['AGENTS.md', 'CLAUDE.md']),
|
|
);
|
|
|
|
expect(commitCount(repoDir)).toBe(2);
|
|
expect(lastCommitMessage(repoDir)).toBe('chore(gitnexus): refresh index stats [skip ci]');
|
|
const status = execSync('git status --porcelain', { cwd: repoDir, encoding: 'utf8' });
|
|
// unrelated.txt is still untracked/dirty — proves the commit was scoped.
|
|
expect(status).toContain('unrelated.txt');
|
|
expect(status).not.toContain('AGENTS.md');
|
|
} finally {
|
|
fs.rmSync(repoDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('no-ops (no new commit) when neither candidate file changed', async () => {
|
|
const { selfCommitContextFiles } = await import('../../src/storage/git.js');
|
|
const repoDir = initRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'v1\n');
|
|
execSync('git add AGENTS.md', { cwd: repoDir });
|
|
execSync('git commit -q -m "initial"', { cwd: repoDir });
|
|
|
|
selfCommitContextFiles(
|
|
repoDir,
|
|
['AGENTS.md', 'CLAUDE.md'],
|
|
allSafe(['AGENTS.md', 'CLAUDE.md']),
|
|
);
|
|
|
|
expect(commitCount(repoDir)).toBe(1);
|
|
} finally {
|
|
fs.rmSync(repoDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('commits newly-created (untracked) candidate files, not just modified ones', async () => {
|
|
// Regression guard: a first-time `analyze --self-commit` run creates
|
|
// AGENTS.md/CLAUDE.md fresh — they are untracked, not modified. An
|
|
// implementation based on `git diff --quiet` misses untracked files
|
|
// entirely and would silently skip this case.
|
|
const { selfCommitContextFiles } = await import('../../src/storage/git.js');
|
|
const repoDir = initRepo();
|
|
try {
|
|
execSync('git commit -q --allow-empty -m "initial"', { cwd: repoDir });
|
|
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'fresh from analyze\n');
|
|
|
|
selfCommitContextFiles(
|
|
repoDir,
|
|
['AGENTS.md', 'CLAUDE.md'],
|
|
allSafe(['AGENTS.md', 'CLAUDE.md']),
|
|
);
|
|
|
|
expect(commitCount(repoDir)).toBe(2);
|
|
expect(lastCommitMessage(repoDir)).toBe('chore(gitnexus): refresh index stats [skip ci]');
|
|
const status = execSync('git status --porcelain', { cwd: repoDir, encoding: 'utf8' });
|
|
expect(status.trim()).toBe('');
|
|
} finally {
|
|
fs.rmSync(repoDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('no-ops when neither candidate file exists on disk', async () => {
|
|
const { selfCommitContextFiles } = await import('../../src/storage/git.js');
|
|
const repoDir = initRepo();
|
|
try {
|
|
execSync('git commit -q --allow-empty -m "initial"', { cwd: repoDir });
|
|
|
|
expect(() =>
|
|
selfCommitContextFiles(
|
|
repoDir,
|
|
['AGENTS.md', 'CLAUDE.md'],
|
|
allSafe(['AGENTS.md', 'CLAUDE.md']),
|
|
),
|
|
).not.toThrow();
|
|
expect(commitCount(repoDir)).toBe(1);
|
|
} finally {
|
|
fs.rmSync(repoDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('never throws when repoPath is not a git repository', async () => {
|
|
const { selfCommitContextFiles } = await import('../../src/storage/git.js');
|
|
const tmpDir = makeIsolatedTempDir('gitnexus-self-commit-nongit-');
|
|
try {
|
|
fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), 'not a git repo\n');
|
|
expect(() =>
|
|
selfCommitContextFiles(
|
|
tmpDir,
|
|
['AGENTS.md', 'CLAUDE.md'],
|
|
allSafe(['AGENTS.md', 'CLAUDE.md']),
|
|
),
|
|
).not.toThrow();
|
|
} finally {
|
|
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('commits both files when both changed, still scoped (no -A)', async () => {
|
|
const { selfCommitContextFiles } = await import('../../src/storage/git.js');
|
|
const repoDir = initRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'v1\n');
|
|
fs.writeFileSync(path.join(repoDir, 'CLAUDE.md'), 'v1\n');
|
|
execSync('git add AGENTS.md CLAUDE.md', { cwd: repoDir });
|
|
execSync('git commit -q -m "initial"', { cwd: repoDir });
|
|
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'v2\n');
|
|
fs.writeFileSync(path.join(repoDir, 'CLAUDE.md'), 'v2\n');
|
|
|
|
selfCommitContextFiles(
|
|
repoDir,
|
|
['AGENTS.md', 'CLAUDE.md'],
|
|
allSafe(['AGENTS.md', 'CLAUDE.md']),
|
|
);
|
|
|
|
expect(commitCount(repoDir)).toBe(2);
|
|
const status = execSync('git status --porcelain', { cwd: repoDir, encoding: 'utf8' });
|
|
expect(status.trim()).toBe('');
|
|
} finally {
|
|
fs.rmSync(repoDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('logs a warning (never throws) when the commit step fails, e.g. no git identity', async () => {
|
|
const { selfCommitContextFiles } = await import('../../src/storage/git.js');
|
|
const { _captureLogger } = await import('../../src/core/logger.js');
|
|
const repoDir = initRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'v1\n');
|
|
execSync('git add AGENTS.md', { cwd: repoDir });
|
|
execSync('git commit -q -m "initial"', { cwd: repoDir });
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'v2\n');
|
|
|
|
// useConfigOnly forces git to error on a missing identity instead of
|
|
// guessing from OS user/hostname; HOME/XDG_CONFIG_HOME are redirected
|
|
// and GIT_CONFIG_NOSYSTEM disables the system config, so no ambient
|
|
// global identity on the CI runner can leak in and make git succeed
|
|
// anyway. Together these deterministically reproduce "no git identity
|
|
// configured" regardless of the machine running the test.
|
|
execSync('git config user.useConfigOnly true', { cwd: repoDir });
|
|
execSync('git config --unset user.name', { cwd: repoDir });
|
|
execSync('git config --unset user.email', { cwd: repoDir });
|
|
|
|
const savedHome = process.env.HOME;
|
|
const savedXdg = process.env.XDG_CONFIG_HOME;
|
|
const savedNoSystem = process.env.GIT_CONFIG_NOSYSTEM;
|
|
process.env.HOME = makeIsolatedTempDir('gitnexus-self-commit-noidentity-home-');
|
|
process.env.XDG_CONFIG_HOME = process.env.HOME;
|
|
process.env.GIT_CONFIG_NOSYSTEM = '1';
|
|
|
|
const cap = _captureLogger();
|
|
try {
|
|
expect(() =>
|
|
selfCommitContextFiles(
|
|
repoDir,
|
|
['AGENTS.md', 'CLAUDE.md'],
|
|
allSafe(['AGENTS.md', 'CLAUDE.md']),
|
|
),
|
|
).not.toThrow();
|
|
} finally {
|
|
if (savedHome === undefined) delete process.env.HOME;
|
|
else process.env.HOME = savedHome;
|
|
if (savedXdg === undefined) delete process.env.XDG_CONFIG_HOME;
|
|
else process.env.XDG_CONFIG_HOME = savedXdg;
|
|
if (savedNoSystem === undefined) delete process.env.GIT_CONFIG_NOSYSTEM;
|
|
else process.env.GIT_CONFIG_NOSYSTEM = savedNoSystem;
|
|
}
|
|
const warning = cap
|
|
.records()
|
|
.find((r) => r.msg.includes('--self-commit failed to commit context files'));
|
|
cap.restore();
|
|
|
|
expect(warning).toBeDefined();
|
|
expect(commitCount(repoDir)).toBe(1); // commit never landed
|
|
} finally {
|
|
fs.rmSync(repoDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('skips (and logs) a candidate that already had an uncommitted edit before this run, never sweeping it into the generated commit', async () => {
|
|
// Regression for #2640 review round 1/2: without snapshotSelfCommitSafety,
|
|
// a pre-existing unstaged user edit in AGENTS.md and this run's stats
|
|
// refresh are indistinguishable — both just show up as "AGENTS.md is
|
|
// dirty" — so the old implementation silently committed both together.
|
|
const { selfCommitContextFiles, snapshotSelfCommitSafety } =
|
|
await import('../../src/storage/git.js');
|
|
const { _captureLogger } = await import('../../src/core/logger.js');
|
|
const repoDir = initRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'v1\n');
|
|
fs.writeFileSync(path.join(repoDir, 'CLAUDE.md'), 'v1\n');
|
|
execSync('git add AGENTS.md CLAUDE.md', { cwd: repoDir });
|
|
execSync('git commit -q -m "initial"', { cwd: repoDir });
|
|
|
|
// A user edit lands in AGENTS.md BEFORE analyze/self-commit ever runs.
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'user note\n');
|
|
|
|
// The real call sequence: snapshot safety first (this is what
|
|
// analyze.ts does before writing), THEN simulate analyze's own write
|
|
// on top of the user's pre-existing edit, for both candidates.
|
|
const safety = snapshotSelfCommitSafety(repoDir, ['AGENTS.md', 'CLAUDE.md']);
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'user note\ngenerated stats refresh\n');
|
|
fs.writeFileSync(path.join(repoDir, 'CLAUDE.md'), 'generated stats refresh\n');
|
|
|
|
const cap = _captureLogger();
|
|
selfCommitContextFiles(repoDir, ['AGENTS.md', 'CLAUDE.md'], safety);
|
|
const warning = cap
|
|
.records()
|
|
.find((r) => r.msg.includes('skipping file(s) with uncommitted changes'));
|
|
cap.restore();
|
|
|
|
expect(warning).toBeDefined();
|
|
// CLAUDE.md was clean pre-run (safe) and got committed; AGENTS.md was
|
|
// already dirty pre-run (unsafe) and must stay out of the commit and
|
|
// out of the index entirely — proving its edit wasn't swept in.
|
|
expect(commitCount(repoDir)).toBe(2);
|
|
expect(lastCommitMessage(repoDir)).toBe('chore(gitnexus): refresh index stats [skip ci]');
|
|
const diffTreeFiles = execSync('git diff-tree --no-commit-id --name-only -r HEAD', {
|
|
cwd: repoDir,
|
|
encoding: 'utf8',
|
|
})
|
|
.split('\n')
|
|
.map((s) => s.trim())
|
|
.filter(Boolean);
|
|
expect(diffTreeFiles).toEqual(['CLAUDE.md']);
|
|
const status = execSync('git status --porcelain -- AGENTS.md', {
|
|
cwd: repoDir,
|
|
encoding: 'utf8',
|
|
});
|
|
expect(status.trim()).not.toBe(''); // AGENTS.md's edit is still there, untouched
|
|
} finally {
|
|
fs.rmSync(repoDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('restores the index for exactly the staged files when commit fails after git add (no leftover staged state)', async () => {
|
|
// Regression for #2640 review round 2: `git add` runs before `git commit`;
|
|
// if commit then fails (e.g. missing identity), the old implementation
|
|
// left the candidate staged even though it reported nothing happened —
|
|
// silently mutating the user's index on a run that "did nothing."
|
|
const { selfCommitContextFiles } = await import('../../src/storage/git.js');
|
|
const repoDir = initRepo();
|
|
try {
|
|
execSync('git commit -q --allow-empty -m "initial"', { cwd: repoDir });
|
|
fs.writeFileSync(path.join(repoDir, 'AGENTS.md'), 'fresh from analyze\n');
|
|
|
|
execSync('git config user.useConfigOnly true', { cwd: repoDir });
|
|
execSync('git config --unset user.name', { cwd: repoDir });
|
|
execSync('git config --unset user.email', { cwd: repoDir });
|
|
|
|
const savedHome = process.env.HOME;
|
|
const savedXdg = process.env.XDG_CONFIG_HOME;
|
|
const savedNoSystem = process.env.GIT_CONFIG_NOSYSTEM;
|
|
process.env.HOME = makeIsolatedTempDir('gitnexus-self-commit-noidentity-home2-');
|
|
process.env.XDG_CONFIG_HOME = process.env.HOME;
|
|
process.env.GIT_CONFIG_NOSYSTEM = '1';
|
|
try {
|
|
selfCommitContextFiles(
|
|
repoDir,
|
|
['AGENTS.md', 'CLAUDE.md'],
|
|
allSafe(['AGENTS.md', 'CLAUDE.md']),
|
|
);
|
|
} finally {
|
|
if (savedHome === undefined) delete process.env.HOME;
|
|
else process.env.HOME = savedHome;
|
|
if (savedXdg === undefined) delete process.env.XDG_CONFIG_HOME;
|
|
else process.env.XDG_CONFIG_HOME = savedXdg;
|
|
if (savedNoSystem === undefined) delete process.env.GIT_CONFIG_NOSYSTEM;
|
|
else process.env.GIT_CONFIG_NOSYSTEM = savedNoSystem;
|
|
}
|
|
|
|
expect(commitCount(repoDir)).toBe(1); // commit never landed
|
|
expect(stagedFiles(repoDir)).toEqual([]); // and nothing was left staged
|
|
// The file itself is still there, unstaged, exactly as analyze left it.
|
|
const status = execSync('git status --porcelain -- AGENTS.md', {
|
|
cwd: repoDir,
|
|
encoding: 'utf8',
|
|
});
|
|
expect(status.trim()).toBe('?? AGENTS.md');
|
|
} finally {
|
|
fs.rmSync(repoDir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
// ─── isWorkingTreeDirty ───────────────────────────────────────────────────
|
|
//
|
|
// analyze's fast-path gate. GitNexus writes to .gitnexus/, .claude/, .cursor/,
|
|
// AGENTS.md, CLAUDE.md, and the repo-local .agents/ skill mirror during a run;
|
|
// those writes must never count as "dirty" or the up-to-date fast path is
|
|
// defeated on every re-run. Real temporary git repos exercise the actual
|
|
// `git status --porcelain` pathspec exclude list.
|
|
|
|
/** Create a fresh git repo in an isolated temp dir and return its path. */
|
|
function makeIsolatedGitRepo(): string {
|
|
const dir = makeIsolatedTempDir('gn-dirty-');
|
|
execSync('git init -q', { cwd: dir, stdio: 'ignore' });
|
|
// Set a stable identity so commit doesn't fail on environments without
|
|
// global git config (CI containers, fresh sandboxes).
|
|
execSync('git config user.email t@t', { cwd: dir, stdio: 'ignore' });
|
|
execSync('git config user.name t', { cwd: dir, stdio: 'ignore' });
|
|
return dir;
|
|
}
|
|
|
|
describe('isWorkingTreeDirty', () => {
|
|
it('returns false for a clean tree with only GitNexus-managed paths written', async () => {
|
|
const { isWorkingTreeDirty } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
// Initial commit so the tree has a HEAD.
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
execSync('git add -A && git commit -q -m init', { cwd: repo, stdio: 'ignore' });
|
|
|
|
// Simulate GitNexus writing its managed outputs.
|
|
fs.mkdirSync(path.join(repo, '.gitnexus'), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, '.gitnexus', 'meta.json'), '{}');
|
|
fs.mkdirSync(path.join(repo, '.claude', 'skills', 'gitnexus-cli'), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, '.claude', 'skills', 'gitnexus-cli', 'SKILL.md'), 'x');
|
|
fs.mkdirSync(path.join(repo, '.agents', 'skills', 'gitnexus-area-auth'), {
|
|
recursive: true,
|
|
});
|
|
fs.writeFileSync(path.join(repo, '.agents', 'skills', 'gitnexus-area-auth', 'SKILL.md'), 'x');
|
|
fs.writeFileSync(path.join(repo, 'AGENTS.md'), 'x');
|
|
fs.writeFileSync(path.join(repo, 'CLAUDE.md'), 'x');
|
|
|
|
expect(isWorkingTreeDirty(repo)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns true when a real source file changes (regression: excludes must not mask real edits)', async () => {
|
|
const { isWorkingTreeDirty } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
execSync('git add -A && git commit -q -m init', { cwd: repo, stdio: 'ignore' });
|
|
|
|
// A real business-file edit alongside GitNexus writes.
|
|
fs.mkdirSync(path.join(repo, 'src'), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, 'src', 'foo.ts'), 'export const x = 2;');
|
|
fs.mkdirSync(path.join(repo, '.agents', 'skills', 'x'), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, '.agents', 'skills', 'x', 'SKILL.md'), 'x');
|
|
|
|
expect(isWorkingTreeDirty(repo)).toBe(true);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('treats the entire .agents/ tree as excluded (root file, nested skills, deep paths)', async () => {
|
|
const { isWorkingTreeDirty } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
execSync('git add -A && git commit -q -m init', { cwd: repo, stdio: 'ignore' });
|
|
|
|
// Root-level file under .agents/.
|
|
fs.mkdirSync(path.join(repo, '.agents'), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, '.agents', 'foo.txt'), 'x');
|
|
// Deep nested mirror path.
|
|
fs.mkdirSync(path.join(repo, '.agents', 'skills', 'gitnexus-area-auth'), {
|
|
recursive: true,
|
|
});
|
|
fs.writeFileSync(path.join(repo, '.agents', 'skills', 'gitnexus-area-auth', 'SKILL.md'), 'x');
|
|
|
|
expect(isWorkingTreeDirty(repo)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('does not error when .agents/ does not exist (no pathspec failure)', async () => {
|
|
const { isWorkingTreeDirty } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
execSync('git add -A && git commit -q -m init', { cwd: repo, stdio: 'ignore' });
|
|
|
|
expect(isWorkingTreeDirty(repo)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('does not error when .agents is a file rather than a directory', async () => {
|
|
const { isWorkingTreeDirty } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
execSync('git add -A && git commit -q -m init', { cwd: repo, stdio: 'ignore' });
|
|
|
|
// .agents exists as a regular file (e.g. user created it by mistake).
|
|
fs.writeFileSync(path.join(repo, '.agents'), 'not a directory');
|
|
|
|
// Must not throw; the tree is otherwise clean so it is not dirty.
|
|
expect(isWorkingTreeDirty(repo)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('does NOT exclude prefix-colliding names like .agentsrc or .claudefoo', async () => {
|
|
// pathspec `:(exclude).agents` must not swallow `.agentsrc` (no path
|
|
// separator). A change to such a colliding name still counts as dirty.
|
|
const { isWorkingTreeDirty } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
execSync('git add -A && git commit -q -m init', { cwd: repo, stdio: 'ignore' });
|
|
|
|
fs.writeFileSync(path.join(repo, '.agentsrc'), 'x');
|
|
fs.writeFileSync(path.join(repo, '.claudefoo'), 'x');
|
|
|
|
expect(isWorkingTreeDirty(repo)).toBe(true);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('does NOT exclude a nested .agents/ inside a subdirectory (root-relative pathspec)', async () => {
|
|
// `:(exclude).agents` is relative to the repo root; a subdirectory's
|
|
// .agents/ is unrelated and must still count as dirty.
|
|
const { isWorkingTreeDirty } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
execSync('git add -A && git commit -q -m init', { cwd: repo, stdio: 'ignore' });
|
|
|
|
fs.mkdirSync(path.join(repo, 'subdir', '.agents'), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, 'subdir', '.agents', 'x'), 'x');
|
|
|
|
expect(isWorkingTreeDirty(repo)).toBe(true);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns true (conservative) when called outside a git repository', async () => {
|
|
const { isWorkingTreeDirty } = await import('../../src/storage/git.js');
|
|
const dir = makeIsolatedTempDir('gn-nongit-');
|
|
try {
|
|
// No git init — git status fails, and the gate must fail closed (dirty).
|
|
expect(isWorkingTreeDirty(dir)).toBe(true);
|
|
} finally {
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns true (conservative) when git is not on PATH', async () => {
|
|
// PATH cleared so `git` cannot be found. The catch block must return true
|
|
// (fail closed) rather than silently treating the tree as clean — a clean
|
|
// false-positive would skip re-indexing of a genuinely-changed repo.
|
|
const { isWorkingTreeDirty } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
const savedPath = process.env.PATH;
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
execSync('git add -A && git commit -q -m init', { cwd: repo, stdio: 'ignore' });
|
|
process.env.PATH = '';
|
|
expect(isWorkingTreeDirty(repo)).toBe(true);
|
|
} finally {
|
|
process.env.PATH = savedPath;
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
describe('listWorkingTreeDirtyPaths', () => {
|
|
it('returns an empty list for a clean repository', async () => {
|
|
const { listWorkingTreeDirtyPaths } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
execFileSync(gitExecutable, ['add', '--', 'README.md'], { cwd: repo, stdio: 'ignore' });
|
|
execFileSync(gitExecutable, ['commit', '-q', '-m', 'init'], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
|
|
expect(listWorkingTreeDirtyPaths(repo)).toEqual([]);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns dirty source paths and omits GitNexus-managed writes', async () => {
|
|
const { listWorkingTreeDirtyPaths } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
execSync('git add -A && git commit -q -m init', { cwd: repo, stdio: 'ignore' });
|
|
fs.mkdirSync(path.join(repo, 'src'), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, 'src', 'foo.ts'), 'export const x = 1;');
|
|
fs.mkdirSync(path.join(repo, '.gitnexus'), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, '.gitnexus', 'meta.json'), '{}');
|
|
fs.writeFileSync(path.join(repo, 'AGENTS.md'), 'x');
|
|
|
|
expect(listWorkingTreeDirtyPaths(repo)).toEqual(['src/foo.ts']);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('still reports nested lookalikes that are not GitNexus-managed', async () => {
|
|
const { isWorkingTreeDirty, listWorkingTreeDirtyPaths } =
|
|
await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.mkdirSync(path.join(repo, 'docs'), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, 'docs', 'AGENTS.md'), 'project notes');
|
|
execFileSync(gitExecutable, ['add', '--', 'docs/AGENTS.md'], { cwd: repo, stdio: 'ignore' });
|
|
execFileSync(gitExecutable, ['commit', '-q', '-m', 'init'], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
fs.writeFileSync(path.join(repo, 'docs', 'AGENTS.md'), 'edited notes');
|
|
|
|
expect(isWorkingTreeDirty(repo)).toBe(true);
|
|
expect(listWorkingTreeDirtyPaths(repo)).toEqual(['docs/AGENTS.md']);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('returns null (not an empty list) outside a git repository', async () => {
|
|
const { listWorkingTreeDirtyPaths } = await import('../../src/storage/git.js');
|
|
const dir = makeIsolatedTempDir('gn-nongit-paths-');
|
|
try {
|
|
expect(listWorkingTreeDirtyPaths(dir)).toBeNull();
|
|
} finally {
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('preserves non-ASCII, newline, and arrow-shaped filenames exactly', async () => {
|
|
const { listWorkingTreeDirtyPaths } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
const names = ['src/ä.ts'];
|
|
if (process.platform !== 'win32') {
|
|
names.push('src/a -> b.ts', 'src/line\nbreak.ts', 'src/tab\tname.ts', 'src/back\\slash.ts');
|
|
}
|
|
try {
|
|
for (const name of names) {
|
|
fs.mkdirSync(path.dirname(path.join(repo, name)), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, name), 'before');
|
|
}
|
|
execFileSync(gitExecutable, ['add', '--', ...names], { cwd: repo, stdio: 'ignore' });
|
|
execFileSync(gitExecutable, ['commit', '-q', '-m', 'init'], { cwd: repo, stdio: 'ignore' });
|
|
for (const name of names) fs.writeFileSync(path.join(repo, name), 'after');
|
|
|
|
expect(listWorkingTreeDirtyPaths(repo)?.sort()).toEqual([...names].sort());
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it.skipIf(process.platform === 'win32')(
|
|
'returns both paths for a rename without parsing filename text',
|
|
async () => {
|
|
const { listWorkingTreeDirtyPaths } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
const before = 'src/before -> literal.ts';
|
|
const after = 'src/after -> literal.ts';
|
|
try {
|
|
fs.mkdirSync(path.join(repo, 'src'), { recursive: true });
|
|
fs.writeFileSync(path.join(repo, before), 'content');
|
|
execFileSync(gitExecutable, ['add', '--', before], { cwd: repo, stdio: 'ignore' });
|
|
execFileSync(gitExecutable, ['commit', '-q', '-m', 'init'], { cwd: repo, stdio: 'ignore' });
|
|
execFileSync(gitExecutable, ['mv', '--', before, after], { cwd: repo, stdio: 'ignore' });
|
|
|
|
expect(listWorkingTreeDirtyPaths(repo)?.sort()).toEqual([after, before].sort());
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
},
|
|
);
|
|
|
|
it.each(['--assume-unchanged', '--skip-worktree'])(
|
|
'includes paths hidden by git update-index %s',
|
|
async (flag) => {
|
|
const { listWorkingTreeDirtyPaths } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'hidden.ts'), 'before');
|
|
execFileSync(gitExecutable, ['add', '--', 'hidden.ts'], { cwd: repo, stdio: 'ignore' });
|
|
execFileSync(gitExecutable, ['commit', '-q', '-m', 'init'], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
execFileSync(gitExecutable, ['update-index', flag, '--', 'hidden.ts'], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
fs.writeFileSync(path.join(repo, 'hidden.ts'), 'after');
|
|
|
|
expect(listWorkingTreeDirtyPaths(repo)).toContain('hidden.ts');
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
},
|
|
);
|
|
|
|
it.each(['--assume-unchanged', '--skip-worktree'])(
|
|
'omits GitNexus-managed paths hidden by git update-index %s',
|
|
async (flag) => {
|
|
const { listWorkingTreeDirtyPaths } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'README.md'), 'hi');
|
|
fs.writeFileSync(path.join(repo, 'AGENTS.md'), 'before');
|
|
execFileSync(gitExecutable, ['add', '--', 'README.md', 'AGENTS.md'], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
execFileSync(gitExecutable, ['commit', '-q', '-m', 'init'], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
execFileSync(gitExecutable, ['update-index', flag, '--', 'AGENTS.md'], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
fs.writeFileSync(path.join(repo, 'AGENTS.md'), 'after');
|
|
|
|
expect(listWorkingTreeDirtyPaths(repo)).toEqual([]);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
},
|
|
);
|
|
|
|
it.skipIf(process.platform === 'win32')(
|
|
'preserves exact unusual names hidden by index bits, including both bits',
|
|
async () => {
|
|
const { listWorkingTreeDirtyPaths } = await import('../../src/storage/git.js');
|
|
const repo = makeIsolatedGitRepo();
|
|
const names = ['ä.ts', 'a -> b.ts', 'tab\tname.ts', 'line\nbreak.ts'];
|
|
try {
|
|
for (const name of names) fs.writeFileSync(path.join(repo, name), 'before');
|
|
execFileSync(gitExecutable, ['add', '--', ...names], { cwd: repo, stdio: 'ignore' });
|
|
execFileSync(gitExecutable, ['commit', '-q', '-m', 'init'], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
execFileSync(gitExecutable, ['update-index', '--assume-unchanged', '--', names[0]], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
execFileSync(gitExecutable, ['update-index', '--skip-worktree', '--', names[1]], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
execFileSync(gitExecutable, ['update-index', '--assume-unchanged', '--', names[2]], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
execFileSync(gitExecutable, ['update-index', '--skip-worktree', '--', names[2]], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
execFileSync(gitExecutable, ['update-index', '--skip-worktree', '--', names[3]], {
|
|
cwd: repo,
|
|
stdio: 'ignore',
|
|
});
|
|
for (const name of names) fs.writeFileSync(path.join(repo, name), 'after');
|
|
|
|
expect(listWorkingTreeDirtyPaths(repo)?.sort()).toEqual([...names].sort());
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
},
|
|
);
|
|
});
|
|
|
|
// ─── isWorkingTreePristine ────────────────────────────────────────────────
|
|
//
|
|
// The shared-store publish gate (#3374): a graph built from a working tree
|
|
// that hides committed content (sparse checkout, index bits, an uninitialized
|
|
// submodule) must never become the commit graph other checkouts reuse.
|
|
|
|
/** A repo with two committed files, `a.ts` and `lib/b.ts`. */
|
|
function makeCommittedRepo(): string {
|
|
const repo = makeIsolatedGitRepo();
|
|
fs.writeFileSync(path.join(repo, 'a.ts'), 'export const a = 1;');
|
|
fs.mkdirSync(path.join(repo, 'lib'));
|
|
fs.writeFileSync(path.join(repo, 'lib', 'b.ts'), 'export const b = 1;');
|
|
execFileSync(gitExecutable, ['add', '-A'], { cwd: repo, stdio: 'ignore' });
|
|
execFileSync(gitExecutable, ['commit', '-q', '-m', 'init'], { cwd: repo, stdio: 'ignore' });
|
|
return repo;
|
|
}
|
|
|
|
const gitIn = (repo: string, ...args: string[]): string =>
|
|
execFileSync(gitExecutable, args, { cwd: repo, encoding: 'utf8' }).trim();
|
|
|
|
describe('isWorkingTreePristine', () => {
|
|
it('is true for a clean checkout, ignoring GitNexus-managed writes', async () => {
|
|
const { isWorkingTreePristine } = await import('../../src/storage/git.js');
|
|
const repo = makeCommittedRepo();
|
|
try {
|
|
fs.mkdirSync(path.join(repo, '.gitnexus'));
|
|
fs.writeFileSync(path.join(repo, '.gitnexus', 'meta.json'), '{}');
|
|
fs.writeFileSync(path.join(repo, 'AGENTS.md'), 'x');
|
|
|
|
expect(isWorkingTreePristine(repo)).toBe(true);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('is false with an untracked source file', async () => {
|
|
const { isWorkingTreePristine } = await import('../../src/storage/git.js');
|
|
const repo = makeCommittedRepo();
|
|
try {
|
|
fs.writeFileSync(path.join(repo, 'new.ts'), 'export const n = 1;');
|
|
|
|
expect(isWorkingTreePristine(repo)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it.each(['--assume-unchanged', '--skip-worktree'])(
|
|
'is false when git update-index %s hides a path, even with unchanged content',
|
|
async (flag) => {
|
|
const { isWorkingTreePristine } = await import('../../src/storage/git.js');
|
|
const repo = makeCommittedRepo();
|
|
try {
|
|
gitIn(repo, 'update-index', flag, '--', 'a.ts');
|
|
|
|
expect(isWorkingTreePristine(repo)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
},
|
|
);
|
|
|
|
// Every sparse mode marks the left-out entries skip-worktree, which is what
|
|
// the check reads; a sparse index still expands for `git ls-files -v`.
|
|
it.each([
|
|
['no-cone', ['set', '--no-cone', '/a.ts']],
|
|
['cone', ['set', '--cone']],
|
|
['cone with a sparse index', ['set', '--cone', '--sparse-index']],
|
|
])('is false in a %s sparse checkout that leaves committed files out', async (_mode, args) => {
|
|
const { isWorkingTreePristine } = await import('../../src/storage/git.js');
|
|
const repo = makeCommittedRepo();
|
|
try {
|
|
gitIn(repo, 'sparse-checkout', ...args);
|
|
|
|
expect(fs.existsSync(path.join(repo, 'lib', 'b.ts'))).toBe(false);
|
|
expect(isWorkingTreePristine(repo)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('is false with a registered but uninitialized submodule', async () => {
|
|
const { isWorkingTreePristine } = await import('../../src/storage/git.js');
|
|
const repo = makeCommittedRepo();
|
|
try {
|
|
const head = gitIn(repo, 'rev-parse', 'HEAD');
|
|
gitIn(repo, 'update-index', '--add', '--cacheinfo', `160000,${head},vendor/dep`);
|
|
gitIn(repo, 'commit', '-q', '-m', 'add gitlink');
|
|
|
|
expect(isWorkingTreePristine(repo)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('is true with a checked-out submodule', async () => {
|
|
const { isWorkingTreePristine } = await import('../../src/storage/git.js');
|
|
const repo = makeCommittedRepo();
|
|
try {
|
|
const sub = path.join(repo, 'vendor', 'dep');
|
|
fs.mkdirSync(sub, { recursive: true });
|
|
gitIn(sub, 'init', '-q');
|
|
fs.writeFileSync(path.join(sub, 'c.ts'), 'export const c = 1;');
|
|
gitIn(sub, 'add', '-A');
|
|
gitIn(sub, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-q', '-m', 'sub');
|
|
gitIn(repo, 'add', 'vendor/dep');
|
|
gitIn(repo, 'commit', '-q', '-m', 'add submodule');
|
|
|
|
expect(isWorkingTreePristine(repo)).toBe(true);
|
|
} finally {
|
|
fs.rmSync(repo, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it('is false (fails closed) outside a git repository', async () => {
|
|
const { isWorkingTreePristine } = await import('../../src/storage/git.js');
|
|
const dir = makeIsolatedTempDir('gn-nongit-pristine-');
|
|
try {
|
|
expect(isWorkingTreePristine(dir)).toBe(false);
|
|
} finally {
|
|
fs.rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|