GitNexus/.devcontainer/profiles.test.cjs
Gergő Magyar 5b968a098c
fix(devcontainer): move workspace and snapshots to Linux volumes (#3835)
* fix(devcontainer): move workspace and snapshots to Linux volumes

* fix(devcontainer): exclude evaluation virtualenv from source import

* fix(devcontainer): preserve WSL links during volume imports

* fix(devcontainer): skip parser caches and report import progress

Exclude regenerable GitNexus parser caches from every nested worktree
while preserving graph databases, Git state, and local work.

Report archive bytes and elapsed time every five seconds, and stream
output with activity updates during longer Docker initialization stages.

* fix(devcontainer): resolve workspace volume ID before startup

* fix(devcontainer): relink nested worktrees and harden host imports

- Relink nested worktrees whose Git pointers still name the host path
  (C:/..., /Users/...): match the longest existing suffix in the copy
  and rewrite both pointers, as `git worktree repair` would.
- Fail the import when a file changes while tar reads it. bsdtar on
  macOS and Windows pads or truncates such files and exits 0.
- Disable AppleDouble `._*` entries from macOS tar (COPYFILE_DISABLE).
- Follow selected snapshot roots that are symlinks (dotfile-managed
  ~/.config/gh, ~/.claude.json) like the bind mounts they replace.
- Keep node at UID 1000 for root host users; the Dev Containers CLI
  skips UID realignment for UID 0.
- Make fixture modes independent of the process umask and check the
  no-partial-write case with lstat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(devcontainer): stage on the host and commit once at container creation

initializeCommand also runs when an existing container is reopened. A
developer who pulled the volume change and reopened the old bind-mount
container got an import marked ready, and the eventual rebuild silently
showed that stale copy.

- The host now only stages the checkout into gitnexus-seed-<id>
  (tree/ plus a stage-complete marker written last); the helper mounts
  the source volume read-only.
- onCreateCommand, which runs once per container creation, commits a
  complete stage into the empty source volume, empties the stage and
  repairs ownership. initializeCommand copies the host's
  seed-workspace.cjs into the seed volume on every start, so the
  commit matches devcontainer.json and works with any image.
- Staging and snapshot retakes are best-effort: a failure clears its
  target, warns and is retried next start, so a busy host never locks
  out reopening an existing container. Creation without a complete
  stage stops at onCreateCommand with a clear message.
- Snapshots are retaken while the source volume is uncommitted, and a
  partial snapshot is replaced instead of failing closed; snapshots are
  read-only host copies, so replacing them is safe.
- Node writes the tar stream (ustar + PAX for long and UTF-8 names).
  Windows tar.exe read the file list in the ANSI code page, so any
  non-ASCII path failed; macOS tar added AppleDouble files; both padded
  or truncated a file that changed while being read. A changed file now
  discards that copy. The host no longer needs tar. Sockets and FIFOs
  are skipped, as tar did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(devcontainer): simplify importer helpers and read small files whole

- tarStream reads files up to 1 MiB in one call instead of opening a
  stream per file: 50k files stream in 1.0 s instead of 12 s, with a
  byte-identical archive and unchanged change detection.
- Drop copyArchive's dead `excludes` parameter; the snapshot marker is
  excluded through the existing predicate.
- Share the source/target overlap check and the common-dir check.
- Remove exports with no consumer and two comments left from the
  host-tar implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(devcontainer): skip POSIX-only tar assertions on Windows (#3835)

- Address PR review feedback: the tar round-trip test ran mkfifo and
  asserted a 0755 mode unconditionally. Split it: UTF-8, long-name and
  empty-file round-trips run everywhere; POSIX mode preservation and
  FIFO exclusion move to a test skipped on win32, where tarStream
  writes 0644 by design.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(devcontainer): skip POSIX-tooling importer tests on Windows (#3835)

- Address PR review feedback: the Docker-adapter fixture assumed a POSIX
  PATH separator. A Windows-safe separator would not help: the fake
  `docker` is a shebang script Windows cannot spawn, and it runs Linux
  helper commands. One shared `posixOnly` skip option now covers the
  seven Docker-adapter tests, the bash credential test and the POSIX
  modes/FIFO test; all still run on Linux.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(devcontainer): keep failed snapshots retryable and nested worktrees local (#3835)

Address PR review feedback:
- Select snapshot roots with lstat, so a dangling or unfollowable
  `.claude.json` link reaches the archiver and is preserved as a link.
  A path under a non-directory still counts as absent.
- post-create.sh publishes the one-shot identity and shareable seed
  markers only when /host carries its completion marker; a snapshot
  skipped during initialization is seeded by a later rebuild.
- Remove an absolute core.worktree from each relinked nested worktree's
  config.worktree before Git first reads that checkout, as already done
  for the root configuration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(devcontainer): run fake-Docker importer tests only on Linux (#3835)

- Address PR review feedback: on macOS the importer passes container
  UID 1000, and the fake Docker adapter ran finishSnapshot's chown as the
  unprivileged host user. The adapter emulates the Linux helper
  container on the host, so its seven tests now share a `linuxHelper`
  gate; the bash, mode and FIFO tests keep the narrower `posixOnly`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* ci(devcontainer): run host importer tests on macOS and Windows (#3835)

Address PR review feedback: the suite's platform assumptions surfaced one
review finding per push. The host-side importer now runs on all three CI
hosts and the tests state what each one needs.

- New `host-importer` job runs initialize-volumes.test.cjs on
  macos-latest and windows-latest (Linux already runs every test).
- The importer reads its Docker CLI from GITNEXUS_IMPORT_DOCKER (JSON
  argv, default docker). Windows spawn resolves only .exe/.com, so the
  test adapter is now a Node script on every OS instead of a shebang
  file on PATH. The adapter emulates the helper's find/mkdir/touch and,
  on Windows, snapshot finalization.
- Gates: posixOnly (bash, modes, mkfifo), a symlink capability probe,
  and containerSide (Linux only) for code that runs only in the dev
  container or helper. Host staging assertions read the staged tree;
  the commit and 0600 snapshot modes stay in one Linux test.
- seed-workspace.test.cjs is container-side, so it skips on other hosts.
- The long-name round trip stays above 100 bytes (PAX) but under
  Windows MAX_PATH once extracted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(devcontainer): verify the tar stream with Python's PAX reader (#3835)

Windows tar.exe converts names to the ANSI code page while extracting, so
it cannot write `jegyzet-ő.md` or an emoji directory ("empty or
unreadable filename") - the limitation the Node writer exists to avoid.
Production never extracts with it; Docker's Go extractor does.

Read the round-trip archive with Python's tarfile instead, an
independent PAX reader that handles UTF-8 on every host, so the UTF-8
check also runs on Windows CI. A capability gate skips the test when no
Python 3 is installed. Removing the PAX path record fails the test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 20:36:27 +00:00

352 lines
14 KiB
JavaScript

'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync, spawnSync } = require('node:child_process');
const ts = require('typescript');
const { profile } = require('./profile.cjs');
const { bootstrap } = require('./bootstrap-native.cjs');
const source = fs.readFileSync(path.join(__dirname, 'devcontainer.json'), 'utf8');
const parse = (text) => {
const result = ts.parseConfigFileTextToJson('devcontainer.json', text);
assert.equal(result.error, undefined);
return result.config;
};
test('runtime profiles use the substituted mounts list and disable the automatic workspace mount', () => {
for (const text of [
source,
...[
{},
{ native: true },
{ ui: true, playwright: '1.63.0' },
{ native: true, image: 'example/toolchain' },
{ native: true, ui: true, playwright: '1.63.0' },
{ ui: true, image: 'example/toolchain' },
{ native: true, ui: true, image: 'example/toolchain' },
].map((options) => profile(source, options)),
]) {
const config = parse(text);
assert.equal(config.workspaceMount, '');
assert.equal(
config.mounts.filter((mount) => mount.split(',').includes('target=/workspace')).length,
1,
);
for (const mount of config.mounts) {
assert.match(mount, /(?:^|,)type=volume(?:,|$)/);
assert.doesNotMatch(mount, /localEnv|type=bind|workspace-host/);
}
assert.equal(config.capAdd, undefined);
assert.equal(config.postStartCommand, undefined);
assert.equal(config.containerEnv.WORKSPACE_9P_TUNE, undefined);
assert.equal(config.mounts.filter((m) => m.includes('-snapshot-')).length, 6);
}
});
test('default, UI and prebuilt profiles seed local work into a source volume', () => {
for (const text of [
source,
profile(source, { ui: true, playwright: '1.63.0' }),
profile(source, { image: 'example/toolchain' }),
]) {
const c = parse(text);
assert.deepEqual(
c.mounts.filter((mount) => mount.split(',').includes('target=/workspace')),
['source=gitnexus-source-${devcontainerId},target=/workspace,type=volume,volume-nocopy'],
);
assert.ok(c.mounts.includes('source=gitnexus-seed-${devcontainerId},target=/seed,type=volume'));
assert.equal(c.workspaceFolder, '/workspace');
assert.equal(
c.onCreateCommand,
'sudo -n node /seed/seed-workspace.cjs --prepare /workspace /seed',
);
assert.deepEqual(c.initializeCommand, [
'node',
'.devcontainer/initialize-volumes.cjs',
'${devcontainerId}',
'source',
]);
}
});
test('native/UI profile inherits hooks, storage and defaults while changing workspace and browser setup', () => {
const c = parse(
profile(source, { native: true, ui: true, playwright: '1.63.0', ref: 'feature/test' }),
);
assert.equal(c.workspaceMount, '');
assert.match(c.onCreateCommand, /bootstrap-native/);
assert.deepEqual(
c.mounts.filter((mount) => mount.split(',').includes('target=/workspace')),
['source=gitnexus-workspace-${devcontainerId},target=/workspace,type=volume'],
);
assert.equal(
c.mounts.some((m) => m.includes('target=/workspace-host,') || m.includes('gitnexus-seed-')),
false,
);
assert.equal(c.containerEnv.GITNEXUS_CLONE_REF, 'feature/test');
assert.equal(c.build.args.PLAYWRIGHT_VERSION, '1.63.0');
assert.equal(c.containerEnv.GITNEXUS_DEV_UI, '1');
assert.ok(c.mounts.some((m) => m.includes('ms-playwright')));
assert.ok(c.mounts.some((m) => m.includes('/home/node/.gitnexus')));
assert.equal(c.capAdd, undefined);
assert.equal(c.initializeCommand.at(-1), 'native');
assert.equal(c.updateContentCommand, 'bash .devcontainer/install-deps.sh');
});
test('image consumers retain configured features and runtime lifecycle', () => {
for (const options of [{}, { native: true }, { ui: true }, { native: true, ui: true }]) {
const image = 'ghcr.io/example/devcontainer@sha256:abcd';
const c = parse(profile(source, { ...options, image }));
assert.equal(c.build, undefined);
assert.equal(c.image, image);
assert.deepEqual(c.features, parse(source).features);
assert.ok(c.features['ghcr.io/devcontainers/features/github-cli:1']);
assert.equal(c.postCreateCommand, 'bash .devcontainer/post-create.sh');
}
});
test('image selection accepts short names, uppercase tags, ports and digests', () => {
for (const image of [
'a',
'a:RC',
'ghcr.io/example/image:ReleaseCandidate',
'localhost:5000/example/image:ReleaseCandidate',
`ghcr.io/example/image@sha256:${'a'.repeat(64)}`,
`ghcr.io/example/image:RC@sha256:${'a'.repeat(64)}`,
]) {
assert.equal(parse(profile(source, { image })).image, image);
}
for (const image of [
'--privileged',
'image;bad',
'image name',
'image\nname',
'$(id)',
'"image"',
])
assert.throws(() => profile(source, { image }), /Invalid image reference/);
});
test('published toolchain metadata excludes host mounts and lifecycle hooks', () => {
const c = parse(profile(source, { imageOnly: true, ui: true, playwright: '1.63.0' }));
assert.equal(c.mounts, undefined);
assert.equal(c.updateContentCommand, undefined);
assert.equal(c.containerEnv, undefined);
assert.equal(c.build.args.INSTALL_BROWSER_DEPS, 'true');
assert.ok(c.features['ghcr.io/devcontainers/features/github-cli:1']);
});
test('profile generator rejects unsafe values and changed canonical layout', () => {
assert.throws(() => profile(source, { ref: '--upload-pack=bad' }), /Invalid/);
assert.throws(() => profile(source, { image: 'image;bad' }), /Invalid/);
assert.throws(
() => profile(source, { imageOnly: true, image: 'ghcr.io/example/image' }),
/--image cannot/,
);
for (const url of ['--upload-pack=bad', 'ext::command', 'https://token@github.com/user/repo.git'])
assert.throws(() => profile(source, { native: true, url }), /Invalid clone URL/);
assert.throws(
() => profile(source.replace('"context": "."', '"context": "elsewhere"')),
/layout changed/,
);
});
test('native branch validation rejects invalid Git refs before generation', () => {
for (const ref of [
'foo..',
'topic/.hidden',
'topic/name.lock',
'topic/name.lock/child',
'topic//child',
'topic/name.',
'topic/',
'HEAD',
]) {
assert.notEqual(spawnSync('git', ['check-ref-format', '--branch', ref]).status, 0);
assert.throws(() => profile(source, { native: true, ref }), /Invalid clone branch/);
}
for (const ref of [
'main',
'feature/fix-123',
'release/v1.2.3',
'topic/name.locked',
'topic/name.LOCK',
]) {
assert.equal(spawnSync('git', ['check-ref-format', '--branch', ref]).status, 0);
assert.equal(
parse(profile(source, { native: true, ref })).containerEnv.GITNEXUS_CLONE_REF,
ref,
);
}
});
test('UI variants preserve empty, custom, and absent capability selections', () => {
for (const capabilities of [[], ['SYS_PTRACE'], undefined]) {
const customized = source.replace(
' "init": true,',
' "init": true,' +
(capabilities === undefined ? '' : `\n "capAdd": ${JSON.stringify(capabilities)},`),
);
for (const options of [{}, { native: true }, { image: 'ghcr.io/example/devcontainer:ui' }]) {
const c = parse(profile(customized, { ...options, ui: true, playwright: '1.63.0' }));
assert.deepEqual(c.capAdd, capabilities);
assert.deepEqual(c.runArgs, ['--shm-size=1g']);
}
}
});
test('native profiles accept fork remotes over HTTPS and Git SSH', () => {
for (const url of [
'https://github.com/contributor/GitNexus.git',
'git@github.com:contributor/GitNexus.git',
'ssh://git@example.com:2222/contributor/GitNexus.git',
]) {
const c = parse(profile(source, { native: true, url, ref: 'feature/fork-only' }));
assert.equal(c.containerEnv.GITNEXUS_CLONE_URL, url);
assert.equal(c.containerEnv.GITNEXUS_CLONE_REF, 'feature/fork-only');
}
});
test('profile CLI validates combinations before writing and generates fork configuration', (t) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-profile-cli-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const config = path.join(root, '.devcontainer');
fs.mkdirSync(config);
for (const file of ['profile.cjs', 'devcontainer.json', 'devcontainer-lock.json'])
fs.copyFileSync(path.join(__dirname, file), path.join(config, file));
fs.mkdirSync(path.join(root, 'gitnexus-web'));
fs.writeFileSync(
path.join(root, 'gitnexus-web/package-lock.json'),
JSON.stringify({
packages: { 'node_modules/@playwright/test': { version: '1.63.0' } },
}),
);
const run = (...args) =>
spawnSync(process.execPath, [path.join(config, 'profile.cjs'), ...args], {
cwd: root,
encoding: 'utf8',
});
for (const [args, error] of [
[
['image-build', '--image', 'ghcr.io/example/image'],
/--image cannot be used with image-build/,
],
[['native', '--url'], /--url requires a value/],
[['native', '--ref', '--ui'], /--ref requires a value/],
[['prebuilt', '--url', 'https://github.com/user/repo.git'], /require the native profile/],
[['native', '--ref', 'main', '--ref', 'other'], /Duplicate profile argument/],
[['native', '--ref', 'foo..'], /Invalid clone branch/],
]) {
const result = run(...args);
assert.notEqual(result.status, 0);
assert.match(result.stderr, error);
assert.equal(fs.existsSync(path.join(config, 'generated')), false);
}
const result = run(
'native',
'--url',
'https://github.com/contributor/GitNexus.git',
'--ref',
'feature/fork-only',
);
assert.equal(result.status, 0, result.stderr);
const c = parse(fs.readFileSync(path.join(config, 'generated/devcontainer.json'), 'utf8'));
assert.equal(c.containerEnv.GITNEXUS_CLONE_URL, 'https://github.com/contributor/GitNexus.git');
assert.equal(c.containerEnv.GITNEXUS_CLONE_REF, 'feature/fork-only');
for (const args of [
['prebuilt'],
['prebuilt', '--ui'],
['native', '--image', 'a'],
['ui', '--image', 'ghcr.io/example/image:ReleaseCandidate'],
]) {
const result = run(...args);
assert.equal(result.status, 0, result.stderr);
const generated = parse(
fs.readFileSync(path.join(config, 'generated/devcontainer.json'), 'utf8'),
);
assert.deepEqual(generated.features, parse(source).features);
if (args.includes('--image')) assert.equal(generated.image, args.at(-1));
}
});
test('native workspace preserves edits, rejects a different origin and resumes interrupted fetches', (t) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-native-profile-'));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const origin = path.join(root, 'origin');
fs.mkdirSync(origin);
const git = (...args) => execFileSync('git', args, { cwd: origin, stdio: 'pipe' });
git('init', '-b', 'main');
git('config', 'user.name', 'Profile test');
git('config', 'user.email', 'profile@example.invalid');
git('config', 'commit.gpgsign', 'false');
git('config', 'core.hooksPath', '/dev/null');
fs.writeFileSync(path.join(origin, 'file'), 'source');
git('add', 'file');
git('commit', '-m', 'fixture');
const checkout = path.join(root, 'checkout');
fs.mkdirSync(path.join(checkout, 'node_modules'), { recursive: true });
const bin = path.join(root, 'bin');
fs.mkdirSync(bin);
const ownershipLog = path.join(root, 'ownership.json');
fs.writeFileSync(
path.join(bin, 'sudo'),
`#!${process.execPath}\nrequire('node:fs').writeFileSync(${JSON.stringify(ownershipLog)}, JSON.stringify(process.argv.slice(2)));\n`,
{ mode: 0o755 },
);
const result = spawnSync(
process.execPath,
[path.join(__dirname, 'bootstrap-native.cjs'), checkout],
{
encoding: 'utf8',
env: {
...process.env,
PATH: `${bin}:${process.env.PATH}`,
GITNEXUS_CLONE_URL: origin,
GITNEXUS_CLONE_REF: 'main',
},
},
);
assert.equal(result.status, 0, result.stderr);
const ownership = JSON.parse(fs.readFileSync(ownershipLog, 'utf8'));
assert.deepEqual(ownership.slice(0, 4), ['-n', 'find', checkout, '-xdev']);
assert.ok(ownership.includes('-h'));
const checkoutGit = (...args) =>
execFileSync('git', args, { cwd: checkout, encoding: 'utf8' }).trim();
assert.equal(checkoutGit('rev-parse', '--abbrev-ref', '@{upstream}'), 'origin/main');
assert.match(checkoutGit('pull'), /Already up to date/);
fs.writeFileSync(path.join(checkout, 'file'), 'local edits');
bootstrap(checkout, origin, 'main');
assert.equal(fs.readFileSync(path.join(checkout, 'file'), 'utf8'), 'local edits');
assert.throws(() => bootstrap(checkout, path.join(root, 'other'), 'main'), /another origin/);
const retry = path.join(root, 'retry');
assert.throws(() => bootstrap(retry, origin, 'new-branch'));
git('branch', 'new-branch');
bootstrap(retry, origin, 'new-branch');
assert.equal(fs.readFileSync(path.join(retry, 'file'), 'utf8'), 'source');
assert.equal(
execFileSync('git', ['rev-parse', '--abbrev-ref', '@{upstream}'], {
cwd: retry,
encoding: 'utf8',
}).trim(),
'origin/new-branch',
);
const conflict = path.join(root, 'conflict');
fs.mkdirSync(conflict);
fs.writeFileSync(path.join(conflict, 'file'), 'pre-existing user file');
assert.throws(() => bootstrap(conflict, origin, 'main'));
assert.equal(fs.readFileSync(path.join(conflict, 'file'), 'utf8'), 'pre-existing user file');
const ignored = path.join(root, 'ignored-conflict');
fs.mkdirSync(ignored);
execFileSync('git', ['init', '-q'], { cwd: ignored });
fs.writeFileSync(path.join(ignored, '.git/info/exclude'), 'file\n');
fs.writeFileSync(path.join(ignored, 'file'), 'ignored user file');
assert.throws(() => bootstrap(ignored, origin, 'main'));
assert.equal(fs.readFileSync(path.join(ignored, 'file'), 'utf8'), 'ignored user file');
// Preserve the user's file elsewhere, then verify the same checkout can resume.
fs.renameSync(path.join(ignored, 'file'), path.join(ignored, 'saved-user-file'));
bootstrap(ignored, origin, 'main');
assert.equal(fs.readFileSync(path.join(ignored, 'file'), 'utf8'), 'source');
assert.equal(fs.readFileSync(path.join(ignored, 'saved-user-file'), 'utf8'), 'ignored user file');
});