@adrifer/winix 0.3.0-preview.0 → 0.3.0-preview.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -100,7 +100,8 @@ For what it's worth: Winix today works just as well on macOS and native NixOS as
100
100
  `winix-windows-x64.exe`, `winix-windows-arm64.exe`, `winix-linux-x64`,
101
101
  `winix-linux-arm64`, and `SHA256SUMS`. Choose a versioned release and the native
102
102
  architecture, compare its SHA256 with `SHA256SUMS`, and keep the executable
103
- outside the config checkout. Windows binaries are not yet code-signed:
103
+ outside tracked files (repository bootstrap uses the ignored `.winix` directory).
104
+ Windows binaries are not yet code-signed:
104
105
  checksums detect corruption, not publisher identity. Respect organizational
105
106
  execution/network policies; do not disable TLS verification.
106
107
  Redistribution notices and runtime source/rebuild references accompany the
@@ -144,6 +145,87 @@ must come from a complete official release; developer single-target builds
144
145
  lack the Linux checksums. ARM64 assets are cross-compiled; fresh-machine
145
146
  activation and ARM64 execution are not yet verified.
146
147
 
148
+ ### Bootstrap an existing repository
149
+
150
+ The Winix-owned `bootstrap-windows.ps1` and `bootstrap-linux.sh` release assets
151
+ prepare a trusted config repository without Node/npm. Download the script and
152
+ its `.sha256` from a **versioned release supporting repository bootstrap**,
153
+ verify the checksum, and review the script before running it. Do not pipe
154
+ unreviewed internet code into a shell. Checksums share the release's trust
155
+ boundary; they are not signatures.
156
+
157
+ ```powershell
158
+ .\bootstrap-windows.ps1 -Repository https://github.com/example/dotfiles.git `
159
+ -Ref main -Destination "$HOME\dotfiles" -ConfigDirectory winix `
160
+ -HostName windows-devbox -PrepareOnly
161
+ ```
162
+
163
+ ```bash
164
+ bash bootstrap-linux.sh --repository https://github.com/example/dotfiles.git \
165
+ --ref main --destination "$HOME/dotfiles" --config-directory winix \
166
+ --host linux-desktop --prepare-only
167
+ ```
168
+
169
+ Windows needs App Installer/WinGet initially. It ensures Git, makes a regular
170
+ clone, reads `config-directory/package.json` **without importing the config**,
171
+ then verifies and installs that exact release's native executable and
172
+ prerequisite-only script. Native PowerShell/DSC prerequisites are installed
173
+ without Node or PSGallery registration: feeds belong to the selected host.
174
+ Linux uses existing Nix to obtain temporary Git/Python tools, or requires
175
+ Git and Python 3 installed through your approved package manager. It does not
176
+ install Nix or turn another distribution into NixOS. Generic glibc Linux needs
177
+ libstdc++; NixOS gets a private, GC-rooted pinned libc/compiler launcher.
178
+ Real activation still requires the target's existing Nix/activation tools.
179
+
180
+ Pin `@adrifer/winix` in dependencies/devDependencies to an exact release version
181
+ or its matching official GitHub release SDK tarball URL. Floating ranges,
182
+ local SDK links, third-party URLs, and mismatched asset versions are refused.
183
+ `winix init` now generates an exact pin. No independent runtime version is
184
+ stored in dotfiles, and no global Winix/npm installation is performed.
185
+
186
+ `-DryRun` / `--dry-run` makes **no changes**, including no clone, tool downloads,
187
+ prerequisite installation, or config evaluation. `-PrepareOnly` / `--prepare-only`
188
+ allows those preparation steps, then runs `check` and `switch --dry` but stops
189
+ before activation. Config evaluation can itself run arbitrary code, so it
190
+ requires consent **before** `check`. Omit prepare-only to review the preview
191
+ and confirm activation separately. `-Yes` / `--yes` explicitly accepts trust,
192
+ prerequisite changes, activation (unless prepare-only), and managed removals.
193
+ Host selection does not rename the machine. Reboot/WSL shutdown are manual.
194
+
195
+ Existing checkouts must have the expected origin, local ref/HEAD and clean
196
+ working tree. Bootstrap never pulls, resets, stashes, changes branches in an
197
+ existing checkout, or overwrites an unrelated directory; links/path escapes
198
+ are rejected. Rerun after resolving a reported prerequisite/reboot boundary.
199
+ Updating an existing checkout is an explicit Git operation, not a bootstrap side effect.
200
+
201
+ For ongoing use, bootstrap writes `.winix/bin/winix.ps1` (Windows) or
202
+ `.winix/bin/winix` (Linux). These call `winix run <args>` from the config directory:
203
+
204
+ ```powershell
205
+ .\.winix\bin\winix.ps1 check
206
+ .\.winix\bin\winix.ps1 switch --host windows-devbox
207
+ ```
208
+
209
+ ```bash
210
+ ./.winix/bin/winix check
211
+ ./.winix/bin/winix switch --host linux-desktop
212
+ ```
213
+
214
+ The launcher rereads the manifest on every invocation. If an optional
215
+ `node_modules/@adrifer/winix` is installed, its version must match the pin and
216
+ the launcher uses its own CLI/SDK under Node >=22.13. Install dependencies
217
+ explicitly with `npm ci` using an approved npm source; bootstrap never does it.
218
+ Existing `npm run` scripts also use that local CLI, without a global installation.
219
+ Without the npm SDK, the verified standalone executable must match the pin;
220
+ after changing the pin, rerun bootstrap to download the matching executable.
221
+ A stale/corrupt local installation is an error, never a silent standalone fallback.
222
+
223
+ Fresh Windows-driven WSL setups using a branch now fetch full history and
224
+ create a local tracking branch **at the locked first-run commit**, even if
225
+ upstream has advanced. `HEAD` resolves the default branch; commit/tag refs stay
226
+ detached intentionally. Completed setups and their existing detached checkouts
227
+ are not migrated or updated automatically.
228
+
147
229
  ### npm installation (optional)
148
230
 
