@adrifer/winix 0.2.3 → 0.2.4-preview.0

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.
Files changed (36) hide show
  1. package/README.md +364 -2
  2. package/dist/backends/windows/index.d.ts +3 -1
  3. package/dist/backends/windows/index.js +99 -7
  4. package/dist/backends/windows/lockfile.d.ts +36 -1
  5. package/dist/backends/windows/lockfile.js +168 -0
  6. package/dist/backends/windows/paths.d.ts +2 -0
  7. package/dist/backends/windows/paths.js +17 -0
  8. package/dist/backends/windows/powershell.d.ts +6 -0
  9. package/dist/backends/windows/powershell.js +51 -0
  10. package/dist/backends/windows/wsl-setup-runtime.d.ts +32 -0
  11. package/dist/backends/windows/wsl-setup-runtime.js +387 -0
  12. package/dist/backends/windows/wsl-setup.d.ts +12 -0
  13. package/dist/backends/windows/wsl-setup.js +108 -0
  14. package/dist/backends/windows/wsl.d.ts +9 -0
  15. package/dist/backends/windows/wsl.js +194 -0
  16. package/dist/cli/commands/apply.d.ts +7 -1
  17. package/dist/cli/commands/apply.js +39 -15
  18. package/dist/cli/commands/check.js +3 -0
  19. package/dist/cli/commands/switch.d.ts +6 -0
  20. package/dist/cli/commands/switch.js +53 -13
  21. package/dist/cli/commands/update.d.ts +6 -1
  22. package/dist/cli/commands/update.js +41 -10
  23. package/dist/cli/index.js +33 -2
  24. package/dist/cli/windows-state.d.ts +56 -0
  25. package/dist/cli/windows-state.js +341 -0
  26. package/dist/helpers/index.d.ts +1 -1
  27. package/dist/helpers/utils.d.ts +1 -0
  28. package/dist/helpers/utils.js +8 -0
  29. package/dist/helpers/windows.d.ts +53 -7
  30. package/dist/helpers/windows.js +351 -28
  31. package/dist/index.d.ts +4 -2
  32. package/dist/skill.js +114 -5
  33. package/dist/types/windows.d.ts +82 -1
  34. package/package.json +3 -1
  35. package/scripts/bootstrap-nixos.sh +51 -0
  36. package/scripts/bootstrap-windows.ps1 +216 -0
