@adrifer/winix 0.2.3 → 0.2.4-preview.1

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 (39) hide show
  1. package/README.md +423 -3
  2. package/dist/backends/windows/index.d.ts +3 -1
  3. package/dist/backends/windows/index.js +99 -7
  4. package/dist/backends/windows/lockfile.d.ts +36 -1
  5. package/dist/backends/windows/lockfile.js +168 -0
  6. package/dist/backends/windows/paths.d.ts +2 -0
  7. package/dist/backends/windows/paths.js +17 -0
  8. package/dist/backends/windows/powershell.d.ts +6 -0
  9. package/dist/backends/windows/powershell.js +51 -0
  10. package/dist/backends/windows/wsl-setup-runtime.d.ts +35 -0
  11. package/dist/backends/windows/wsl-setup-runtime.js +401 -0
  12. package/dist/backends/windows/wsl-setup.d.ts +12 -0
  13. package/dist/backends/windows/wsl-setup.js +150 -0
  14. package/dist/backends/windows/wsl.d.ts +9 -0
  15. package/dist/backends/windows/wsl.js +194 -0
  16. package/dist/cli/commands/apply.d.ts +7 -1
  17. package/dist/cli/commands/apply.js +39 -15
  18. package/dist/cli/commands/check.js +3 -0
  19. package/dist/cli/commands/init.js +5 -1
  20. package/dist/cli/commands/switch.d.ts +6 -0
  21. package/dist/cli/commands/switch.js +53 -13
  22. package/dist/cli/commands/update.d.ts +6 -1
  23. package/dist/cli/commands/update.js +41 -10
  24. package/dist/cli/index.js +40 -3
  25. package/dist/cli/windows-state.d.ts +56 -0
  26. package/dist/cli/windows-state.js +341 -0
  27. package/dist/helpers/index.d.ts +1 -1
  28. package/dist/helpers/utils.d.ts +1 -0
  29. package/dist/helpers/utils.js +8 -0
  30. package/dist/helpers/windows.d.ts +53 -7
  31. package/dist/helpers/windows.js +351 -28
  32. package/dist/index.d.ts +4 -2
  33. package/dist/runtime.d.ts +10 -0
  34. package/dist/runtime.js +9 -0
  35. package/dist/skill.js +126 -5
  36. package/dist/types/windows.d.ts +82 -1
  37. package/package.json +4 -1
  38. package/scripts/bootstrap-nixos.sh +51 -0
  39. package/scripts/bootstrap-windows.ps1 +225 -0
package/README.md CHANGED
@@ -94,6 +94,58 @@ For what it's worth: Winix today works just as well on macOS and native NixOS as
94
94
 
95
95
  ## Install and create a config
96
96
 
