@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,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)
@@ -6,7 +6,7 @@ import { dirname, join } from "node:path";
6
6
  import { createInterface } from "node:readline/promises";
7
7
  import { powerShellLiteral } from "../helpers/utils.js";
8
8
  import { runCommand } from "./run.js";
9
- import { compareWindowsPackageVersions, effectiveWindowsPackageVersion } from "./windows-package-versions.js";
9
+ import { compareWindowsPackageVersions, effectiveWindowsPackageVersion, isComparableWindowsPackageVersion, } from "./windows-package-versions.js";
10
10
  export function resourceKey(resource) {
11
11
  return JSON.stringify(resource.kind === "startup"
12
12
  ? ["startup", resource.name.toLowerCase()]
@@ -77,6 +77,17 @@ export function managedWindowsResources(host) {
77
77
  function sameSnapshot(a, b) {
78
78
  return JSON.stringify(a) === JSON.stringify(b);
79
79
  }
80
+ function comparePackageSnapshots(id, current, previous) {
81
+ if (!isComparableWindowsPackageVersion(current.version) || !isComparableWindowsPackageVersion(previous.version))
82
+ return undefined;
83
+ return compareWindowsPackageVersions(id, current.version, previous.version);
84
+ }
85
+ function assertRemovablePackageVersion(id, version) {
86
+ if (!isComparableWindowsPackageVersion(version)) {
87
+ throw new Error(`Refusing automatic removal of ${id}: installed version was reported as non-comparable (${JSON.stringify(version)}). ` +
88
+ `Uninstall it manually, or keep it installed and release Winix ownership with \`winix state forget package <source> ${id}\`.`);
89
+ }
90
+ }
80
91
  function validResource(value) {
81
92
  if (!value || typeof value !== "object")
82
93
  return false;
@@ -228,12 +239,19 @@ export async function reconcileWindows(opts) {
228
239
  }
229
240
  }
230
241
  if (entry?.owned && current !== null && !sameSnapshot(current, entry.snapshot)) {
231
- const upgrade = requirement && !requirement.exact && "version" in current &&
232
- entry.snapshot && "version" in entry.snapshot &&
233
- compareWindowsPackageVersions(current.version, entry.snapshot.version) > 0;
234
- if (!upgrade)
235
- throw new Error(`Managed resource changed outside Winix: ${key}. Restore it or explicitly resolve ownership before activation.`);
236
- report(`Keeping externally upgraded package: ${key} ${current.version}`);
242
+ if (resource.kind === "package" && requirement && !requirement.exact && "version" in current &&
243
+ entry.snapshot && "version" in entry.snapshot) {
244
+ const change = comparePackageSnapshots(resource.id, current, entry.snapshot);
245
+ if (change === undefined) {
246
+ report(`Skipping version drift check for ${key}: non-comparable version (${current.version} vs ${entry.snapshot.version})`);
247
+ continue;
248
+ }
249
+ if (change > 0) {
250
+ report(`Keeping externally upgraded package: ${key} ${current.version}`);
251
+ continue;
252
+ }
253
+ }
254
+ throw new Error(`Managed resource changed outside Winix: ${key}. Restore it or explicitly resolve ownership before activation.`);
237
255
  }
238
256
  }
239
257
  const removals = [];
@@ -250,6 +268,9 @@ export async function reconcileWindows(opts) {
250
268
  continue;
251
269
  }
252
270
  const current = await opts.adapter.inspect(entry.resource);
271
+ if (entry.resource.kind === "package" && current && "version" in current) {
272
+ assertRemovablePackageVersion(entry.resource.id, current.version);
273
+ }
253
274
  if (current !== null && !sameSnapshot(current, entry.snapshot)) {
254
275
  throw new Error(`Refusing to remove externally modified resource: ${key}. Resolve ownership explicitly.`);
255
276
  }
@@ -273,24 +294,30 @@ export async function reconcileWindows(opts) {
273
294
  throw new Error(`Activation succeeded but managed resource is missing: ${key}`);
274
295
  const entry = state.entries[key];
275
296
  const requirement = resource.kind === "package" ? opts.packageRequirements?.[key] : undefined;
276
- if (requirement) {
277
- if (!("version" in current) || (requirement.exact
278
- ? current.version !== requirement.version
279
- : compareWindowsPackageVersions(current.version, requirement.version) < 0)) {
297
+ if (resource.kind === "package" && requirement) {
298
+ if (!("version" in current)) {
299
+ throw new Error(`Activation did not satisfy package version requirement: ${key}`);
300
+ }
301
+ if (requirement.exact) {
302
+ effectiveWindowsPackageVersion(resource.id, requirement, current.version);
303
+ }
304
+ else if (isComparableWindowsPackageVersion(current.version) &&
305
+ compareWindowsPackageVersions(resource.id, current.version, requirement.version) < 0) {
280
306
  throw new Error(`Activation did not satisfy package version requirement: ${key}`);
281
307
  }
282
308
  const initial = before.get(key);
283
309
  if (!requirement.exact && initial && "version" in initial &&
284
- compareWindowsPackageVersions(current.version, initial.version) < 0) {
310
+ (comparePackageSnapshots(resource.id, current, initial) ?? 0) < 0) {
285
311
  throw new Error(`Activation unexpectedly downgraded package: ${key}`);
286
312
  }
287
313
  }
288
314
  if (entry && entry.owners.some((owner) => owner !== opts.owner) && !sameSnapshot(current, entry.snapshot)) {
289
- const upgrade = requirement && !requirement.exact && entry.packageExact === false && "version" in current &&
290
- entry.snapshot && "version" in entry.snapshot &&
291
- compareWindowsPackageVersions(current.version, entry.snapshot.version) > 0;
292
- if (!upgrade)
315
+ const change = resource.kind === "package" && requirement && !requirement.exact &&
316
+ entry.packageExact === false && "version" in current && entry.snapshot && "version" in entry.snapshot
317
+ ? comparePackageSnapshots(resource.id, current, entry.snapshot) : 0;
318
+ if (change !== undefined && change <= 0) {
293
319
  throw new Error(`Activation changed a resource required by another workspace/host: ${key}`);
320
+ }
294
321
  }
295
322
  after.set(key, current);
296
323
  }
@@ -393,7 +420,8 @@ if (Test-Path -LiteralPath $path) {
393
420
  async remove(resource, snapshot) {
394
421
  if (resource.kind === "package") {
395
422
  if (!("version" in snapshot))
396
- throw new Error("Missing package version for uninstall");
423
+ throw new Error(`Missing package version for uninstall: ${resource.id}`);
424
+ assertRemovablePackageVersion(resource.id, snapshot.version);
397
425
  await runCommand("winget", [
398
426
  "uninstall", "--id", resource.id, "--exact", "--source", resource.source,
399
427
  "--version", snapshot.version, "--silent", "--disable-interactivity",
@@ -12,6 +12,8 @@ export interface Fragment {
12
12
  __id?: string;
13
13
  /** Internal: marks this as a platform fragment */
14
14
  __platform?: boolean;
15
+ /** Internal: account requesting a NixOS-WSL default user */
16
+ __wslDefaultUser?: string;
15
17
  }
16
18
  /**
17
19
  * Internal reference to a workspace-relative raw Nix module file.
@@ -102,6 +104,8 @@ export interface LazyFragment {
102
104
  */
103
105
  export interface PlatformLazyFragment extends LazyFragment {
104
106
  __platform: true;
107
+ /** Platform variant within the platform id (e.g. "wsl" for NixOS-WSL hosts). */
108
+ __variant?: string;
105
109
  }
106
110
  /**
107
111
  * A fragment factory: callable to produce a LazyFragment, with .isActive getter.
@@ -153,6 +157,20 @@ export interface HostDef {
153
157
  */
154
158
  export interface EvalContext {
155
159
  platform: string;
160
+ /** Platform variant, e.g. "wsl" for `platforms.wsl()` hosts (platform stays "nixos"). */
161
+ variant?: string;
156
162
  hostname: string;
157
163
  activeIds: Set<string>;
164
+ /** Directory containing the evaluated winix.config.ts, when known. */
165
+ configDir?: string;
166
+ }
167
+ /**
168
+ * Options for evaluating a workspace.
169
+ */
170
+ export interface EvaluateOptions {
171
+ /**
172
+ * Directory containing winix.config.ts. Enables config-relative helpers such
173
+ * as `home.symlink("../nvim")` and WSL setup `repository: "self"`.
174
+ */
175
+ configDir?: string;
158
176
  }
@@ -1,4 +1,4 @@
1
- import type { HostDef, WorkspaceDef } from "../core/types.js";
1
+ import type { HostDef, WorkspaceDef, EvalContext, EvaluateOptions } from "../core/types.js";
2
2
  /**
3
3
  * Evaluated host: the merged result of all fragments for one host.
4
4
  */
@@ -12,8 +12,10 @@ export interface EvaluatedHost {
12
12
  /**
13
13
  * Evaluate a workspace: process each host's fragments and merge them.
14
14
  */
15
- export declare function evaluate(workspace: WorkspaceDef): EvaluatedHost[];
16
- export declare function collectActiveIds(host: HostDef): Set<string>;
15
+ export declare function evaluate(workspace: WorkspaceDef, options?: EvaluateOptions): EvaluatedHost[];
16
+ /** Build the evaluation context for one host. */
17
+ export declare function hostEvalContext(host: HostDef, activeIds: Set<string>, options?: EvaluateOptions): EvalContext;
18
+ export declare function collectActiveIds(host: HostDef, options?: EvaluateOptions): Set<string>;
17
19
  /**
18
20
  * Deep merge two objects. Arrays are appended + deduped.
19
21
  * Scalars: last wins.
@@ -1,24 +1,31 @@
1
1
  // Evaluator: takes a workspace config, evaluates fragments per host, produces merged IR
2
2
  import { setEvalContext, restoreEvalContext } from "../sdk/index.js";
3
+ import { nix } from "../helpers/nix.js";
3
4
  import { powerShellRepositoryPolicyIdentity, validateWindowsPowerShellPolicy } from "../helpers/windows-repositories.js";
4
5
  /**
5
6
  * Evaluate a workspace: process each host's fragments and merge them.
6
7
  */
7
- export function evaluate(workspace) {
8
- return workspace.hosts.map((host) => evaluateHost(host));
8
+ export function evaluate(workspace, options = {}) {
9
+ return workspace.hosts.map((host) => evaluateHost(host, options));
9
10
  }
10
- function evaluateHost(host) {
11
+ /** Build the evaluation context for one host. */
12
+ export function hostEvalContext(host, activeIds, options = {}) {
13
+ return {
14
+ platform: host.platform.__id,
15
+ ...(host.platform.__variant === undefined ? {} : { variant: host.platform.__variant }),
16
+ hostname: host.name,
17
+ activeIds,
18
+ ...(options.configDir === undefined ? {} : { configDir: options.configDir }),
19
+ };
20
+ }
21
+ function evaluateHost(host, options) {
11
22
  // The platform is always host.platform (exactly one, guaranteed by type system)
12
23
  const platformEntry = host.platform;
13
24
  const allEntries = [platformEntry, ...host.fragments];
14
25
  const platformId = platformEntry.__id;
15
- const activeIds = collectActiveIds(host);
26
+ const activeIds = collectActiveIds(host, options);
16
27
  // Pass 2: set context → resolve lazy fragments (now .isActive works)
17
- const ctx = {
18
- platform: platformId,
19
- hostname: host.name,
20
- activeIds,
21
- };
28
+ const ctx = hostEvalContext(host, activeIds, options);
22
29
  const prevCtx = setEvalContext(ctx);
23
30
  const resolvedFragments = [];
24
31
  try {
@@ -37,7 +44,9 @@ function evaluateHost(host) {
37
44
  darwin: {},
38
45
  windows: {},
39
46
  };
47
+ let defaultUser;
40
48
  for (const fragment of resolvedFragments) {
49
+ defaultUser = fragment.__wslDefaultUser ?? defaultUser;
41
50
  if (fragment.nixos && shouldMergeScope(resolvedFragments, "nixos")) {
42
51
  result.nixos = deepMerge(result.nixos, fragment.nixos);
43
52
  }
@@ -51,6 +60,16 @@ function evaluateHost(host) {
51
60
  result.windows = mergeWindowsOptions(result.windows, fragment.windows);
52
61
  }
53
62
  }
63
+ const wsl = result.nixos.wsl;
64
+ if (defaultUser && (platformId === "nixos" || platformId === "linux") &&
65
+ (wsl === undefined || isPlainObject(wsl))) {
66
+ const options = wsl ?? {};
67
+ const imports = result.nixos.imports;
68
+ const importsWsl = Array.isArray(imports) && imports.some((entry) => typeof entry === "string" && /^inputs\.[a-z0-9._-]+\.nixosModules\.wsl$/i.test(entry.trim()));
69
+ if (options.defaultUser === undefined && (options.enable === true || (options.enable === undefined && importsWsl))) {
70
+ result.nixos.wsl = { ...options, defaultUser: nix.lib.mkDefault(defaultUser) };
71
+ }
72
+ }
54
73
  validateWindowsPowerShellPolicy(result.windows);
55
74
  return result;
56
75
  }
@@ -81,7 +100,7 @@ function shouldMergeScope(fragments, scope) {
81
100
  function isLazy(entry) {
82
101
  return typeof entry === "object" && entry !== null && "__lazy" in entry && entry.__lazy === true;
83
102
  }
84
- export function collectActiveIds(host) {
103
+ export function collectActiveIds(host, options = {}) {
85
104
  const activeIds = new Set([host.platform.__id]);
86
105
  let previousSize = -1;
87
106
  let iterations = 0;
@@ -92,12 +111,7 @@ export function collectActiveIds(host) {
92
111
  throw new Error(`Could not stabilize active fragment IDs for host "${host.name}". ` +
93
112
  "Check for fragments that generate new fragment IDs dynamically.");
94
113
  }
95
- const ctx = {
96
- platform: host.platform.__id,
97
- hostname: host.name,
98
- activeIds,
99
- };
100
- const prevCtx = setEvalContext(ctx);
114
+ const prevCtx = setEvalContext(hostEvalContext(host, activeIds, options));
101
115
  try {
102
116
  collectIds(host.platform, activeIds);
103
117
  for (const entry of host.fragments) {
@@ -18,7 +18,6 @@ function accountFragment(username, opts) {
18
18
  const ctx = getEvalContext();
19
19
  const isDarwin = ctx.platform === "darwin";
20
20
  const isNixos = ctx.platform === "nixos" || ctx.platform === "linux";
21
- const isWsl = ctx.activeIds.has("wsl");
22
21
  const usesHomebrew = ctx.activeIds.has("homebrew");
23
22
  const homeDirectory = opts.homeDirectory ?? opts.home ?? (isDarwin ? `/Users/${username}` : `/home/${username}`);
24
23
  const shell = normalizeShell(opts.shell);
@@ -43,6 +42,7 @@ function accountFragment(username, opts) {
43
42
  ...(isPlainObject(homeManager) && homeManager),
44
43
  },
45
44
  ...(isNixos && {
45
+ ...(opts.wslDefault && { __wslDefaultUser: username }),
46
46
  nixos: {
47
47
  users: {
48
48
  users: {
@@ -66,12 +66,6 @@ function accountFragment(username, opts) {
66
66
  [nixosShellProgram]: { enable: true },
67
67
  },
68
68
  }),
69
- ...(opts.wslDefault &&
70
- isWsl && {
71
- wsl: {
72
- defaultUser: nix.lib.mkDefault(username),
73
- },
74
- }),
75
69
  },
76
70
  }),
77
71
  ...(isDarwin && {
@@ -27,9 +27,27 @@ export interface HomeHelper {
27
27
  files(files: Record<string, HomeFile>): Fragment;
28
28
  configFile(name: string, opts: HomeFile): Fragment;
29
29
  configFiles(files: Record<string, HomeFile>): Fragment;
30
+ /**
31
+ * Out-of-store symlink source. `~/` paths are home-relative; `./` and
32
+ * `../` paths are relative to the directory holding winix.config.ts.
33
+ */
30
34
  symlink(path: string, opts?: Omit<HomeFile, "source" | "text">): HomeFile;
31
35
  raw(config: string): Fragment;
32
36
  activation(name: string, opts: ActivationOpts): Fragment;
37
+ /** Home Manager helpers for NixOS-WSL hosts. */
38
+ wsl: HomeWslHelper;
39
+ }
40
+ export interface HomeWslHelper {
41
+ /**
42
+ * Use the Windows Git Credential Manager from WSL: enables
43
+ * `programs.git` and sets `credential.helper` to a shim that finds
44
+ * Git for Windows' GCM at run time.
45
+ */
46
+ gitCredentialManager(opts?: HomeWslGitCredentialManagerOpts): Fragment;
47
+ }
48
+ export interface HomeWslGitCredentialManagerOpts {
49
+ /** Windows paths to try, in order. Defaults to Git for Windows' ucrt64/mingw64 GCM. */
50
+ paths?: readonly string[];
33
51
  }
34
52
  export interface ActivationOpts {
35
53
  /** DAG dependencies. Defaults to ["writeBoundary"]. */
@@ -1,4 +1,7 @@
1
+ import { posix as pathPosix } from "node:path";
1
2
  import { normalizeArgs } from "./utils.js";
3
+ import { getOptionalEvalContext } from "../sdk/index.js";
4
+ import { GIT_CREDENTIAL_MANAGER_PATHS, windowsBin } from "./wsl-interop.js";
2
5
  import { escapeNixDoubleQuoted, nixStringLiteral } from "../nix/serialize.js";
3
6
  export const home = Object.assign((config) => ({ homeManager: config }), {
4
7
  program: (name, opts = {}) => ({
@@ -36,6 +39,25 @@ export const home = Object.assign((config) => ({ homeManager: config }), {
36
39
  },
37
40
  }),
38
41
  raw: (config) => ({ homeManager: { __raw: [config] } }),
42
+ wsl: {
43
+ gitCredentialManager: (opts = {}) => {
44
+ const shim = windowsBin("git-credential-manager", opts.paths ?? GIT_CREDENTIAL_MANAGER_PATHS);
45
+ return {
46
+ homeManager: {
47
+ programs: {
48
+ git: {
49
+ enable: true,
50
+ settings: {
51
+ credential: {
52
+ helper: { __winixNixExpr: true, expr: `"\${${shim.expr}}/bin/git-credential-manager"` },
53
+ },
54
+ },
55
+ },
56
+ },
57
+ },
58
+ };
59
+ },
60
+ },
39
61
  activation: (name, opts) => {
40
62
  const after = opts.after ?? ["writeBoundary"];
41
63
  const afterList = after.map((s) => nixStringLiteral(s)).join(" ");
@@ -57,5 +79,22 @@ function homePathToNixString(path) {
57
79
  if (path.startsWith("~/")) {
58
80
  return '"${config.home.homeDirectory}/' + escapeNixDoubleQuoted(path.slice(2)) + '"';
59
81
  }
82
+ if (path.startsWith("./") || path.startsWith("../")) {
83
+ return nixStringLiteral(configRelativePath(path));
84
+ }
60
85
  return nixStringLiteral(path);
61
86
  }
87
+ /**
88
+ * Resolve a "./" or "../" path against the directory holding winix.config.ts,
89
+ * matching how Windows file sources resolve. The result is an absolute POSIX
90
+ * path into the checkout, so out-of-store symlinks follow the working tree.
91
+ */
92
+ function configRelativePath(path) {
93
+ const configDir = getOptionalEvalContext()?.configDir;
94
+ if (!configDir) {
95
+ throw new Error(`home.symlink("${path}"): config-relative paths need the config directory; ` +
96
+ "evaluate the workspace through the Winix CLI");
97
+ }
98
+ const base = configDir.replace(/\\/g, "/");
99
+ return pathPosix.normalize(pathPosix.join(base, path)).replace(/\/+$/, "");
100
+ }
@@ -1,7 +1,7 @@
1
1
  export { account } from "./account.js";
2
2
  export type { AccountGroupFactory, AccountGroupMember, AccountGroupOpts, AccountNamespace, AccountOpts, AccountUserFactory, AccountUserRef, } from "./account.js";
3
3
  export { platforms } from "./platforms.js";
4
- export type { DarwinPlatformOpts, NixosPlatformOpts, WindowsPlatformOpts, PlatformsHelper } from "./platforms.js";
4
+ export type { DarwinPlatformOpts, NixosPlatformOpts, WindowsPlatformOpts, WslPlatformOpts, PlatformsHelper } from "./platforms.js";
5
5
  export { nix } from "./nix.js";
6
6
  export type { BinaryReleaseArch, BinaryReleaseCompletions, BinaryReleaseFormat, BinaryReleaseMeta, BinaryReleaseOpts, BinaryReleasePlatform, NixNamespace, PkgHelper, ScriptHelper, } from "./nix.js";
7
7
  export { overlay } from "./overlay.js";
@@ -13,4 +13,4 @@ export type { NixosHelper, NixosProgramOptions, NixosServiceOptions, SysctlSetti
13
13
  export { darwin } from "./darwin.js";
14
14
  export type { DarwinHelper, DarwinProgramOptions, DarwinServiceOptions, LaunchdHelper } from "./darwin.js";
15
15
  export { windows } from "./windows.js";
16
- export type { WindowsHelper, WinDscSpec, WinEnvNamespace, WinEnvOpts, WinEnvScope, WinFileEncoding, WinFileNamespace, WinFileOpts, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, WinSettingOpts, WinPowerShellModuleOpts, WinStartupCommandSpec, WinStartupNamespace, WinOptionalFeatureOpts, WinWslDistroSpec, WinWslOpts, WinWslNamespace, } from "./windows.js";
16
+ export type { WindowsHelper, WinDscSpec, WinEnvNamespace, WinEnvOpts, WinEnvScope, WinFileEncoding, WinFileNamespace, WinFileOpts, WinPackageArg, WinPackageSpec, WinPathNamespace, WinRawCommandArg, WinRawCommandSpec, WinSettingOpts, WinPowerShellModuleOpts, WinStartupCommandSpec, WinStartupNamespace, WinOptionalFeatureOpts, WinWslDistroSpec, WinWslSetupSpec, WinWslOpts, WinWslNamespace, } from "./windows.js";
@@ -69,6 +69,20 @@ export interface NixNamespace {
69
69
  * @see {@link BinaryReleaseOpts} for the full options interface
70
70
  */
71
71
  binaryRelease(opts: BinaryReleaseOpts): NixExpr;
72
+ /** Helpers for NixOS-WSL hosts reaching into Windows. */
73
+ wsl: {
74
+ /**
75
+ * Package with `bin/<name>`: a shim that runs the first existing Windows
76
+ * executable among `paths`. Paths are absolute (`C:\\...`) or start with
77
+ * an environment variable (`%LOCALAPPDATA%\\...`), resolved through interop
78
+ * on each run, so no Windows user name or drive is hard-coded.
79
+ *
80
+ * @example
81
+ * home.packages(nix.wsl.windowsBin("code-insiders",
82
+ * "%LOCALAPPDATA%\\Programs\\Microsoft VS Code Insiders\\bin\\code-insiders"));
83
+ */
84
+ windowsBin(name: string, paths: string | readonly string[]): NixExpr;
85
+ };
72
86
  lib: {
73
87
  mkDefault(value: NixValue): NixExpr;
74
88
  mkForce(value: NixValue): NixExpr;