@@ -0,0 +1,194 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { filePathExpression, filePathPrelude } from "../../helpers/windows.js";
3
+ import { powerShellLiteral as ps } from "../../helpers/utils.js";
4
+ import { wslRepositoryKey, wslSetupPrelude } from "./wsl-setup.js";
5
+ export function validWslImage(value) {
6
+ if (!value || typeof value !== "object")
7
+ return false;
8
+ const entry = value;
9
+ if (entry.source !== "nixos-wsl" || !["x64", "arm64"].includes(String(entry.architecture)) ||
10
+ typeof entry.version !== "string" || !/^[a-z0-9][a-z0-9._-]*$/i.test(entry.version) ||
11
+ typeof entry.sha256 !== "string" || !/^[a-f0-9]{64}$/.test(entry.sha256) ||
12
+ typeof entry.resolvedAt !== "string")
13
+ return false;
14
+ const asset = entry.architecture === "x64" ? "nixos.wsl" : "nixos.aarch64.wsl";
15
+ return entry.url === `https://github.com/nix-community/NixOS-WSL/releases/download/${entry.version}/${asset}`;
16
+ }
17
+ export const resolveNixosWslImage = (architecture) => {
18
+ const assetName = architecture === "x64" ? "nixos.wsl" : "nixos.aarch64.wsl";
19
+ const script = `
20
+ const response = await fetch("https://api.github.com/repos/nix-community/NixOS-WSL/releases/latest", {
21
+ headers: { Accept: "application/vnd.github+json", "User-Agent": "Winix" },
22
+ signal: AbortSignal.timeout(30000),
23
+ });
24
+ if (!response.ok) throw new Error("NixOS-WSL release lookup failed: HTTP " + response.status);
25
+ const release = await response.json();
26
+ if (release.draft || release.prerelease) throw new Error("Expected a stable NixOS-WSL release");
27
+ const asset = release.assets?.find(asset => asset.name === ${JSON.stringify(assetName)});
28
+ if (!asset || !/^sha256:[a-f0-9]{64}$/.test(asset.digest)) throw new Error("Release asset lacks a SHA256 digest");
29
+ console.log(JSON.stringify({
30
+ source: "nixos-wsl", architecture: ${JSON.stringify(architecture)},
31
+ version: release.tag_name, url: asset.browser_download_url, sha256: asset.digest.slice(7),
32
+ }));
33
+ `;
34
+ const image = JSON.parse(execFileSync(process.execPath, ["--input-type=module", "--eval", script], {
35
+ encoding: "utf8", timeout: 45000, stdio: ["pipe", "pipe", "pipe"],
36
+ }));
37
+ if (!image || typeof image !== "object" || !validWslImage({ ...image, resolvedAt: "" })) {
38
+ throw new Error("Invalid official NixOS-WSL release image");
39
+ }
40
+ const validated = image;
41
+ if (validated.architecture !== architecture)
42
+ throw new Error("NixOS-WSL image architecture mismatch");
43
+ return validated;
44
+ };
45
+ export function optionalFeatureProperties(names, enabled) {
46
+ const prelude = [
47
+ "$ErrorActionPreference = 'Stop'",
48
+ ` $names = @(${names.map(ps).join(", ")})`,
49
+ ` $enabled = ${enabled ? "$true" : "$false"}`,
50
+ "function Get-WinixFeatureStates {",
51
+ " foreach ($name in $names) { Get-WindowsOptionalFeature -Online -FeatureName $name -ErrorAction Stop }",
52
+ "}",
53
+ "function Test-WinixFeatures {",
54
+ " foreach ($feature in @(Get-WinixFeatureStates)) {",
55
+ " $state = [string]$feature.State",
56
+ " if ($enabled) { if ($state -ne 'Enabled') { return $false } }",
57
+ " elseif ($state -notin @('Disabled', 'DisabledWithPayloadRemoved')) { return $false }",
58
+ " }",
59
+ " return $true",
60
+ "}",
61
+ ];
62
+ return {
63
+ getScript: [...prelude, "Get-WinixFeatureStates | Select-Object FeatureName,State"].join("\n"),
64
+ testScript: [...prelude, "Test-WinixFeatures"].join("\n"),
65
+ setScript: [
66
+ ...prelude,
67
+ "$restart = $false",
68
+ "foreach ($feature in @(Get-WinixFeatureStates)) {",
69
+ " $state = [string]$feature.State",
70
+ " if ($state -in @('EnablePending', 'DisablePending')) { $restart = $true; continue }",
71
+ " if ($enabled -and $state -ne 'Enabled') {",
72
+ " $result = Enable-WindowsOptionalFeature -Online -FeatureName $feature.FeatureName -All -NoRestart -ErrorAction Stop",
73
+ " $restart = $restart -or [bool]$result.RestartNeeded",
74
+ " } elseif (-not $enabled -and $state -notin @('Disabled', 'DisabledWithPayloadRemoved')) {",
75
+ " $result = Disable-WindowsOptionalFeature -Online -FeatureName $feature.FeatureName -NoRestart -ErrorAction Stop",
76
+ " $restart = $restart -or [bool]$result.RestartNeeded",
77
+ " }",
78
+ "}",
79
+ "if ($restart -or -not (Test-WinixFeatures)) {",
80
+ " throw 'WINIX_REBOOT_REQUIRED: Restart Windows yourself, then rerun winix switch. Dependent provisioning was not completed.'",
81
+ "}",
82
+ ].join("\n"),
83
+ };
84
+ }
85
+ export function wslDistroProperties(distro, pins, repositories = {}) {
86
+ const images = [];
87
+ for (const architecture of ["x64", "arm64"]) {
88
+ const pin = pins[`nixos-wsl/${architecture}`];
89
+ if (!validWslImage(pin) || pin.architecture !== architecture) {
90
+ throw new Error(`Missing/invalid nixos-wsl/${architecture} image pin. Run winix update --windows nixos-wsl.`);
91
+ }
92
+ images.push(`${architecture} = @{ Url = ${ps(pin.url)}; Sha256 = ${ps(pin.sha256)}; Version = ${ps(pin.version)} }`);
93
+ }
94
+ const prelude = [
95
+ "$ErrorActionPreference = 'Stop'",
96
+ ...filePathPrelude(),
97
+ "if ([Security.Principal.WindowsIdentity]::GetCurrent().IsSystem) { throw 'WSL provisioning must run as the intended Windows user, not SYSTEM' }",
98
+ `$name = ${ps(distro.name)}`,
99
+ `$location = ${filePathExpression(distro.installLocation)}`,
100
+ "if (-not [IO.Path]::IsPathFullyQualified($location)) { throw 'WSL installLocation must resolve to an absolute path' }",
101
+ "$location = [IO.Path]::GetFullPath($location)",
102
+ "if ($location -notmatch '^[a-zA-Z]:\\\\' -or $location.TrimEnd('\\') -eq [IO.Path]::GetPathRoot($location).TrimEnd('\\')) {",
103
+ " throw 'WSL installLocation must be an absolute local-drive directory, not a drive root or UNC path'",
104
+ "}",
105
+ "$marker = Join-Path $location '.winix-wsl.json'",
106
+ "$lxss = 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Lxss'",
107
+ ` $makeDefault = ${distro.default ? "$true" : "$false"}`,
108
+ ` $images = @{ ${images.join("; ")} }`,
109
+ "function Normalize-WinixWslPath([string]$Path) {",
110
+ " if ($Path.StartsWith('\\\\?\\')) { $Path = $Path.Substring(4) }",
111
+ " [IO.Path]::GetFullPath($Path).TrimEnd('\\')",
112
+ "}",
113
+ "function Get-WinixWslRegistration {",
114
+ " if (-not (Test-Path -LiteralPath $lxss)) { return $null }",
115
+ " $matches = @(Get-ChildItem -LiteralPath $lxss | ForEach-Object { Get-ItemProperty -LiteralPath $_.PSPath } |",
116
+ " Where-Object { $_.DistributionName -ieq $name })",
117
+ " if ($matches.Count -gt 1) { throw \"Ambiguous WSL registration: $name\" }",
118
+ " if ($matches.Count -eq 1) { return $matches[0] }",
119
+ " return $null",
120
+ "}",
121
+ "function Assert-WinixWslRegistration($Registration, [bool]$RequireMarker = $true) {",
122
+ " if ((Normalize-WinixWslPath $Registration.BasePath) -ine (Normalize-WinixWslPath $location) -or $Registration.Version -ne 2) {",
123
+ " throw \"Conflicting WSL registration for $name; refusing to move, replace, or convert an existing distro\"",
124
+ " }",
125
+ " if ($RequireMarker) {",
126
+ " if (-not (Test-Path -LiteralPath $marker -PathType Leaf)) { throw \"Existing WSL distro $name is not recorded by Winix; refusing automatic adoption\" }",
127
+ " $record = [IO.File]::ReadAllText($marker) | ConvertFrom-Json",
128
+ " if ($record.version -ne 1 -or $record.source -ne 'nixos-wsl' -or $record.name -ine $name -or $record.registration -ine $Registration.PSChildName) {",
129
+ " throw \"WSL ownership marker does not match registration for $name\"",
130
+ " }",
131
+ " }",
132
+ "}",
133
+ "function Test-WinixWslDefault($Registration) {",
134
+ " if (-not $makeDefault) { return $true }",
135
+ " return (Get-ItemProperty -LiteralPath $lxss).DefaultDistribution -ieq $Registration.PSChildName",
136
+ "}",
137
+ "function Invoke-WinixWsl([string[]]$Arguments) {",
138
+ " $output = @(& wsl.exe @Arguments)",
139
+ " if ($LASTEXITCODE -ne 0) { throw \"WSL command failed ($LASTEXITCODE): $($Arguments -join ' ') $($output -join ' ')\" }",
140
+ "}",
141
+ ];
142
+ if (distro.setup) {
143
+ const pin = repositories[wslRepositoryKey(distro.setup)];
144
+ if (!pin)
145
+ throw new Error("Missing WSL setup repository pin. Run winix update --windows wsl-setup.");
146
+ prelude.push(...wslSetupPrelude(distro.setup, pin));
147
+ }
148
+ return {
149
+ getScript: [...prelude, "Get-WinixWslRegistration | Select-Object DistributionName,BasePath,Version"].join("\n"),
150
+ testScript: [
151
+ ...prelude,
152
+ "$registration = Get-WinixWslRegistration",
153
+ "if ($null -eq $registration) { return $false }",
154
+ "Assert-WinixWslRegistration $registration",
155
+ ...(distro.setup ? ["if (-not (Invoke-WinixWslSetup $true)) { return $false }"] : []),
156
+ "Test-WinixWslDefault $registration",
157
+ ].join("\n"),
158
+ setScript: [
159
+ ...prelude,
160
+ "$registration = Get-WinixWslRegistration",
161
+ "if ($null -ne $registration) { Assert-WinixWslRegistration $registration } else {",
162
+ " if ((Test-Path -LiteralPath 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Component Based Servicing\\RebootPending') -or",
163
+ " (Test-Path -LiteralPath 'HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update\\RebootRequired')) {",
164
+ " throw 'WINIX_REBOOT_REQUIRED: Restart Windows yourself, then rerun winix switch before registering WSL.'",
165
+ " }",
166
+ " if (Test-Path -LiteralPath $location) { throw \"WSL install location already exists; refusing to overwrite: $location\" }",
167
+ " $architecture = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString().ToLowerInvariant()",
168
+ " if (-not $images.ContainsKey($architecture)) { throw \"Unsupported WSL image architecture: $architecture\" }",
169
+ " $image = $images[$architecture]",
170
+ " $temporary = Join-Path ([IO.Path]::GetTempPath()) ('winix-wsl-' + [guid]::NewGuid().ToString('N'))",
171
+ " [IO.Directory]::CreateDirectory($temporary) | Out-Null",
172
+ " try {",
173
+ " $archive = Join-Path $temporary 'nixos.wsl'",
174
+ " Invoke-WebRequest -Uri $image.Url -OutFile $archive -ErrorAction Stop",
175
+ " if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash.ToLowerInvariant() -cne $image.Sha256) {",
176
+ " throw 'NixOS-WSL download checksum mismatch; refusing registration'",
177
+ " }",
178
+ " [IO.Directory]::CreateDirectory((Split-Path -Parent $location)) | Out-Null",
179
+ " Invoke-WinixWsl @('--import', $name, $location, $archive, '--version', '2')",
180
+ " $registration = Get-WinixWslRegistration",
181
+ " if ($null -eq $registration) { throw 'WSL import returned success without registering the requested distro' }",
182
+ " Assert-WinixWslRegistration $registration $false",
183
+ " $record = @{ version = 1; source = 'nixos-wsl'; name = $name; registration = $registration.PSChildName; imageVersion = $image.Version; sha256 = $image.Sha256 }",
184
+ " $stream = [IO.File]::Open($marker, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::None)",
185
+ " $writer = [IO.StreamWriter]::new($stream, [Text.UTF8Encoding]::new($false))",
186
+ " try { $writer.Write(($record | ConvertTo-Json -Compress)) } finally { $writer.Dispose() }",
187
+ " } finally { Remove-Item -LiteralPath $temporary -Recurse -Force }",
188
+ "}",
189
+ ...(distro.setup ? ["[void](Invoke-WinixWslSetup $false)"] : []),
190
+ "if (-not (Test-WinixWslDefault $registration)) { Invoke-WinixWsl @('--set-default', $name) }",
191
+ "if (-not (Test-WinixWslDefault $registration)) { throw 'WSL default distribution verification failed' }",
192
+ ].join("\n"),
193
+ };
194
+ }
@@ -1,4 +1,6 @@
1
- import { type WindowsPackageVersionResolver } from "../../backends/windows/lockfile.js";
1
+ import { type WindowsLock, type WindowsPackageVersionResolver, type WindowsModuleVersionResolver } from "../../backends/windows/lockfile.js";
2
+ import { type WindowsWslImageResolver } from "../../backends/windows/wsl.js";
3
+ import { type WindowsWslRepositoryResolver } from "../../backends/windows/wsl-setup.js";
2
4
  import { type ActivationPlatform } from "../activation.js";
