GitNexus/.devcontainer/profile.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

170 lines
6.6 KiB
JavaScript

'use strict';
const fs = require('node:fs');
const path = require('node:path');
function replaceOnce(text, pattern, replacement) {
const matches = text.match(new RegExp(pattern.source, 'g'));
if (matches?.length !== 1) throw new Error(`Canonical devcontainer layout changed: ${pattern}`);
return text.replace(pattern, () => replacement);
}
function profile(
source,
{
native = false,
ui = false,
image,
imageOnly = false,
ref = 'main',
playwright,
url = 'https://github.com/abhigyanpatwari/GitNexus.git',
} = {},
) {
if (imageOnly && image) throw new Error('--image cannot be used with image-build');
if (
typeof ref !== 'string' ||
!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(ref) ||
ref === 'HEAD' ||
ref.includes('..') ||
ref.endsWith('.') ||
ref.split('/').some((part) => !part || part.startsWith('.') || part.endsWith('.lock'))
)
throw new Error('Invalid clone branch');
// Character safety check only; Docker validates the image reference grammar.
if (image && !/^[a-zA-Z0-9][a-zA-Z0-9./:_@-]*$/.test(image))
throw new Error('Invalid image reference');
if (
native &&
!/^(?:https:\/\/[a-zA-Z0-9.-]+(?::[0-9]+)?\/|ssh:\/\/git@[a-zA-Z0-9.-]+(?::[0-9]+)?\/|git@[a-zA-Z0-9.-]+:)[a-zA-Z0-9._/-]+$/.test(
url,
)
)
throw new Error('Invalid clone URL; use HTTPS or Git SSH without embedded credentials');
let result = source;
if (image) {
const start = result.indexOf(' "build": {');
const end = result.indexOf('\n // Runs on the HOST', start);
if (start < 0 || end < 0) throw new Error('Canonical build block changed');
result = result.slice(0, start) + ` "image": ${JSON.stringify(image)},\n` + result.slice(end);
} else {
result = replaceOnce(result, /"dockerfile": "Dockerfile"/, '"dockerfile": "../Dockerfile"');
result = replaceOnce(result, /"context": "\."/, '"context": ".."');
if (ui) {
if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(playwright))
throw new Error('Locked Playwright version required');
result = replaceOnce(
result,
/"BUN_VERSION":/,
`"INSTALL_BROWSER_DEPS": "true",\n "PLAYWRIGHT_VERSION": ${JSON.stringify(playwright)},\n "BUN_VERSION":`,
);
}
}
if (native) {
// The explicit native profile still clones a remote branch; the default
// profile instead preserves the host checkout, including uncommitted work.
result = replaceOnce(
result,
/"\$\{devcontainerId\}",\s*"source"/,
'"${devcontainerId}", "native"',
);
result = replaceOnce(
result,
/"source=gitnexus-source-\$\{devcontainerId\},target=\/workspace,[^"]+",\s*"source=gitnexus-seed-[^"]+"/,
'"source=gitnexus-workspace-${devcontainerId},target=/workspace,type=volume"',
);
result = replaceOnce(
result,
/"CODEX_HOME":/,
`"GITNEXUS_CLONE_URL": ${JSON.stringify(url)},\n ` +
`"GITNEXUS_CLONE_REF": ${JSON.stringify(ref)},\n "CODEX_HOME":`,
);
result = replaceOnce(
result,
/"onCreateCommand": "[^"\n]+"/,
'"onCreateCommand": "node /usr/local/share/gitnexus-devcontainer/bootstrap-native.cjs"',
);
}
if (imageOnly) {
const start = result.indexOf(' "build": {');
const end = result.indexOf('\n // Runs on the HOST', start);
const features = result.match(/"features": \{[\s\S]*?\n \},/);
if (start < 0 || end < 0 || !features)
throw new Error('Image build requires the canonical build and feature blocks');
// Publish toolchain metadata only. Lifecycle hooks and host mounts belong
// to the consuming profile, avoiding duplicate hook execution on attach.
return '{\n' + result.slice(start, end) + '\n ' + features[0].slice(0, -1) + '\n}\n';
}
if (ui) {
result = replaceOnce(
result,
/"CODEX_HOME":/,
'"GITNEXUS_DEV_UI": "1",\n "PLAYWRIGHT_BROWSERS_PATH": "/home/node/.cache/ms-playwright",\n "CODEX_HOME":',
);
result = replaceOnce(
result,
/"source=npm-cache-/,
'"source=playwright-cache-${devcontainerId},target=/home/node/.cache/ms-playwright,type=volume",\n "source=npm-cache-',
);
result = replaceOnce(
result,
/"workspaceMount":/,
'"runArgs": ["--shm-size=1g"],\n "workspaceMount":',
);
}
return result;
}
module.exports = { profile };
if (require.main === module) {
const [mode, ...args] = process.argv.slice(2);
if (!['native', 'ui', 'prebuilt', 'image-build'].includes(mode))
throw new Error(
'Usage: node .devcontainer/profile.cjs native [--ui] [--image IMAGE] [--ref BRANCH] [--url URL]\n' +
' node .devcontainer/profile.cjs ui [--image IMAGE]\n' +
' node .devcontainer/profile.cjs prebuilt [--ui] [--image IMAGE]\n' +
' node .devcontainer/profile.cjs image-build [--ui]',
);
const options = new Map();
for (let i = 0; i < args.length; i++) {
const flag = args[i];
if (!['--ui', '--image', '--ref', '--url'].includes(flag))
throw new Error(`Unknown profile argument: ${flag}`);
if (options.has(flag)) throw new Error(`Duplicate profile argument: ${flag}`);
if (flag === '--ui') options.set(flag, true);
else {
const value = args[++i];
if (!value || value.startsWith('--')) throw new Error(`${flag} requires a value`);
options.set(flag, value);
}
}
if (mode === 'image-build' && options.has('--image'))
throw new Error('--image cannot be used with image-build');
if (mode !== 'native' && (options.has('--ref') || options.has('--url')))
throw new Error('--ref and --url require the native profile');
const lock = JSON.parse(
fs.readFileSync(path.join(__dirname, '../gitnexus-web/package-lock.json')),
);
const output = path.join(__dirname, 'generated');
const contents = profile(fs.readFileSync(path.join(__dirname, 'devcontainer.json'), 'utf8'), {
native: mode === 'native',
ui: mode === 'ui' || options.has('--ui'),
image:
options.get('--image') ||
(mode === 'prebuilt'
? `ghcr.io/abhigyanpatwari/gitnexus-devcontainer:main${options.has('--ui') ? '-ui' : ''}`
: undefined),
imageOnly: mode === 'image-build',
ref: options.get('--ref'),
url: options.get('--url'),
playwright: lock.packages['node_modules/@playwright/test'].version,
});
fs.mkdirSync(output, { recursive: true });
fs.writeFileSync(path.join(output, 'devcontainer.json'), contents);
fs.copyFileSync(
path.join(__dirname, 'devcontainer-lock.json'),
path.join(output, 'devcontainer-lock.json'),
);
console.log(
'Generated .devcontainer/generated/devcontainer.json; select it when reopening in container. Regenerate after updating the main configuration.',
);
}