@adrifer/winix 0.3.0-preview.6 → 0.3.0-preview.9

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 (53) hide show
  1. package/README.md +137 -12
  2. package/dist/backends/nix/index.d.ts +1 -0
  3. package/dist/backends/nix/index.js +18 -1
  4. package/dist/backends/windows/index.d.ts +9 -1
  5. package/dist/backends/windows/index.js +18 -11
  6. package/dist/backends/windows/lockfile.d.ts +3 -3
  7. package/dist/backends/windows/lockfile.js +4 -3
  8. package/dist/backends/windows/npm.d.ts +2 -0
  9. package/dist/backends/windows/npm.js +60 -0
  10. package/dist/backends/windows/powershell.d.ts +4 -2
  11. package/dist/backends/windows/powershell.js +152 -21
  12. package/dist/backends/windows/wsl-setup-runtime.d.ts +17 -1
  13. package/dist/backends/windows/wsl-setup-runtime.js +75 -11
  14. package/dist/backends/windows/wsl-setup.d.ts +7 -1
  15. package/dist/backends/windows/wsl-setup.js +29 -8
  16. package/dist/backends/windows/wsl.js +1 -1
  17. package/dist/cli/analysis.d.ts +11 -2
  18. package/dist/cli/analysis.js +35 -7
  19. package/dist/cli/commands/apply.d.ts +6 -1
  20. package/dist/cli/commands/apply.js +12 -6
  21. package/dist/cli/commands/check.js +11 -5
  22. package/dist/cli/commands/inspect.js +2 -2
  23. package/dist/cli/commands/switch.d.ts +7 -0
  24. package/dist/cli/commands/switch.js +58 -11
  25. package/dist/cli/commands/update.js +4 -4
  26. package/dist/cli/windows-package-versions.d.ts +2 -1
  27. package/dist/cli/windows-package-versions.js +12 -5
  28. package/dist/cli/windows-state.js +45 -17
  29. package/dist/core/types.d.ts +18 -0
  30. package/dist/evaluator/index.d.ts +5 -3
  31. package/dist/evaluator/index.js +30 -16
  32. package/dist/helpers/account.js +1 -7
  33. package/dist/helpers/home.d.ts +18 -0
  34. package/dist/helpers/home.js +39 -0
  35. package/dist/helpers/index.d.ts +2 -2
  36. package/dist/helpers/nix.d.ts +14 -0
  37. package/dist/helpers/nix.js +2 -0
  38. package/dist/helpers/platforms.d.ts +13 -0
  39. package/dist/helpers/platforms.js +35 -19
  40. package/dist/helpers/windows-npm.d.ts +3 -0
  41. package/dist/helpers/windows-npm.js +52 -0
  42. package/dist/helpers/windows.d.ts +39 -2
  43. package/dist/helpers/windows.js +62 -4
  44. package/dist/helpers/wsl-interop.d.ts +13 -0
  45. package/dist/helpers/wsl-interop.js +72 -0
  46. package/dist/helpers/wsl-repository.d.ts +12 -0
  47. package/dist/helpers/wsl-repository.js +93 -0
  48. package/dist/index.d.ts +4 -4
  49. package/dist/sdk/index.d.ts +5 -1
  50. package/dist/sdk/index.js +9 -2
  51. package/dist/skill.js +34 -2
  52. package/dist/types/windows.d.ts +17 -0
  53. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { powerShellLiteral } from "../../helpers/utils.js";
3
- import { powerShellModuleVersion } from "../../helpers/windows-repositories.js";
3
+ import { powerShellModuleVersion, powerShellRepositoryName, powerShellRepositoryUri, } from "../../helpers/windows-repositories.js";
4
4
  export function powerShellRepositoryScripts(name, uri) {
5
5
  const prelude = [
6
6
  "$ErrorActionPreference = 'Stop'",
@@ -18,37 +18,168 @@ export function powerShellRepositoryScripts(name, uri) {
18
18
  ].join("\n"),
19
19
  };
20
20
  }