97
+ ### Standalone executable (no Node.js or npm)
98
+
99
+ [GitHub releases](https://github.com/adrifer/winix/releases) include
100
+ `winix-windows-x64.exe`, `winix-windows-arm64.exe`, `winix-linux-x64`,
101
+ `winix-linux-arm64`, and `SHA256SUMS`. Choose a versioned release and the native
102
+ architecture, compare its SHA256 with `SHA256SUMS`, and keep the executable
103
+ outside the config checkout. Windows binaries are not yet code-signed:
104
+ checksums detect corruption, not publisher identity. Respect organizational
105
+ execution/network policies; do not disable TLS verification.
106
+ Redistribution notices and runtime source/rebuild references accompany the
107
+ assets as `LICENSE`, `NOTICE.txt`, and `BUN-LICENSE.md`.
108
+
109
+ On Windows, rename the verified executable to `winix.exe` and either add its
110
+ directory to PATH or invoke it by full path:
111
+
112
+ ```powershell
113
+ & "$HOME\winix-bootstrap\winix.exe" --version
114
+ cd "$HOME\dotfiles\winix"
115
+ & "$HOME\winix-bootstrap\winix.exe" check
116
+ & "$HOME\winix-bootstrap\winix.exe" switch --host windows-devbox --dry
117
+ ```
118
+
119
+ No `npm ci` is needed for normal configs. The executable contains its runtime
120
+ and SDK, supports local TypeScript/JavaScript imports and Node builtins, and
121
+ shares SDK evaluation context across all config files. Its version, not an
122
+ installed npm SDK or the config's package lock, determines the SDK used.
123
+ `winix init` works without npm too; its package/TypeScript files are optional
124
+ editor/development tooling. Type-only `@adrifer/winix/types` imports work;
125
+ runtime SDK imports must use `@adrifer/winix`. Other npm dependencies must
126
+ already be installed: Winix never downloads them automatically.
127
+
128
+ Native prerequisites remain Git, PowerShell 7, WinGet, DSC and the required DSC
129
+ resources on Windows, or Nix/activation tools for Linux targets. Use
130
+ `bootstrap-windows.ps1 -Standalone -Check` to inspect native prerequisites or
131
+ `-Standalone` to install missing ones; this mode never installs/checks Node/npm.
132
+ Standalone Windows WSL setup downloads the matching release's Linux executable,
133
+ verifies a checksum embedded in the Windows binary, and prepares its NixOS
134
+ runtime linker with pinned Nix dependencies. Account/config generation remains
135
+ unprivileged and does not run npm. Keep `flake.lock` committed; package manifests
136
+ are required only by the npm-based setup path. These downloads still need
137
+ approved access to GitHub and Nix caches.
138
+
139
+ Linux release binaries target glibc systems (with libstdc++); use `chmod +x`
140
+ before running. NixOS does not provide an FHS runtime linker by default:
141
+ automatic WSL setup handles this explicitly, while direct manual use needs a
142
+ compatible linker/library environment. Windows binaries used for WSL setup
143
+ must come from a complete official release; developer single-target builds
144
+ lack the Linux checksums. ARM64 assets are cross-compiled; fresh-machine
145
+ activation and ARM64 execution are not yet verified.
146
+
147
+ ### npm installation (optional)
148
+
97
149
  ```bash
98
150
  mkdir my-winix-config
99
151
  cd my-winix-config
@@ -101,7 +153,9 @@ npx @adrifer/winix@latest init
101
153
  npm install
102
154
  ```
103
155
 
104
- Winix expects Node.js with native TypeScript stripping support for `winix.config.ts` files. Node 22+ is recommended.
156
+ The npm CLI requires Node.js with native TypeScript transformation and the
157
+ `--experimental-transform-types` flag (Node 22.13+ or 24; use Node 24).
158
+ The standalone executable has no installed Node version requirement.
105
159
 
106
160
  If you prefer to set up files yourself instead of using `init`, add the package to your own `package.json`:
107
161
 
@@ -126,6 +180,36 @@ You can also install it globally, but local project installs are recommended:
126
180
  npm install -g @adrifer/winix
127
181
  ```
128
182
 
183
+ ### Bootstrap prerequisites on NixOS
184
+
185
+ On an existing NixOS installation (including NixOS-WSL), a reviewed copy of
186
+ `scripts/bootstrap-nixos.sh` opens a temporary prerequisite environment:
187
+
188
+ ```bash
189
+ bash bootstrap-nixos.sh
190
+ # Inside the shell, clone your config, install its dependencies, and run Winix yourself.
191
+ # Type exit when finished.
192
+ ```
193
+
194
+ Git, Node.js 24/npm, and interactive Bash come from one nixpkgs commit pinned
195
+ in the script, without relying on your channels or flake registry. The script
196
+ enables `nix-command`/flakes for the child session only and disables Bash startup
197
+ files so user profiles cannot replace the bootstrap PATH. The working directory
198
+ is preserved. Network/store access is required on a cold machine; normal Nix
199
+ permissions, cache verification, and trust settings still apply.
200
+
201
+ Nothing is installed into a user profile or system configuration, though Nix
202
+ may download packages into its store. The script does not install NixOS, clone
203
+ a repo, install Winix/npm dependencies, select a host, or rebuild anything.
204
+ Declare tools and Nix settings in your own config for permanent availability.
205
+ Maintainers update the pinned nixpkgs commit deliberately alongside the script.
206
+
207
+ Future stable and preview [GitHub releases](https://github.com/adrifer/winix/releases)
208
+ include `bootstrap-nixos.sh` and `bootstrap-nixos.sh.sha256`. Download both,
209
+ check with `sha256sum --check bootstrap-nixos.sh.sha256`, review the script, then
210
+ run it; do not pipe an unreviewed download into a shell. Checksums detect
211
+ corruption but do not independently establish publisher identity.
212
+
129
213
  ## CLI
130
214
 
131
215
  From a Winix project:
@@ -417,8 +501,344 @@ host("desktop", platforms.windows(), ({ windows }) => {
417
501
  });
418
502
  ```
419
503
 
420
- This generates a DSC v3 document that `winget configure` applies. The backend is
421
- an MVP: only `windows.package` and `windows.raw` exist today. See
504
+ This generates a DSC v3 document that `winget configure` applies. Typed helpers
505
+ also cover environment variables, PATH, files, Windows settings, and PowerShell
506
+ modules:
507
+
508
+ ```ts
509
+ host("desktop", platforms.windows(), ({ windows }) => {
510
+ const developerMode = windows.setting({ DeveloperMode: true });
511
+ const icons = windows.powershell.module("Terminal-Icons");
512
+
513
+ windows.file.symlink(
514
+ windows.knownFolder.documents("PowerShell\\Microsoft.PowerShell_profile.ps1"),
515
+ "../windows/powershell/Microsoft.PowerShell_profile.ps1",
516
+ { backup: true, dependsOn: [icons, developerMode] },
517
+ );
518
+ });
519
+ ```
520
+
521
+ `windows.knownFolder.documents(childPath?)` resolves redirected Documents **during activation**,
522
+ not on the machine generating the configuration. Supported folders are
523
+ `documents`, `desktop`, `localAppData`, `appData`, and `userProfile`. The optional
524
+ child path must stay within the folder. All `windows.file.*` targets accept it.
525
+ Copy/symlink source strings are relative to the directory containing
526
+ `winix.config.ts`, not the calling feature or working directory. Absolute paths,
527
+ `%VARIABLE%` paths, and `file:` URL objects remain supported. Symlinks stay live
528
+ and require the checkout to remain in place. Existing backup/force protections
529
+ are unchanged. Direct `generateWindows(hosts, lock, configDir)` callers must
530
+ supply `configDir` when using relative sources.
531
+
532
+ When generating in WSL, Winix uses `wslpath` to translate filesystem sources to
533
+ Windows drive/UNC paths. Sources inside the Linux filesystem use a WSL UNC path,
534
+ so that distribution must remain available during activation. Generation on
535
+ other Linux/macOS systems does not translate local paths; use Windows-reachable
536
+ absolute or environment-variable sources when generating there.
537
+
538
+ PowerShell module versions and repositories are pinned in the optional `modules`
539
+ section of the existing `winix-windows.lock` (lowercase module-name keys).
540
+ Old package-only locks remain valid. First apply resolves missing entries;
541
+ subsequent applies reuse pins without querying the repository.
542
+ `winix update --windows` refreshes packages and modules, or pass names to update
543
+ only selected entries; `--dry` resolves without writing. Resolution errors never
544
+ replace existing pins. Network access is still needed for installation.
545
+
546
+ `windows.powershell.module(name, { repository?, dependsOn? })` defaults to
547
+ PSGallery, selects stable releases, and installs the exact locked version for
548
+ the current user. PowerShell 7 with PSResourceGet must already be available for
549
+ resolution. Installation is idempotent and runs directly in DSC's
550
+ `Microsoft.DSC.Transitional/PowerShellScript` resource; a declared `Microsoft.PowerShell` package is an
551
+ automatic dependency. Other versions are not removed. Profiles still import
552
+ modules themselves; an unversioned `Import-Module` can load a newer installed
553
+ version, so installation locking alone does not enforce session imports.
554
+
555
+ ### Provision WSL from a Windows host
556
+
557
+ ```ts
558
+ host("DESKTOP", platforms.windows(), ({ windows }) => {
559
+ const runtime = windows.package("Microsoft.WSL");
560
+ const setup = windows.wsl({
561
+ config: {
562
+ wsl2: { memory: "16GB", processors: 8 },
563
+ experimental: { autoMemoryReclaim: "gradual" },
564
+ },
565
+ backup: true,
566
+ });
567
+ windows.wsl.distro("NixOS", {
568
+ source: "nixos-wsl",
569
+ installLocation: "D:/WSL/NixOS",
570
+ default: true,
571
+ dependsOn: [setup, runtime],
572
+ });
573
+ });
574
+ ```
575
+
576
+ `windows.wsl({ config?, backup?, force?, dependsOn? })` enables the WSL and
577
+ Virtual Machine Platform Windows features and optionally manages `.wslconfig`.
578
+ Calling `windows.wsl()` without config leaves that file untouched.
579
+ `windows.optionalFeature(name,
580
+ { enabled?, dependsOn? })` also supports individual optional features.
581
+ Feature changes require administrator approval. If a restart is required,
582
+ dependent provisioning stops: restart Windows yourself and rerun `winix switch`.
583
+ Winix never automatically restarts Windows or shuts down WSL.
584
+
585
+ Declare both the features and `Microsoft.WSL` package in the same Windows host.
586
+ The distro automatically depends on the features, optional configuration file,
587
+ and runtime package; explicit `dependsOn` also supports other handles. The setup
588
+ handle covers both features and configuration when provided. Registration runs
589
+ as the current Windows user, not SYSTEM;
590
+ use the intended account rather than another administrator's credentials.
591
+ `installLocation` accepts an absolute local-drive path, an environment-variable
592
+ path, or a known-folder target. It must not already exist. Names and locations
593
+ must be unique per host; at most one distro may be declared default.
594
+
595
+ The `config` option owns the current user's complete `.wslconfig`, using the
596
+ normal file backup/force protections. Changes print a reminder to restart WSL
597
+ manually when safe. They do not immediately alter running distros.
598
+
599
+ First apply pins official stable NixOS-WSL image URLs and SHA256 digests for x64
600
+ and ARM64 in the optional `wslImages` section of `winix-windows.lock`. Subsequent
601
+ applies reuse these pins. `winix update --windows nixos-wsl` refreshes them;
602
+ updating all Windows entries includes images too. Downloads are verified before
603
+ import. Image updates affect **new registrations only**, never existing Linux
604
+ filesystems. Dry generation can resolve missing pins but neither writes the lock
605
+ nor downloads images.
606
+
607
+ Winix refuses conflicting or unrecorded existing distros; it does not automatically
608
+ adopt, replace, move, convert, or unregister them. Successful imports create
609
+ `.winix-wsl.json` in the installation directory to identify that registration.
610
+ If import is interrupted before recording completes, inspect the existing
611
+ registration and disk manually; Winix will not unregister it as rollback.
612
+ Removing declarations leaves distro data and enabled optional features intact.
613
+ Only explicit `enabled: false` disables a feature. The separately declared
614
+ WSL package follows normal package ownership/removal rules.
615
+
616
+ The Windows registration name (`NixOS`) and Linux Winix host name (`wsl-work`,
617
+ for example) are independent. To automate their first-run link, opt into `setup`:
618
+
619
+ ```ts
620
+ windows.wsl.distro("NixOS", {
621
+ source: "nixos-wsl",
622
+ installLocation: windows.knownFolder.localAppData("Winix\\WSL\\NixOS"),
623
+ default: true,
624
+ setup: {
625
+ repository: "https://github.com/example/dotfiles.git",
626
+ ref: "main",
627
+ configDirectory: "winix",
628
+ host: "wsl-work",
629
+ user: "alice",
630
+ checkout: "/home/alice/dotfiles",
631
+ },
632
+ });
633
+ ```
634
+
635
+ This explicitly trusts the repository and its Winix configuration (including
636
+ npm lifecycle scripts when using the npm SDK). Commit `flake.lock` in
637
+ `configDirectory`; the npm path additionally requires `package.json`,
638
+ `package-lock.json`, and a released Winix dependency supporting this API.
639
+ Only HTTPS Git URLs without embedded credentials are accepted. Private repository
640
+ and dependency authentication must already be available inside Linux; credentials
641
+ are never provisioned by this helper.
642
+
643
+ The Linux host must explicitly enable NixOS-WSL, import its input module, declare
644
+ `system.stateVersion`, and match the distro architecture. `user` selects an
645
+ already-declared normal account, not a second account definition. Omit it when
646
+ Home Manager or the sole normal account identifies the user unambiguously.
647
+ Home Manager's username/home must agree with the selected account. `checkout`
648
+ defaults to `<declared-home>/dotfiles` and must stay inside that home.
649
+
650
+ First apply locks the repository ref (default `HEAD`) to a commit in
651
+ `wslRepositories`. `winix update --windows wsl-setup` refreshes these pins;
652
+ an update without names includes them too. Dry generation never clones or executes
653
+ repository code. Pins affect **first-run setup only**, not subsequent dotfiles
654
+ updates; an interrupted setup retains its original commit.
655
+
656
+ During activation, Git/config preparation (and npm on the npm path) runs as the image's initial `nixos`
657
+ user. A root coordinator first activates only the selected declarative account
658
+ and required WSL/shell settings, moves checkout ownership to it, then generates
659
+ the full host as that user and activates it as root. No password is invented and
660
+ sudo policy is not changed. External secret files required by the account must
661
+ already exist. The full host must set `wsl.defaultUser` to the selected user.
662
+
663
+ Setup records resumable stages under `/var/lib/winix/wsl-setup`; rerun Windows
664
+ `winix switch` after a reported failure. Dirty, occupied, or changed checkouts and
665
+ changed setup settings are refused, never reset or adopted. A killed coordinator
666
+ can leave `run.lock`: inspect its recorded PID/state and confirm no setup is
667
+ running before manually removing that lock. Other conflicts require explicit
668
+ manual recovery or a new distro. Successful setup is not repeated; later Linux
669
+ updates remain ordinary Linux Winix operations. No shutdown/reboot is performed;
670
+ restart WSL manually when safe if its new default-user setting needs it.
671
+ Fresh-image end-to-end activation remains unverified.
672
+
673
+ Without `setup`, repository installation and Linux activation remain manual.
674
+
675
+ ### Bootstrap a Windows machine
676
+
677
+ `scripts/bootstrap-windows.ps1` runs with built-in Windows PowerShell 5.1 or
678
+ PowerShell 7, without needing Node, Git, or Winix first. Save a reviewed copy
679
+ from your chosen Winix checkout/revision (or carry it on your restore drive).
680
+ Starting with the next release containing this change, stable and preview
681
+ [GitHub releases](https://github.com/adrifer/winix/releases) include
682
+ `bootstrap-windows.ps1` and `bootstrap-windows.ps1.sha256` as downloadable assets,
683
+ so no checkout, Git, or npm is needed to obtain the script. Use
684
+ `Get-FileHash .\bootstrap-windows.ps1 -Algorithm SHA256` to compare its hash with
685
+ the downloaded checksum file. The checksum detects corruption, not publisher
686
+ identity; the script is not yet code-signed.
687
+ Do not pipe an unreviewed download into a shell.
688
+
689
+ App Installer/WinGet must already be available for the current Windows account.
690
+ If missing, the script stops with the official Store link and first-sign-in
691
+ registration instructions; it does not download unsigned installers or bypass
692
+ Store policy. Run from a normal Windows account, not WSL or another admin account:
693
+
694
+ ```powershell
695
+ # Read-only: reports missing/old prerequisites and exits unsuccessfully if not ready.
696
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1 -Check
697
+ # Executable workflow: omit all Node/npm checks and installations.
698
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1 -Standalone -Check
699
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1 -Standalone
700
+ # Review and confirm installation/upgrade of missing or outdated prerequisites.
701
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1
702
+ # Choose NVM for Windows rather than standalone Node on NVM-based setups.
703
+ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\scripts\bootstrap-windows.ps1 -UseNvm
704
+ ```
705
+
706
+ `-ExecutionPolicy Bypass` applies to this process only, not the machine/user
707
+ policy; organizational policy may still block execution. `-Yes` accepts bootstrap
708
+ installation for automation. Installers may request UAC elevation. The script
709
+ checks Git, Node (22.13+), npm, PowerShell (7.4+), PSResourceGet/PSGallery, DSC
710
+ (3.2+), and the backend's required DSC resources. Supported existing versions
711
+ are kept; standalone installs use `Git.Git`, `OpenJS.NodeJS.LTS`,
712
+ `Microsoft.PowerShell`, and `Microsoft.DSC` from the exact WinGet source/IDs.
713
+ `-UseNvm` installs `CoreyButler.NVMforWindows` if needed and selects Node LTS
714
+ through NVM instead. It refuses to introduce standalone Node alongside an
715
+ existing NVM installation when Node needs setup. Install mode also enables
716
+ WinGet configuration components (requires Store access); `-Check` does not.
717
+
718
+ Only the process PATH/NVM environment is refreshed; no persistent policy or
719
+ environment values are written by the script itself. Installers can change
720
+ their normal installation settings. Errors stop the bootstrap; restart requests
721
+ are reported, never performed automatically. Reopen PowerShell 7 afterward.
722
+ Bootstrap installations are prerequisites, not Winix-owned host resources, and
723
+ are not pinned by a host's Windows lockfile.
724
+
725
+ This is the reusable prerequisite layer, not a dotfiles installer. Preparing a
726
+ config checkout, restoring its npm dependencies, selecting a compatible Winix
727
+ version/local SDK, reviewing `check`/`switch --dry`, and confirming `switch` are
728
+ separate steps. It never clones repositories, installs Winix globally, activates
729
+ a host, changes execution policy persistently, or provisions WSL. Repository
730
+ setup, npm installation, and all Winix commands remain the user's responsibility.
731
+
732
+ All generated file, PATH, and module scripts use PowerShell 7; string-form
733
+ `windows.raw("...")` commands also default to `pwsh`, without loading a profile
734
+ or prompting interactively. Explicit executable choices
735
+ remain unchanged. Winix no longer requires Windows PowerShell 5.1 for these
736
+ flows, but it does not remove it from Windows.
737
+
738
+ Install PowerShell 7 and make `pwsh` available on PATH **before** DSC discovers
739
+ the configuration's resources; a `dependsOn` package alone does not bootstrap
740
+ resource discovery. Script `setScript` operations independently check current
741
+ state because the transitional resource can invoke set without first running
742
+ `testScript`. Native Registry resources still manage persistent environment
743
+ variables, with machine-scope writes requiring elevation as before.
744
+ Generated script literals escape Unicode to survive DSC's script transport
745
+ without corrupting file contents or paths.
746
+
747
+ ### Windows sign-in startup
748
+
749
+ ```ts
750
+ windows.startup.command("my-app", {
751
+ executable: "%ProgramFiles%/MyApp/app.exe",
752
+ arguments: ["--config", windows.knownFolder.appData("MyApp/config.json")],
753
+ workingDirectory: windows.knownFolder.userProfile(),
754
+ windowStyle: "minimized",
755
+ backup: true,
756
+ dependsOn: appPackage,
757
+ });
758
+ ```
759
+
760
+ `windows.startup.command(name, spec)` manages `<name>.lnk` in the current user's
761
+ actual Startup known folder. It only registers the shortcut: nothing is launched,
762
+ stopped, or reloaded during apply. Commands run at sign-in, not at machine boot;
763
+ this is not a service, scheduled task, elevated launch, or all-users startup API.
764
+
765
+ The executable may be an absolute path, an environment-variable path, a named
766
+ known-folder path, or an application name resolved on PATH during activation.
767
+ The executable and working directory must exist then; use `dependsOn` for
768
+ installation/configuration ordering. Relative filesystem paths are rejected.
769
+ The default working directory is the user profile. `arguments` is an argv array:
770
+ strings are literal (including `%VAR%`), while known-folder values resolve during
771
+ activation. Standard Windows argv quoting preserves spaces, empty arguments,
772
+ embedded quotes, backslashes, and Unicode; no shell is implicitly inserted.
773
+
774
+ `windowStyle` accepts `normal` (default), `minimized`, or `maximized`; minimized
775
+ does not guarantee a hidden console. Correct shortcuts are left untouched.
776
+ Replacement is refused by default; `backup: true` preserves an existing entry
777
+ as `.lnk.bak` and refuses backup collisions, while `force: true` opts into
778
+ replacement without a backup. A new shortcut is staged and verified before
779
+ replacing the old one. Keep names unique per host.
780
+
781
+ ### Windows removal and ownership
782
+
783
+ Native Windows `winix switch` keeps a separate applied-state inventory under
784
+ `%LOCALAPPDATA%\Winix\applied-<machine-and-user-hash>.json`. This is machine-local
785
+ state, not the version lockfile and not something to commit or copy to another
786
+ machine. Canonical workspace directories and host names identify recorded
787
+ requirements across activations by the same Windows account.
788
+
789
+ - A shortcut Winix creates or explicitly replaces becomes owned after successful
790
+ activation. Removing its declaration removes that unchanged shortcut on the
791
+ next successful switch, without stopping the running program. An already
792
+ matching, pre-existing shortcut is not automatically adopted.
793
+ - A package absent before and present after successful activation becomes owned.
794
+ Already-installed packages satisfy requirements without gaining uninstall
795
+ ownership. Removing a declaration automatically uninstalls an unused,
796
+ previously owned package after successful activation. Preview all cleanup with
797
+ `winix switch --dry`. Uninstallers may remove application data.
798
+ - External resources are never swept. Other recorded hosts/workspaces retain
799
+ their requirements; incompatible shared declarations fail before activation.
800
+ Removing a host or moving a workspace does not automatically release its old
801
+ recorded requirements.
802
+
803
+ When packages or startup shortcuts would be removed, `switch` lists them and asks
804
+ `Continue with switch? [y/N]` before activation. Declining or closing the prompt
805
+ cancels the whole switch without activation or cleanup. Switches without removals
806
+ and `--dry` do not prompt. Use `winix switch --yes` (or `-y`) to accept removals
807
+ for automation; noninteractive switches with removals require this flag.
808
+
809
+ Startup file hashes and installed package versions detect drift. External edits
810
+ or version changes block reconciliation rather than silently deleting or
811
+ overwriting managed resources. Restore the recorded resource, or explicitly
812
+ release Winix's removal rights without deleting anything:
813
+
814
+ ```powershell
815
+ winix state forget startup komorebi --dry
816
+ winix state forget startup komorebi
817
+ winix state forget package winget Example.App
818
+ ```
819
+
820
+ `state forget` preserves recorded requirements but releases ownership for that
821
+ resource across this user's inventory. If still declared, it remains required;
822
+ future creation or explicit shortcut replacement can grant ownership again.
823
+ Package removal requires an exact installed-version match and uses exact ID,
824
+ source, and version selection.
825
+
826
+ Dry Windows switches inspect and report removals without changing inventory,
827
+ system resources, or generated output. `apply`, running generated
828
+ scripts directly, or invoking `winget configure` yourself does not record
829
+ ownership or perform cleanup. A failed/interrupted activation never grants new
830
+ ownership; partial installations can remain unmanaged. Removal progress is saved
831
+ after each successful removal so failures can be retried conservatively.
832
+ Concurrent switches are refused. After a crash, inspect the inventory and
833
+ `.lock`/`.tmp` siblings before manually clearing stale files.
834
+
835
+ This coordinates recorded activations for one user/machine, not other users,
836
+ unrecorded configurations, or independent installers running concurrently.
837
+ Losing the inventory loses deletion rights; Winix does not reconstruct ownership
838
+ from installed software, existing shortcuts, generated output, or lockfiles.
839
+ Files, modules, Registry values, and PATH entries do not yet have removal tracking.
840
+
841
+ See
422
842
  [`examples/windows/`](examples/windows) and
423
843
  [`spec/proposals/windows-backend.md`](spec/proposals/windows-backend.md).
424
844
 
@@ -1,4 +1,5 @@
1
1
  import type { EvaluatedHost } from "../../evaluator/index.js";
2
+ import type { WindowsOptions } from "../../types/index.js";
2
3
  import { type WindowsLock } from "./lockfile.js";
3
4
  export { isWindowsHost } from "./host.js";
4
5
  /**
@@ -21,4 +22,5 @@ export interface WindowsOutput {
21
22
  * Generate Windows bundles for every Windows host in the evaluated workspace.
22
23
  * Non-Windows hosts are skipped.
23
24
  */
24
- export declare function generateWindows(evaluatedHosts: EvaluatedHost[], lock?: WindowsLock): WindowsOutput;
25
+ export declare function generateWindows(evaluatedHosts: EvaluatedHost[], lock?: WindowsLock, configDir?: string): WindowsOutput;
26
+ export declare function validateWindowsWslResources(win: WindowsOptions): void;
@@ -25,9 +25,15 @@
25
25
  //
26
26
  // `winget configure -f configuration.winget` runs this directly; the dscv3
27
27
  // processor is selected by the metadata block.
28
+ import { win32 } from "node:path";
28
29
  import { yamlEntry, yamlScalar } from "./yaml.js";
29
30
  import { emptyWindowsLock, reconcileInlinePins, } from "./lockfile.js";
30
31
  import { isWindowsHost } from "./host.js";
32
+ import { resolveWindowsFileProperties } from "../../helpers/windows.js";
33
+ import { powerShellModuleProperties } from "./powershell.js";
34
+ import { powerShellLiteral as psSingleQuoted } from "../../helpers/utils.js";
35
+ import { windowsSourcePath } from "./paths.js";
36
+ import { optionalFeatureProperties, wslDistroProperties } from "./wsl.js";
31
37
  export { isWindowsHost } from "./host.js";
32
38
  const DSC_SCHEMA = "https://raw.githubusercontent.com/PowerShell/DSC/main/schemas/2023/08/config/document.json";
33
39
  const WINGET_PACKAGE_TYPE = "Microsoft.WinGet/Package";
@@ -37,7 +43,7 @@ const WINDOWS_SETTINGS_MODULE_COMMAND_NAME = "Ensure Microsoft Windows Settings
37
43
  * Generate Windows bundles for every Windows host in the evaluated workspace.
38
44
  * Non-Windows hosts are skipped.
39
45
  */
40
- export function generateWindows(evaluatedHosts, lock = emptyWindowsLock()) {
46
+ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock(), configDir) {
41
47
  const hosts = {};
42
48
  const warnings = [];
43
49
  const windowsHosts = evaluatedHosts.filter(isWindowsHost);
@@ -45,7 +51,7 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock()) {
45
51
  for (const host of windowsHosts) {
46
52
  const win = host.windows;
47
53
  hosts[host.name] = {
48
- "configuration.winget": generateConfiguration(host.name, win, resolvedLock),
54
+ "configuration.winget": generateConfiguration(host.name, win, resolvedLock, configDir),
49
55
  "apply.ps1": generateApplyScript(),
50
56
  };
51
57
  }
@@ -54,9 +60,48 @@ export function generateWindows(evaluatedHosts, lock = emptyWindowsLock()) {
54
60
  /**
55
61
  * Render the WinGet Configuration YAML document (DSC v3) for one host.
56
62
  */
57
- function generateConfiguration(hostName, win, lock) {
63
+ function generateConfiguration(hostName, win, lock, configDir) {
64
+ validateWindowsWslResources(win);
58
65
  const packages = sortedPackages(win.packages ?? {});
59
- const prepared = prepareWindowsDscResources(win.commands ?? [], win.dsc ?? []);
66
+ const resources = (win.dsc ?? []).map((resource) => {
67
+ const metadata = resource.winix;
68
+ if (metadata?.kind === "file") {
69
+ const properties = resolveWindowsFileProperties(resource, configDir, windowsSourcePath);
70
+ if (metadata.wslConfig && properties) {
71
+ properties.setScript += "\nWrite-Warning 'WSL configuration changed. Restart WSL manually when safe; Winix will not stop running distros.'";
72
+ }
73
+ return cloneDscResource(resource, properties);
74
+ }
75
+ if (metadata?.kind === "optional-features") {
76
+ return cloneDscResource(resource, optionalFeatureProperties(metadata.names, metadata.enabled));
77
+ }
78
+ if (metadata?.kind === "wsl-distro") {
79
+ const setupRefs = (win.dsc ?? [])
80
+ .filter((entry) => (entry.winix?.kind === "optional-features" && entry.winix.enabled &&
81
+ entry.winix.names.some((name) => WSL_FEATURES.includes(name.toLowerCase()))) ||
82
+ (entry.winix?.kind === "file" && entry.winix.wslConfig))
83
+ .map((entry) => ({ kind: "dsc", token: entry.token }));
84
+ const runtime = packages.find((pkg) => pkg.id.toLowerCase() === "microsoft.wsl");
85
+ return cloneDscResource(resource, wslDistroProperties(metadata.distro, lock.wslImages ?? {}, lock.wslRepositories ?? {}), [
86
+ ...setupRefs, { kind: "package", id: runtime.id }, ...(resource.dependsOn ?? []),
87
+ ]);
88
+ }
89
+ if (metadata?.kind === "powershell-module") {
90
+ const module = metadata.module;
91
+ const pin = lock.modules?.[module.name.toLowerCase()];
92
+ if (!pin || pin.repository.toLowerCase() !== module.repository.toLowerCase()) {
93
+ throw new Error(`PowerShell module "${module.name}" has no matching pin in winix-windows.lock. Run winix update --windows.`);
94
+ }
95
+ const dependencies = [...(resource.dependsOn ?? [])];
96
+ if (packages.some((pkg) => pkg.id === "Microsoft.PowerShell") &&
97
+ !dependencies.some((ref) => ref.kind === "package" && ref.id === "Microsoft.PowerShell")) {
98
+ dependencies.push({ kind: "package", id: "Microsoft.PowerShell" });
99
+ }
100
+ return cloneDscResource(resource, powerShellModuleProperties(module, pin), dependencies);
101
+ }
102
+ return resource;
103
+ });
104
+ const prepared = prepareWindowsDscResources(win.commands ?? [], resources);
60
105
  const commands = prepared.commands;
61
106
  const dscResources = prepared.dscResources;
62
107
  const lines = [];
@@ -89,6 +134,56 @@ function generateConfiguration(hostName, win, lock) {
89
134
  }
90
135
  return lines.join("\n") + "\n";
91
136
  }
137
+ const WSL_FEATURES = ["microsoft-windows-subsystem-linux", "virtualmachineplatform"];
138
+ export function validateWindowsWslResources(win) {
139
+ const features = new Map();
140
+ const names = new Set();
141
+ const locations = new Set();
142
+ let defaults = 0;
143
+ let configs = 0;
144
+ let distros = 0;
145
+ for (const resource of win.dsc ?? []) {
146
+ const metadata = resource.winix;
147
+ if (metadata?.kind === "optional-features") {
148
+ for (const name of metadata.names) {
149
+ const key = name.toLowerCase();
150
+ if (features.has(key) && features.get(key) !== metadata.enabled) {
151
+ throw new Error(`Conflicting desired state for Windows optional feature: ${name}`);
152
+ }
153
+ features.set(key, metadata.enabled);
154
+ }
155
+ }
156
+ else if (metadata?.kind === "wsl-distro") {
157
+ distros++;
158
+ const { distro } = metadata;
159
+ const name = distro.name.toLowerCase();
160
+ const location = (typeof distro.installLocation === "string"
161
+ ? win32.normalize(distro.installLocation)
162
+ : JSON.stringify({ ...distro.installLocation, path: win32.normalize(distro.installLocation.path ?? "") })).toLowerCase();
163
+ if (names.has(name))
164
+ throw new Error(`Duplicate WSL distro: ${distro.name}`);
165
+ if (locations.has(location))
166
+ throw new Error("WSL distros cannot share an installLocation");
167
+ names.add(name);
168
+ locations.add(location);
169
+ if (distro.default)
170
+ defaults++;
171
+ }
172
+ else if (metadata?.kind === "file" && metadata.wslConfig) {
173
+ configs++;
174
+ }
175
+ }
176
+ if (defaults > 1)
177
+ throw new Error("Only one WSL distro can be declared default per Windows host");
178
+ if (configs > 1)
179
+ throw new Error("Declare only one windows.wsl({ config }) per Windows host");
180
+ if (distros && !WSL_FEATURES.every((name) => features.get(name) === true)) {
181
+ throw new Error("WSL distro provisioning requires windows.wsl() or both required optional features enabled");
182
+ }
183
+ if (distros && !Object.values(win.packages ?? {}).some((pkg) => pkg.id.toLowerCase() === "microsoft.wsl")) {
184
+ throw new Error('WSL distro provisioning requires windows.package("Microsoft.WSL")');
185
+ }
186
+ }
92
187
  function prepareWindowsDscResources(commands, resources) {
93
188
  const envResolvedResources = resolveManagedEnvironmentReferences(resources);
94
189
  if (!envResolvedResources.some((resource) => resource.winix?.kind === "setting")) {
@@ -539,6 +634,3 @@ function yamlQuoted(value) {
539
634
  function yamlStringArray(values) {
540
635
  return `[${values.map((value) => yamlQuoted(value)).join(", ")}]`;
541
636
  }
542
- function psSingleQuoted(value) {
543
- return `'${value.replace(/'/g, "''")}'`;
544
- }
@@ -1,5 +1,7 @@
1
1
  import type { EvaluatedHost } from "../../evaluator/index.js";
2
- import type { WinPackage, WinPackageSource } from "../../types/index.js";
2
+ import type { WinPackage, WinPackageSource, WinPowerShellModule } from "../../types/index.js";
3
+ import { type WslArchitecture, type WindowsWslImageResolver } from "./wsl.js";
4
+ import { type WindowsLockWslRepository, type WindowsWslRepositoryResolver } from "./wsl-setup.js";
3
5
  export declare const WINDOWS_LOCKFILE_NAME = "winix-windows.lock";
4
6
  export declare const WINDOWS_LOCK_VERSION = 1;
5
7
  export interface WindowsLockPackage {
@@ -11,7 +13,25 @@ export interface WindowsLock {
11
13
  version: typeof WINDOWS_LOCK_VERSION;
12
14
  generatedAt: string;
13
15
  packages: Record<string, WindowsLockPackage>;
16
+ /** PowerShell module names are case-insensitive, stored as lowercase keys. */
17
+ modules?: Record<string, WindowsLockModule>;
18
+ wslImages?: Record<string, WindowsLockWslImage>;
19
+ wslRepositories?: Record<string, WindowsLockWslRepository>;
14
20
  }
21
+ export interface WindowsLockWslImage {
22
+ source: "nixos-wsl";
23
+ architecture: WslArchitecture;
24
+ version: string;
25
+ url: string;
26
+ sha256: string;
27
+ resolvedAt: string;
28
+ }
29
+ export interface WindowsLockModule {
30
+ repository: string;
31
+ version: string;
32
+ resolvedAt: string;
33
+ }
34
+ export type WindowsModuleVersionResolver = (name: string, repository: string) => string;
15
35
  export type WindowsPackageVersionResolver = (id: string, source: WinPackageSource) => string;
16
36
  export interface WindowsLockResolution {
17
37
  id: string;
@@ -33,3 +53,18 @@ export declare function resolveMissingWindowsLockEntries(lock: WindowsLock, eval
33
53
  export declare function resolveWindowsLockEntries(lock: WindowsLock, packages: Iterable<WinPackage>, resolveVersion: WindowsPackageVersionResolver, now?: Date): WindowsLockResolutionResult;
34
54
  export declare function windowsLockChanged(before: WindowsLock, after: WindowsLock): boolean;
35
55
  export declare function serializeWindowsLock(lock: WindowsLock): string;
56
+ export declare function collectWindowsModules(hosts: EvaluatedHost[]): Map<string, WinPowerShellModule>;
57
+ export declare function hasWindowsWslDistros(hosts: EvaluatedHost[]): boolean;
58
+ export declare function resolveWindowsWslImages(lock: WindowsLock, resolve: WindowsWslImageResolver, now?: Date, missingOnly?: boolean): {
59
+ lock: WindowsLock;
60
+ changed: boolean;
61
+ };
62
+ export declare function resolveWindowsWslRepositories(lock: WindowsLock, hosts: EvaluatedHost[], resolve: WindowsWslRepositoryResolver, now?: Date, missingOnly?: boolean): {
63
+ lock: WindowsLock;
64
+ changed: boolean;
65
+ };
66
+ export declare function resolveWindowsModuleLockEntries(lock: WindowsLock, modules: Iterable<WinPowerShellModule>, resolveVersion: WindowsModuleVersionResolver, now?: Date, missingOnly?: boolean): {
67
+ lock: WindowsLock;
68
+ resolutions: Omit<WindowsLockResolution, "source">[];
69
+ changed: boolean;
70
+ };