149
231
  ```bash
@@ -18,6 +18,7 @@ interface CommandOptions {
18
18
  env?: NodeJS.ProcessEnv;
19
19
  }
20
20
  export type SetupRunner = (command: string, args: string[], options?: CommandOptions) => string;
21
+ export declare function checkoutWslRevision(git: (args: string[]) => string, ref: string, revision: string, existingHead?: string): void;
21
22
  export declare function createWslAccountPlan(host: EvaluatedHost, setup: WinWslSetup, architecture: string): {
22
23
  plan: Plan;
23
24
  accountHost: EvaluatedHost;
@@ -11,6 +11,51 @@ import { randomUUID } from "node:crypto";
11
11
  import * as fs from "node:fs/promises";
12
12
  import { join, resolve, dirname, relative, isAbsolute } from "node:path";
13
13
  import { pathToFileURL } from "node:url";
14
+ export function checkoutWslRevision(git, ref, revision, existingHead) {
15
+ git(["config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"]);
16
+ git(["fetch", "--no-tags", "origin"]);
17
+ git(["fetch", "--no-tags", "origin", revision]);
18
+ let branch;
19
+ if (ref === "HEAD") {
20
+ const remoteHead = git(["ls-remote", "--symref", "origin", "HEAD"]);
21
+ branch = /^ref: refs\/heads\/([^\s]+)\s+HEAD$/m.exec(remoteHead)?.[1];
22
+ if (!branch)
23
+ throw new Error("Cannot determine the repository default branch; use an explicit branch or commit");
24
+ }
25
+ else if (!ref.startsWith("refs/tags/") && !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(ref)) {
26
+ const candidate = ref.replace(/^refs\/heads\//, "");
27
+ let isBranch = true;
28
+ try {
29
+ git(["show-ref", "--verify", "--quiet", `refs/remotes/origin/${candidate}`]);
30
+ }
31
+ catch (error) {
32
+ if (error.status !== 1)
33
+ throw error;
34
+ isBranch = false;
35
+ }
36
+ if (isBranch)
37
+ branch = candidate;
38
+ }
39
+ if (branch) {
40
+ git(["check-ref-format", "--branch", branch]);
41
+ let current;
42
+ try {
43
+ current = git(["symbolic-ref", "--quiet", "--short", "HEAD"]);
44
+ }
45
+ catch (error) {
46
+ if (error.status !== 1)
47
+ throw error;
48
+ }
49
+ if (!existingHead || current !== branch) {
50
+ // An unborn HEAD may already name this branch, but still needs its locked tree.
51
+ git(["checkout", existingHead ? "-b" : "-B", branch, revision]);
52
+ }
53
+ git(["branch", "--set-upstream-to", `origin/${branch}`, branch]);
54
+ }
55
+ else {
56
+ git(["checkout", "--detach", revision]);
57
+ }
58
+ }
14
59
  function object(value) {
15
60
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
16
61
  }
@@ -270,8 +315,7 @@ export async function runWslSetup(request, options = {}) {
270
315
  }
271
316
  if (existingHead && existingHead !== state.revision)
272
317
  throw new Error("Staging revision changed; refusing reset");
273
- git(["fetch", "--depth=1", "--no-tags", "origin", state.revision]);
274
- git(["checkout", "--detach", state.revision]);
318
+ checkoutWslRevision(git, request.setup.ref ?? "HEAD", state.revision, existingHead);
275
319
  verify(repository, "nixos", initial.home);
276
320
  const config = await fs.realpath(join(repository, request.setup.configDirectory));
277
321
  const inside = relative(await fs.realpath(repository), config);
@@ -0,0 +1,15 @@
1
+ import { runCommand } from "../run.js";
2
+ export declare function pinnedWinixVersion(spec: unknown): string;
3
+ export declare function checkoutWinixVersion(directory: string): Promise<string>;
4
+ export declare function localWinixCommand(directory: string, expected: string, runtimeVersion: string, executable: string): Promise<{
5
+ command: string;
6
+ args: string[];
7
+ }>;
8
+ export declare function runCheckout(directory: string, args: string[], run?: typeof runCommand): Promise<void>;
9
+ export declare function nodeTypeArguments(version: string): string[];
10
+ export declare function bootstrapCheckout(directory: string, opts: {
11
+ host: string;
12
+ yes: boolean;
13
+ prepareOnly: boolean;
14
+ dry: boolean;
15
+ }, run?: typeof runCheckout): Promise<void>;
@@ -0,0 +1,154 @@
1
+ import { readFile, mkdir, writeFile, lstat } from "node:fs/promises";
2
+ import { join, dirname } from "node:path";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { stdin, stdout } from "node:process";
5
+ import { fileURLToPath } from "node:url";
6
+ import { execFileSync } from "node:child_process";
7
+ import { standaloneRuntime } from "../../runtime.js";
8
+ import { resolveWinixVersionRange } from "./init.js";
9
+ import { runCommand } from "../run.js";
10
+ export function pinnedWinixVersion(spec) {
11
+ if (typeof spec !== "string")
12
+ throw new Error("package.json must declare an exact @adrifer/winix dependency");
13
+ if (/^\d+\.\d+\.\d+(?:-preview\.\d+)?$/.test(spec))
14
+ return spec;
15
+ const match = /^https:\/\/github\.com\/adrifer\/winix\/releases\/download\/v(\d+\.\d+\.\d+(?:-preview\.\d+)?)\/adrifer-winix-\1\.tgz$/.exec(spec);
16
+ if (!match)
17
+ throw new Error("Winix bootstrap requires an exact version or matching official GitHub release SDK URL; floating versions are not supported");
18
+ return match[1];
19
+ }
20
+ export async function checkoutWinixVersion(directory) {
21
+ const pkg = JSON.parse(await readFile(join(directory, "package.json"), "utf8"));
22
+ return pinnedWinixVersion(pkg.dependencies?.["@adrifer/winix"] ?? pkg.devDependencies?.["@adrifer/winix"]);
23
+ }
24
+ export async function localWinixCommand(directory, expected, runtimeVersion, executable) {
25
+ const packagePath = join(directory, "node_modules", "@adrifer", "winix", "package.json");
26
+ let local;
27
+ let installed = false;
28
+ try {
29
+ local = JSON.parse(await readFile(packagePath, "utf8"));
30
+ installed = true;
31
+ }
32
+ catch (error) {
33
+ if (error.code !== "ENOENT")
34
+ throw error;
35
+ try {
36
+ await lstat(dirname(packagePath));
37
+ throw new Error("Local node_modules Winix is incomplete (missing package.json). Run npm ci or remove the optional SDK explicitly.");
38
+ }
39
+ catch (directoryError) {
40
+ if (directoryError.code !== "ENOENT")
41
+ throw directoryError;
42
+ }
43
+ }
44
+ if (installed) {
45
+ if (!local || typeof local !== "object" || !("version" in local))
46
+ throw new Error("Local node_modules Winix has invalid package metadata. Run npm ci.");
47
+ if (local.version !== expected) {
48
+ throw new Error(`Local node_modules Winix is ${local.version}, expected ${expected}. Run npm ci using your approved repository; bootstrap will not install dependencies automatically.`);
49
+ }
50
+ return {
51
+ command: standaloneRuntime() ? "node" : process.execPath,
52
+ args: ["--no-warnings", join(dirname(packagePath), "dist", "cli", "index.js")],
53
+ };
54
+ }
55
+ if (runtimeVersion !== expected) {
56
+ throw new Error(`Checkout requires Winix ${expected}, but this executable is ${runtimeVersion}. Rerun the repository bootstrap to download the matching release.`);
57
+ }
58
+ return { command: executable, args: [] };
59
+ }
60
+ export async function runCheckout(directory, args, run = runCommand) {
61
+ if (!args.length || ["run", "bootstrap"].includes(args[0])) {
62
+ throw new Error("Usage: winix run <check|apply|switch|update|inspect|...> [options]; run/bootstrap cannot be nested");
63
+ }
64
+ const version = (await resolveWinixVersionRange()).replace(/^\^/, "");
65
+ const executable = process.env.WINIX_STANDALONE_EXECUTABLE ?? process.execPath;
66
+ let command = await localWinixCommand(directory, await checkoutWinixVersion(directory), version, executable);
67
+ if (command.args.length) {
68
+ const nodeVersion = execFileSync(command.command, ["--version"], { encoding: "utf8" }).trim();
69
+ command.args.unshift(...nodeTypeArguments(nodeVersion));
70
+ }
71
+ if (!standaloneRuntime() && command.command === process.execPath && command.args.length === 0) {
72
+ command = {
73
+ command: process.execPath,
74
+ args: [...nodeTypeArguments(process.version), "--no-warnings",
75
+ fileURLToPath(new URL(`../index.${import.meta.url.endsWith(".ts") ? "ts" : "js"}`, import.meta.url))],
76
+ };
77
+ }
78
+ await run(command.command, [...command.args, ...args], { cwd: directory });
79
+ }
80
+ export function nodeTypeArguments(version) {
81
+ const parsed = /^v?(\d+)\.(\d+)\.\d+$/.exec(version);
82
+ if (!parsed || Number(parsed[1]) < 22 || Number(parsed[1]) === 22 && Number(parsed[2]) < 13) {
83
+ throw new Error(`Local SDK requires stable Node >=22.13, found ${version}. Install it explicitly or remove the optional node_modules SDK to retain standalone mode.`);
84
+ }
85
+ return Number(parsed[1]) >= 26 ? [] : ["--experimental-transform-types"];
86
+ }
87
+ async function confirm(message, yes) {
88
+ if (yes)
89
+ return;
90
+ if (!stdin.isTTY)
91
+ throw new Error(`${message} Noninteractive bootstrap requires --yes.`);
92
+ const reader = createInterface({ input: stdin, output: stdout });
93
+ try {
94
+ if (!/^(y|yes)$/i.test((await reader.question(`${message} [y/N] `)).trim())) {
95
+ throw new Error("Bootstrap cancelled.");
96
+ }
97
+ }
98
+ finally {
99
+ reader.close();
100
+ }
101
+ }
102
+ export async function bootstrapCheckout(directory, opts, run = runCheckout) {
103
+ if (!opts.host || opts.host.startsWith("-") || /[\0\r\n]/.test(opts.host))
104
+ throw new Error("bootstrap requires --host <declared-host>");
105
+ const expected = await checkoutWinixVersion(directory);
106
+ const version = (await resolveWinixVersionRange()).replace(/^\^/, "");
107
+ if (expected !== version)
108
+ throw new Error(`Checkout requires Winix ${expected}; run its matching bootstrap executable, not ${version}.`);
109
+ if (opts.dry) {
110
+ console.log(`Would prepare checkout ${directory} with Winix ${expected}, validate host "${opts.host}", preview, and ${opts.prepareOnly ? "stop before activation" : "ask before activation"}. No config was evaluated.`);
111
+ return;
112
+ }
113
+ await confirm("Evaluate trusted TypeScript from this checkout? Config code can execute commands.", opts.yes);
114
+ const bin = join(directory, ".winix", "bin");
115
+ for (const path of [join(directory, ".winix"), bin]) {
116
+ try {
117
+ if (!(await lstat(path)).isDirectory())
118
+ throw new Error(`Refusing a linked/non-directory bootstrap path: ${path}`);
119
+ }
120
+ catch (error) {
121
+ if (error.code !== "ENOENT")
122
+ throw error;
123
+ }
124
+ }
125
+ await run(directory, ["check"]);
126
+ await run(directory, ["switch", "--dry", "--host", opts.host]);
127
+ if (standaloneRuntime()) {
128
+ const executable = process.env.WINIX_STANDALONE_EXECUTABLE ?? process.execPath;
129
+ await mkdir(bin, { recursive: true });
130
+ const windows = process.platform === "win32";
131
+ const launcher = join(bin, windows ? "winix.ps1" : "winix");
132
+ const content = windows
133
+ ? `# Generated by Winix bootstrap\n$ErrorActionPreference = 'Stop'\nSet-Location -LiteralPath (Split-Path (Split-Path $PSScriptRoot -Parent) -Parent)\n& '${executable.replaceAll("'", "''")}' run @args\nexit $LASTEXITCODE\n`
134
+ : `#!/usr/bin/env bash\n# Generated by Winix bootstrap\nset -euo pipefail\ncd -- "$(dirname -- "\${BASH_SOURCE[0]}")/../.."\nexec '${executable.replaceAll("'", "'\\''")}' run "$@"\n`;
135
+ try {
136
+ const stat = await lstat(launcher);
137
+ if (!stat.isFile() || !(await readFile(launcher, "utf8")).includes("# Generated by Winix bootstrap")) {
138
+ throw new Error(`Refusing to overwrite an unrecognized launcher: ${launcher}`);
139
+ }
140
+ }
141
+ catch (error) {
142
+ if (error.code !== "ENOENT")
143
+ throw error;
144
+ }
145
+ await writeFile(launcher, content, { mode: 0o755 });
146
+ console.log(`Checkout launcher: ${launcher}. It prefers a matching node_modules SDK, never installs npm packages, and rejects stale versions.`);
147
+ }
148
+ if (opts.prepareOnly) {
149
+ console.log("Prepared and validated. No host activation performed.");
150
+ return;
151
+ }
152
+ await confirm(`Activate host "${opts.host}"? Reboot and WSL shutdown are never automatic.`, opts.yes);
153
+ await run(directory, ["switch", "--host", opts.host, ...(opts.yes ? ["--yes"] : [])]);
154
+ }
@@ -7,7 +7,7 @@ import { standaloneRuntime } from "../../runtime.js";
7
7
  export async function init(cwd, opts) {
8
8
  await mkdir(cwd, { recursive: true });
9
9
  const versionRange = await resolveWinixVersionRange();
10
- const packageJson = renderPackageJson(versionRange);
10
+ const packageJson = renderPackageJson(versionRange.replace(/^\^/, ""));
11
11
  await writeIfAllowed(join(cwd, "winix.config.ts"), CONFIG, opts.force);
12
12
  await writeIfAllowed(join(cwd, "tsconfig.json"), TSCONFIG, opts.force);
13
13
  await writeIfAllowed(join(cwd, "package.json"), packageJson, opts.force);
package/dist/cli/index.js CHANGED
@@ -9,7 +9,18 @@ import { inspect } from "./commands/inspect.js";
9
9
  import { switchCommand } from "./commands/switch.js";
10
10
  import { update } from "./commands/update.js";
11
11
  import { renderSkill } from "../skill.js";
12
+ import { bootstrapCheckout, runCheckout } from "./commands/bootstrap.js";
12
13
  import { forgetWindowsResource, windowsStatePath } from "./windows-state.js";
14
+ if (process.argv[2] === "run") {
15
+ try {
16
+ await runCheckout(process.cwd(), process.argv.slice(3));
17
+ }
18
+ catch (error) {
19
+ console.error(`Error: ${error.message}`);
20
+ process.exit(1);
21
+ }
22
+ process.exit(0);
23
+ }
13
24
  const { positionals, values } = parseArgs({
14
25
  allowPositionals: true,
15
26
  options: {
@@ -24,6 +35,7 @@ const { positionals, values } = parseArgs({
24
35
  "escape-report": { type: "boolean", default: false },
25
36
  help: { type: "boolean", short: "h", default: false },
26
37
  version: { type: "boolean", short: "v", default: false },
38
+ "prepare-only": { type: "boolean", default: false },
27
39
  },
28
40
  });
29
41
  const command = positionals[0];
@@ -44,6 +56,8 @@ if (values.help || !command) {
44
56
  winix - TypeScript-first system configuration
45
57
 
46
58
  Commands:
59
+ bootstrap Validate/preview a trusted checkout, then confirm activation
60
+ run <args> Prefer checkout-local SDK, enforcing the checkout's exact Winix pin
47
61
  init Scaffold a Winix project
48
62
  install skill Install the agent skill wrapper
49
63
  apply Generate backend output in .winix/out/
@@ -55,6 +69,7 @@ Commands:
55
69
 
56
70
  Options:
57
71
  --host <name> Target a specific host
72
+ --prepare-only Stop bootstrap after validation/preview; no activation
58
73
  --dry Preview generation (apply) or activation and managed cleanup (switch)
59
74
  -y, --yes Confirm managed Windows removals without prompting (switch)
60
75
  --diff Show diff against current output (apply)
@@ -81,11 +96,26 @@ Examples:
81
96
  process.exit(0);
82
97
  }
83
98
  const cwd = process.cwd();
84
- if (values.yes && command !== "switch") {
85
- console.error("--yes is only supported by winix switch.");
99
+ if (values["prepare-only"] && command !== "bootstrap") {
100
+ console.error("--prepare-only is only supported by winix bootstrap.");
101
+ process.exit(2);
102
+ }
103
+ if (values.yes && command !== "switch" && command !== "bootstrap") {
104
+ console.error("--yes is only supported by winix switch or bootstrap.");
86
105
  process.exit(2);
87
106
  }
88
107
  switch (command) {
108
+ case "bootstrap":
109
+ try {
110
+ await bootstrapCheckout(cwd, {
111
+ host: values.host ?? "", yes: values.yes, prepareOnly: values["prepare-only"], dry: values.dry,
112
+ });
113
+ }
114
+ catch (error) {
115
+ console.error(`Error: ${error.message}`);
116
+ process.exit(1);
117
+ }
118
+ break;
89
119
  case "init":
90
120
  try {
91
121
  await init(cwd, { force: values.force });
package/dist/skill.js CHANGED
@@ -336,6 +336,9 @@ Resources return handles that can be passed through \`dependsOn\`.
336
336
  or occupied checkouts/changed settings are refused, never reset or adopted.
337
337
  State lives at /var/lib/winix/wsl-setup. Inspect stale run.lock and its PID
338
338
  before manual recovery; never remove a live coordinator's lock.
339
+ Fresh branch-based clones retain full history and an upstream-tracking branch
340
+ at the locked commit, even if upstream is newer. Tags/commits stay detached.
341
+ Completed checkouts are never switched or migrated automatically.
339
342
  No shutdown/reboot is automatic. Fresh-image activation remains unverified.
340
343
  Omit setup to retain separate manual Linux activation.
341
344
  - \`windows.raw()\` runs a command on every apply. It is not idempotent, so use
@@ -386,10 +389,34 @@ hashes; custom single-target builds cannot provision WSL. Linux assets use glibc
386
389
  automatic WSL setup prepares NixOS's linker explicitly. No ARM64 execution or
387
390
  fresh-image activation is claimed.
388
391
  \`-UseNvm\` chooses NVM for Windows instead of standalone Node; \`-Yes\` accepts
389
- bootstrap changes. It never installs Winix globally, activates a host, provisions
392
+ bootstrap changes. Prerequisite-only mode never installs Winix globally, activates a host, provisions
390
393
  WSL, reboots, or changes execution policy persistently. Prepare the config and
391
394
  compatible SDK separately, then review \`switch --dry\` before activation.
392
395
 
396
+ Repository mode adds \`-Repository HTTPS_URL -Ref main -Destination PATH
397
+ -ConfigDirectory winix -HostName HOST\`. Linux's \`bootstrap-linux.sh\` uses
398
+ \`--repository\`, \`--ref\`, \`--destination\`, \`--config-directory\`, \`--host\`.
399
+ It uses existing Nix for temporary Git/Python tools, or requires installed
400
+ Git/Python; it never installs Nix or converts other Linux distributions.
401
+ Both clone or validate a clean existing checkout without pulling/resetting,
402
+ read its exact SDK dependency (version or official release SDK tarball URL),
403
+ and verify matching release executables before running them. Windows additionally
404
+ verifies that release's prerequisite-only script. Review scripts and release
405
+ checksums first; hashes are not signatures. No Node/npm installation is automatic.
406
+ \`-DryRun\`/\`--dry-run\` performs no changes/evaluation; \`-PrepareOnly\`/
407
+ \`--prepare-only\` allows setup plus check/switch preview but no activation.
408
+ Trust confirmation occurs before config evaluation. Omit prepare-only to
409
+ confirm activation separately; \`-Yes\`/\`--yes\` accepts trust/activation/removals.
410
+ Do not run real bootstrap/activation as a development check on a shared machine.
411
+
412
+ \`winix bootstrap --host HOST\` performs the checkout validation/preview/confirmation
413
+ phase. Its generated \`.winix/bin/winix.ps1\` or \`.winix/bin/winix\` launcher invokes
414
+ \`winix run <args>\`, rereading the exact pin on every invocation. A matching
415
+ optional node_modules SDK uses its own CLI under Node >=22.13; stale/corrupt
416
+ local packages fail, never silently fall back. Otherwise the standalone must
417
+ match the manifest; rerun bootstrap after changing the pin. The user may run
418
+ \`npm ci\` explicitly using an approved source, then use normal local npm scripts.
419
+
393
420
  On existing NixOS/NixOS-WSL, \`bash bootstrap-nixos.sh\` (from
394
421
  \`scripts/bootstrap-nixos.sh\` or a reviewed release asset) opens a temporary
395
422
  Git/Node.js 24/npm/Bash environment using pinned nixpkgs. Nix must already be
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adrifer/winix",
3
- "version": "0.3.0-preview.0",
3
+ "version": "0.3.0-preview.2",
4
4
  "description": "TypeScript-first system configuration for NixOS, nix-darwin, and Home Manager",
5
5
  "license": "MIT",
6
6
  "author": "Adrian Fernandez",
@@ -45,6 +45,7 @@
45
45
  "files": [
46
46
  "scripts/bootstrap-windows.ps1",
47
47
  "scripts/bootstrap-nixos.sh",
48
+ "scripts/bootstrap-linux.sh",
48
49
  "dist",
49
50
  "types",
50
51
  "index.d.ts",
@@ -0,0 +1,227 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ # Repository mode never installs Nix or changes the system before confirmation.
5
+ if [[ "${1:-}" == --help || "${1:-}" == -h ]]; then
6
+ printf '%s\n' \
7
+ 'Usage: bash bootstrap-linux.sh --repository HTTPS_URL --ref BRANCH --host HOST [--destination PATH] [--config-directory winix] [--prepare-only] [--dry-run] [--yes]' \
8
+ 'Uses existing Nix for temporary Git/Python tools, or requires installed git and python3.' \
9
+ 'No Node/npm, package installation, reboot, checkout reset, or activation without confirmation.'
10
+ exit 0
11
+ fi
12
+
13
+ arguments=("$@")
14
+ repository='' hostname='' dry_run=0
15
+ while (($#)); do
16
+ case "$1" in
17
+ --repository|--ref|--host|--destination|--config-directory)
18
+ [[ $# -ge 2 && -n "$2" && "$2" != -* ]] || { echo "Missing value for $1" >&2; exit 2; }
19
+ case "$1" in
20
+ --repository) repository="$2" ;;
21
+ --host) hostname="$2" ;;
22
+ esac
23
+ shift 2 ;;
24
+ --dry-run) dry_run=1; shift ;;
25
+ --yes|--prepare-only) shift ;;
26
+ *) echo "Unknown bootstrap option: $1" >&2; exit 2 ;;
27
+ esac
28
+ done
29
+ [[ -n "$repository" && -n "$hostname" ]] || { echo '--repository and --host are required; see --help' >&2; exit 2; }
30
+ [[ "$repository" == https://* && "$repository" != *'@'* && "$repository" != *'?'* && "$repository" != *'#'* ]] || {
31
+ echo 'Repository must be HTTPS without credentials, query, or fragment' >&2; exit 2;
32
+ }
33
+ set -- "${arguments[@]}"
34
+ if ((dry_run)); then
35
+ printf '%s\n' 'Dry run: would validate arguments, ensure temporary tools, clone/validate the checkout, read its exact Winix pin, verify release downloads, then preview/confirm activation. No changes or config evaluation performed.'
36
+ exit 0
37
+ fi
38
+
39
+ if [[ "${WINIX_BOOTSTRAP_TOOLS:-}" != 1 ]] && command -v nix >/dev/null 2>&1; then
40
+ printf '%s\n' 'Preparing a temporary Git/Python environment using existing Nix; no profile changes.'
41
+ export WINIX_BOOTSTRAP_TOOLS=1
42
+ export NIX_CONFIG="${NIX_CONFIG:+$NIX_CONFIG$'\n'}extra-experimental-features = nix-command flakes"
43
+ pin='github:NixOS/nixpkgs/0bb2eedc20e4739f29e8045034f2828ad7054f8f'
44
+ exec nix shell --no-write-lock-file "$pin#git" "$pin#python3" "$pin#bash" \
45
+ --command bash "$0" "$@"
46
+ fi
47
+ command -v git >/dev/null 2>&1 || { echo 'Git is required. Install it through your approved package manager, or provide an existing Nix installation.' >&2; exit 1; }
48
+ command -v python3 >/dev/null 2>&1 || { echo 'Python 3 is required for bootstrap JSON and HTTPS handling; Node/npm are not needed.' >&2; exit 1; }
49
+
50
+ python3 - "$@" <<'PY'
51
+ import argparse
52
+ import hashlib
53
+ import json
54
+ import os
55
+ from pathlib import Path
56
+ import platform
57
+ import re
58
+ import shlex
59
+ import shutil
60
+ import subprocess
61
+ import sys
62
+ import tempfile
63
+ import urllib.request
64
+ from urllib.parse import urlparse
65
+
66
+
67
+ def run(args, cwd=None, capture=False):
68
+ return subprocess.run(args, cwd=cwd, check=True, text=True,
69
+ stdout=subprocess.PIPE if capture else None).stdout
70
+
71
+
72
+ def confirm(message, yes):
73
+ if yes:
74
+ return
75
+ # stdin contains this script, not an interactive terminal.
76
+ try:
77
+ with open("/dev/tty", "w") as tty:
78
+ tty.write(message + " [y/N] ")
79
+ tty.flush()
80
+ with open("/dev/tty", "r") as tty:
81
+ answer = tty.readline().strip().lower()
82
+ except OSError as error:
83
+ raise RuntimeError("Interactive confirmation unavailable; pass --yes only after reviewing the repository/script") from error
84
+ if answer not in ("y", "yes"):
85
+ raise RuntimeError("Bootstrap cancelled")
86
+
87
+
88
+ def safe_directory(path):
89
+ for current in (path, *path.parents):
90
+ if current.is_symlink() or (current.exists() and not current.is_dir()):
91
+ raise RuntimeError("Unsafe bootstrap directory: " + str(current))
92
+
93
+
94
+ class HTTPSRedirects(urllib.request.HTTPRedirectHandler):
95
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
96
+ if urlparse(newurl).scheme != "https":
97
+ raise RuntimeError("Refusing non-HTTPS download redirect")
98
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
99
+
100
+
101
+ opener = urllib.request.build_opener(HTTPSRedirects)
102
+
103
+
104
+ def fetch(url):
105
+ with opener.open(url, timeout=90) as response:
106
+ return response.read()
107
+
108
+
109
+ def download(release, name, destination):
110
+ sums = fetch(release + "/SHA256SUMS").decode("utf-8")
111
+ entries = re.findall(r"^([a-fA-F0-9]{64})\s+\*?" + re.escape(name) + r"$", sums, re.M)
112
+ if len(entries) != 1:
113
+ raise RuntimeError("Missing or duplicate release checksum for " + name)
114
+ if destination.is_symlink():
115
+ raise RuntimeError("Refusing linked executable destination")
116
+ expected = entries[0].lower()
117
+ if destination.is_file() and hashlib.sha256(destination.read_bytes()).hexdigest() == expected:
118
+ return
119
+ data = fetch(release + "/" + name)
120
+ if hashlib.sha256(data).hexdigest() != expected:
121
+ raise RuntimeError("Executable checksum mismatch; nothing was executed")
122
+ fd, temporary = tempfile.mkstemp(prefix=".download-", dir=destination.parent)
123
+ try:
124
+ with os.fdopen(fd, "wb") as stream:
125
+ stream.write(data)
126
+ os.chmod(temporary, 0o755)
127
+ os.replace(temporary, destination)
128
+ finally:
129
+ if os.path.exists(temporary):
130
+ os.unlink(temporary)
131
+
132
+
133
+ def main():
134
+ parser = argparse.ArgumentParser()
135
+ parser.add_argument("--repository", required=True)
136
+ parser.add_argument("--ref", default="main")
137
+ parser.add_argument("--host", required=True)
138
+ parser.add_argument("--destination", default=str(Path.home() / "dotfiles"))
139
+ parser.add_argument("--config-directory", default="winix")
140
+ parser.add_argument("--prepare-only", action="store_true")
141
+ parser.add_argument("--yes", action="store_true")
142
+ args = parser.parse_args()
143
+ uri = urlparse(args.repository)
144
+ if uri.scheme != "https" or not uri.hostname or uri.username or uri.password or uri.query or uri.fragment:
145
+ raise RuntimeError("Repository must be HTTPS without credentials, query, or fragment")
146
+ if not args.ref or args.ref.startswith("-") or any(c in args.ref + args.host for c in "\x00\r\n"):
147
+ raise RuntimeError("Invalid host/ref")
148
+ subdir = Path(args.config_directory)
149
+ if subdir.is_absolute() or ".." in subdir.parts:
150
+ raise RuntimeError("config-directory must be inside the checkout")
151
+ destination = Path(os.path.abspath(os.path.expanduser(args.destination)))
152
+ safe_directory(destination)
153
+ confirm("Trust " + args.repository + " and allow cloning/downloads? Config evaluation is confirmed separately.", args.yes)
154
+ if not destination.exists():
155
+ run(["git", "clone", "--origin", "origin", "--", args.repository, str(destination)])
156
+ run(["git", "checkout", args.ref], destination)
157
+ if not (destination / ".git").is_dir():
158
+ raise RuntimeError("Existing destination is not a regular Git checkout; refusing adoption")
159
+ safe_directory(destination / ".git")
160
+ if run(["git", "remote", "get-url", "origin"], destination, True).strip() != args.repository:
161
+ raise RuntimeError("Existing checkout has a different origin")
162
+ if run(["git", "status", "--porcelain", "--untracked-files=normal"], destination, True).strip():
163
+ raise RuntimeError("Checkout has local changes; bootstrap never resets, cleans, or stashes them")
164
+ head = run(["git", "rev-parse", "HEAD"], destination, True).strip()
165
+ wanted = run(["git", "rev-parse", "--verify", args.ref + "^{commit}"], destination, True).strip()
166
+ if head != wanted:
167
+ raise RuntimeError("Existing checkout differs from the requested local ref; switch it explicitly. No automatic pull/reset.")
168
+ config = destination / subdir
169
+ safe_directory(config)
170
+ package = json.loads((config / "package.json").read_text())
171
+ spec = package.get("dependencies", {}).get("@adrifer/winix") or package.get("devDependencies", {}).get("@adrifer/winix")
172
+ if not isinstance(spec, str):
173
+ raise RuntimeError("Missing exact @adrifer/winix dependency")
174
+ version = spec if re.fullmatch(r"\d+\.\d+\.\d+(?:-preview\.\d+)?", spec) else None
175
+ if not version:
176
+ match = re.fullmatch(r"https://github\.com/adrifer/winix/releases/download/v(\d+\.\d+\.\d+(?:-preview\.\d+)?)/adrifer-winix-\1\.tgz", spec)
177
+ if not match:
178
+ raise RuntimeError("Winix pin must be an exact version or matching official release SDK URL")
179
+ version = match[1]
180
+ architecture = {"x86_64": "x64", "aarch64": "arm64"}.get(platform.machine())
181
+ if not architecture or sys.platform != "linux":
182
+ raise RuntimeError("Supported standalone targets: Linux x64 and ARM64")
183
+ runtime = config / ".winix" / "runtime" / version
184
+ safe_directory(runtime)
185
+ runtime.mkdir(parents=True, exist_ok=True)
186
+ release = "https://github.com/adrifer/winix/releases/download/v" + version
187
+ binary = runtime / "winix.bin"
188
+ download(release, "winix-linux-" + architecture, binary)
189
+ nixos = Path("/etc/NIXOS").exists()
190
+ launcher = runtime / "winix"
191
+ if launcher.is_symlink() or (launcher.exists() and not launcher.is_file()):
192
+ raise RuntimeError("Unsafe runtime launcher")
193
+ if nixos:
194
+ if not shutil.which("nix"):
195
+ raise RuntimeError("Existing NixOS installation must provide nix")
196
+ pin = "github:NixOS/nixpkgs/0bb2eedc20e4739f29e8045034f2828ad7054f8f"
197
+ for name, output in (("libc", "glibc.out"), ("compiler", "stdenv.cc.cc.lib")):
198
+ run(["nix", "build", "--no-write-lock-file", "--out-link", str(runtime / name), pin + "#" + output])
199
+ linker = "ld-linux-x86-64.so.2" if architecture == "x64" else "ld-linux-aarch64.so.1"
200
+ command = [str(runtime / "libc" / "lib" / linker), "--argv0", str(binary),
201
+ "--library-path", str(runtime / "libc" / "lib") + ":" + str(runtime / "compiler" / "lib"), str(binary)]
202
+ else:
203
+ command = [str(binary)]
204
+ if launcher.exists() and not launcher.read_text().startswith("#!/usr/bin/env bash\n# Generated by Winix bootstrap\n"):
205
+ raise RuntimeError("Refusing to overwrite an unrecognized runtime launcher")
206
+ launcher.write_text("#!/usr/bin/env bash\n# Generated by Winix bootstrap\nset -euo pipefail\nexport WINIX_STANDALONE_EXECUTABLE=" +
207
+ shlex.quote(str(launcher)) + "\nexec " + shlex.join(command) + ' "$@"\n')
208
+ launcher.chmod(0o755)
209
+ if run([str(launcher), "--version"], config, True).strip() != version:
210
+ raise RuntimeError("Executable version does not match the checkout")
211
+ command = [str(launcher), "bootstrap", "--host", args.host]
212
+ if args.prepare_only:
213
+ command.append("--prepare-only")
214
+ if args.yes:
215
+ command.append("--yes")
216
+ # Config confirmations in Winix require a terminal, not the Python source pipe.
217
+ with open("/dev/tty", "r") if not args.yes else open(os.devnull) as input_stream:
218
+ subprocess.run(command, cwd=config, stdin=input_stream, check=True)
219
+
220
+
221
+ if __name__ == "__main__":
222
+ try:
223
+ main()
224
+ except (OSError, ValueError, RuntimeError, subprocess.CalledProcessError) as error:
225
+ print("Winix bootstrap failed: " + str(error), file=sys.stderr)
226
+ sys.exit(1)
227
+ PY
@@ -1,7 +1,7 @@
1
1
  #Requires -Version 5.1
2
2
  <#
3
3
  .SYNOPSIS
4
- Checks or installs the Windows prerequisites for Winix, without activating a host.
4
+ Checks/installs Winix prerequisites, or prepares a trusted repository and confirms host activation.
5
5
  .PARAMETER Check
6
6
  Only inspect prerequisites. No installation or configuration enablement is performed.
7
7
  .PARAMETER Yes
@@ -10,13 +10,28 @@ Accept prerequisite installation and WinGet configuration enablement without pro
10
10
  Install/select Node LTS through NVM for Windows instead of standalone Node.js.
11
11
  .PARAMETER Standalone
12
12
  Check/install only native prerequisites for the Winix executable; Node.js/npm are not needed.
13
+ .PARAMETER Repository
14
+ Opt into HTTPS repository bootstrap. The checkout's exact SDK pin selects the executable.
15
+ .PARAMETER HostName
16
+ Declared Winix target for repository mode; does not rename Windows.
17
+ .PARAMETER PrepareOnly
18
+ Prepare prerequisites/runtime and validate/preview the repository without activating a host.
19
+ .PARAMETER DryRun
20
+ Describe repository bootstrap without downloads, installation, cloning or config evaluation.
13
21
  #>
14
22
  [CmdletBinding()]
15
23
  param(
16
24
  [switch]$Check,
17
25
  [switch]$Yes,
18
26
  [switch]$UseNvm,
19
- [switch]$Standalone
27
+ [switch]$Standalone,
28
+ [string]$Repository,
29
+ [string]$Ref = 'main',
30
+ [string]$Destination = (Join-Path $HOME 'dotfiles'),
31
+ [string]$ConfigDirectory = 'winix',
32
+ [string]$HostName,
33
+ [switch]$PrepareOnly,
34
+ [switch]$DryRun
20
35
  )
21
36
 
22
37
  function Get-WinixBootstrapApplication {
@@ -110,7 +125,7 @@ function Test-WinixBootstrapCapabilities {
110
125
  $script = @'
111
126
  $ErrorActionPreference = 'Stop'
112
127
  Get-Command Find-PSResource, Install-PSResource -ErrorAction Stop | Out-Null
113
- Get-PSResourceRepository -Name PSGallery -ErrorAction Stop | Out-Null
128
+ Get-Command Get-PSResourceRepository, Register-PSResourceRepository -ErrorAction Stop | Out-Null
114
129
  '@
115
130
  $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($script))
116
131
  Invoke-WinixBootstrapNative $pwsh @('-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', $encoded) | Out-Null
@@ -128,7 +143,7 @@ Get-PSResourceRepository -Name PSGallery -ErrorAction Stop | Out-Null
128
143
  }
129
144
  }
130
145
  if (-not $Standalone) { Write-Host 'OK: npm and Node TypeScript support.' }
131
- Write-Host 'OK: PSResourceGet/PSGallery and required DSC resources.'
146
+ Write-Host 'OK: PSResourceGet and required DSC resources (repository selection belongs to the host config).'
132
147
  }
133
148
 
134
149
  function Invoke-WinixWindowsBootstrap {
@@ -215,9 +230,174 @@ Then rerun this bootstrap. No prerequisites have been installed.
215
230
  Write-Host 'Open a new PowerShell 7 terminal before preparing the Winix/config checkout and running winix check or switch --dry.'
216
231
  }
217
232
 
233
+ function Assert-WinixBootstrapDirectory {
234
+ param([string]$Path)
235
+ $current = [IO.Path]::GetFullPath($Path)
236
+ while ($current) {
237
+ if (Test-Path -LiteralPath $current) {
238
+ $item = Get-Item -LiteralPath $current -Force
239
+ if (-not $item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
240
+ throw "Unsafe bootstrap directory (not a directory or is a link): $current"
241
+ }
242
+ }
243
+ $parent = Split-Path $current -Parent
244
+ if ($parent -eq $current) { break }
245
+ $current = $parent
246
+ }
247
+ }
248
+
249
+ function Get-WinixCheckoutVersion {
250
+ param([string]$Directory)
251
+ $package = Get-Content -LiteralPath (Join-Path $Directory 'package.json') -Raw | ConvertFrom-Json
252
+ $spec = $package.dependencies.'@adrifer/winix'
253
+ if (-not $spec) { $spec = $package.devDependencies.'@adrifer/winix' }
254
+ if ($spec -isnot [string]) { throw 'Checkout must declare a string-valued exact @adrifer/winix dependency.' }
255
+ if ($spec -match '^\d+\.\d+\.\d+(?:-preview\.\d+)?$') { return $spec }
256
+ if ($spec -match '^https://github\.com/adrifer/winix/releases/download/v(\d+\.\d+\.\d+(?:-preview\.\d+)?)/adrifer-winix-\1\.tgz$') {
257
+ return $Matches[1]
258
+ }
259
+ throw 'Checkout must pin an exact @adrifer/winix version or matching official GitHub release SDK URL.'
260
+ }
261
+
262
+ function Invoke-WinixBootstrapHost {
263
+ param([string]$Binary, [string[]]$Arguments)
264
+ & $Binary @Arguments
265
+ if ($LASTEXITCODE -ne 0) { throw "Winix bootstrap failed (exit $LASTEXITCODE). Resolve the error and rerun; no checkout reset/reboot is performed." }
266
+ }
267
+
268
+ function Get-WinixBootstrapSha256 {
269
+ param([string]$Path)
270
+ $stream = [IO.File]::OpenRead($Path)
271
+ $algorithm = [Security.Cryptography.SHA256]::Create()
272
+ try { return [BitConverter]::ToString($algorithm.ComputeHash($stream)).Replace('-', '') }
273
+ finally { $algorithm.Dispose(); $stream.Dispose() }
274
+ }
275
+
276
+ function Save-WinixVerifiedDownload {
277
+ param([string]$Url, [string]$ChecksumUrl, [string]$Asset, [string]$Destination)
278
+ if (Test-Path -LiteralPath $Destination) {
279
+ if ((Get-Item -LiteralPath $Destination -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) {
280
+ throw "Refusing linked download destination: $Destination"
281
+ }
282
+ }
283
+ $temporary = "$Destination.$([guid]::NewGuid().ToString('N')).download"
284
+ try {
285
+ $sums = (Invoke-WebRequest -UseBasicParsing -Uri $ChecksumUrl -TimeoutSec 90).Content
286
+ if ($sums -is [byte[]]) { $sums = [Text.Encoding]::UTF8.GetString($sums) }
287
+ $entries = @($sums -split '\r?\n' | Where-Object { $_ -match ('^[a-fA-F0-9]{64}\s+\*?' + [regex]::Escape($Asset) + '$') })
288
+ if ($entries.Count -ne 1) { throw "Release checksum missing or duplicated for $Asset" }
289
+ $expected = ($entries[0] -split '\s+')[0]
290
+ if ((Test-Path -LiteralPath $Destination) -and (Get-WinixBootstrapSha256 $Destination) -eq $expected) {
291
+ return
292
+ }
293
+ Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $temporary -TimeoutSec 90
294
+ if ((Get-WinixBootstrapSha256 $temporary) -ne $expected) {
295
+ throw "Release checksum mismatch for $Asset; nothing was executed"
296
+ }
297
+ Move-Item -LiteralPath $temporary -Destination $Destination -Force
298
+ } finally {
299
+ if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary -Force }
300
+ }
301
+ }
302
+
303
+ function Invoke-WinixRepositoryBootstrap {
304
+ param(
305
+ [string]$Repository, [string]$Ref = 'main', [string]$Destination = (Join-Path $HOME 'dotfiles'), [string]$ConfigDirectory = 'winix',
306
+ [string]$HostName, [switch]$Yes, [switch]$PrepareOnly, [switch]$DryRun
307
+ )
308
+ $ErrorActionPreference = 'Stop'
309
+ $uri = $null
310
+ if (-not [uri]::TryCreate($Repository, [UriKind]::Absolute, [ref]$uri) -or
311
+ $uri.Scheme -ne 'https' -or $uri.UserInfo -or $uri.Query -or $uri.Fragment) {
312
+ throw 'Repository must be HTTPS without credentials, query, or fragment.'
313
+ }
314
+ if (-not $HostName -or $HostName.StartsWith('-') -or $HostName -match '[\x00\r\n]') { throw '-HostName requires a declared host name, not a Windows rename.' }
315
+ if (-not $Ref -or $Ref.StartsWith('-') -or $Ref -match '[\x00\r\n]') { throw 'Invalid repository ref.' }
316
+ if ([IO.Path]::IsPathRooted($ConfigDirectory) -or $ConfigDirectory -match '(^|[\\/])\.\.([\\/]|$)' -or $ConfigDirectory -match '[:\x00\r\n]') {
317
+ throw 'ConfigDirectory must be inside the checkout.'
318
+ }
319
+ $Destination = [IO.Path]::GetFullPath($Destination)
320
+ Assert-WinixBootstrapDirectory $Destination
321
+ $config = [IO.Path]::GetFullPath((Join-Path $Destination $ConfigDirectory))
322
+ if ($DryRun) {
323
+ Write-Host "Would ensure Git, clone/validate $Repository ($Ref) at $Destination, read its Winix pin, verify downloads, prepare prerequisites and preview host $HostName. No changes or config evaluation performed."
324
+ return
325
+ }
326
+ Write-Host "Repository: $Repository ($Ref), checkout: $Destination, config: $config, host: $HostName"
327
+ if (-not $Yes) {
328
+ if ([Console]::IsInputRedirected) { throw 'Noninteractive repository bootstrap requires -Yes.' }
329
+ if ((Read-Host 'Trust this repository and allow bootstrap downloads/prerequisite installation? [y/N]').Trim() -notmatch '^(?i:y|yes)$') {
330
+ throw 'Bootstrap cancelled.'
331
+ }
332
+ }
333
+ Update-WinixBootstrapPath
334
+ $git = Get-WinixBootstrapApplication 'git.exe'
335
+ if (-not $git) {
336
+ $winget = Get-WinixBootstrapApplication 'winget.exe'
337
+ if (-not $winget) { throw 'WinGet is unavailable. Install App Installer, open a new terminal, and rerun.' }
338
+ Invoke-WinixBootstrapNative $winget @('install', '--id', 'Git.Git', '--exact', '--source', 'winget',
339
+ '--silent', '--accept-package-agreements', '--accept-source-agreements', '--disable-interactivity') | ForEach-Object { Write-Host $_ }
340
+ Update-WinixBootstrapPath
341
+ $git = Get-WinixBootstrapApplication 'git.exe'
342
+ if (-not $git) { throw 'Git is not ready. Open a new terminal or restart if requested, then rerun the same bootstrap.' }
343
+ }
344
+ if (-not (Test-Path -LiteralPath $Destination)) {
345
+ Invoke-WinixBootstrapNative $git @('clone', '--origin', 'origin', '--', $Repository, $Destination) | ForEach-Object { Write-Host $_ }
346
+ # A normal clone retains history; branch selection never advances on a later bootstrap.
347
+ if ($Ref -ne 'main' -or (Invoke-WinixBootstrapNative $git @('-C', $Destination, 'branch', '--show-current')) -ne 'main') {
348
+ Invoke-WinixBootstrapNative $git @('-C', $Destination, 'checkout', $Ref) | ForEach-Object { Write-Host $_ }
349
+ }
350
+ }
351
+ if (-not (Test-Path -LiteralPath (Join-Path $Destination '.git') -PathType Container)) { throw 'Existing destination is not a regular Git checkout; refusing adoption.' }
352
+ Assert-WinixBootstrapDirectory (Join-Path $Destination '.git')
353
+ if (((Invoke-WinixBootstrapNative $git @('-C', $Destination, 'remote', 'get-url', 'origin')) -join '').Trim() -ne $Repository) {
354
+ throw 'Existing checkout has a different origin; refusing to change it.'
355
+ }
356
+ if ((Invoke-WinixBootstrapNative $git @('-C', $Destination, 'status', '--porcelain', '--untracked-files=normal'))) {
357
+ throw 'Checkout has local changes. Commit/stash them explicitly; bootstrap never resets or cleans files.'
358
+ }
359
+ $head = ((Invoke-WinixBootstrapNative $git @('-C', $Destination, 'rev-parse', 'HEAD')) -join '').Trim()
360
+ $wanted = ((Invoke-WinixBootstrapNative $git @('-C', $Destination, 'rev-parse', '--verify', "$Ref^{commit}")) -join '').Trim()
361
+ if ($head -ne $wanted) { throw 'Existing checkout is not at the requested local ref; switch it explicitly. Bootstrap never pulls or resets.' }
362
+ Assert-WinixBootstrapDirectory $config
363
+ $version = Get-WinixCheckoutVersion $config
364
+ $architecture = [Environment]::GetEnvironmentVariable('PROCESSOR_ARCHITEW6432')
365
+ if (-not $architecture) { $architecture = $env:PROCESSOR_ARCHITECTURE }
366
+ switch ($architecture.ToUpperInvariant()) {
367
+ 'AMD64' { $asset = 'winix-windows-x64.exe' }
368
+ 'ARM64' { $asset = 'winix-windows-arm64.exe' }
369
+ default { throw "Unsupported Windows architecture: $architecture" }
370
+ }
371
+ $runtime = Join-Path $config ".winix\runtime\$version"
372
+ Assert-WinixBootstrapDirectory $runtime
373
+ New-Item -ItemType Directory -Path $runtime -Force | Out-Null
374
+ $release = "https://github.com/adrifer/winix/releases/download/v$version"
375
+ $binary = Join-Path $runtime 'winix.exe'
376
+ Save-WinixVerifiedDownload "$release/$asset" "$release/SHA256SUMS" $asset $binary
377
+ $prerequisites = Join-Path $runtime 'bootstrap-windows.ps1'
378
+ Save-WinixVerifiedDownload "$release/bootstrap-windows.ps1" "$release/bootstrap-windows.ps1.sha256" 'bootstrap-windows.ps1' $prerequisites
379
+ if (((Invoke-WinixBootstrapNative $binary @('--version')) -join '').Trim() -ne $version) { throw 'Downloaded executable version does not match the checkout.' }
380
+ & $prerequisites -Standalone -Yes
381
+ if (-not $?) { throw 'Prerequisites failed; resolve the error/reboot manually, then rerun the same bootstrap.' }
382
+ $arguments = @('bootstrap', '--host', $HostName)
383
+ if ($PrepareOnly) { $arguments += '--prepare-only' }
384
+ if ($Yes) { $arguments += '--yes' }
385
+ Push-Location -LiteralPath $config
386
+ try { Invoke-WinixBootstrapHost $binary $arguments }
387
+ finally { Pop-Location }
388
+ }
389
+
218
390
  if ($MyInvocation.InvocationName -ne '.') {
219
391
  try {
220
- Invoke-WinixWindowsBootstrap -Check:$Check -Yes:$Yes -UseNvm:$UseNvm -Standalone:$Standalone
392
+ if ($Repository) {
393
+ if ($Check -or $UseNvm) { throw 'Repository mode cannot be combined with -Check or -UseNvm; it always uses standalone prerequisites.' }
394
+ Invoke-WinixRepositoryBootstrap -Repository $Repository -Ref $Ref -Destination $Destination `
395
+ -ConfigDirectory $ConfigDirectory -HostName $HostName -Yes:$Yes -PrepareOnly:$PrepareOnly -DryRun:$DryRun
396
+ } elseif ($DryRun -or $PrepareOnly -or $HostName) {
397
+ throw '-DryRun, -PrepareOnly and -HostName require -Repository. Use -Check for prerequisite-only inspection.'
398
+ } else {
399
+ Invoke-WinixWindowsBootstrap -Check:$Check -Yes:$Yes -UseNvm:$UseNvm -Standalone:$Standalone
400
+ }
221
401
  } catch {
222
402
  Write-Error $_ -ErrorAction Continue
223
403
  exit 1