@adrifer/winix 0.3.0-preview.8 → 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 (49) hide show
  1. package/README.md +102 -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 +10 -10
  6. package/dist/backends/windows/lockfile.d.ts +3 -3
  7. package/dist/backends/windows/lockfile.js +4 -3
  8. package/dist/backends/windows/powershell.d.ts +4 -2
  9. package/dist/backends/windows/powershell.js +152 -21
  10. package/dist/backends/windows/wsl-setup-runtime.d.ts +17 -1
  11. package/dist/backends/windows/wsl-setup-runtime.js +75 -11
  12. package/dist/backends/windows/wsl-setup.d.ts +7 -1
  13. package/dist/backends/windows/wsl-setup.js +29 -8
  14. package/dist/backends/windows/wsl.js +1 -1
  15. package/dist/cli/analysis.d.ts +11 -2
  16. package/dist/cli/analysis.js +35 -7
  17. package/dist/cli/commands/apply.d.ts +6 -1
  18. package/dist/cli/commands/apply.js +12 -6
  19. package/dist/cli/commands/check.js +11 -5
  20. package/dist/cli/commands/inspect.js +2 -2
  21. package/dist/cli/commands/switch.d.ts +7 -0
  22. package/dist/cli/commands/switch.js +58 -11
  23. package/dist/cli/commands/update.js +4 -4
  24. package/dist/cli/windows-package-versions.d.ts +2 -1
  25. package/dist/cli/windows-package-versions.js +12 -5
  26. package/dist/cli/windows-state.js +45 -17
  27. package/dist/core/types.d.ts +18 -0
  28. package/dist/evaluator/index.d.ts +5 -3
  29. package/dist/evaluator/index.js +30 -16
  30. package/dist/helpers/account.js +1 -7
  31. package/dist/helpers/home.d.ts +18 -0
  32. package/dist/helpers/home.js +39 -0
  33. package/dist/helpers/index.d.ts +2 -2
  34. package/dist/helpers/nix.d.ts +14 -0
  35. package/dist/helpers/nix.js +2 -0
  36. package/dist/helpers/platforms.d.ts +13 -0
  37. package/dist/helpers/platforms.js +35 -19
  38. package/dist/helpers/windows.d.ts +35 -2
  39. package/dist/helpers/windows.js +55 -4
  40. package/dist/helpers/wsl-interop.d.ts +13 -0
  41. package/dist/helpers/wsl-interop.js +72 -0
  42. package/dist/helpers/wsl-repository.d.ts +12 -0
  43. package/dist/helpers/wsl-repository.js +93 -0
  44. package/dist/index.d.ts +3 -3
  45. package/dist/sdk/index.d.ts +5 -1
  46. package/dist/sdk/index.js +9 -2
  47. package/dist/skill.js +23 -2
  48. package/dist/types/windows.d.ts +6 -0
  49. package/package.json +1 -1
@@ -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
  }
@@ -1,8 +1,8 @@
1
1
  import { analyzeWorkspace } from "../analysis.js";
2
2
  import { loadWorkspace } from "../loader.js";