21
- /** Find-PSResource returns the newest stable release unless -Prerelease is requested. */
22
- export function resolvePowerShellModuleVersion(name, repository, repositoryUriOrRunner, prereleaseOrRunner = false, runner) {
23
- const repositoryUri = typeof repositoryUriOrRunner === "string" ? repositoryUriOrRunner : undefined;
24
- const prerelease = prereleaseOrRunner === true;
25
- const run = (typeof repositoryUriOrRunner === "function" ? repositoryUriOrRunner :
26
- typeof prereleaseOrRunner === "function" ? prereleaseOrRunner : runner) ??
27
- ((script) => execFileSync("pwsh", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", encode(script)], { encoding: "utf8" }));
28
- const script = [
21
+ const galleryUri = "https://www.powershellgallery.com/api/v2";
22
+ export async function resolvePowerShellModuleVersion(name, repository, repositoryUri, prerelease = false, { run = runPowerShell, fetch: fetchFeed = fetch } = {}) {
23
+ const isGallery = !repositoryUri && repository.toLowerCase() === "psgallery";
24
+ try {
25
+ if (!powerShellRepositoryName.test(name) || !powerShellRepositoryName.test(repository)) {
26
+ throw new Error("Expected an exact module and repository name without paths or wildcards");
27
+ }
28
+ const uri = repositoryUri === undefined ? undefined : powerShellRepositoryUri(repositoryUri);
29
+ const find = registeredModuleScript(name, repository, uri ?? (isGallery ? galleryUri : undefined), prerelease);
30
+ let version;
31
+ try {
32
+ version = JSON.parse(run(find).trim());
33
+ }
34
+ catch (error) {
35
+ if (!uri || !(error instanceof Error && "code" in error && error.code === "ENOENT"))
36
+ throw error;
37
+ // An anonymous V3 policy feed can also be resolved without pwsh.
38
+ version = null;
39
+ }
40
+ if (version === null) {
41
+ if (uri)
42
+ version = await resolveNugetV3Version(name, uri, prerelease, fetchFeed);
43
+ else if (isGallery)
44
+ version = JSON.parse(run(galleryModuleScript(name, prerelease)).trim());
45
+ else
46
+ throw new Error("The repository must already be registered for the current user");
47
+ }
48
+ if (typeof version !== "string" || !powerShellModuleVersion.test(version) || (!prerelease && version.includes("-"))) {
49
+ throw new Error("Repository did not return an allowed module version");
50
+ }
51
+ return version;
52
+ }
53
+ catch (error) {
54
+ const source = repositoryUri === undefined ? (isGallery ? galleryUri : "registered URI") :
55
+ describeRepositoryUri(repositoryUri);
56
+ throw new Error(`Failed to resolve PowerShell module "${name}" from "${repository}" (${source}): ` +
57
+ (error instanceof Error ? error.message : String(error)), { cause: error });
58
+ }
59
+ }
60
+ function describeRepositoryUri(value) {
61
+ try {
62
+ return powerShellRepositoryUri(value);
63
+ }
64
+ catch {
65
+ return "invalid repository URI";
66
+ }
67
+ }
68
+ function registeredModuleScript(name, repository, uri, prerelease) {
69
+ return [
29
70
  "$ErrorActionPreference = 'Stop'",
30
- ...(repositoryUri ? [powerShellRepositoryScripts(repository, repositoryUri).set] : []),
71
+ // Both PSResourceGet cmdlets initialize a missing store. Keep the existing file open read-only
72
+ // and deny deletion on Windows until the lookup completes.
73
+ "$localAppData = [Environment]::GetFolderPath('LocalApplicationData')",
74
+ "if (-not $localAppData) { 'null'; return }",
75
+ "$store = Join-Path $localAppData 'PSResourceGet/PSResourceRepository.xml'",
76
+ "try { $storeHandle = [IO.File]::Open($store, 'Open', 'Read', 'Read') }",
77
+ "catch [IO.FileNotFoundException], [IO.DirectoryNotFoundException] { 'null'; return }",
78
+ "try {",
79
+ `$registeredRepository = @(Get-PSResourceRepository -ErrorAction Stop | Where-Object { $_.Name -ieq ${powerShellLiteral(repository)} })`,
80
+ `if ($registeredRepository.Count -ne 1${uri ? ` -or $registeredRepository[0].Uri.AbsoluteUri.TrimEnd('/') -cne ${powerShellLiteral(uri)}` : ""}) { 'null'; return }`,
31
81
  `$found = @(Find-PSResource -Name ${powerShellLiteral(name)} -Repository ${powerShellLiteral(repository)}${prerelease ? " -Prerelease" : ""} -ErrorAction Stop)`,
32
82
  `if ($found.Count -ne 1 -or $found[0].Name -ine ${powerShellLiteral(name)}${prerelease ? "" : " -or $found[0].Prerelease"}) { throw 'Expected one matching module release' }`,
33
83
  "$version = $found[0].Version.ToString()",
34
84
  "if ($found[0].Prerelease) { $version += '-' + $found[0].Prerelease }",
35
85
  "$version | ConvertTo-Json -Compress",
86
+ "} finally { $storeHandle.Dispose() }",
36
87
  ].join("\n");
37
- try {
38
- const version = JSON.parse(run(script).trim());
39
- if (typeof version !== "string" || !powerShellModuleVersion.test(version) || (!prerelease && version.includes("-"))) {
40
- throw new Error("Repository did not return an allowed module version");
88
+ }
89
+ function galleryModuleScript(name, prerelease) {
90
+ const url = new URL(`${galleryUri}/FindPackagesById()`);
91
+ url.searchParams.set("id", `'${name}'`);
92
+ url.searchParams.set("$filter", `Id eq '${name}' and ${prerelease ? "IsAbsoluteLatestVersion" : "IsLatestVersion"} eq true`);
93
+ return [
94
+ "$ErrorActionPreference = 'Stop'",
95
+ `[xml]$feed = (Invoke-WebRequest -Uri ${powerShellLiteral(url.href)} -MaximumRedirection 0 -TimeoutSec 30).Content`,
96
+ "$ns = [Xml.XmlNamespaceManager]::new($feed.NameTable)",
97
+ "$ns.AddNamespace('a', 'http://www.w3.org/2005/Atom')",
98
+ "$ns.AddNamespace('m', 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata')",
99
+ "$ns.AddNamespace('d', 'http://schemas.microsoft.com/ado/2007/08/dataservices')",
100
+ "$releases = @($feed.SelectNodes('/a:feed/a:entry/m:properties', $ns) |",
101
+ ` Where-Object { $_.SelectSingleNode('d:Id', $ns).InnerText -ieq ${powerShellLiteral(name)} })`,
102
+ "if ($releases.Count -ne 1) { throw 'Expected one matching module release from the PowerShell Gallery' }",
103
+ "$releases[0].SelectSingleNode('d:Version', $ns).InnerText | ConvertTo-Json -Compress",
104
+ ].join("\n");
105
+ }
106
+ async function resolveNugetV3Version(name, uri, prerelease, fetchFeed) {
107
+ async function getJson(url) {
108
+ let response;
109
+ try {
110
+ response = await fetchFeed(url, {
111
+ credentials: "omit", redirect: "manual", signal: AbortSignal.timeout(30000),
112
+ headers: { Accept: "application/json" },
113
+ });
41
114
  }
42
- return version;
115
+ catch (error) {
116
+ // undici reports only "fetch failed"; the cause names TLS, DNS, proxy or timeout failures.
117
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : undefined;
118
+ const code = cause && "code" in cause && typeof cause.code === "string" ? `${cause.code}: ` : "";
119
+ const message = error instanceof Error ? error.message : String(error);
120
+ const detail = ` (${cause ? `${message}: ${code}${cause.message.split("\n")[0]}` : message})`;
121
+ throw new Error(`NuGet request to ${url} failed${detail}. Check network access to the feed.`, { cause: error });
122
+ }
123
+ if (!response.ok) {
124
+ await response.body?.cancel();
125
+ throw new Error(`NuGet request failed (HTTP ${response.status}) for ${url}`);
126
+ }
127
+ return response.json();
43
128
  }
44
- catch (error) {
45
- throw new Error(`Failed to resolve PowerShell module "${name}" from "${repository}". ` +
46
- `PowerShell 7 with PSResourceGet and the registered repository is required: ` +
47
- (error instanceof Error ? error.message : String(error)), { cause: error });
129
+ const index = await getJson(uri).catch((error) => {
130
+ if (!(error instanceof SyntaxError))
131
+ throw error;
132
+ throw new Error("Expected a JSON NuGet v3 service index; other feeds require an existing matching PSResourceGet registration", { cause: error });
133
+ });
134
+ const resources = index && typeof index === "object" && "resources" in index ? index.resources : undefined;
135
+ const resource = Array.isArray(resources) ? resources.find((value) => value && typeof value === "object" && "@type" in value && value["@type"] === "PackageBaseAddress/3.0.0") : undefined;
136
+ if (!resource || typeof resource !== "object" || !("@id" in resource) || typeof resource["@id"] !== "string") {
137
+ throw new Error("Expected a NuGet v3 service index with PackageBaseAddress/3.0.0; other feeds require an existing matching PSResourceGet registration");
138
+ }
139
+ const base = powerShellRepositoryUri(resource["@id"]);
140
+ const releases = await getJson(`${base}/${name.toLowerCase()}/index.json`);
141
+ const versions = releases && typeof releases === "object" && "versions" in releases ? releases.versions : undefined;
142
+ if (!Array.isArray(versions) || !versions.every((value) => typeof value === "string" && powerShellModuleVersion.test(value))) {
143
+ throw new Error("NuGet feed did not return valid module versions");
144
+ }
145
+ const latest = versions.filter((version) => prerelease || !version.includes("-")).sort(compareModuleVersions).at(-1);
146
+ if (!latest)
147
+ throw new Error(`NuGet feed has no ${prerelease ? "matching" : "stable"} module releases`);
148
+ return latest;
149
+ }
150
+ function compareModuleVersions(left, right) {
151
+ const [leftVersion, leftLabel] = left.toLowerCase().split(/-(.*)/);
152
+ const [rightVersion, rightLabel] = right.toLowerCase().split(/-(.*)/);
153
+ const a = leftVersion.split(".").map(BigInt);
154
+ const b = rightVersion.split(".").map(BigInt);
155
+ for (let i = 0; i < 4; i++) {
156
+ const x = a[i] ?? 0n;
157
+ const y = b[i] ?? 0n;
158
+ if (x !== y)
159
+ return x < y ? -1 : 1;
160
+ }
161
+ if (!leftLabel || !rightLabel)
162
+ return Number(!leftLabel) - Number(!rightLabel);
163
+ const leftParts = leftLabel.split(".");
164
+ const rightParts = rightLabel.split(".");
165
+ for (let i = 0; i < Math.min(leftParts.length, rightParts.length); i++) {
166
+ const x = leftParts[i];
167
+ const y = rightParts[i];
168
+ const xNumeric = /^\d+$/.test(x);
169
+ const yNumeric = /^\d+$/.test(y);
170
+ if (xNumeric && yNumeric) {
171
+ if (BigInt(x) !== BigInt(y))
172
+ return BigInt(x) < BigInt(y) ? -1 : 1;
173
+ }
174
+ else if (xNumeric !== yNumeric)
175
+ return xNumeric ? -1 : 1;
176
+ else if (x !== y)
177
+ return x < y ? -1 : 1;
48
178
  }
179
+ return leftParts.length - rightParts.length;
49
180
  }
50
- function encode(script) {
51
- return Buffer.from(script, "utf16le").toString("base64");
181
+ function runPowerShell(script) {
182
+ return execFileSync("pwsh", ["-NoLogo", "-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")], { encoding: "utf8" });
52
183
  }
53
184
  export function powerShellModuleProperties(module, pin) {
54
185
  if (!powerShellModuleVersion.test(pin.version) || (!module.prerelease && pin.version.includes("-"))) {
@@ -1,3 +1,4 @@
1
+ import type { WorkspaceDef } from "../../core/types.js";
1
2
  import type { EvaluatedHost } from "../../evaluator/index.js";
2
3
  import type { WinWslSetup } from "../../types/index.js";
3
4
  interface Request {
@@ -5,7 +6,7 @@ interface Request {
5
6
  revision: string;
6
7
  fingerprint: string;
7
8
  }
8
- interface Plan {
9
+ export interface Plan {
9
10
  user: string;
10
11
  home: string;
11
12
  checkout: string;
@@ -19,6 +20,21 @@ interface CommandOptions {
19
20
  }
20
21
  export type SetupRunner = (command: string, args: string[], options?: CommandOptions) => string;
21
22
  export declare function checkoutWslRevision(git: (args: string[]) => string, ref: string, revision: string, existingHead?: string): void;
23
+ export interface WindowsWslSetupTarget {
24
+ windowsHost: string;
25
+ distro: string;
26
+ setup: WinWslSetup;
27
+ /** Linux account, home and checkout the first-run setup will use. */
28
+ plan: Plan;
29
+ }
30
+ /**
31
+ * Validate every Windows WSL distro setup against its Linux host offline and
32
+ * return the account/checkout plan each would use. Catches host/user typos,
33
+ * a missing NixOS-WSL module, ambiguous accounts and checkouts outside the
34
+ * account's home before any distro is created.
35
+ */
36
+ export declare function windowsWslSetupTargets(workspace: WorkspaceDef, evaluated: EvaluatedHost[], windowsHosts: EvaluatedHost[]): WindowsWslSetupTarget[];
37
+ export declare function validateWindowsWslSetupTargets(workspace: WorkspaceDef, evaluated: EvaluatedHost[], windowsHosts: EvaluatedHost[]): void;
22
38
  export declare function createWslAccountPlan(host: EvaluatedHost, setup: WinWslSetup, architecture: string): {
23
39
  plan: Plan;
24
40
  accountHost: EvaluatedHost;
@@ -64,18 +64,84 @@ function linuxDirectory(value) {
64
64
  !/[\\\x00-\x1f\x7f]/.test(value) &&
65
65
  !value.slice(1).split("/").some((part) => part === "" || part === "." || part === "..");
66
66
  }
67
- export function createWslAccountPlan(host, setup, architecture) {
68
- const usersOptions = object(host.nixos.users);
69
- const users = object(usersOptions.users);
67
+ function selectWslSetupHost(hosts, name) {
68
+ const targets = hosts.filter((host) => host.name === name);
69
+ if (targets.length !== 1 || targets[0].platform.__id !== "nixos") {
70
+ throw new Error(`setup.host "${name}" must identify exactly one NixOS host`);
71
+ }
72
+ return targets[0];
73
+ }
74
+ function selectWslSetupUser(host, user) {
75
+ const users = object(object(host.nixos.users).users);
70
76
  const home = object(host.homeManager.home);
71
77
  const candidates = Object.keys(users).filter((name) => object(users[name]).isNormalUser === true && name !== "root");
72
- const selected = setup.user ?? (typeof home.username === "string" ? home.username : candidates.length === 1 ? candidates[0] : undefined);
78
+ const selected = user ?? (typeof home.username === "string" ? home.username : candidates.length === 1 ? candidates[0] : undefined);
73
79
  if (!selected || !/^[a-z_][a-z0-9_-]*$/.test(selected) || !candidates.includes(selected)) {
74
- throw new Error("WSL setup must select a declared normal Linux user; specify setup.user when ambiguous");
80
+ throw new Error(user === undefined
81
+ ? "WSL setup must select a declared normal Linux user; specify setup.user when ambiguous"
82
+ : `setup.user "${user}" must name a declared normal Linux user`);
75
83
  }
76
84
  const account = object(users[selected]);
77
85
  if (account.isSystemUser === true || account.uid === 0)
78
- throw new Error("WSL setup cannot select a system/root account");
86
+ throw new Error(`WSL setup cannot select a system/root account: ${selected}`);
87
+ return selected;
88
+ }
89
+ /**
90
+ * Validate every Windows WSL distro setup against its Linux host offline and
91
+ * return the account/checkout plan each would use. Catches host/user typos,
92
+ * a missing NixOS-WSL module, ambiguous accounts and checkouts outside the
93
+ * account's home before any distro is created.
94
+ */
95
+ export function windowsWslSetupTargets(workspace, evaluated, windowsHosts) {
96
+ const targets = [];
97
+ for (const host of windowsHosts) {
98
+ for (const resource of host.windows.dsc ?? []) {
99
+ if (resource.winix?.kind !== "wsl-distro")
100
+ continue;
101
+ const { distro } = resource.winix;
102
+ if (!distro.setup)
103
+ continue;
104
+ const context = `Windows host "${host.name}", WSL distro "${distro.name}"`;
105
+ let target;
106
+ try {
107
+ target = selectWslSetupHost(workspace.hosts, distro.setup.host);
108
+ }
109
+ catch (error) {
110
+ const available = workspace.hosts.filter((entry) => entry.platform.__id === "nixos").map((entry) => entry.name);
111
+ throw new Error(`${context}: ${error.message}. Available NixOS hosts: ${available.join(", ") || "(none)"}.`, { cause: error });
112
+ }
113
+ const linuxHost = evaluated[workspace.hosts.indexOf(target)];
114
+ try {
115
+ selectWslSetupUser(linuxHost, distro.setup.user);
116
+ }
117
+ catch (error) {
118
+ const users = object(object(linuxHost.nixos.users).users);
119
+ const normal = Object.keys(users).filter((name) => object(users[name]).isNormalUser === true && name !== "root");
120
+ throw new Error(`${context}: ${error.message}. Normal users declared by "${target.name}": ${normal.join(", ") || "(none)"}.`, { cause: error });
121
+ }
122
+ const hostPlatform = object(linuxHost.nixos.nixpkgs).hostPlatform;
123
+ try {
124
+ if (hostPlatform !== "x86_64-linux" && hostPlatform !== "aarch64-linux") {
125
+ throw new Error("Linux host platform must be x86_64-linux or aarch64-linux");
126
+ }
127
+ const { plan } = createWslAccountPlan(linuxHost, distro.setup, hostPlatform);
128
+ targets.push({ windowsHost: host.name, distro: distro.name, setup: distro.setup, plan });
129
+ }
130
+ catch (error) {
131
+ throw new Error(`${context}, Linux host "${target.name}": ${error.message}`, { cause: error });
132
+ }
133
+ }
134
+ }
135
+ return targets;
136
+ }
137
+ export function validateWindowsWslSetupTargets(workspace, evaluated, windowsHosts) {
138
+ windowsWslSetupTargets(workspace, evaluated, windowsHosts);
139
+ }
140
+ export function createWslAccountPlan(host, setup, architecture) {
141
+ const usersOptions = object(host.nixos.users);
142
+ const selected = selectWslSetupUser(host, setup.user);
143
+ const account = object(object(usersOptions.users)[selected]);
144
+ const home = object(host.homeManager.home);
79
145
  const userHome = account.home ?? `/home/${selected}`;
80
146
  if (!linuxDirectory(userHome))
81
147
  throw new Error("Invalid declared Linux home directory");
@@ -92,7 +158,7 @@ export function createWslAccountPlan(host, setup, architecture) {
92
158
  const imports = host.nixos.imports;
93
159
  const wslImports = Array.isArray(imports) ? imports.filter((entry) => typeof entry === "string" && /^inputs\.[a-z0-9._-]+\.nixosModules\.wsl$/i.test(entry)) : [];
94
160
  if (object(host.nixos.wsl).enable !== true || wslImports.length !== 1 || typeof object(host.nixos.system).stateVersion !== "string") {
95
- throw new Error("Setup host must explicitly enable NixOS-WSL, import its input module, and declare system.stateVersion");
161
+ throw new Error("Setup host must explicitly enable NixOS-WSL, import its input module, and declare system.stateVersion (platforms.wsl({ stateVersion }) does all three)");
96
162
  }
97
163
  const { packages: _packages, ...bootstrapUser } = account;
98
164
  const groupNames = [...(Array.isArray(account.extraGroups) ? account.extraGroups : []),
@@ -135,10 +201,8 @@ export async function prepareWslAccount(configDirectory, accountDirectory, setup
135
201
  const workspace = (await import(__rewriteRelativeImportExtension(pathToFileURL(join(configDirectory, configName[0])).href))).default;
136
202
  if (!workspace || !Array.isArray(workspace.hosts))
137
203
  throw new Error("Invalid Winix workspace");
138
- const targets = workspace.hosts.filter((host) => host.name === setup.host && host.platform.__id === "nixos");
139
- if (targets.length !== 1)
140
- throw new Error(`WSL setup target "${setup.host}" must identify one NixOS host`);
141
- const [evaluated] = sdk.evaluate({ ...workspace, hosts: targets });
204
+ const target = selectWslSetupHost(workspace.hosts, setup.host);
205
+ const [evaluated] = sdk.evaluate({ ...workspace, hosts: [target] }, { configDir: configDirectory });
142
206
  const architecture = process.arch === "x64" ? "x86_64-linux" : process.arch === "arm64" ? "aarch64-linux" : "";
143
207
  const { plan, accountHost } = createWslAccountPlan(evaluated, setup, architecture);
144
208
  const output = sdk.generateNix(workspace, [accountHost]);
@@ -9,5 +9,11 @@ export type WindowsWslRepositoryResolver = (repository: string, ref: string) =>
9
9
  export declare function wslRepositoryKey(setup: WinWslSetup): string;
10
10
  export declare function validWslRepository(value: unknown): value is WindowsLockWslRepository;
11
11
  export declare const resolveWslRepository: WindowsWslRepositoryResolver;
12
- export declare function wslSetupPrelude(setup: WinWslSetup, pin: WindowsLockWslRepository): string[];
12
+ /**
13
+ * Fingerprint recorded when setup completes; a later mismatch refuses to touch
14
+ * the distro. A ref inferred from the config checkout's branch is excluded, so
15
+ * switching branches on Windows does not invalidate a completed setup.
16
+ */
17
+ export declare function wslSetupFingerprint(setup: WinWslSetup, refFromCheckout?: boolean): string;
18
+ export declare function wslSetupPrelude(setup: WinWslSetup, pin: WindowsLockWslRepository, refFromCheckout?: boolean): string[];
13
19
  export declare function wslScriptInvocation(name: string, probe: string, activate: string, operation?: string): string[];
@@ -30,12 +30,23 @@ export const resolveWslRepository = (repository, ref) => {
30
30
  return ref;
31
31
  const refsToLookup = ref.startsWith("refs/") ? [ref, `${ref}^{}`] :
32
32
  ref === "HEAD" ? ["HEAD"] : [`refs/heads/${ref}`, `refs/tags/${ref}`, `refs/tags/${ref}^{}`];
33
- const output = execFileSync("git", [
34
- "ls-remote", "--exit-code", "--", repository, ...refsToLookup,
35
- ], {
36
- encoding: "utf8", timeout: 45000, stdio: ["ignore", "pipe", "pipe"],
37
- env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "Never" },
38
- });
33
+ let output;
34
+ try {
35
+ output = execFileSync("git", [
36
+ "ls-remote", "--exit-code", "--", repository, ...refsToLookup,
37
+ ], {
38
+ encoding: "utf8", timeout: 45000, stdio: ["ignore", "pipe", "pipe"],
39
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "Never" },
40
+ });
41
+ }
42
+ catch (error) {
43
+ const failure = error;
44
+ const detail = String(failure.stderr ?? "").trim().split(/\r?\n/)[0];
45
+ const reason = failure.status === 2
46
+ ? `ref "${ref}" was not found on the remote; push it or set setup.ref to a published branch, tag or commit`
47
+ : detail || error.message;
48
+ throw new Error(`Could not resolve WSL setup repository ${repository} at "${ref}": ${reason}`, { cause: error });
49
+ }
39
50
  const refs = new Map();
40
51
  for (const line of output.trim().split(/\r?\n/)) {
41
52
  const [sha, name] = line.split(/\s+/);
@@ -53,12 +64,22 @@ export const resolveWslRepository = (repository, ref) => {
53
64
  throw new Error(`Ambiguous Git ref "${ref}"; use a full ref or immutable commit`);
54
65
  return [...revisions][0];
55
66
  };
56
- export function wslSetupPrelude(setup, pin) {
67
+ /**
68
+ * Fingerprint recorded when setup completes; a later mismatch refuses to touch
69
+ * the distro. A ref inferred from the config checkout's branch is excluded, so
70
+ * switching branches on Windows does not invalidate a completed setup.
71
+ */
72
+ export function wslSetupFingerprint(setup, refFromCheckout = false) {
73
+ // Keep the original key order: existing completion records hash `setup` as is.
74
+ const { ref: _ref, ...withoutRef } = setup;
75
+ return createHash("sha256").update(JSON.stringify(refFromCheckout ? withoutRef : setup)).digest("hex");
76
+ }
77
+ export function wslSetupPrelude(setup, pin, refFromCheckout = false) {
57
78
  setup = normalizeWslSetup(setup);
58
79
  if (!validWslRepository(pin) || pin.repository !== setup.repository || pin.ref !== setup.ref) {
59
80
  throw new Error("Missing/mismatched WSL repository pin. Run winix update --windows wsl-setup.");
60
81
  }
61
- const fingerprint = createHash("sha256").update(JSON.stringify(setup)).digest("hex");
82
+ const fingerprint = wslSetupFingerprint(setup, refFromCheckout);
62
83
  const request = Buffer.from(JSON.stringify({ setup, revision: pin.revision, fingerprint })).toString("base64");
63
84
  const standalone = standaloneRuntime();
64
85
  let launch;
@@ -209,7 +209,7 @@ export function wslDistroProperties(distro, pins, repositories = {}) {
209
209
  const pin = repositories[wslRepositoryKey(distro.setup)];
210
210
  if (!pin)
211
211
  throw new Error("Missing WSL setup repository pin. Run winix update --windows wsl-setup.");
212
- prelude.push(...wslSetupPrelude(distro.setup, pin));
212
+ prelude.push(...wslSetupPrelude(distro.setup, pin, distro.setupRefFromCheckout === true));
213
213
  }
214
214
  return {
215
215
  getScript: [
@@ -1,4 +1,5 @@
1
- import type { Fragment, WorkspaceDef } from "../core/types.js";
1
+ import type { Fragment, WorkspaceDef, EvaluateOptions } from "../core/types.js";
2
+ import { type EvaluatedHost } from "../evaluator/index.js";
2
3
  export interface FragmentRecord {
3
4
  label: string;
4
5
  fragment: Fragment;
@@ -32,8 +33,16 @@ export interface SuspiciousNixReference {
32
33
  reference: string;
33
34
  recommendation: string;
34
35
  }
35
- export declare function analyzeWorkspace(workspace: WorkspaceDef): HostAnalysis[];
36
+ export declare function analyzeWorkspace(workspace: WorkspaceDef, options?: EvaluateOptions): HostAnalysis[];
36
37
  export declare function findDuplicateHosts(workspace: WorkspaceDef): string[];
38
+ declare const scopes: readonly ["nixos", "darwin", "homeManager", "windows"];
39
+ type Scope = typeof scopes[number];
40
+ export declare function collectIgnoredFragments(analyses: HostAnalysis[], evaluated: EvaluatedHost[]): {
41
+ host: string;
42
+ fragment: string;
43
+ scopes: Scope[];
44
+ }[];
37
45
  export declare function detectConflicts(analyses: HostAnalysis[]): Conflict[];
38
46
  export declare function collectEscapeReport(analyses: HostAnalysis[]): EscapeReportItem[];
39
47
  export declare function collectSuspiciousNixReferences(analyses: HostAnalysis[]): SuspiciousNixReference[];
48
+ export {};
@@ -1,7 +1,8 @@
1
- import { collectActiveIds } from "../evaluator/index.js";
1
+ import { collectActiveIds, hostEvalContext } from "../evaluator/index.js";
2
2
  import { restoreEvalContext, setEvalContext } from "../sdk/index.js";
3
- export function analyzeWorkspace(workspace) {
4
- return workspace.hosts.map((host) => analyzeHost(host));
3
+ import { hasHomeManagerImport } from "../backends/nix/index.js";
4
+ export function analyzeWorkspace(workspace, options = {}) {
5
+ return workspace.hosts.map((host) => analyzeHost(host, options));
5
6
  }
6
7
  export function findDuplicateHosts(workspace) {
7
8
  const seen = new Set();
@@ -13,6 +14,34 @@ export function findDuplicateHosts(workspace) {
13
14
  }
14
15
  return [...duplicates];
15
16
  }
17
+ const scopes = ["nixos", "darwin", "homeManager", "windows"];
18
+ export function collectIgnoredFragments(analyses, evaluated) {
19
+ return analyses.flatMap((analysis, index) => {
20
+ const platform = analysis.fragments.find(({ fragment }) => fragment.__platform)?.fragment;
21
+ if (!platform)
22
+ return [];
23
+ const applicable = new Set(scopes.filter((scope) => platform[scope]));
24
+ if (!applicable.has("windows") &&
25
+ (hasHomeManagerImport(evaluated[index]) || !["nixos", "darwin"].includes(analysis.platform))) {
26
+ applicable.add("homeManager");
27
+ }
28
+ const byLabel = new Map();
29
+ for (const { label, fragment } of analysis.fragments) {
30
+ if (fragment.__platform)
31
+ continue;
32
+ const contributed = byLabel.get(label) ?? new Set();
33
+ for (const scope of scopes) {
34
+ const data = fragment[scope];
35
+ if (data && walkLeaves(data).some(({ value }) => value !== undefined))
36
+ contributed.add(scope);
37
+ }
38
+ byLabel.set(label, contributed);
39
+ }
40
+ return [...byLabel].flatMap(([fragment, contributed]) => contributed.size > 0 && ![...contributed].some((scope) => applicable.has(scope))
41
+ ? [{ host: analysis.name, fragment, scopes: [...contributed] }]
42
+ : []);
43
+ });
44
+ }
16
45
  export function detectConflicts(analyses) {
17
46
  const conflicts = [];
18
47
  for (const analysis of analyses) {
@@ -78,11 +107,10 @@ export function collectSuspiciousNixReferences(analyses) {
78
107
  }
79
108
  return items;
80
109
  }
81
- function analyzeHost(host) {
110
+ function analyzeHost(host, options) {
82
111
  const platform = host.platform.__id;
83
- const activeIds = collectActiveIds(host);
84
- const ctx = { platform, hostname: host.name, activeIds };
85
- const prev = setEvalContext(ctx);
112
+ const activeIds = collectActiveIds(host, options);
113
+ const prev = setEvalContext(hostEvalContext(host, activeIds, options));
86
114
  const fragments = [];
87
115
  try {
88
116
  resolveEntry(host.platform, host.platform.__id, fragments);
@@ -7,7 +7,12 @@ import { type WindowsFontResolver } from "../../backends/windows/fonts.js";
7
7
  interface ApplyOptions {
8
8
  resolveWindowsFont?: WindowsFontResolver;
9
9
  /** Activation-only overrides; the committed lock and inline declarations remain unchanged. */
10
- windowsPackageVersions?: (hosts: ReturnType<typeof evaluate>, lock: WindowsLock) => Promise<Record<string, string>>;
10
+ /**
11
+ * Activation-time package versions keyed by package id. `null` means the
12
+ * package is installed with a non-comparable version (e.g. winget reports
13
+ * "Unknown"): emit it presence-only so activation does not reinstall it.
14
+ */
15
+ windowsPackageVersions?: (hosts: ReturnType<typeof evaluate>, lock: WindowsLock) => Promise<Record<string, string | null>>;
11
16
  host?: string;
12
17
  dry: boolean;
13
18
  diff: boolean;
@@ -11,17 +11,18 @@ import { resolveWingetVersion } from "../../backends/windows/resolver.js";
11
11
  import { resolvePowerShellModuleVersion } from "../../backends/windows/powershell.js";
12
12
  import { resolveNixosWslImage } from "../../backends/windows/wsl.js";
13
13
  import { resolveWslRepository } from "../../backends/windows/wsl-setup.js";
14
+ import { validateWindowsWslSetupTargets } from "../../backends/windows/wsl-setup-runtime.js";
14
15
  import { platformForEvaluatedHost } from "../activation.js";
15
16
  import { collectFontSources, resolveWindowsFonts, resolveFontSource } from "../../backends/windows/fonts.js";
16
17
  export async function applyWorkspace(cwd, opts) {
17
18
  const { workspace, configDir } = await loadWorkspace(cwd);
18
- let evaluated = evaluate(workspace);
19
+ const allHosts = evaluate(workspace, { configDir });
20
+ let evaluated = allHosts;
19
21
  if (opts.host) {
20
22
  evaluated = evaluated.filter((h) => h.name === opts.host);
21
23
  if (evaluated.length === 0) {
22
- const all = evaluate(workspace);
23
24
  throw new Error(`Host "${opts.host}" not found. Available hosts:\n` +
24
- all.map((h) => ` - ${h.name}`).join("\n"));
25
+ allHosts.map((h) => ` - ${h.name}`).join("\n"));
25
26
  }
26
27
  }
27
28
  const hostPlatforms = platformsForHosts(evaluated);
@@ -29,18 +30,23 @@ export async function applyWorkspace(cwd, opts) {
29
30
  const windowsHosts = evaluated.filter((host) => hostPlatforms.get(host.name) === "windows");
30
31
  for (const host of windowsHosts)
31
32
  validateWindowsWslResources(host.windows);
33
+ validateWindowsWslSetupTargets(workspace, allHosts, windowsHosts);
32
34
  const windowsLock = windowsHosts.length > 0
33
35
  ? await prepareWindowsLock(configDir, windowsHosts, opts.dry || opts.windowsLockDry === true, opts.resolveWindowsPackageVersion ?? resolveWingetVersion, opts.resolveWindowsModuleVersion ?? resolvePowerShellModuleVersion, opts.resolveWindowsWslImage ?? resolveNixosWslImage, opts.resolveWindowsWslRepository ?? resolveWslRepository, opts.resolveWindowsFont ?? resolveFontSource)
34
36
  : undefined;
35
37
  const nixOutput = nixHosts.length > 0 ? generateNix(workspace, nixHosts) : undefined;
36
38
  const runtimeVersions = windowsLock && opts.windowsPackageVersions
37
39
  ? await opts.windowsPackageVersions(windowsHosts, windowsLock) : {};
40
+ const presenceOnlyPackages = new Set(Object.entries(runtimeVersions).filter(([, version]) => version === null).map(([id]) => id));
38
41
  const activationLock = windowsLock ? {
39
42
  ...windowsLock,
40
- packages: Object.fromEntries(Object.entries(windowsLock.packages).map(([id, pin]) => [id, runtimeVersions[id] === undefined ? pin : { ...pin, version: runtimeVersions[id] }])),
43
+ packages: Object.fromEntries(Object.entries(windowsLock.packages).map(([id, pin]) => {
44
+ const version = runtimeVersions[id];
45
+ return [id, typeof version === "string" ? { ...pin, version } : pin];
46
+ })),
41
47
  } : undefined;
42
48
  const windowsOutput = windowsHosts.length > 0
43
- ? generateWindows(windowsHosts, activationLock, configDir)
49
+ ? generateWindows(windowsHosts, activationLock, configDir, { presenceOnlyPackages })
44
50
  : undefined;
45
51
  printWarnings(nixOutput?.warnings ?? []);
46
52
  printWarnings(windowsOutput?.warnings ?? []);
@@ -97,7 +103,7 @@ async function prepareWindowsLock(configDir, windowsHosts, dry, resolveVersion,
97
103
  const lock = readWindowsLock(configDir) ?? emptyWindowsLock(now);
98
104
  const reconciled = reconcileInlinePins(lock, windowsHosts, now);
99
105
  const resolved = resolveMissingWindowsLockEntries(reconciled, windowsHosts, resolveVersion, now);
100
- const modules = resolveWindowsModuleLockEntries(resolved.lock, collectWindowsModules(windowsHosts).values(), resolveModuleVersion, now, true);
106
+ const modules = await resolveWindowsModuleLockEntries(resolved.lock, collectWindowsModules(windowsHosts).values(), resolveModuleVersion, now, true);
101
107
  const images = hasWindowsWslDistros(windowsHosts)
102
108
  ? await resolveWindowsWslImages(modules.lock, resolveWslImage, now, true)
103
109
  : { lock: modules.lock, changed: false };
@@ -4,19 +4,22 @@ import { loadWorkspace } from "../loader.js";
4
4
  import { evaluate } from "../../evaluator/index.js";
5
5
  import { generateNix } from "../../backends/nix/index.js";
6
6
  import { validateWindowsWslResources } from "../../backends/windows/index.js";
7
- import { analyzeWorkspace, collectEscapeReport, collectSuspiciousNixReferences, detectConflicts, findDuplicateHosts, } from "../analysis.js";
7
+ import { validateWindowsWslSetupTargets } from "../../backends/windows/wsl-setup-runtime.js";
8
+ import { analyzeWorkspace, collectEscapeReport, collectIgnoredFragments, collectSuspiciousNixReferences, detectConflicts, findDuplicateHosts, } from "../analysis.js";
8
9
  export async function check(cwd, opts) {
9
10
  try {
10
- const { workspace } = await loadWorkspace(cwd);
11
+ const { workspace, configDir } = await loadWorkspace(cwd);
11
12
  const duplicateHosts = findDuplicateHosts(workspace);
12
- const evaluated = evaluate(workspace);
13
+ const evaluated = evaluate(workspace, { configDir });
13
14
  for (const host of evaluated)
14
15
  validateWindowsWslResources(host.windows);
16
+ validateWindowsWslSetupTargets(workspace, evaluated, evaluated);
15
17
  const output = generateNix(workspace, evaluated);
16
18
  validateGeneratedNixSyntax(output);
17
- const analyses = analyzeWorkspace(workspace);
19
+ const analyses = analyzeWorkspace(workspace, { configDir });
18
20
  const conflicts = detectConflicts(analyses);
19
21
  const suspiciousReferences = collectSuspiciousNixReferences(analyses);
22
+ const ignoredFragments = collectIgnoredFragments(analyses, evaluated);
20
23
  console.log(`✓ Configuration valid`);
21
24
  console.log(` Hosts: ${evaluated.map((h) => h.name).join(", ")}`);
22
25
  for (const warning of output.warnings) {
@@ -41,6 +44,9 @@ export async function check(cwd, opts) {
41
44
  console.warn(` ${item.recommendation}`);
42
45
  }
43
46
  }
47
+ for (const item of ignoredFragments) {
48
+ console.warn(`Warning: ${item.host} ${item.fragment}: no applicable configuration (ignored scopes: ${item.scopes.join(", ")}).`);
49
+ }
44
50
  if (opts.escapeReport) {
45
51
  const report = collectEscapeReport(analyses);
46
52
  console.log(`\nEscape hatch report: ${report.length} item(s)`);
@@ -48,7 +54,7 @@ export async function check(cwd, opts) {
48
54
  console.log(` ${item.host} ${item.fragment} ${item.kind} ${item.scope}.${item.path}`);
49
55
  }
50
56
  }
51
- if (opts.strict && (duplicateHosts.length > 0 || conflicts.length > 0)) {
57
+ if (opts.strict && (duplicateHosts.length > 0 || conflicts.length > 0 || ignoredFragments.length > 0)) {
52
58
  throw new Error("Strict check failed");
53
59
  }
54
60
  }