Search/Build a Rootless Container Tool with Container Locks and Verified Image Downloads

Build a Rootless Container Tool with Container Locks and Verified Image Downloads

Use when building a container tool that runs without root. The AI locks containers during changes, checks every downloaded image layer, keeps host settings out of containers, stops whole process trees, and rejects unsafe paths when restoring backups.

To use this AI rule
## Build the Core on the Standard Library and Detect Mobile Hosts Keep the core runtime free of third-party dependencies and prefer language-native facilities over shelling out for system queries, downloads, archives, and platform inspection. ### Dependency Policy - Use the standard library for terminal capability checks, user and group data, binary inspection, architecture detection, HTTP, and archives. - Run only the container runtime required for actual isolation. - If that runtime is missing on a supported host, offer installation only on an interactive terminal and only after the user agrees. - Execute the runtime by replacing the current process when appropriate instead of adding a shell layer. - Keep the package manifest as the version source of truth, with a documented fallback for uninstalled source trees. - Route all command aliases and console entrypoints to one canonical main function. ### Platform Detection - Detect a specialized mobile host only when at least two independent signals agree: operating-system evidence, dedicated environment variables, and an accessible platform prefix. - Compute the result once and use it consistently for paths, default environment, available flags, bindings, and runtime extensions. - Default ordinary hosts to standard base-directory conventions with no mobile-specific bindings. ## Identify Containers by Folder Name and Handle Special Guests Separately Make directory identity, metadata presence, legacy migration, and guest behavior separate decisions. ### Storage Model - Use the validated directory name as the sole container identifier. - Store the assembled filesystem beneath that directory and keep image metadata in a separate manifest. - Allow plain archive installs to omit image metadata when no registry image exists. - Migrate legacy layouts on the first operation that needs the new structure, then rewrite affected compatibility links. - Derive runtime, cache, container, session, layer, and manifest locations from one platform-aware path module. - Validate container names at every entrypoint, including aliases derived from images and names read from archives. ### Guest Classification - Detect a specialized guest with a sentinel that must be a file, not merely an existing path; concurrent sessions may materialize bind targets as directories. - Give specialized guests their own home, path, prefix, and temporary-directory baseline. - Never bind the host application's private directories or installation prefix over a guest that supplies its own. - Disable incompatible link conversion and identity-changing options for that guest type. - Apply optional host-system bindings only outside isolated and minimal modes. - Refuse cross-architecture specialized guests when a shared prefix would let host binaries shadow guest binaries. ## Route Commands Correctly and Protect Writes with Locks and Temp Files Command parsing and lock ownership must remain correct across interruption, re-entrancy, process replacement, detachment, and concurrent cache activity. ### CLI Flow 1. Map secondary quit signals into the normal interruption path so progress and partial files are cleaned consistently. 2. Warn about elevated execution without making the warning fatal, and reject nested container-runtime invocation. 3. Probe the runtime only for commands that need it; let inspection, process, and image-only commands define narrower gates. 4. Intercept command help before positional validation, and reject unknown commands before general parsing. 5. Preserve tokens after the literal option delimiter for commands that launch an inner program. 6. Enforce required arguments centrally, except where input mode intentionally determines requirements. 7. Apply global quiet mode before dispatch while preserving command-specific meanings and always showing errors and warnings. ### Locks and Atomicity - Use shared locks for read-like sessions and backups, and exclusive locks for install, remove, rename, reset, restore, and destination writes. - Acquire multiple container locks in sorted path order. - Key build locks by output image and architecture while protecting shared cache indexes with their own lock. - Make exclusive locks re-entrant for commands that call another mutating command on the same container. - Let session locks survive process replacement, and disown rather than unlock them when a detached descendant inherits ownership. - On lock conflict, fail immediately and report the holder when it can be identified. - Every cache and sentinel writer must use temporary-file creation followed by atomic replacement and cleanup on all exceptions. ## Check Downloaded Image Layers and Protect Registry Credentials Treat registry references, authentication, redirects, digests, layers, and archive members as hostile until validated. ### Pull and Cache - Prefer a complete verified cache for offline use; when only layers are missing, fetch only those layers. - Stream-hash every downloaded layer and compare its digest before promotion. - Validate digest syntax before converting it into a filesystem path so crafted references cannot escape the cache root. - Refuse compression formats that the archive implementation cannot safely decode. - Implement opaque and per-entry whiteouts, filter hardlink targets, and reject member-name traversal. ### Authentication and Push - Require an explicit username-and-password form before forwarding basic credentials to a token service. - Strip authorization headers on cross-host redirects. - Scope acquired tokens to the requested pull or push actions. - Before push, canonicalize the stored configuration and verify its digest against the manifest. - Probe remote blobs and upload only missing content. - Keep unsupported upload modes and multi-architecture indexes out of scope rather than approximating them. - Surface authorization failures as permission errors without exposing credentials. ## Report the Guest's Architecture and Build the Child Environment from Scratch Architecture reporting and child environments must describe the guest, not accidentally inherit the host. ### Architecture - Detect an installed guest architecture from binary headers in known executables. - Normalize native, registry, and platform-prefixed architecture names through one mapping. - Select an emulator only when native execution is unavailable, and bind only the system paths its loader requires. - Report the guest architecture and emulated kernel identity instead of copying the host value. ### Child Environment - Build the child environment from an empty mapping and pass it directly to process replacement. - Apply precedence deliberately: baseline, filtered image variables, allowed host variables, user overrides, identity variables, then terminal variables. - Apply image and user variables in every mode, while limiting mobile host variables to the ordinary non-isolated mode. - In minimal mode, omit baseline path, host integration variables, and user identity unless explicitly required. - Validate variable names before writing a login profile and quote values safely. - Exclude per-session, runtime-internal, loader, and identity variables from persistent profiles. - Strip loader-preload variables before execution and keep shared compatibility directories stable across concurrent sessions. ## Run Containers in the Background and Stop Their Whole Process Tree Run, detach, terminate, and build operations must preserve manifest behavior, lock lifetime, portability, and process ownership. ### Run and Detach - Combine image entrypoint and command values according to container-image semantics. - Honor an explicit working-directory override and otherwise use the image setting or the filesystem root. - Resolve command-preview mode before any detach branch. - Detach with a double fork and new session, redirect standard streams, and register the final runtime process in the grandchild. - Relay the final process identifier to the foreground and leave the inherited container lock held by the detached descendant. ### Safe Termination and Builds - Resolve termination targets only from the active-session registry. - Terminate the complete descendant tree, not only the root runtime process. - Build a cycle-safe parent map, never signal the current process or system-critical process identifiers, and verify the root executable before walking it. - Use a graceful termination signal by default and allow an explicit named or numeric override. - Parse build stages and global arguments before execution, validate targets early, and dispatch metadata, run, copy, and add operations through dedicated handlers. - Run build steps isolated and non-interactive unless a here-document supplies input. - Key build cache entries by parent state, instruction, and relevant extra input; lock cache-index updates. - Exclude runtime compatibility metadata from portable layer snapshots while preserving the referenced file content. ## Back Up and Restore Containers While Rejecting Unsafe Archive Entries Archives and terminal output cross trust boundaries and must not corrupt container state or interactive prompts. ### Backup and Restore - Store each container under one archive root containing optional metadata and the filesystem tree. - Make unreadable subtrees accessible for backup, filter devices and communication endpoints, and normalize ownership metadata. - Refuse binary archive output to an interactive terminal unless an explicit output destination is provided. - Detect compression from archive data and standard formats, including streamed input. - Re-root legacy archive layouts into the current container structure. - Reject empty, current-directory, parent-directory, and invalid container-name members. - Acquire the destination lock and clear an existing filesystem only when the first valid member for that container is ready to restore. ### Terminal and Command Integration - Suppress informational terminal writes while a sibling password or full-screen prompt owns terminal echo or canonical mode. - Keep help content as data and render it responsively within documented width bounds. - Register every new command in dispatch, parsing metadata, required arguments, help data, and alias maps. - Preserve the package license header and naming conventions in every new source file.