3
3
  export async function inspect(cwd) {
4
- const { workspace, configPath } = await loadWorkspace(cwd);
5
- const analyses = analyzeWorkspace(workspace);
4
+ const { workspace, configPath, configDir } = await loadWorkspace(cwd);
5
+ const analyses = analyzeWorkspace(workspace, { configDir });
6
6
  console.log(`Config: ${configPath}`);
7
7
  console.log(`Hosts: ${analyses.length}`);
8
8
  for (const analysis of analyses) {
@@ -1,3 +1,5 @@
1
+ import type { WorkspaceDef } from "../../core/types.js";
2
+ import type { EvaluatedHost } from "../../evaluator/index.js";
1
3
  import { type WindowsStateAdapter } from "../windows-state.js";
2
4
  interface SwitchOptions {
3
5
  host?: string;
@@ -9,6 +11,11 @@ interface SwitchOptions {
9
11
  };
10
12
  }
11
13
  export declare function switchCommand(cwd: string, opts: SwitchOptions): Promise<void>;
14
+ /**
15
+ * The Linux side of a Windows host's WSL distros is activated separately.
16
+ * Tell the user exactly how, using the setup plan when there is one.
17
+ */
18
+ export declare function wslNextSteps(workspace: WorkspaceDef, evaluated: EvaluatedHost[], windowsHost: EvaluatedHost): string[];
12
19
  export declare function selectHost(hosts: string[], requested?: string, currentHostname?: string): string;
13
20
  export declare function flakeRefForHost(outDir: string, hostName: string): string;
14
21
  export declare function windowsConfigurationForHost(outDir: string, hostName: string): string;
@@ -1,5 +1,7 @@
1
1
  import { hostname } from "node:os";
2
- import { join } from "node:path";
2
+ import { join, posix } from "node:path";
3
+ import { windowsWslSetupTargets } from "../../backends/windows/wsl-setup-runtime.js";
4
+ import { standaloneRuntime } from "../../runtime.js";
3
5
  import { createHash } from "node:crypto";
4
6
  import { managedWindowsResources, nativeWindowsStateAdapter, reconcileWindows, resourceKey, windowsStatePath, windowsStateOwner, withWindowsStateLock, } from "../windows-state.js";
5
7
  import { evaluate } from "../../evaluator/index.js";
@@ -8,10 +10,10 @@ import { runCommand } from "../run.js";
8
10
  import { activationCommand, assertActivationSupported, platformForEvaluatedHost, } from "../activation.js";
9
11
  import { applyWorkspace } from "./apply.js";
10
12
  import { readWindowsLock, serializeWindowsLock, writeWindowsLock } from "../../backends/windows/lockfile.js";
11
- import { compareWindowsPackageVersions, confirmWindowsPackageLockUpdate, effectiveWindowsPackageVersion, } from "../windows-package-versions.js";
13
+ import { compareWindowsPackageVersions, confirmWindowsPackageLockUpdate, effectiveWindowsPackageVersion, isComparableWindowsPackageVersion, } from "../windows-package-versions.js";
12
14
  export async function switchCommand(cwd, opts) {
13
15
  const { workspace, configDir } = await loadWorkspace(cwd);
14
- const evaluated = evaluate(workspace);
16
+ const evaluated = evaluate(workspace, { configDir });
15
17
  const hostName = selectHost(evaluated.map((host) => host.name), opts.host);
16
18
  const selected = evaluated.find((host) => host.name === hostName);
17
19
  if (!selected)
@@ -26,6 +28,7 @@ export async function switchCommand(cwd, opts) {
26
28
  const adapter = opts.windowsState?.adapter ?? nativeWindowsStateAdapter;
27
29
  const requirements = {};
28
30
  const activationVersions = {};
31
+ const unknownVersions = new Set();
29
32
  const newer = [];
30
33
  const result = await applyWorkspace(cwd, {
31
34
  host: hostName,
@@ -43,16 +46,27 @@ export async function switchCommand(cwd, opts) {
43
46
  if (!version)
44
47
  throw new Error(`Missing package version: ${resource.id}`);
45
48
  const requirement = { version, exact: pkg?.version !== undefined };
46
- requirements[resourceKey(resource)] = requirement;
49
+ const key = resourceKey(resource);
50
+ requirements[key] = requirement;
47
51
  const snapshot = await adapter.inspect(resource);
48
52
  if (snapshot !== null && !("version" in snapshot))
49
53
  throw new Error(`Invalid package snapshot: ${resource.id}`);
50
54
  const installed = snapshot?.version;
51
- versions[resource.id] = effectiveWindowsPackageVersion(resource.id, requirement, installed);
52
- activationVersions[resourceKey(resource)] = versions[resource.id];
53
- if (!requirement.exact && installed !== undefined && compareWindowsPackageVersions(installed, version) > 0) {
54
- console.log(`Keeping ${resource.id} ${installed} (locked ${version}).`);
55
- newer.push({ id: resource.id, installed, locked: version });
55
+ const effective = effectiveWindowsPackageVersion(resource.id, requirement, installed);
56
+ versions[resource.id] = effective;
57
+ activationVersions[key] = effective;
58
+ if (!requirement.exact && installed !== undefined) {
59
+ if (!isComparableWindowsPackageVersion(installed)) {
60
+ unknownVersions.add(key);
61
+ // Emitting the locked version would make DSC report drift on every
62
+ // run and reinstall it; ensure presence only instead.
63
+ versions[resource.id] = null;
64
+ console.warn(`Warning: ${resource.id} reported a non-comparable installed version (${JSON.stringify(installed)}); ensuring it is installed without enforcing locked version ${version}.`);
65
+ }
66
+ else if (compareWindowsPackageVersions(resource.id, installed, version) > 0) {
67
+ console.log(`Keeping ${resource.id} ${installed} (locked ${version}).`);
68
+ newer.push({ id: resource.id, installed, locked: version });
69
+ }
56
70
  }
57
71
  }
58
72
  }
@@ -75,8 +89,9 @@ export async function switchCommand(cwd, opts) {
75
89
  if (!("version" in current))
76
90
  throw new Error(`Invalid package snapshot: ${resource.id}`);
77
91
  effectiveWindowsPackageVersion(resource.id, requirements[key], current.version);
78
- if (!requirements[key].exact &&
79
- compareWindowsPackageVersions(current.version, activationVersions[key]) > 0) {
92
+ if (!requirements[key].exact && !unknownVersions.has(key) &&
93
+ isComparableWindowsPackageVersion(current.version) &&
94
+ compareWindowsPackageVersions(resource.id, current.version, activationVersions[key]) > 0) {
80
95
  throw new Error(`Package ${resource.id} updated during switch. Rerun switch to keep ${current.version}; refusing stale activation.`);
81
96
  }
82
97
  }
@@ -146,6 +161,38 @@ export async function switchCommand(cwd, opts) {
146
161
  await withWindowsStateLock(statePath, opts.dry, performSwitch);
147
162
  else
148
163
  await performSwitch();
164
+ if (platform === "windows") {
165
+ for (const line of wslNextSteps(workspace, evaluated, selected))
166
+ console.log(line);
167
+ }
168
+ }
169
+ /**
170
+ * The Linux side of a Windows host's WSL distros is activated separately.
171
+ * Tell the user exactly how, using the setup plan when there is one.
172
+ */
173
+ export function wslNextSteps(workspace, evaluated, windowsHost) {
174
+ const distros = (windowsHost.windows.dsc ?? [])
175
+ .flatMap((resource) => resource.winix?.kind === "wsl-distro" ? [resource.winix.distro] : []);
176
+ if (distros.length === 0)
177
+ return [];
178
+ const planned = new Map(windowsWslSetupTargets(workspace, evaluated, [windowsHost]).map((target) => [target.distro, target]));
179
+ const standalone = standaloneRuntime();
180
+ const winix = standalone ? `/var/lib/winix/runtime/${standalone.version}/winix` : "npm exec -- winix";
181
+ const lines = ["", "WSL: Linux hosts are activated separately from Windows."];
182
+ for (const distro of distros) {
183
+ const target = planned.get(distro.name);
184
+ if (target) {
185
+ const directory = posix.join(target.plan.checkout, target.setup.configDirectory);
186
+ lines.push(` ${distro.name} → ${target.plan.host}: apply Linux changes inside the distro with`, ` wsl.exe -d ${distro.name} --cd ${directory} -- ${winix} switch --host ${target.plan.host}`);
187
+ }
188
+ else if (distro.host) {
189
+ lines.push(` ${distro.name} → ${distro.host}: from the distro's checkout, run ${winix} switch --host ${distro.host}`);
190
+ }
191
+ else {
192
+ lines.push(` ${distro.name}: Linux activation is manual (no setup declared)`);
193
+ }
194
+ }
195
+ return lines;
149
196
  }
150
197
  export function selectHost(hosts, requested, currentHostname = hostname()) {
151
198
  if (requested) {
@@ -24,8 +24,8 @@ export async function update(cwd, opts) {
24
24
  // `winix update` resolves the Nix flake lock. A Windows-only workspace has
25
25
  // no flake.nix, so there is nothing to update; fail clearly instead of
26
26
  // letting `nix flake update` error out generically.
27
- const { workspace } = await loadWorkspace(cwd);
28
- const evaluated = evaluate(workspace);
27
+ const { workspace, configDir } = await loadWorkspace(cwd);
28
+ const evaluated = evaluate(workspace, { configDir });
29
29
  const hasNixHost = evaluated.some((host) => platformForEvaluatedHost(host) !== "windows");
30
30
  if (!hasNixHost) {
31
31
  throw new Error("`winix update` updates the Nix flake lock, but this workspace has no " +
@@ -61,7 +61,7 @@ export async function update(cwd, opts) {
61
61
  }
62
62
  async function updateWindowsLock(cwd, opts) {
63
63
  const { workspace, configDir } = await loadWorkspace(cwd);
64
- const evaluated = evaluate(workspace);
64
+ const evaluated = evaluate(workspace, { configDir });
65
65
  const windowsHosts = evaluated.filter(isWindowsHost);
66
66
  if (windowsHosts.length === 0) {
67
67
  throw new Error("`winix update --windows` found no Windows hosts in this workspace.");
@@ -104,7 +104,7 @@ async function updateWindowsLock(cwd, opts) {
104
104
  const resolved = resolveWindowsLockEntries(lock, selected.values(), resolveVersion, now);
105
105
  lock = resolved.lock;
106
106
  changed = changed || resolved.changed;
107
- const resolvedModules = resolveWindowsModuleLockEntries(lock, selectedModules, opts.resolveWindowsModuleVersion ?? resolvePowerShellModuleVersion, now);
107
+ const resolvedModules = await resolveWindowsModuleLockEntries(lock, selectedModules, opts.resolveWindowsModuleVersion ?? resolvePowerShellModuleVersion, now);
108
108
  lock = resolvedModules.lock;
109
109
  changed = changed || resolvedModules.changed;
110
110
  if (wslImages && (opts.inputs.length === 0 || opts.inputs.includes("nixos-wsl"))) {
@@ -1,5 +1,6 @@
1
1
  /** Only dotted numeric versions have an unambiguous ordering across Windows installers. */
2
- export declare function compareWindowsPackageVersions(left: string, right: string): number;
2
+ export declare function isComparableWindowsPackageVersion(version: string): boolean;
3
+ export declare function compareWindowsPackageVersions(id: string, left: string, right: string): number;
3
4
  export interface WindowsPackageRequirement {
4
5
  version: string;
5
6
  exact: boolean;
@@ -1,10 +1,13 @@
1
1
  import { createInterface } from "node:readline/promises";
2
2
  /** Only dotted numeric versions have an unambiguous ordering across Windows installers. */
3
- export function compareWindowsPackageVersions(left, right) {
3
+ export function isComparableWindowsPackageVersion(version) {
4
+ return /^\d+(?:\.\d+)*$/.test(version);
5
+ }
6
+ export function compareWindowsPackageVersions(id, left, right) {
4
7
  if (left === right)
5
8
  return 0;
6
- if (!/^\d+(?:\.\d+)*$/.test(left) || !/^\d+(?:\.\d+)*$/.test(right)) {
7
- throw new Error(`Cannot reliably compare Windows package versions "${left}" and "${right}". Declare an exact version or resolve the package version explicitly.`);
9
+ if (!isComparableWindowsPackageVersion(left) || !isComparableWindowsPackageVersion(right)) {
10
+ throw new Error(`Cannot reliably compare Windows package versions "${left}" and "${right}" for ${id}. Declare an exact version or resolve the package version explicitly.`);
8
11
  }
9
12
  const a = left.split(".").map(BigInt);
10
13
  const b = right.split(".").map(BigInt);
@@ -20,11 +23,15 @@ export function effectiveWindowsPackageVersion(id, requirement, installed) {
20
23
  return requirement.version;
21
24
  if (requirement.exact) {
22
25
  if (installed !== requirement.version) {
23
- throw new Error(`Exact version mismatch for ${id}: installed ${installed}, required ${requirement.version}. Resolve it explicitly; Winix will not silently replace or downgrade it.`);
26
+ const observed = isComparableWindowsPackageVersion(installed)
27
+ ? `installed ${installed}` : `installed version reported as non-comparable (${JSON.stringify(installed)})`;
28
+ throw new Error(`Exact version mismatch for ${id}: ${observed}, required ${requirement.version}. Resolve it explicitly; Winix will not silently replace or downgrade it.`);
24
29
  }
25
30
  return requirement.version;
26
31
  }
27
- return compareWindowsPackageVersions(installed, requirement.version) >= 0 ? installed : requirement.version;
32
+ if (!isComparableWindowsPackageVersion(installed))
33
+ return requirement.version;
34
+ return compareWindowsPackageVersions(id, installed, requirement.version) >= 0 ? installed : requirement.version;
28
35
  }
29
36
  export async function confirmWindowsPackageLockUpdate(id, installed, locked) {
30
37
  if (!process.stdin.isTTY || !process.stdout.isTTY)