diff --git a/AGENTS.md b/AGENTS.md index 773417c..730d39b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -604,3 +604,11 @@ validated exports of older historical data will use a dedicated Atlas NFS datase not depend on the AdGuard container during startup. - Aegis iCloudPD has been retired and is no longer managed by this role. Its service, Quadlet, data, and MFA state were removed with the operator's explicit authorization. + +## Project Devcontainer Generator +- `scripts/devcontainer.py` generates standalone per-project language configurations; + it does not replace existing deadalus ecaas/cdp provisioning or remove host tools. +- Keep shared Git/agent behavior documented in `docs/project-devcontainers.md`. +- Focused validation: `python3 -m unittest discover -s tests -p test_devcontainer.py -v`. +- Real engine builds, host credential forwarding and Fedora SELinux/Podman checks + require target-host validation; do not report generator tests as runtime evidence. diff --git a/README.md b/README.md index 0ef4845..e825965 100644 --- a/README.md +++ b/README.md @@ -893,3 +893,10 @@ For a future Void desktop host: 4. Put hardware-specific details in `host_vars/.yml`. The legacy `void` and `desktop` groups remain compatibility parents, so hosts in `platform_void` and `graphical_desktop` still receive the existing Void and desktop variables. + +## Project devcontainer generator + +Generate a reusable language environment for an existing project with +`python3 scripts/devcontainer.py ~/src/project --language python --agents codex,cline`. +Git and selected coding-agent configuration are shared from the development host. +See [profiles, host requirements and validation](docs/project-devcontainers.md). diff --git a/docs/project-devcontainers.md b/docs/project-devcontainers.md new file mode 100644 index 0000000..74ce465 --- /dev/null +++ b/docs/project-devcontainers.md @@ -0,0 +1,90 @@ +# Reusable project devcontainers + +`scripts/devcontainer.py` is a Python 3 CLI (standard library only). Run it on +**the development host**, from an `infra` checkout, against an existing project: + +```sh +python3 scripts/devcontainer.py ~/src/my-project --language go +python3 scripts/devcontainer.py ~/src/my-project --language python --agents codex,cline +python3 scripts/devcontainer.py ~/src/my-project --language c-cpp --agents none +``` + +Profiles: `c-cpp`, `go`, `rust`, `python`, `node`, `java`, `infra`. They generate +`.devcontainer/devcontainer.json` and `Dockerfile`. Open the project in local VS +Code (in Fedora WSL on deadalus) and choose **Reopen in Container**. The generator +never builds or starts a container, selects a Docker context, modifies application +sources, or removes host packages. Existing `.devcontainer` directories are refused; +`--force` replaces only the two generated files, so commit or back up edits first. + +The definitions live centrally in the generator; generated files are standalone. +Regenerate explicitly to take updates. Profile images select a language version +or release family, not immutable digests; npm agents other than Claude currently +resolve the latest release at container creation, matching the host lifecycle. +Rebuilds are therefore not bit-for-bit reproducible. Pin image digests and agent +versions in generated project files when a project requires that guarantee. +Project-specific dependencies, ports, services and build commands belong in the +project configuration. The `infra` profile provides Ansible and linters; install +that project's collection requirements inside it separately. + +## Shared Git and agents + +Like the ecaas/cdp model, executables run inside the container and personal +configuration stays on the host. The generator detects existing configuration +paths without reading credentials. With `--agents auto` (the default), it selects +agents whose configuration directories already exist. Explicit agent selection +fails if required directories are missing. Supported agents: `codex`, `cline`, +`opencode`, `claude`, `gemini`. IBM Bob and desktop applications are not included. + +Host `~/.gitconfig` is mounted read-only at `/run/host-gitconfig` and included from +a writable container Git config, allowing VS Code to register its credential +helper. Existing `~/.config/git` and `~/.gitignore_global` are mounted read-only. +Git, Git LFS, delta, OpenSSH and GnuPG are installed. VS Code Dev Containers handles +SSH-agent and HTTPS credential-helper forwarding; start VS Code from the host +session with its working agent. No SSH/GPG private-key directories are mounted. +GPG signing needs a functioning agent-forwarding setup and a test with your key; +the generator does not provision it. Host-specific helpers, `pinentry`, external +Git includes, conditional includes and CA paths still need container-compatible +configuration or additional narrowly scoped mounts. Recreate the container after +replacing a bind-mounted configuration file atomically on the host. + +`~/.config/ai` is mounted read-only when present. Selected agents mount their host +configuration/state directories read-write, including credentials, sessions and +rules; changes inside the container affect the host. OpenCode also shares its +XDG data/state directories. The container user remains `vscode`, with its home set +to the **same absolute path as the generating host**, so Codex's absolute +`model_instructions_file` keeps working. This does not mount the full home. +For a different host home path, regenerate there. Host-only programs referenced +by agent settings are not made available automatically. + +Claude also mounts `~/.claude.json` when present and forwards +`ANTHROPIC_AUTH_TOKEN` using `${localEnv:ANTHROPIC_AUTH_TOKEN}` as on deadalus. +Start VS Code from a shell that exports it; no token value is generated. Host +keyring-backed logins require separate integration; sharing a directory does not +forward the desktop keyring. VS Code extension storage is not shared. + +Only existing paths are mounted. Regenerate after configuring an additional +agent. Generated files use `${localEnv:HOME}` for mount sources and contain no +credential contents, but do contain the host's absolute home path. + +## Runtime and validation + +Use a local development container engine. Docker CE is currently provisioned on +deadalus; ikaros explicitly has Podman, while nymph's runtime needs verification. +Podman requires VS Code's `dev.containers.dockerPath` and compatible rootless/UID +configuration; generation alone does not configure it. SELinux bind-mount access +must also be validated on Fedora. Do not recursively relabel the personal home. +No engine socket is mounted inside these containers by default; add access only +for projects that need to launch sibling containers. + +Host-side regression checks: + +```sh +python3 -m unittest discover -s tests -p test_devcontainer.py -v +``` + +On the target host, build/open a generated project, check the language toolchain, +`git config --show-origin --get user.email`, `git ls-remote origin HEAD` against +the expected development remote, and each selected agent's version/login. +Run project tests and verify signing if enabled. These runtime checks require the +real host and are separate from generator tests. Existing ecaas/cdp Ansible +provisioning is unchanged. diff --git a/scripts/devcontainer.py b/scripts/devcontainer.py new file mode 100755 index 0000000..391be9c --- /dev/null +++ b/scripts/devcontainer.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""Generate a project devcontainer using host Git and coding-agent configuration.""" +import argparse +import json +import os +from pathlib import Path +import shlex +import tempfile + +PROFILES = { + 'c-cpp': ('mcr.microsoft.com/devcontainers/base:bookworm', + 'build-essential clang clangd cmake gdb valgrind universal-ctags cscope', + ['ms-vscode.cpptools', 'ms-vscode.cmake-tools']), + 'go': ('mcr.microsoft.com/devcontainers/go:1.25-bookworm', '', ['golang.go']), + 'rust': ('mcr.microsoft.com/devcontainers/rust:1-bookworm', '', ['rust-lang.rust-analyzer']), + 'python': ('mcr.microsoft.com/devcontainers/python:3.13-bookworm', '', + ['ms-python.python', 'charliermarsh.ruff']), + 'node': ('mcr.microsoft.com/devcontainers/javascript-node:22-bookworm', '', ['esbenp.prettier-vscode']), + 'java': ('mcr.microsoft.com/devcontainers/java:21-bookworm', 'maven', ['vscjava.vscode-java-pack']), + 'infra': ('mcr.microsoft.com/devcontainers/python:3.13-bookworm', 'shellcheck shfmt', + ['redhat.ansible', 'redhat.vscode-yaml']), +} +AGENTS = { + 'codex': ('@openai/codex', ['.codex']), + 'cline': ('cline', ['.cline', '.agents']), + 'opencode': ('opencode-ai', ['.config/opencode', '.local/share/opencode', '.local/state/opencode']), + 'claude': ('@anthropic-ai/claude-code@2.1.312', ['.claude']), + 'gemini': ('@google/gemini-cli', ['.gemini']), +} + + +def generate(project, profile, home, agents, force=False): + project, home = Path(project).resolve(), Path(home).resolve() + if not project.is_dir(): + raise ValueError(f'Project directory does not exist: {project}') + if home == Path('/') or any(c in str(home) for c in '\n\r$,'): + raise ValueError('Unsupported host home path') + target = project / '.devcontainer' + if target.is_symlink(): + raise ValueError('Refusing a symlinked .devcontainer directory') + if target.exists() and not force: + raise ValueError('.devcontainer already exists; use --force to replace generated files') + mount_paths = [('.gitconfig', True), ('.config/git', True), ('.gitignore_global', True), + ('.config/ai', True)] + for agent in agents: + for path in AGENTS[agent][1]: + if not (home / path).is_dir(): + raise ValueError(f'Missing host directory for {agent}: {home / path}') + mount_paths.append((path, False)) + # Claude uses both a config directory and a separate onboarding/account file. + if 'claude' in agents: + mount_paths.append(('.claude.json', False)) + mounts = [] + for path, readonly in mount_paths: + if (home / path).exists(): + mounts.append({'type': 'bind', 'source': '${localEnv:HOME}/' + path, + 'target': '/run/host-gitconfig' if path == '.gitconfig' else str(home / path), + 'readOnly': readonly}) + base, packages, extensions = PROFILES[profile] + dockerfile = f'''FROM {base} +USER root +RUN apt-get update && apt-get install -y --no-install-recommends \\ + bash-completion ca-certificates curl fzf git git-lfs gnupg openssh-client ripgrep zoxide {packages} \\ + && rm -rf /var/lib/apt/lists/* +''' + dockerfile += r'''RUN apt-get update \ + && arch="$(dpkg --print-architecture)" \ + && case "$arch" in \ + amd64) sha256=ea4f0222950ee750a3d38dd80d03bce4cee07a3f63928fc47548383bcaf23093 ;; \ + arm64) sha256=0edc36cf514f1bd84becac3e94ee8ae9f8818c6a1f99f7b2ee67b362afa253d3 ;; \ + *) echo "Unsupported architecture for delta: $arch" >&2; exit 1 ;; \ + esac \ + && curl -fsSL --retry 3 "https://github.com/dandavison/delta/releases/download/0.19.2/git-delta_0.19.2_${arch}.deb" -o /tmp/git-delta.deb \ + && echo "$sha256 /tmp/git-delta.deb" | sha256sum -c - \ + && apt-get install -y --no-install-recommends /tmp/git-delta.deb \ + && rm -rf /var/lib/apt/lists/* /tmp/git-delta.deb +''' + # Preserve absolute references from host agent configuration without mounting the home. + if home != Path('/home/vscode'): + dockerfile += 'RUN usermod --home ' + shlex.quote(str(home)) + ' --move-home vscode\n' + dockerfile += 'ENV HOME=' + shlex.quote(str(home)) + '\n' + if profile in ('python', 'infra'): + tools = 'uv ruff ty' if profile == 'python' else 'ansible-core ansible-lint yamllint' + dockerfile += f'RUN python -m pip install --no-cache-dir {tools}\n' + features = {} + if agents and profile != 'node': + features['ghcr.io/devcontainers/features/node:1'] = {'version': '22'} + config = { + 'name': f'{project.name} — {profile}', + 'build': {'dockerfile': 'Dockerfile'}, + 'remoteUser': 'vscode', 'updateRemoteUserUID': True, + 'containerEnv': {'HOME': str(home)}, + 'mounts': mounts, + 'customizations': {'vscode': {'extensions': extensions}}, + } + if agents: + # Node feature is installed after the Dockerfile, so install CLIs at creation. + npm = ' '.join(shlex.quote(AGENTS[a][0]) for a in agents) + config['postCreateCommand'] = f'sudo npm install --global --no-audit --no-fund {npm}' + if features: + config['features'] = features + if 'claude' in agents: + config['remoteEnv'] = {'ANTHROPIC_AUTH_TOKEN': '${localEnv:ANTHROPIC_AUTH_TOKEN}'} + dockerfile += 'USER vscode\n' + if (home / '.gitconfig').exists(): + dockerfile += 'RUN git config --global include.path /run/host-gitconfig\n' + for name, content in [('Dockerfile', dockerfile), + ('devcontainer.json', json.dumps(config, indent=2) + '\n')]: + destination = target / name + if destination.is_symlink(): + raise ValueError(f'Refusing symlink: {destination}') + target.mkdir(exist_ok=True) + for name, content in [('Dockerfile', dockerfile), + ('devcontainer.json', json.dumps(config, indent=2) + '\n')]: + with tempfile.NamedTemporaryFile(mode='w', dir=target, delete=False) as stream: + stream.write(content) + temp = Path(stream.name) + temp.chmod(0o644) + os.replace(temp, target / name) + return target + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('project', type=Path) + parser.add_argument('--language', required=True, choices=PROFILES) + parser.add_argument('--agents', default='auto', + help='Comma-separated codex,cline,opencode,claude,gemini; auto detects host config; none disables') + parser.add_argument('--force', action='store_true', help='Replace the two generated files') + args = parser.parse_args() + home = Path.home() + if args.agents == 'auto': + agents = [a for a, (_, paths) in AGENTS.items() if all((home / p).is_dir() for p in paths)] + else: + agents = [] if args.agents == 'none' else list(dict.fromkeys(args.agents.split(','))) + if any(a not in AGENTS for a in agents): + parser.error('Unknown agent; choose ' + ', '.join(AGENTS)) + try: + target = generate(args.project, args.language, home, agents, args.force) + except (ValueError, OSError) as error: + parser.exit(1, f'{error}\n') + print(f'Created {target}; agents: {", ".join(agents) or "none"}') + print('Open the project in VS Code and choose Dev Containers: Reopen in Container.') + + +if __name__ == '__main__': + main() diff --git a/tests/test_devcontainer.py b/tests/test_devcontainer.py new file mode 100644 index 0000000..8bdc0e1 --- /dev/null +++ b/tests/test_devcontainer.py @@ -0,0 +1,68 @@ +"""Host-side generator regression tests; no engine or credentials required.""" +import importlib.util +import json +from pathlib import Path +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location('generator', Path(__file__).resolve().parents[1] / 'scripts/devcontainer.py') +generator = importlib.util.module_from_spec(spec) +spec.loader.exec_module(generator) + + +class GeneratorTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.home = self.root / 'host home' + self.home.mkdir() + self.project = self.root / 'project with spaces' + self.project.mkdir() + + def test_every_profile_produces_valid_config(self): + for profile in generator.PROFILES: + with self.subTest(profile=profile): + target = generator.generate(self.project, profile, self.home, [], force=True) + config = json.loads((target / 'devcontainer.json').read_text()) + self.assertEqual(config['containerEnv']['HOME'], str(self.home)) + self.assertNotIn('postCreateCommand', config) + self.assertTrue((target / 'Dockerfile').read_text().endswith('USER vscode\n')) + + def test_host_config_is_mounted_without_copying_secrets(self): + (self.home / '.codex').mkdir() + (self.home / '.codex/auth.json').write_text('secret-value') + (self.home / '.gitconfig').write_text('[user]\nname = Test\n') + target = generator.generate(self.project, 'python', self.home, ['codex']) + text = (target / 'devcontainer.json').read_text() + config = json.loads(text) + self.assertNotIn('secret-value', text + (target / 'Dockerfile').read_text()) + git_mount = next(m for m in config['mounts'] if m['target'] == '/run/host-gitconfig') + self.assertTrue(git_mount['readOnly']) + agent_mount = next(m for m in config['mounts'] if m['target'] == str(self.home / '.codex')) + self.assertFalse(agent_mount['readOnly']) + self.assertIn('include.path /run/host-gitconfig', (target / 'Dockerfile').read_text()) + + def test_refuses_existing_config(self): + target = generator.generate(self.project, 'go', self.home, []) + before = (target / 'devcontainer.json').read_bytes() + with self.assertRaises(ValueError): + generator.generate(self.project, 'rust', self.home, []) + self.assertEqual(before, (target / 'devcontainer.json').read_bytes()) + + def test_missing_agent_config_does_not_write(self): + with self.assertRaises(ValueError): + generator.generate(self.project, 'go', self.home, ['codex']) + self.assertFalse((self.project / '.devcontainer').exists()) + + def test_force_rejects_symlink_without_modifying_other_files(self): + target = generator.generate(self.project, 'go', self.home, []) + before = (target / 'Dockerfile').read_bytes() + (target / 'devcontainer.json').unlink() + victim = self.root / 'victim' + victim.write_text('keep') + (target / 'devcontainer.json').symlink_to(victim) + with self.assertRaises(ValueError): + generator.generate(self.project, 'rust', self.home, [], force=True) + self.assertEqual(victim.read_text(), 'keep') + self.assertEqual(before, (target / 'Dockerfile').read_bytes())