-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaudearium.ps1
More file actions
3850 lines (3565 loc) · 179 KB
/
claudearium.ps1
File metadata and controls
3850 lines (3565 loc) · 179 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env pwsh
# Entry point for the Claude Code WSL2 sandbox tool.
# Verb dispatch for setup / status / nuke / reconcile / profile / project /
# session / mount / tools / login / vpn / host-tools / hooks / claude-settings.
# Run with no args for the interactive central dashboard.
[CmdletBinding()]
param(
[Parameter(Position = 0)][string]$Verb,
[Parameter(Position = 1)][string]$SubVerb,
[Parameter(Position = 2)][string]$Arg,
[string]$Name = 'claudearium',
[string]$Base = 'debian-12',
[string]$ProfilePath,
[string]$RootfsPath,
[string]$RootfsUrl,
[string]$InstallPath,
[string]$Out,
[string]$Remote,
[string]$DefaultBranch,
[string]$Project,
[string]$Branch,
[string]$BaseBranch,
[string]$HostCheckout,
[string]$To,
[switch]$DiscardDirty,
[string]$Scope,
[switch]$DryRun,
[switch]$IncludeTodos,
[switch]$IncludePlans,
[string]$HostPath,
[string]$Guest,
[string]$Mode,
[string]$MountOptions,
[string]$HostExe,
[string]$GuestCommand,
[string]$SmokeTest,
[string[]]$HostShadows,
[switch]$HostProject,
[switch]$NewBranch,
[switch]$Force,
[switch]$NonInteractive,
[switch]$Help
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# Snapshot the SCRIPT'S bound parameters. Inside a function `$PSBoundParameters`
# rebinds to that function's bound params, so a script-level check like
# `$PSBoundParameters.ContainsKey('Name')` is silently always-false from inside
# Invoke-Setup / Resolve-DistroForOps / etc. We capture once here and let the
# verb functions read $Script:RootBoundParams instead.
$Script:RootBoundParams = $PSBoundParameters
$Script:ScriptRoot = $PSScriptRoot
$Script:ModulesDir = Join-Path $Script:ScriptRoot 'modules'
$Script:PayloadDir = Join-Path $Script:ScriptRoot 'payload'
$Script:ScriptsDir = Join-Path $Script:ScriptRoot 'scripts'
# Mark-of-the-Web: files extracted from a downloaded zip carry a
# Zone.Identifier alternate data stream that triggers "is not digitally
# signed" under the default RemoteSigned execution policy. The first launch
# uses claudearium.cmd with -ExecutionPolicy Bypass to get us this far;
# unblock the rest of the install tree so future direct .ps1 invocations
# work too. Write a sentinel afterwards so subsequent launches skip the
# tree walk. The sentinel is deleted by `update apply` so freshly-extracted
# files get unblocked on the next launch.
$Script:MotwSentinel = Join-Path $Script:ScriptRoot '.motw-unblocked'
if (-not (Test-Path -LiteralPath $Script:MotwSentinel -PathType Leaf)) {
try {
Get-ChildItem -LiteralPath $Script:ScriptRoot -Recurse -File -Force -ErrorAction SilentlyContinue |
Unblock-File -ErrorAction SilentlyContinue
New-Item -ItemType File -Path $Script:MotwSentinel -Force -ErrorAction SilentlyContinue | Out-Null
} catch { }
}
Import-Module (Join-Path $Script:ModulesDir 'State.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'UI.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'Wsl.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'Profile.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'Projects.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'Sessions.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'Mounts.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'Tools.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'Vpn.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'HostTools.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'HostShadows.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'ClaudeSettings.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'ClaudeFile.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'HostToolNotes.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'SelfUpdate.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'ToolUpdates.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'Prune.psm1') -Force
Import-Module (Join-Path $Script:ModulesDir 'Temp.psm1') -Force
Set-VpnPayloadRoot -Path $Script:PayloadDir
# Snapshot the wt tab title so we can prefix it with '*' when tool updates are
# available (and restore the original when there are none). The .cmd launcher
# sets this via `wt --title` (claudearium.cmd:23); honor CLAUDEARIUM_WT_TITLE
# overrides by capturing whatever is current rather than hardcoding.
$Script:BaseWtTitle = $null
try { $Script:BaseWtTitle = [string]$Host.UI.RawUI.WindowTitle } catch { }
function Show-Help {
@"
claudearium.ps1 <verb> [<sub-verb>] [<arg>] [options]
claudearium.ps1 # bare = interactive central dashboard
Verbs:
setup Create and provision the WSL2 sandbox distro.
status Show distro and sandbox state.
nuke Unregister the distro and remove all sandbox state.
reconcile Diff profile against state; prompt; apply.
prune [-Scope <a>] Drift detection + repair. -Scope sessions|worktrees|
mounts|artifacts|all. -DryRun to report only.
temp Print scratch sizes (/tmp, ~/.cache, ~/.claude).
temp size Same as bare.
temp clean -Scope <s> Wipe a scratch scope. -Scope tmp|cache|claude|all.
claude scope keeps todos/plans by default; pass
-IncludeTodos / -IncludePlans to wipe those too.
profile validate <path> Validate a profile (or the default profile if omitted).
profile export -Out <p> Write current state to a profile file at <p>.
profile edit [<path>] Open the profile in `$env:EDITOR (or VS Code, then notepad).
profile show [<path>] Pretty-print the parsed profile (with env-vars expanded).
project Bare = interactive dashboard.
project add [<name>] Add a project to the profile.
Default: distroProject — clones a bare mirror into the distro.
With -HostProject -HostCheckout C:\path: hostProject — uses
the Windows checkout directly, sessions are host-side
worktrees mounted into the distro, and -HostShadows
wraps host tools (default: pwsh, git) per-project.
Smart defaults: -HostCheckout / cwd's git origin URL.
project list Table of projects (profile + materialization status).
project remove <name> Delete bare mirror (or per-project bin dir for hostProjects),
sessions, and profile entry.
project move <name> Migrate a project between distro and host types in place.
-To host -HostCheckout <p>: distro -> host.
-To distro [-Remote <url>]: host -> distro (auto-detects
Remote from the existing hostCheckout's origin).
Refuses dirty sessions unless -DiscardDirty / -Force.
project show <name> Inspect a project's profile entry + mirror status.
session Bare = interactive dashboard.
session new <name> Create a worktree. -Project required; -Branch or -NewBranch + -BaseBranch.
session list Table of sessions across all projects (filter with -Project).
session remove <name> Remove a session's worktree. -Project required; -Force for dirty.
mount Bare = interactive dashboard.
mount add [<host-path>] Add a host folder mount via drvfs. -Guest, -Mode (ro|rw),
-MountOptions for extras (e.g. 'umask=077' for ~/.ssh).
mount list Table of mounts (profile + actual fstab state).
mount remove <guest> Drop a mount. Refuses if the mount is busy unless -Force.
mount sync Re-apply profile mounts to the distro idempotently.
tools Bare = interactive dashboard.
tools list Desired-vs-installed table for catalog tools.
tools install <name> Install one tool now; also marks enabled in profile.
tools attach <name> Attach the Windows-host copy of an OAuth-pain CLI
(gh/glab/acli/seqcli) as a drop-in /usr/local/bin/<name>
wrapper — reuses host auth instead of re-logging in WSL.
tools enable <name> Mark tool enabled in profile + install if missing.
tools disable <name> Mark tool disabled in profile (does NOT uninstall).
tools sync Install every enabled-but-missing tool from the profile.
login Bare = list available identity flows.
login claude Run 'claude' (first-run triggers OAuth).
login gh 'gh auth login'.
login glab 'glab auth login'.
login acli-jira 'acli jira auth login' (CLI-token Atlassian auth, Jira).
login acli-confluence 'acli confluence auth login' (CLI-token Atlassian auth, Confluence).
vpn Bare = status + interactive menu.
vpn enable Install payload (idempotent) and bring wg0 up.
vpn disable Bring wg0 down (killswitch stays armed; sandbox is offline).
vpn reload Restart killswitch-prep + nftables + wg-quick@wg0.
vpn status Print tunnel state, killswitch state, host.internal reachability.
vpn test Quick connectivity probes (host.internal + via-wg).
host-tools Bare = interactive dashboard.
host-tools add [<exe>] Register a Windows .exe as a guest command via WSL interop.
-HostExe / -GuestCommand / -SmokeTest flags.
host-tools list Profile + actual wrapper status.
host-tools remove <cmd> Drop the wrapper + profile entry.
host-tools sync Re-apply profile wrappers to the distro.
host-tools scan Detect OAuth-pain catalog CLIs (gh/glab/acli/seqcli) on
the Windows host PATH and offer to attach each as a
drop-in wrapper.
hooks test Run each registered host-tool's smokeTest.
claude-settings show Print /home/claude/.claude/settings.json.
claude-settings apply Apply profile.claudeSettings to the distro.
claude-settings reconfigure Interactive wizard, then apply.
update [check] Compare local version against the latest GitHub release.
update apply Download + install the latest release (preserves user files).
update status Show cached version info; no network call.
diagnostics Run the read-only diagnostic test lane (troubleshooting).
Common options:
-Name <distro> Distro name (default: 'claudearium' or profile.distro.name)
-Base <id> Distro base (default: 'debian-12')
-ProfilePath <path> Profile JSON file (default: %LOCALAPPDATA%\claudearium\claudearium.profile.json)
-InstallPath <path> Where to install (default: %LOCALAPPDATA%\WSL\<Name>)
-Out <path> Output path (used by 'profile export')
-RootfsPath / -RootfsUrl Override rootfs source for setup.
-Remote <url> Project remote URL (used by 'project add')
-DefaultBranch <b> Project default branch (default: master)
-HostCheckout <path> Auto-detect remote/branch from a host git checkout (distroProject),
or the working tree for a hostProject when combined with -HostProject.
-HostProject Register as a hostProject (sessions live on the host, not the distro).
-HostShadows <names> Host tools to wrap for a hostProject (default: pwsh,git).
-Project <name> Project name (used by session verbs)
-Branch <b> Branch to check out (session new)
-NewBranch Create a new branch when starting the session
-BaseBranch <b> Base for -NewBranch (default: profile project's defaultBranch)
-HostPath <path> Windows path to mount (mount add)
-Guest <path> Linux mount point (default: /host/<basename>)
-Mode <ro|rw> Mount mode (default: ro)
-MountOptions <opts> Extra drvfs options appended after the defaults
-NonInteractive Don't prompt; use defaults / fail if input would be required.
-Force Override safety checks.
Examples:
.\claudearium.ps1 setup
.\claudearium.ps1 status
.\claudearium.ps1 reconcile
.\claudearium.ps1 project add -HostCheckout C:\src
.\claudearium.ps1 project list
.\claudearium.ps1 session new feat-1234 -Project acme -Branch feature/PROJ-1234-some-feature -NewBranch -BaseBranch master
.\claudearium.ps1 session list -Project acme
.\claudearium.ps1 session remove feat-1234 -Project acme -Force
"@
}
function Resolve-ProfilePath {
if ($ProfilePath) { return (Resolve-Path -LiteralPath $ProfilePath -ErrorAction SilentlyContinue)?.Path ?? $ProfilePath }
return (Get-DefaultProfilePath)
}
function Get-Editor {
# $env:EDITOR (POSIX-style) wins, then VS Code, then notepad.
if ($env:EDITOR) { return $env:EDITOR }
$code = Get-Command code -ErrorAction SilentlyContinue
if ($code) { return $code.Source }
$codeCmd = Get-Command code.cmd -ErrorAction SilentlyContinue
if ($codeCmd) { return $codeCmd.Source }
$np = Get-Command notepad.exe -ErrorAction SilentlyContinue
if ($np) { return $np.Source }
throw 'No editor found. Set $env:EDITOR or install VS Code (`code` on PATH).'
}
function Read-ProfileIfPresent {
# Returns parsed+validated profile hashtable, or $null if no profile / invalid.
# Prints warnings; throws on validation errors.
$path = Resolve-ProfilePath
if (-not (Test-Path $path)) { return $null }
$spec = Read-Profile -Path $path
$v = Test-Profile -Spec $spec
foreach ($w in $v.Warnings) { Write-Host " profile warn: $w" -ForegroundColor DarkYellow }
if (-not $v.IsValid) {
Write-Host " Profile $path is invalid:" -ForegroundColor Red
foreach ($e in $v.Errors) { Write-Host " error: $e" -ForegroundColor Red }
throw "Profile validation failed at $path"
}
return $spec
}
function Resolve-InstallPath {
if ($InstallPath) { return $InstallPath }
if (-not $env:LOCALAPPDATA) { throw 'LOCALAPPDATA is not set.' }
return (Join-Path $env:LOCALAPPDATA (Join-Path 'WSL' $Name))
}
function Get-PayloadFile {
param([Parameter(Mandatory)][string]$RelativePath)
$p = Join-Path $Script:PayloadDir $RelativePath
if (-not (Test-Path $p)) { throw "Payload file missing: $p" }
return $p
}
function Get-ScriptFile {
param([Parameter(Mandatory)][string]$RelativePath)
$p = Join-Path $Script:ScriptsDir $RelativePath
if (-not (Test-Path $p)) { throw "Script file missing: $p" }
return $p
}
function Send-FileToDistro {
param(
[Parameter(Mandatory)][string]$DistroName,
[Parameter(Mandatory)][string]$SourcePath,
[Parameter(Mandatory)][string]$DestPath,
[string]$Mode = '0644'
)
# Transport via base64 in the command-line arg, not stdin. PowerShell's pipe to
# native commands re-inserts CRLF on Windows even after we LF-normalize the
# content — base64 is pure ASCII and survives that round-trip intact, and we
# also strip CR on the bash side as a belt-and-braces guard for shell scripts.
$bytes = [IO.File]::ReadAllBytes($SourcePath)
# Some text editors / git autocrlf leave CRLF in payload files; normalize on the
# source side so the rest of the pipeline can stay binary-safe.
if ($DestPath -like '*.sh' -or $DestPath -like '/etc/wsl.conf' -or $DestPath -like '/etc/*.conf') {
$text = [Text.Encoding]::UTF8.GetString($bytes)
$text = $text -replace "`r`n", "`n" -replace "`r", "`n"
$bytes = [Text.Encoding]::UTF8.GetBytes($text)
}
$b64 = [Convert]::ToBase64String($bytes)
$parent = (Split-Path -Parent $DestPath) -replace '\\','/'
$cmd = "set -e; mkdir -p '$parent'; printf '%s' '$b64' | base64 -d > '$DestPath'; chmod $Mode '$DestPath'"
Invoke-InDistro -Name $DistroName -User 'root' -Command $cmd
}
function Invoke-Setup {
# If a profile exists and the user didn't explicitly override on the CLI,
# take distro.name / distro.installPath from it.
$spec = Read-ProfileIfPresent
if ($spec) {
if (-not $Script:RootBoundParams.ContainsKey('Name')) { $script:Name = [string]$spec.distro.name }
if (-not $Script:RootBoundParams.ContainsKey('InstallPath')) { $script:InstallPath = [string]$spec.distro.installPath }
Write-Host " Profile in use: $(Resolve-ProfilePath)" -ForegroundColor DarkGray
}
Write-Host ""
Write-Host "=== Claudearium: setup '$Name' ===" -ForegroundColor Cyan
$distroExists = Test-DistroExists -Name $Name
$stateExists = Test-State -DistroName $Name
if (($distroExists -or $stateExists) -and -not $Force) {
Write-Host " Distro '$Name' or its state already exists." -ForegroundColor Yellow
Write-Host " Re-run with -Force to wipe and re-setup, or pick a different -Name." -ForegroundColor Yellow
return
}
if ($Force -and ($distroExists -or $stateExists)) {
Write-Host " -Force: removing existing distro and state for '$Name'."
if ($distroExists) { Unregister-Distro -Name $Name }
if ($stateExists) { Remove-State -DistroName $Name }
}
$installDir = Resolve-InstallPath
Write-Host " Install path: $installDir"
# Resolve rootfs
$tempDir = Join-Path ([IO.Path]::GetTempPath()) "claudearium-setup-$([guid]::NewGuid().ToString('N').Substring(0,8))"
# .NET API (literal + idempotent); wsl2-gotchas #19.
[void][System.IO.Directory]::CreateDirectory($tempDir)
try {
if ($RootfsPath) {
# -LiteralPath on both Test-Path and Resolve-Path so a user-supplied
# rootfs path containing wildcard glyphs ([, ], *) isn't expanded
# by the provider; wsl2-gotchas #19.
if (-not (Test-Path -LiteralPath $RootfsPath -PathType Leaf)) { throw "RootfsPath does not exist: $RootfsPath" }
$srcRootfs = (Resolve-Path -LiteralPath $RootfsPath).Path
Write-Host " Using local rootfs: $srcRootfs"
}
else {
$url = $RootfsUrl
if (-not $url) {
Write-Host " Resolving latest Debian 12 rootfs from images.linuxcontainers.org..."
$url = Resolve-LatestDebianRootfsUrl
}
$srcRootfs = Join-Path $tempDir 'rootfs.tar.xz'
Save-Rootfs -Url $url -DestPath $srcRootfs
}
# WSL --import wants plain .tar; convert if compressed.
$plainTar = Join-Path $tempDir 'rootfs.tar'
Convert-RootfsToTar -SourcePath $srcRootfs -DestPath $plainTar
Write-Host " Importing distro (this can take a minute)..."
Import-Distro -Name $Name -RootfsPath $plainTar -InstallPath $installDir
Write-Host " Pushing /etc/wsl.conf and bootstrap script..."
Send-FileToDistro -DistroName $Name -SourcePath (Get-PayloadFile 'etc/wsl.conf') -DestPath '/etc/wsl.conf' -Mode '0644'
Send-FileToDistro -DistroName $Name -SourcePath (Get-ScriptFile 'bootstrap-distro.sh') -DestPath '/root/bootstrap.sh' -Mode '0755'
Write-Host " Running bootstrap inside the distro (apt-get update + base packages)..."
& wsl.exe -d $Name -u root -- bash -lc '/root/bootstrap.sh'
if ($LASTEXITCODE -ne 0) { throw "bootstrap-distro.sh failed (exit $LASTEXITCODE)" }
Write-Host " Terminating distro to apply wsl.conf (default user = claude)..."
Stop-Distro -Name $Name
Write-Host " Verifying default user..."
$whoami = (& wsl.exe -d $Name -- whoami).Trim()
if ($whoami -ne 'claude') {
throw "Expected default user 'claude', got '$whoami'."
}
$state = Initialize-State -DistroName $Name
$state.installPath = $installDir
$state.provisioned = $true
# If we consumed a profile, remember it for next time.
$profPath = Resolve-ProfilePath
if (Test-Path $profPath) { Add-Recent -State $state -Key 'profilePaths' -Value $profPath }
Write-State -DistroName $Name -State $state
# Offer to seed the account-level CLAUDE.md. Only prompts when the
# profile doesn't already pin a mode (so re-running setup with -Force
# respects an earlier choice).
$profileHasClaudeFile = $spec -and $spec.ContainsKey('claudeFile') -and $spec.claudeFile
if (-not $profileHasClaudeFile -and -not $NonInteractive) {
try { Invoke-ClaudeFileSetupPrompt -DistroName $Name }
catch { Write-Host " CLAUDE.md seed step failed: $($_.Exception.Message)" -ForegroundColor Yellow }
}
elseif ($profileHasClaudeFile) {
try { Install-ClaudeFile -DistroName $Name -Spec $spec.claudeFile }
catch { Write-Host " Could not apply profile.claudeFile: $($_.Exception.Message)" -ForegroundColor Yellow }
}
# Offer to attach OAuth-pain catalog tools (gh/glab/acli/seqcli) from
# the Windows host if they're detected on PATH. Saves the in-WSL re-auth
# dance. Skip in NonInteractive — the user can always run
# 'host-tools scan' later.
if (-not $NonInteractive) {
try { Invoke-HostToolsScan }
catch { Write-Host " Host-tools scan failed: $($_.Exception.Message)" -ForegroundColor Yellow }
}
Write-Host ""
Write-Host "Setup complete. State: $(Get-StatePath -DistroName $Name)" -ForegroundColor Green
Write-Host "Open a shell: wsl -d $Name" -ForegroundColor Green
}
finally {
if (Test-Path $tempDir) { Remove-Item -LiteralPath $tempDir -Recurse -Force -ErrorAction SilentlyContinue }
}
}
function Invoke-Status {
Write-Host ""
Write-Host "=== Claudearium: status '$Name' ===" -ForegroundColor Cyan
$distroState = Get-DistroState -Name $Name
$stateExists = Test-State -DistroName $Name
$state = if ($stateExists) { Read-State -DistroName $Name } else { $null }
Write-Host (" Distro: {0}" -f $Name)
Write-Host (" WSL state: {0}" -f $distroState)
Write-Host (" State file: {0}" -f (Get-StatePath -DistroName $Name))
Write-Host (" State present: {0}" -f $stateExists)
if ($state) {
Write-Host (" Provisioned: {0}" -f $state.provisioned)
Write-Host (" Install path: {0}" -f ($state.installPath ?? '(unknown)'))
Write-Host (" Created at: {0}" -f $state.createdAt)
Write-Host (" Updated at: {0}" -f $state.updatedAt)
}
Write-Host ""
}
function Invoke-Nuke {
Write-Host ""
Write-Host "=== Claudearium: nuke '$Name' ===" -ForegroundColor Cyan
$distroExists = Test-DistroExists -Name $Name
$stateExists = Test-State -DistroName $Name
$state = if ($stateExists) { Read-State -DistroName $Name } else { $null }
if (-not $distroExists -and -not $stateExists) {
Write-Host " Nothing to nuke." -ForegroundColor Yellow
return
}
if (-not $Force) {
$ok = Read-YesNo -Prompt " Unregister distro '$Name' and delete all sandbox state?" -Default $false -NonInteractive:$NonInteractive
if (-not $ok) { Write-Host " Aborted." -ForegroundColor Yellow; return }
}
if ($distroExists) {
Write-Host " Unregistering distro..."
Unregister-Distro -Name $Name
}
if ($state -and $state.installPath -and (Test-Path $state.installPath)) {
Write-Host " Removing install dir: $($state.installPath)"
Remove-Item -LiteralPath $state.installPath -Recurse -Force -ErrorAction SilentlyContinue
}
if ($stateExists) {
Write-Host " Removing state..."
Remove-State -DistroName $Name
}
Write-Host "Nuked." -ForegroundColor Green
}
function Invoke-ProjectsApply {
# Apply a projects-block diff against a running distro. Mutates $State in
# place (sessions get cleaned up when their project is removed). Branches
# on project type: distroProjects get a bare-mirror clone, hostProjects
# get a shadow-bin-dir + init.sh deployment.
#
# `remove` actions cover two cases: (a) the entry was deleted from the
# profile (drift) — $desired is null; or (b) the entry is still present
# but marked enabled=false — $desired carries the profile spec. The host
# teardown path needs hostCheckout to run `git worktree remove`, so case
# (b) gets a proper session-by-session teardown while case (a) falls back
# to a state-only cleanup (worktrees are orphaned on the Windows side,
# documented in the plan as the trade-off for editing the profile by hand).
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$DistroName,
[Parameter(Mandatory)][hashtable]$State,
[Parameter(Mandatory)][hashtable]$Diff,
[AllowNull()][object[]]$DesiredProjects
)
$hostTeardownHappened = $false
foreach ($c in $Diff.Changes) {
$projectName = ($c.Path -replace '^projects\.', '') -replace '\.remote$', ''
$desired = $null
if ($DesiredProjects) {
$desired = @(@($DesiredProjects) | Where-Object { [string]$_.name -eq $projectName })[0]
}
$type = Get-ProjectType -ProjectSpec $desired
switch ($c.Action) {
'add' {
if (-not $desired) { continue }
if ($type -eq 'host') {
# hostProject: deploy the per-project bin dir + init.sh.
# No mirror clone happens; the host checkout is the source.
Write-Host " registering hostProject '$projectName' ..."
Invoke-HostProjectApply -DistroName $DistroName -ProjectSpec $desired
Add-Recent -State $State -Key 'projectNames' -Value $projectName
} else {
Write-Host " cloning project '$projectName' ..."
New-ProjectMirror -DistroName $DistroName -ProjectName $projectName -Remote ([string]$desired.remote)
Add-Recent -State $State -Key 'projectNames' -Value $projectName
Add-Recent -State $State -Key 'remotes' -Value ([string]$desired.remote)
}
}
'remove' {
# When the disable case provides $desired and it's a host
# entry, do a per-session `git worktree remove` first so the
# Windows-side worktrees aren't orphaned. Then drop the bin
# dir and clear the state records, same as the drift case.
$isHost = (Test-HostShadowsDirExists -DistroName $DistroName -ProjectName $projectName)
if ($isHost) {
Write-Host " removing hostProject '$projectName' (bin dir + sessions, hostCheckout untouched) ..."
if ($desired -and $type -eq 'host') {
$sessionNames = @()
foreach ($s in (Get-Sessions -State $State -Project $projectName)) {
if ($s -is [hashtable] -and $s.ContainsKey('name')) { $sessionNames += [string]$s.name }
}
foreach ($sname in $sessionNames) {
try {
Remove-HostSession -State $State -ProjectSpec $desired -Name $sname -Force
} catch {
Write-Host " warn: could not remove session '$sname': $_" -ForegroundColor Yellow
}
}
}
Remove-HostShadowsForProject -DistroName $DistroName -ProjectName $projectName
Remove-SessionsForProject -State $State -Project $projectName
$hostTeardownHappened = $true
} else {
Write-Host " removing project '$projectName' (and its sessions) ..."
Remove-ProjectMirror -DistroName $DistroName -ProjectName $projectName
Remove-SessionsForProject -State $State -Project $projectName
}
}
'modify' {
Write-Host " '$($c.Path)' changed: do 'project remove $projectName' then 'project add'." -ForegroundColor Yellow
}
}
}
# Refresh the fstab managed block when a host teardown happened. Persist
# state first so Invoke-MergedMountsApply's Read-State sees the just-
# cleared sessions and removes their mount entries.
if ($hostTeardownHappened) {
Write-State -DistroName $DistroName -State $State
Invoke-MergedMountsApply -DistroName $DistroName
}
}
function Test-HostShadowsDirExists {
# Probe whether /home/claude/host-projects/<project>/ exists; that's the
# only signal in the distro that a profile entry was previously applied
# as a hostProject (distroProjects live under /home/claude/mirrors/).
[CmdletBinding()]
param([Parameter(Mandatory)][string]$DistroName, [Parameter(Mandatory)][string]$ProjectName)
$q = ConvertTo-BashQuoted "/home/claude/host-projects/$ProjectName"
$r = Invoke-InDistro -Name $DistroName -User 'claude' -Command "test -d $q" -AllowFail -CaptureOutput
return ($r.ExitCode -eq 0)
}
function Set-ClaudeSettingsInProfile {
# Insert/replace the claudeSettings block on disk, env-token-preserving.
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$ProfilePath,
[Parameter(Mandatory)][hashtable]$Spec
)
$p = if (Test-Path $ProfilePath) { Read-Profile -Path $ProfilePath -Raw } else {
@{
schemaVersion = 1
distro = @{ name = 'claudearium'; base = 'debian-12'; installPath = '%LOCALAPPDATA%\WSL\claudearium' }
}
}
$p['claudeSettings'] = $Spec
Write-Profile -Path $ProfilePath -Spec $p
}
function Invoke-ClaudeSettingsApply {
$distro = Resolve-DistroForOps
if (-not (Test-DistroExists -Name $distro)) { throw "Distro '$distro' missing." }
$spec = Read-ProfileIfPresent
if (-not $spec -or -not $spec.ContainsKey('claudeSettings') -or -not $spec.claudeSettings) {
Write-Host " No claudeSettings in profile. Run 'claude-settings reconfigure' first." -ForegroundColor Yellow
return
}
Write-Host ' Installing /home/claude/.claude/settings.json ...'
Install-ClaudeSettings -DistroName $distro -Spec $spec.claudeSettings
Write-Host 'Claude Code settings applied.' -ForegroundColor Green
}
function Invoke-ClaudeSettingsShow {
$distro = Resolve-DistroForOps
if (-not (Test-DistroExists -Name $distro)) { Write-Host "Distro '$distro' missing." -ForegroundColor Yellow; return }
Invoke-InDistro -Name $distro -User 'claude' -Command 'cat /home/claude/.claude/settings.json 2>/dev/null || echo "(no settings.json)"'
}
function Invoke-ClaudeSettingsReconfigure {
$distro = Resolve-DistroForOps
# Pre-populate from existing claudeSettings if present.
$current = @{}
$existing = $null
try {
$spec = Read-ProfileIfPresent
if ($spec -and $spec.ContainsKey('claudeSettings') -and $spec.claudeSettings) { $existing = $spec.claudeSettings }
} catch { }
if ($existing) { foreach ($k in $existing.Keys) { $current[$k] = $existing[$k] } }
Write-Host ''
Write-Host '=== Claude Code settings wizard ===' -ForegroundColor Cyan
# 1. Model
$modelChoices = @('claude-opus-4-7', 'claude-sonnet-4-6', 'claude-haiku-4-5')
$defModelIdx = if ($current.ContainsKey('model') -and ($modelChoices -contains [string]$current.model)) {
[Array]::IndexOf($modelChoices, [string]$current.model)
} else { 0 }
$model = Read-Choice -Prompt 'Default model:' -Options $modelChoices -DefaultIndex $defModelIdx -NonInteractive:$NonInteractive
$current.model = $model
# 2. Effort
$effortChoices = @('low','medium','high','xhigh')
$defEffortIdx = if ($current.ContainsKey('defaultEffort') -and ($effortChoices -contains [string]$current.defaultEffort)) {
[Array]::IndexOf($effortChoices, [string]$current.defaultEffort)
} else { 3 } # 'xhigh' default for sandbox use
$effort = Read-Choice -Prompt 'Default thinking effort (xhigh recommended for sandbox use):' -Options $effortChoices -DefaultIndex $defEffortIdx -NonInteractive:$NonInteractive
$current.defaultEffort = $effort
# 3. Theme
$themeChoices = @('dark','light','system')
$defThemeIdx = if ($current.ContainsKey('theme') -and ($themeChoices -contains [string]$current.theme)) {
[Array]::IndexOf($themeChoices, [string]$current.theme)
} else { 0 }
$current.theme = Read-Choice -Prompt 'Theme:' -Options $themeChoices -DefaultIndex $defThemeIdx -NonInteractive:$NonInteractive
# 4-6. Auto-approve buckets
$current.autoApproveReadOnlyBash = Read-YesNo -Prompt 'Auto-approve read-only Bash (git status, ls, cat, gh, glab, acli, ...)?' -Default ($(if ($current.ContainsKey('autoApproveReadOnlyBash')) { [bool]$current.autoApproveReadOnlyBash } else { $true })) -NonInteractive:$NonInteractive
$current.autoApproveProjectWrites = Read-YesNo -Prompt 'Auto-approve project-scoped writes (Edit/Write/Glob/Grep)?' -Default ($(if ($current.ContainsKey('autoApproveProjectWrites')) { [bool]$current.autoApproveProjectWrites } else { $true })) -NonInteractive:$NonInteractive
$current.autoApproveBuildCommands = Read-YesNo -Prompt 'Auto-approve build commands (dotnet build/test, npm install, ...)?' -Default ($(if ($current.ContainsKey('autoApproveBuildCommands')) { [bool]$current.autoApproveBuildCommands } else { $false })) -NonInteractive:$NonInteractive
# 7. Claudelk
$hasClaudelk = $false
try {
$spec = Read-ProfileIfPresent
if ($spec -and $spec.ContainsKey('hostTools')) {
$hasClaudelk = [bool](@($spec.hostTools) | Where-Object { [string]$_.guestCommand -eq 'sb-claudelk' })
}
} catch { }
$claudelkDefault = if ($current.ContainsKey('claudelk')) { [bool]$current.claudelk } else { $hasClaudelk }
$current.claudelk = Read-YesNo -Prompt 'Wire Claudelk LED hooks?' -Default $claudelkDefault -NonInteractive:$NonInteractive
if ($current.claudelk) {
$eventOptions = @(
@{ Name = 'Stop'; Selected = $true; Hint = 'session ends' }
@{ Name = 'Notification'; Selected = $true; Hint = 'attention needed' }
@{ Name = 'PreToolUse'; Selected = $false; Hint = 'on every tool call (very noisy)' }
@{ Name = 'SessionStart'; Selected = $false; Hint = 'on session start' }
)
# Pre-set selection from current.claudelkEvents
if ($current.ContainsKey('claudelkEvents') -and $current.claudelkEvents) {
$existingEvents = @($current.claudelkEvents | ForEach-Object { [string]$_ })
foreach ($o in $eventOptions) { $o.Selected = ($existingEvents -contains $o.Name) }
}
$picked = Read-Multi -Prompt 'Which Claudelk events?' -Options $eventOptions -NonInteractive:$NonInteractive
$current.claudelkEvents = @($picked)
}
# 8. Extended thinking on by default
$current.alwaysThinkingEnabled = Read-YesNo -Prompt 'Always-on extended thinking (recommended with xhigh effort)?' -Default ($(if ($current.ContainsKey('alwaysThinkingEnabled')) { [bool]$current.alwaysThinkingEnabled } else { $true })) -NonInteractive:$NonInteractive
# 9. Auto-updates channel
$channelChoices = @('stable','latest')
$defChannelIdx = if ($current.ContainsKey('autoUpdatesChannel') -and ($channelChoices -contains [string]$current.autoUpdatesChannel)) {
[Array]::IndexOf($channelChoices, [string]$current.autoUpdatesChannel)
} else { 0 }
$current.autoUpdatesChannel = Read-Choice -Prompt 'Claude Code release channel:' -Options $channelChoices -DefaultIndex $defChannelIdx -NonInteractive:$NonInteractive
# 10. Bypass-permissions mode (--dangerously-skip-permissions)
$current.disableBypassPermissionsMode = Read-YesNo -Prompt 'Forbid --dangerously-skip-permissions (recommended for sandbox)?' -Default ($(if ($current.ContainsKey('disableBypassPermissionsMode')) { [bool]$current.disableBypassPermissionsMode } else { $true })) -NonInteractive:$NonInteractive
# 11. TUI renderer
$tuiChoices = @('fullscreen','default')
$defTuiIdx = if ($current.ContainsKey('tui') -and ($tuiChoices -contains [string]$current.tui)) {
[Array]::IndexOf($tuiChoices, [string]$current.tui)
} else { 0 }
$current.tui = Read-Choice -Prompt 'Terminal renderer:' -Options $tuiChoices -DefaultIndex $defTuiIdx -NonInteractive:$NonInteractive
# 12. Default shell
$shellChoices = @('bash','powershell')
$defShellIdx = if ($current.ContainsKey('defaultShell') -and ($shellChoices -contains [string]$current.defaultShell)) {
[Array]::IndexOf($shellChoices, [string]$current.defaultShell)
} else { 0 }
$current.defaultShell = Read-Choice -Prompt 'Default shell for Claude Bash invocations:' -Options $shellChoices -DefaultIndex $defShellIdx -NonInteractive:$NonInteractive
# 13. Default permission mode (under permissions.{})
$modeChoices = @('default','acceptEdits','plan','bypassPermissions')
$currentMode = ''
if ($current.ContainsKey('permissions') -and $current.permissions -is [hashtable] -and $current.permissions.ContainsKey('defaultMode')) {
$currentMode = [string]$current.permissions.defaultMode
}
$defModeIdx = if ($currentMode -and ($modeChoices -contains $currentMode)) {
[Array]::IndexOf($modeChoices, $currentMode)
} else { 0 }
$pickedMode = Read-Choice -Prompt 'Default permission mode:' -Options $modeChoices -DefaultIndex $defModeIdx -NonInteractive:$NonInteractive
if (-not ($current.ContainsKey('permissions') -and $current.permissions -is [hashtable])) {
$current.permissions = @{}
}
$current.permissions.defaultMode = $pickedMode
Set-ClaudeSettingsInProfile -ProfilePath (Resolve-ProfilePath) -Spec $current
Write-Host ' Profile updated.' -ForegroundColor Green
if (Test-DistroExists -Name $distro) {
Install-ClaudeSettings -DistroName $distro -Spec $current
Write-Host '/home/claude/.claude/settings.json installed.' -ForegroundColor Green
}
}
function Invoke-ClaudeSettings {
if (-not $SubVerb) {
Write-Host "claude-settings subverbs: show | apply | reconfigure" -ForegroundColor Yellow
return
}
switch ($SubVerb.ToLowerInvariant()) {
'show' { Invoke-ClaudeSettingsShow }
'apply' { Invoke-ClaudeSettingsApply }
'reconfigure' { Invoke-ClaudeSettingsReconfigure }
default {
Write-Host "Unknown claude-settings subverb: $SubVerb" -ForegroundColor Red
Write-Host "Subverbs: show | apply | reconfigure"
exit 64
}
}
}
function Set-ClaudeFileInProfile {
# Insert/replace the claudeFile block on disk, env-token-preserving. When
# the profile file doesn't exist yet (e.g. `setup -Name custom` on a host
# that's never seen claudearium), seed the distro block from the actual
# caller-supplied name + install path — NOT the hardcoded 'claudearium'
# defaults — so subsequent `reconcile` runs target the right distro.
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$ProfilePath,
[Parameter(Mandatory)][hashtable]$Spec,
[string]$SeedDistroName,
[string]$SeedInstallPath
)
$p = if (Test-Path $ProfilePath) { Read-Profile -Path $ProfilePath -Raw } else {
$seedName = if ($SeedDistroName) { $SeedDistroName } else { $Name }
$seedInstall = if ($SeedInstallPath) { $SeedInstallPath } else { (Resolve-InstallPath) }
@{
schemaVersion = 1
distro = @{ name = $seedName; base = 'debian-12'; installPath = $seedInstall }
}
}
$p['claudeFile'] = $Spec
Write-Profile -Path $ProfilePath -Spec $p
}
function Invoke-ClaudeFileSetupPrompt {
# Called once during setup (only when profile.claudeFile is absent) to ask
# how the account-level CLAUDE.md should be seeded inside the distro:
# 1. host-copy — only offered when `claude` is on host PATH AND the host
# file exists at $env:USERPROFILE\.claude\CLAUDE.md
# 2. caveman-lite — literal "be brief." one-liner
# 3. custom-path — copy from a user-supplied Windows path
# 4. skip — leave the distro file unmanaged (no profile entry)
# Choice is persisted to the profile so reconcile picks up host-side edits
# later.
[CmdletBinding()]
param([Parameter(Mandatory)][string]$DistroName)
if ($NonInteractive) { return }
$hostPath = Get-HostClaudeFilePath
$hostAvailable = (Test-HostClaudeAvailable) -and (Test-Path -LiteralPath $hostPath)
Write-Host ''
Write-Host '=== Seed account-level CLAUDE.md ===' -ForegroundColor Cyan
Write-Host ' This is the per-user CLAUDE.md inside the distro at'
Write-Host ' /home/claude/.claude/CLAUDE.md. Pick one of:'
$options = [System.Collections.Generic.List[string]]::new()
$modes = [System.Collections.Generic.List[string]]::new()
if ($hostAvailable) {
[void]$options.Add("Copy from host ($hostPath)")
[void]$modes.Add('host-copy')
}
[void]$options.Add("Caveman-lite mode (just 'be brief.')")
[void]$modes.Add('caveman-lite')
[void]$options.Add('Provide a custom path')
[void]$modes.Add('custom-path')
[void]$options.Add('Skip')
[void]$modes.Add('skip')
$choice = Read-Choice -Prompt 'Choice:' -Options $options.ToArray() -DefaultIndex ($options.Count - 1) -NonInteractive:$NonInteractive
$mode = $modes[$options.IndexOf($choice)]
if ($mode -eq 'skip') {
Write-Host ' Skipped — distro CLAUDE.md is unmanaged.' -ForegroundColor DarkGray
return
}
$spec = @{ mode = $mode }
if ($mode -eq 'custom-path') {
while ($true) {
$entry = (Read-Host ' Windows path to CLAUDE.md').Trim()
if ([string]::IsNullOrWhiteSpace($entry)) {
Write-Host ' Aborted.' -ForegroundColor Yellow
return
}
if (Test-Path -LiteralPath $entry) {
$spec['path'] = $entry
break
}
Write-Host " Not found: $entry" -ForegroundColor Yellow
}
}
Set-ClaudeFileInProfile -ProfilePath (Resolve-ProfilePath) -Spec $spec `
-SeedDistroName $DistroName -SeedInstallPath (Resolve-InstallPath)
Write-Host ' Profile updated.' -ForegroundColor Green
Install-ClaudeFile -DistroName $DistroName -Spec $spec
Write-Host " /home/claude/.claude/CLAUDE.md installed (mode: $mode)." -ForegroundColor Green
}
function Invoke-ClaudeFileApply {
# Apply profile.claudeFile to the distro idempotently. No-op when the block
# is absent (we treat absence as "unmanaged" — never blow away a file the
# user placed manually).
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$DistroName,
[AllowNull()]$Spec
)
if (-not $Spec) { return }
Install-ClaudeFile -DistroName $DistroName -Spec $Spec
}
function Invoke-HostToolsApply {
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$DistroName,
[Parameter(Mandatory)][hashtable]$State,
[Parameter(Mandatory)][hashtable]$Diff,
[AllowNull()]$DesiredTools
)
$desiredByCmd = @{}
foreach ($t in @($DesiredTools)) {
if ($t) { $desiredByCmd[[string]$t.guestCommand] = $t }
}
foreach ($c in $Diff.Changes) {
$gc = ($c.Path -replace '^hostTools\.', '') -replace '\.windowsExe$', ''
switch ($c.Action) {
'add' {
$t = $desiredByCmd[$gc]
if (-not $t) { continue }
Write-Host " installing host-tool wrapper '$gc' -> $($t.windowsExe)"
Install-HostToolWrapper -DistroName $DistroName -ToolSpec $t
Add-Recent -State $State -Key 'hostExePaths' -Value ([string]$t.windowsExe)
}
'modify' {
$t = $desiredByCmd[$gc]
if (-not $t) { continue }
Write-Host " rewriting host-tool wrapper '$gc' -> $($t.windowsExe)"
Install-HostToolWrapper -DistroName $DistroName -ToolSpec $t
Add-Recent -State $State -Key 'hostExePaths' -Value ([string]$t.windowsExe)
}
'remove' {
Write-Host " removing host-tool wrapper '$gc'"
Remove-HostToolWrapper -DistroName $DistroName -GuestCommand $gc
}
}
}
}
function Invoke-ToolsApply {
# Apply a tools-diff against a running distro. Walks dependency edges via
# Install-Tool, which installs missing deps eagerly.
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$DistroName,
[Parameter(Mandatory)][hashtable]$State,
[Parameter(Mandatory)][hashtable]$Diff,
[AllowNull()]$DesiredTools
)
if (-not $DesiredTools) { return }
foreach ($c in $Diff.Changes) {
if ($c.Action -ne 'add') { continue } # only handles installs (no auto-uninstall)
$name = ($c.Path -replace '^tools\.', '')
$entry = $DesiredTools[$name]
if (-not $entry) { continue }
$ver = if ($entry.ContainsKey('version')) { [string]$entry.version } else { 'latest' }
Install-Tool -DistroName $DistroName -Name $name -Version $ver
Add-Recent -State $State -Key 'toolNames' -Value $name
}
}
function Invoke-MountsApply {
# Apply a hostMounts diff. All operations are non-destructive in-place
# (just /etc/fstab + umount/mount). The destructive sense ("you lose data
# inside a removed mount") is the user's call, not the kernel's.
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$DistroName,
[Parameter(Mandatory)][hashtable]$State,
[AllowNull()]$DesiredMounts
)
Set-HostMountsInDistro -DistroName $DistroName -Mounts $DesiredMounts
# Recents: track recently used host paths for future interactive pickers.
if ($DesiredMounts) {
foreach ($m in @($DesiredMounts)) {
Add-Recent -State $State -Key 'hostMountPaths' -Value ([string]$m.host)
}
}
}
function Invoke-Reconcile {
$path = Resolve-ProfilePath
Write-Host ''
Write-Host '=== Claudearium: reconcile ===' -ForegroundColor Cyan
Write-Host " Profile: $path"
if (-not (Test-Path $path)) {
Write-Host " Profile not found." -ForegroundColor Yellow
Write-Host " Create one with: .\claudearium.ps1 profile edit" -ForegroundColor Yellow
return
}
$spec = Read-ProfileIfPresent
if (-not $spec) { return }
$targetName = [string]$spec.distro.name
Write-Host " Target: distro '$targetName'"
if (-not (Test-State -DistroName $targetName)) {
Write-Host ''
Write-Host " Distro '$targetName' has no recorded state — run 'setup' first." -ForegroundColor Yellow
Write-Host " (setup will use this profile automatically.)" -ForegroundColor Yellow
return
}
$state = Read-State -DistroName $targetName
$distroDiff = Get-DistroBlockDiff -DesiredDistro $spec.distro -CurrentState $state
$actualProjects = @()
if ((Get-DistroState -Name $targetName) -ne 'Missing') {
$actualProjects = Get-ProjectsActualFromDistro -DistroName $targetName
}
$desiredProjects = @()
if ($spec.ContainsKey('projects') -and $null -ne $spec.projects) {
$desiredProjects = @($spec.projects)
}
$projectsDiff = Get-ProjectsDiff -DesiredProjects $desiredProjects -ActualProjects $actualProjects
$actualMounts = @()
if ((Get-DistroState -Name $targetName) -ne 'Missing') {
$actualMounts = Get-HostMountsActualFromDistro -DistroName $targetName
}
# Diff against the merged set (profile mounts ∪ active hostProject session
# mounts) so reconcile doesn't see session-derived fstab entries as "user
# mounts that drifted out of profile" and unmount them.
$desiredMounts = Get-MergedDesiredMounts -ProfileSpec $spec -State $state
$mountsDiff = Get-HostMountsDiff -DesiredMounts $desiredMounts -ActualMounts $actualMounts
$actualTools = @()
if ((Get-DistroState -Name $targetName) -ne 'Missing') {
$actualTools = Get-ToolsActualFromDistro -DistroName $targetName
}
$desiredTools = $null
if ($spec.ContainsKey('tools') -and $spec.tools -is [hashtable]) { $desiredTools = $spec.tools }
$toolsDiff = Get-ToolsDiff -DesiredTools $desiredTools -ActualTools $actualTools
$actualHostTools = @()
if ((Get-DistroState -Name $targetName) -ne 'Missing') {