3
5
  interface ApplyOptions {
4
6
  host?: string;
@@ -6,12 +8,16 @@ interface ApplyOptions {
6
8
  diff: boolean;
7
9
  windowsLockDry?: boolean;
8
10
  resolveWindowsPackageVersion?: WindowsPackageVersionResolver;
11
+ resolveWindowsModuleVersion?: WindowsModuleVersionResolver;
12
+ resolveWindowsWslImage?: WindowsWslImageResolver;
13
+ resolveWindowsWslRepository?: WindowsWslRepositoryResolver;
9
14
  }
10
15
  export interface ApplyResult {
11
16
  configDir: string;
12
17
  outDir: string;
13
18
  hostNames: string[];
14
19
  hostPlatforms: Map<string, ActivationPlatform>;
20
+ windowsLock?: WindowsLock;
15
21
  }
16
22
  export declare function applyWorkspace(cwd: string, opts: ApplyOptions): Promise<ApplyResult>;
17
23
  export declare function apply(cwd: string, opts: ApplyOptions): Promise<void>;
@@ -5,9 +5,12 @@ import { existsSync } from "node:fs";
5
5
  import { loadWorkspace } from "../loader.js";
6
6
  import { evaluate } from "../../evaluator/index.js";
7
7
  import { generateNix } from "../../backends/nix/index.js";
8
- import { generateWindows } from "../../backends/windows/index.js";
9
- import { emptyWindowsLock, readWindowsLock, reconcileInlinePins, resolveMissingWindowsLockEntries, windowsLockChanged, writeWindowsLock, } from "../../backends/windows/lockfile.js";
8
+ import { generateWindows, validateWindowsWslResources } from "../../backends/windows/index.js";
9
+ import { emptyWindowsLock, readWindowsLock, reconcileInlinePins, resolveMissingWindowsLockEntries, collectWindowsModules, resolveWindowsModuleLockEntries, hasWindowsWslDistros, resolveWindowsWslImages, resolveWindowsWslRepositories, windowsLockChanged, writeWindowsLock, } from "../../backends/windows/lockfile.js";
10
10
  import { resolveWingetVersion } from "../../backends/windows/resolver.js";
11
+ import { resolvePowerShellModuleVersion } from "../../backends/windows/powershell.js";
12
+ import { resolveNixosWslImage } from "../../backends/windows/wsl.js";
13
+ import { resolveWslRepository } from "../../backends/windows/wsl-setup.js";
11
14
  import { platformForEvaluatedHost } from "../activation.js";
12
15
  export async function applyWorkspace(cwd, opts) {
13
16
  const { workspace, configDir } = await loadWorkspace(cwd);
@@ -23,23 +26,25 @@ export async function applyWorkspace(cwd, opts) {
23
26
  const hostPlatforms = platformsForHosts(evaluated);
24
27
  const nixHosts = evaluated.filter((host) => hostPlatforms.get(host.name) !== "windows");
25
28
  const windowsHosts = evaluated.filter((host) => hostPlatforms.get(host.name) === "windows");
29
+ for (const host of windowsHosts)
30
+ validateWindowsWslResources(host.windows);
26
31
  const windowsLock = windowsHosts.length > 0
27
- ? prepareWindowsLock(configDir, windowsHosts, opts.dry || opts.windowsLockDry === true, opts.resolveWindowsPackageVersion ?? resolveWingetVersion)
32
+ ? prepareWindowsLock(configDir, windowsHosts, opts.dry || opts.windowsLockDry === true, opts.resolveWindowsPackageVersion ?? resolveWingetVersion, opts.resolveWindowsModuleVersion ?? resolvePowerShellModuleVersion, opts.resolveWindowsWslImage ?? resolveNixosWslImage, opts.resolveWindowsWslRepository ?? resolveWslRepository)
28
33
  : undefined;
29
34
  const nixOutput = nixHosts.length > 0 ? generateNix(workspace, nixHosts) : undefined;
30
35
  const windowsOutput = windowsHosts.length > 0
31
- ? generateWindows(windowsHosts, windowsLock)
36
+ ? generateWindows(windowsHosts, windowsLock, configDir)
32
37
  : undefined;
33
38
  printWarnings(nixOutput?.warnings ?? []);
34
39
  printWarnings(windowsOutput?.warnings ?? []);
35
40
  const outDir = join(configDir, ".winix", "out");
36
41
  if (opts.dry) {
37
42
  printDryOutput(nixOutput, windowsOutput);
38
- return resultFor(configDir, outDir, evaluated);
43
+ return { ...resultFor(configDir, outDir, evaluated), windowsLock };
39
44
  }
40
45
  if (opts.diff) {
41
46
  await showDiff(configDir, outDir, nixOutput, windowsOutput);
42
- return resultFor(configDir, outDir, evaluated);
47
+ return { ...resultFor(configDir, outDir, evaluated), windowsLock };
43
48
  }
44
49
  if (nixOutput) {
45
50
  await mkdir(join(outDir, "hosts"), { recursive: true });
@@ -75,26 +80,45 @@ export async function applyWorkspace(cwd, opts) {
75
80
  }
76
81
  }
77
82
  printNextSteps(cwd, outDir, evaluated);
78
- return resultFor(configDir, outDir, evaluated);
83
+ return { ...resultFor(configDir, outDir, evaluated), windowsLock };
79
84
  }
80
85
  export async function apply(cwd, opts) {
81
86
  await applyWorkspace(cwd, opts);
82
87
  }
83
- function prepareWindowsLock(configDir, windowsHosts, dry, resolveVersion) {
88
+ function prepareWindowsLock(configDir, windowsHosts, dry, resolveVersion, resolveModuleVersion, resolveWslImage, resolveRepository) {
84
89
  const now = new Date();
85
90
  const lock = readWindowsLock(configDir) ?? emptyWindowsLock(now);
86
91
  const reconciled = reconcileInlinePins(lock, windowsHosts, now);
87
92
  const resolved = resolveMissingWindowsLockEntries(reconciled, windowsHosts, resolveVersion, now);
88
- const changed = windowsLockChanged(lock, resolved.lock);
93
+ const modules = resolveWindowsModuleLockEntries(resolved.lock, collectWindowsModules(windowsHosts).values(), resolveModuleVersion, now, true);
94
+ const images = hasWindowsWslDistros(windowsHosts)
95
+ ? resolveWindowsWslImages(modules.lock, resolveWslImage, now, true)
96
+ : { lock: modules.lock, changed: false };
97
+ const repositories = resolveWindowsWslRepositories(images.lock, windowsHosts, resolveRepository, now, true);
98
+ const changed = windowsLockChanged(lock, repositories.lock);
89
99
  if (!changed)
90
- return resolved.lock;
100
+ return repositories.lock;
91
101
  if (dry) {
92
- printWindowsLockDryRun(resolved.resolutions);
93
- return resolved.lock;
102
+ if (windowsLockChanged(lock, resolved.lock))
103
+ printWindowsLockDryRun(resolved.resolutions);
104
+ for (const entry of modules.resolutions)
105
+ console.warn(`Would pin PowerShell module ${entry.id} ${entry.version} in winix-windows.lock`);
106
+ if (images.changed)
107
+ console.warn("Would pin verified NixOS-WSL images for x64/arm64 in winix-windows.lock");
108
+ if (repositories.changed)
109
+ console.warn("Would pin WSL setup repository commits in winix-windows.lock");
110
+ return repositories.lock;
94
111
  }
95
- writeWindowsLock(configDir, resolved.lock);
96
- printWindowsLockUpdate(resolved.resolutions);
97
- return resolved.lock;
112
+ writeWindowsLock(configDir, repositories.lock);
113
+ if (windowsLockChanged(lock, resolved.lock))
114
+ printWindowsLockUpdate(resolved.resolutions);
115
+ for (const entry of modules.resolutions)
116
+ console.log(`✓ Pinned PowerShell module ${entry.id} ${entry.version} in winix-windows.lock`);
117
+ if (images.changed)
118
+ console.log("✓ Pinned verified NixOS-WSL images for x64/arm64 in winix-windows.lock");
119
+ if (repositories.changed)
120
+ console.log("✓ Pinned WSL setup repository commits in winix-windows.lock");
121
+ return repositories.lock;
98
122
  }
99
123
  function printWindowsLockDryRun(resolutions) {
100
124
  if (resolutions.length === 0) {
@@ -3,12 +3,15 @@ import { spawnSync } from "node:child_process";
3
3
  import { loadWorkspace } from "../loader.js";
4
4
  import { evaluate } from "../../evaluator/index.js";
5
5
  import { generateNix } from "../../backends/nix/index.js";
6
+ import { validateWindowsWslResources } from "../../backends/windows/index.js";
6
7
  import { analyzeWorkspace, collectEscapeReport, collectSuspiciousNixReferences, detectConflicts, findDuplicateHosts, } from "../analysis.js";
7
8
  export async function check(cwd, opts) {
8
9
  try {
9
10
  const { workspace } = await loadWorkspace(cwd);
10
11
  const duplicateHosts = findDuplicateHosts(workspace);
11
12
  const evaluated = evaluate(workspace);
13
+ for (const host of evaluated)
14
+ validateWindowsWslResources(host.windows);
12
15
  const output = generateNix(workspace, evaluated);
13
16
  validateGeneratedNixSyntax(output);
14
17
  const analyses = analyzeWorkspace(workspace);
@@ -1,6 +1,12 @@
1
+ import { type WindowsStateAdapter } from "../windows-state.js";
1
2
  interface SwitchOptions {
2
3
  host?: string;
3
4
  dry: boolean;
5
+ yes?: boolean;
6
+ windowsState?: {
7
+ path: string;
8
+ adapter: WindowsStateAdapter;
9
+ };
4
10
  }
5
11
  export declare function switchCommand(cwd: string, opts: SwitchOptions): Promise<void>;
6
12
  export declare function selectHost(hosts: string[], requested?: string, currentHostname?: string): string;
@@ -1,12 +1,15 @@
1
1
  import { hostname } from "node:os";
2
2
  import { join } from "node:path";
3
+ import { realpath } from "node:fs/promises";
4
+ import { createHash } from "node:crypto";
5
+ import { managedWindowsResources, nativeWindowsStateAdapter, reconcileWindows, resourceKey, windowsStatePath, withWindowsStateLock, } from "../windows-state.js";
3
6
  import { evaluate } from "../../evaluator/index.js";
4
7
  import { loadWorkspace } from "../loader.js";
5
8
  import { runCommand } from "../run.js";
6
9
  import { activationCommand, assertActivationSupported, platformForEvaluatedHost, } from "../activation.js";
7
10
  import { applyWorkspace } from "./apply.js";
8
11
  export async function switchCommand(cwd, opts) {
9
- const { workspace } = await loadWorkspace(cwd);
12
+ const { workspace, configDir } = await loadWorkspace(cwd);
10
13
  const evaluated = evaluate(workspace);
11
14
  const hostName = selectHost(evaluated.map((host) => host.name), opts.host);
12
15
  const selected = evaluated.find((host) => host.name === hostName);
@@ -16,18 +19,55 @@ export async function switchCommand(cwd, opts) {
16
19
  if (!opts.dry) {
17
20
  assertActivationSupported(platform);
18
21
  }
19
- const result = await applyWorkspace(cwd, {
20
- host: hostName,
21
- dry: false,
22
- diff: false,
23
- windowsLockDry: opts.dry,
24
- });
25
- const activationTarget = platform === "windows"
26
- ? windowsConfigurationForHost(result.outDir, hostName)
27
- : flakeRefForHost(result.outDir, hostName);
28
- const command = activationCommand(platform, activationTarget);
29
- console.log(`\nRunning: ${command.join(" ")}`);
30
- await runCommand(command[0], command.slice(1), { dry: opts.dry });
22
+ const statePath = platform === "windows" && process.platform === "win32"
23
+ ? opts.windowsState?.path ?? windowsStatePath() : undefined;
24
+ const performSwitch = async () => {
25
+ const result = await applyWorkspace(cwd, {
26
+ host: hostName,
27
+ dry: opts.dry && platform === "windows",
28
+ diff: false,
29
+ windowsLockDry: opts.dry,
30
+ });
31
+ const activationTarget = platform === "windows"
32
+ ? windowsConfigurationForHost(result.outDir, hostName)
33
+ : flakeRefForHost(result.outDir, hostName);
34
+ const command = activationCommand(platform, activationTarget);
35
+ console.log(`\nRunning: ${command.join(" ")}`);
36
+ const activate = () => runCommand(command[0], command.slice(1), { dry: opts.dry });
37
+ if (statePath) {
38
+ const desired = managedWindowsResources(selected);
39
+ const windows = selected.windows;
40
+ const definitions = {};
41
+ const lock = result.windowsLock;
42
+ for (const resource of desired) {
43
+ const definition = resource.kind === "package"
44
+ ? windows.packages?.[resource.id].version ?? lock?.packages[resource.id]?.version
45
+ : JSON.stringify(windows.dsc?.find((entry) => entry.winix?.kind === "startup" && entry.winix.name === resource.name)?.properties);
46
+ if (!definition)
47
+ throw new Error(`Missing activation definition: ${resourceKey(resource)}`);
48
+ definitions[resourceKey(resource)] = createHash("sha256").update(definition).digest("hex");
49
+ }
50
+ await reconcileWindows({
51
+ statePath,
52
+ owner: JSON.stringify([(await realpath(configDir)).toLowerCase(), hostName]),
53
+ desired, definitions,
54
+ dry: opts.dry,
55
+ yes: opts.yes,
56
+ adapter: opts.windowsState?.adapter ?? nativeWindowsStateAdapter,
57
+ lockHeld: true,
58
+ activate,
59
+ });
60
+ }
61
+ else {
62
+ if (platform === "windows")
63
+ console.log("Windows removal inventory can only be inspected on native Windows.");
64
+ await activate();
65
+ }
66
+ };
67
+ if (statePath)
68
+ await withWindowsStateLock(statePath, opts.dry, performSwitch);
69
+ else
70
+ await performSwitch();
31
71
  }
32
72
  export function selectHost(hosts, requested, currentHostname = hostname()) {
33
73
  if (requested) {
@@ -1,9 +1,14 @@
1
- import { type WindowsPackageVersionResolver } from "../../backends/windows/lockfile.js";
1
+ import { type WindowsPackageVersionResolver, type WindowsModuleVersionResolver } from "../../backends/windows/lockfile.js";
2
+ import { type WindowsWslImageResolver } from "../../backends/windows/wsl.js";
3
+ import { type WindowsWslRepositoryResolver } from "../../backends/windows/wsl-setup.js";
2
4
  interface UpdateOptions {
3
5
  inputs: string[];
4
6
  dry: boolean;
5
7
  windows?: boolean;
6
8
  resolveWindowsPackageVersion?: WindowsPackageVersionResolver;
9
+ resolveWindowsModuleVersion?: WindowsModuleVersionResolver;
10
+ resolveWindowsWslImage?: WindowsWslImageResolver;
11
+ resolveWindowsWslRepository?: WindowsWslRepositoryResolver;
7
12
  }
8
13
  export declare function update(cwd: string, opts: UpdateOptions): Promise<void>;
9
14
  export declare function assertUpdateSupported(osPlatform?: NodeJS.Platform): void;
@@ -2,7 +2,10 @@ import { join } from "node:path";
2
2
  import { tmpdir } from "node:os";
3
3
  import { cp, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
4
4
  import { evaluate } from "../../evaluator/index.js";
5
- import { emptyWindowsLock, readWindowsLock, reconcileInlinePins, resolveWindowsLockEntries, windowsLockChanged, writeWindowsLock, } from "../../backends/windows/lockfile.js";
5
+ import { emptyWindowsLock, readWindowsLock, reconcileInlinePins, resolveWindowsLockEntries, collectWindowsModules, resolveWindowsModuleLockEntries, hasWindowsWslDistros, resolveWindowsWslImages, resolveWindowsWslRepositories, windowsLockChanged, writeWindowsLock, } from "../../backends/windows/lockfile.js";
6
+ import { resolvePowerShellModuleVersion } from "../../backends/windows/powershell.js";
7
+ import { resolveNixosWslImage } from "../../backends/windows/wsl.js";
8
+ import { resolveWslRepository } from "../../backends/windows/wsl-setup.js";
6
9
  import { isWindowsHost } from "../../backends/windows/index.js";
7
10
  import { assertWingetResolutionSupported, resolveWingetVersion, } from "../../backends/windows/resolver.js";
8
11
  import { platformForEvaluatedHost } from "../activation.js";
@@ -25,9 +28,8 @@ export async function update(cwd, opts) {
25
28
  const hasNixHost = evaluated.some((host) => platformForEvaluatedHost(host) !== "windows");
26
29
  if (!hasNixHost) {
27
30
  throw new Error("`winix update` updates the Nix flake lock, but this workspace has no " +
28
- "NixOS or nix-darwin hosts (Windows packages are pinned via " +
29
- "`winix-windows.lock`, resolved by a future `winix` milestone). " +
30
- "Nothing to update.");
31
+ "NixOS or nix-darwin hosts. Windows packages and PowerShell modules " +
32
+ "are pinned via `winix-windows.lock`; run `winix update --windows` instead.");
31
33
  }
32
34
  const result = await applyWorkspace(cwd, { dry: false, diff: false });
33
35
  const updateDir = await mkdtemp(join(tmpdir(), "winix-update-"));
@@ -63,9 +65,6 @@ async function updateWindowsLock(cwd, opts) {
63
65
  if (windowsHosts.length === 0) {
64
66
  throw new Error("`winix update --windows` found no Windows hosts in this workspace.");
65
67
  }
66
- if (!opts.resolveWindowsPackageVersion) {
67
- assertWingetResolutionSupported();
68
- }
69
68
  const now = new Date();
70
69
  const originalLock = readWindowsLock(configDir) ?? emptyWindowsLock(now);
71
70
  const reconciled = reconcileInlinePins(originalLock, windowsHosts, now);
@@ -75,7 +74,19 @@ async function updateWindowsLock(cwd, opts) {
75
74
  };
76
75
  const pinned = collectInlinePinnedPackages(windowsHosts);
77
76
  const floating = collectFloatingPackages(windowsHosts, pinned);
78
- const selected = selectPackagesForUpdate(floating, pinned, opts.inputs);
77
+ const modules = collectWindowsModules(windowsHosts);
78
+ const wslImages = hasWindowsWslDistros(windowsHosts);
79
+ const wslSetup = windowsHosts.some((host) => host.windows.dsc?.some((resource) => resource.winix?.kind === "wsl-distro" && resource.winix.distro.setup));
80
+ for (const id of opts.inputs) {
81
+ if (!floating.has(id) && !pinned.has(id) && !modules.has(id.toLowerCase()) &&
82
+ !(id === "nixos-wsl" && wslImages) && !(id === "wsl-setup" && wslSetup)) {
83
+ throw new Error(`Windows package, PowerShell module, WSL image or setup repository "${id}" is not declared in this workspace.`);
84
+ }
85
+ }
86
+ const selected = selectPackagesForUpdate(floating, pinned, opts.inputs.filter((id) => floating.has(id) || pinned.has(id)), opts.inputs.length === 0);
87
+ const selectedModules = [...modules.values()].filter((module) => opts.inputs.length === 0 || opts.inputs.some((id) => id.toLowerCase() === module.name.toLowerCase()));
88
+ if (selected.size > 0 && !opts.resolveWindowsPackageVersion)
89
+ assertWingetResolutionSupported();
79
90
  const resolveVersion = opts.resolveWindowsPackageVersion ?? resolveWingetVersion;
80
91
  let changed = windowsLockChanged(originalLock, reconciled);
81
92
  console.log(`Updating winix-windows.lock for ${windowsHosts.length} Windows host(s).`);
@@ -89,6 +100,21 @@ async function updateWindowsLock(cwd, opts) {
89
100
  const resolved = resolveWindowsLockEntries(lock, selected.values(), resolveVersion, now);
90
101
  lock = resolved.lock;
91
102
  changed = changed || resolved.changed;
103
+ const resolvedModules = resolveWindowsModuleLockEntries(lock, selectedModules, opts.resolveWindowsModuleVersion ?? resolvePowerShellModuleVersion, now);
104
+ lock = resolvedModules.lock;
105
+ changed = changed || resolvedModules.changed;
106
+ if (wslImages && (opts.inputs.length === 0 || opts.inputs.includes("nixos-wsl"))) {
107
+ const images = resolveWindowsWslImages(lock, opts.resolveWindowsWslImage ?? resolveNixosWslImage, now);
108
+ lock = images.lock;
109
+ changed = changed || images.changed;
110
+ console.log(` ${images.changed ? "resolved" : "up to date"} NixOS-WSL images (existing distros will not be reinstalled)`);
111
+ }
112
+ if (wslSetup && (opts.inputs.length === 0 || opts.inputs.includes("wsl-setup"))) {
113
+ const repositories = resolveWindowsWslRepositories(lock, windowsHosts, opts.resolveWindowsWslRepository ?? resolveWslRepository, now);
114
+ lock = repositories.lock;
115
+ changed = changed || repositories.changed;
116
+ console.log(` ${repositories.changed ? "resolved" : "up to date"} WSL setup repository commits (first-run only)`);
117
+ }
92
118
  for (const resolution of resolved.resolutions) {
93
119
  if (resolution.status === "up-to-date") {
94
120
  console.log(` up to date ${resolution.id} ${resolution.source} ${resolution.version}`);
@@ -101,6 +127,11 @@ async function updateWindowsLock(cwd, opts) {
101
127
  console.log(` resolved ${resolution.id} ${resolution.source} ${resolution.version} (new)`);
102
128
  }
103
129
  }
130
+ for (const resolution of resolvedModules.resolutions) {
131
+ const change = resolution.status === "updated"
132
+ ? `${resolution.previousVersion} -> ${resolution.version}` : resolution.version;
133
+ console.log(` ${resolution.status === "up-to-date" ? "up to date" : "resolved"} PowerShell module ${resolution.id} ${change}`);
134
+ }
104
135
  if (!changed) {
105
136
  console.log("winix-windows.lock is already up to date.");
106
137
  return;
@@ -149,8 +180,8 @@ function collectFloatingPackages(windowsHosts, pinned) {
149
180
  }
150
181
  return floating;
151
182
  }
152
- function selectPackagesForUpdate(floating, pinned, inputs) {
153
- if (inputs.length === 0)
183
+ function selectPackagesForUpdate(floating, pinned, inputs, all = inputs.length === 0) {
184
+ if (all)
154
185
  return floating;
155
186
  const selected = new Map();
156
187
  for (const id of inputs) {
package/dist/cli/index.js CHANGED
@@ -9,11 +9,13 @@ 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 { forgetWindowsResource, windowsStatePath } from "./windows-state.js";
12
13
  const { positionals, values } = parseArgs({
13
14
  allowPositionals: true,
14
15
  options: {
15
16
  host: { type: "string" },
16
17
  dry: { type: "boolean", default: false },
18
+ yes: { type: "boolean", short: "y", default: false },
17
19
  diff: { type: "boolean", default: false },
18
20
  windows: { type: "boolean", default: false },
19
21
  strict: { type: "boolean", default: false },
@@ -44,12 +46,14 @@ Commands:
44
46
  switch Generate output and run the host activation command
45
47
  update Update generated flake.lock and copy it to project root
46
48
  inspect Print host composition and fragment graph
49
+ state forget Release Windows removal ownership without deleting a resource
47
50
 
48
51
  Options:
49
52
  --host <name> Target a specific host
50
- --dry Show what would be generated (apply)
53
+ --dry Preview generation (apply) or activation and managed cleanup (switch)
54
+ -y, --yes Confirm managed Windows removals without prompting (switch)
51
55
  --diff Show diff against current output (apply)
52
- --windows Resolve Windows package lockfile (update)
56
+ --windows Resolve Windows package/module/WSL image lockfile (update)
53
57
  --strict Treat conflicts as errors (check)
54
58
  --escape-report Show escape hatch usage (check)
55
59
  --force Overwrite files (init, install skill)
@@ -71,6 +75,10 @@ Examples:
71
75
  process.exit(0);
72
76
  }
73
77
  const cwd = process.cwd();
78
+ if (values.yes && command !== "switch") {
79
+ console.error("--yes is only supported by winix switch.");
80
+ process.exit(2);
81
+ }
74
82
  switch (command) {
75
83
  case "init":
76
84
  try {
@@ -121,6 +129,7 @@ switch (command) {
121
129
  await switchCommand(cwd, {
122
130
  host: values.host,
123
131
  dry: values.dry,
132
+ yes: values.yes,
124
133
  });
125
134
  }
126
135
  catch (err) {
@@ -150,6 +159,28 @@ switch (command) {
150
159
  process.exit(1);
151
160
  }
152
161
  break;
162
+ case "state":
163
+ try {
164
+ if (process.platform !== "win32")
165
+ throw new Error("Windows applied state is only available on native Windows.");
166
+ let resource;
167
+ if (positionals[1] === "forget" && positionals[2] === "startup" && positionals.length === 4) {
168
+ resource = { kind: "startup", name: positionals[3] };
169
+ }
170
+ else if (positionals[1] === "forget" && positionals[2] === "package" &&
171
+ positionals.length === 5 && ["winget", "msstore"].includes(positionals[3])) {
172
+ resource = { kind: "package", source: positionals[3], id: positionals[4] };
173
+ }
174
+ else {
175
+ throw new Error("Usage: winix state forget startup <name> [--dry] OR winix state forget package <winget|msstore> <id> [--dry]");
176
+ }
177
+ await forgetWindowsResource(windowsStatePath(), resource, values.dry);
178
+ }
179
+ catch (err) {
180
+ console.error(`\u2717 Error: ${err.message}`);
181
+ process.exit(1);
182
+ }
183
+ break;
153
184
  default:
154
185
  console.error(`Unknown command: ${command}`);
155
186
  process.exit(2);