moyun-ultimate/doctor.ps1
moyun d18db479b7 feat: 0.5.1 - two escape hatches and self-repair
The goal is users who dare to install it. Three additions:

1. doctor.ps1 -Fix
   Runs the 12 checks, then repairs what is safe to repair: re-copy the runtime
   copy, add exports["./client"], add the dependencies entry, sync missing
   skills. It deliberately does NOT touch the profile's own cordis.patch.yml
   (that could break other plugins) - it only prints a hint.

2. install.ps1 -Rollback
   Restores package.json from the newest package.json.bak-* and removes the
   plugin directories. One command back to the pre-install state.

3. Friendly install ending
   Prints the three next steps (quit/reopen, doctor, moyun_ultimate_profile)
   plus the two escape commands, instead of a single terse line.

doctor also detects and reports whether the install is in FULL or COMPLEMENT
mode by reading the bundle patch, so complement mode is no longer misreported.
2026-11-17 14:58:14 +08:00

334 lines
13 KiB
PowerShell

# moyun-ultimate doctor: checks install state, and with -Fix repairs what it can
# ASCII only (PS 5.1 reads BOM-less UTF-8 as ANSI).
[CmdletBinding()]
param(
[string]$Profile = 'desktop',
[string]$DshHome = '',
[switch]$Fix
)
$ErrorActionPreference = 'Continue'
$PkgName = 'moyun-ultimate'
$ok = 0; $warn = 0; $fail = 0
$fixable = New-Object System.Collections.Generic.List[string]
function Say($tag, $msg) {
switch ($tag) {
'OK' { Write-Host "[OK] $msg" -ForegroundColor Green; $script:ok++ }
'WARN' { Write-Host "[WARN] $msg" -ForegroundColor Yellow; $script:warn++ }
'FAIL' { Write-Host "[FAIL] $msg" -ForegroundColor Red; $script:fail++ }
'FIX' { Write-Host "[FIX] $msg" -ForegroundColor Cyan }
'INFO' { Write-Host " $msg" -ForegroundColor Gray }
}
}
Write-Host ""
Write-Host "moyun-ultimate doctor" -ForegroundColor Cyan
Write-Host "=====================" -ForegroundColor Cyan
Write-Host ""
# --- resolve DSH_HOME ---
if (-not $DshHome) {
if ($env:DSH_HOME) { $DshHome = $env:DSH_HOME }
elseif (Test-Path 'G:\DeepSeek_dsh') { $DshHome = 'G:\DeepSeek_dsh' }
elseif (Test-Path (Join-Path $env:USERPROFILE '.dsh')) { $DshHome = Join-Path $env:USERPROFILE '.dsh' }
}
if (-not $DshHome -or -not (Test-Path $DshHome)) {
Say FAIL "DSH_HOME not found. Pass -DshHome <path>."
exit 1
}
Say INFO "DSH_HOME = $DshHome"
$profileDir = Join-Path $DshHome "profiles\$Profile"
$pkgJson = Join-Path $profileDir 'package.json'
$plugDir = Join-Path $profileDir "plugins\$PkgName"
$runDir = Join-Path $profileDir "node_modules\$PkgName"
$profPatch = Join-Path $profileDir 'cordis.patch.yml'
if (-not (Test-Path $profileDir)) {
Say FAIL "profile dir not found: $profileDir"
exit 1
}
Say INFO "profile = $Profile"
if ($Fix) { Say INFO "-Fix mode : will repair what it can (backup created first)" }
Write-Host ""
# --- 1. runtime copy ---
if (Test-Path $runDir) {
$n = (Get-ChildItem $runDir -Recurse -File).Count
Say OK "runtime copy present: node_modules\$PkgName ($n files)"
} else {
Say FAIL "runtime copy MISSING: $runDir"
$fixable.Add('copy-runtime')
}
# --- 2. source copy ---
if (Test-Path $plugDir) {
$n = (Get-ChildItem $plugDir -Recurse -File).Count
Say OK "source copy present: plugins\$PkgName ($n files)"
} else {
Say WARN "source copy missing: plugins\$PkgName (runtime still works)"
$fixable.Add('copy-source')
}
# --- 3/4. package.json registration ---
$hasDep = $false
$hasBundle = $false
if (Test-Path $pkgJson) {
try {
$j = Get-Content $pkgJson -Raw -Encoding UTF8 | ConvertFrom-Json
$hasDep = $j.dependencies.PSObject.Properties.Name -contains $PkgName
$hasBundle = $j.dsh.profile.bundles -contains $PkgName
if ($hasDep) { Say OK "dependencies has $PkgName" } else { Say FAIL "dependencies MISSING $PkgName"; $fixable.Add('dep') }
if ($hasBundle) { Say OK "bundles has $PkgName" } else { Say FAIL "bundles MISSING $PkgName"; $fixable.Add('bundle') }
Say INFO "bundles total = $($j.dsh.profile.bundles.Count)"
} catch {
Say FAIL "package.json parse error: $($_.Exception.Message)"
}
} else {
Say FAIL "package.json not found: $pkgJson"
}
# --- 5. exports["./client"] ---
$runPkg = Join-Path $runDir 'package.json'
if (Test-Path $runPkg) {
try {
$rj = Get-Content $runPkg -Raw -Encoding UTF8 | ConvertFrom-Json
if ($rj.exports.'./client') {
Say OK "exports has './client' -> $($rj.exports.'./client')"
} else {
Say FAIL "exports MISSING './client' (status badge will not load)"
$fixable.Add('exports')
}
Say INFO "installed version = $($rj.version)"
} catch {
Say FAIL "runtime package.json parse error"
}
}
# --- 6. prompt files ---
$promptFiles = @(
'ultimatum-mode.md', '10-refusal-kernel.md', '20-execution.md',
'ultimatum-mode-mirror.md', '40-routing.md', '50-anticensor.md'
)
if (Test-Path $runDir) {
$missing = @()
foreach ($f in $promptFiles) {
if (-not (Test-Path (Join-Path $runDir "prompts\$f"))) { $missing += $f }
}
if ($missing.Count -eq 0) {
Say OK "six prompt layers present (6/6)"
} else {
Say FAIL "prompt files missing: $($missing -join ', ')"
$fixable.Add('copy-runtime')
}
$frameDir = Join-Path $runDir 'prompts\frames'
if (Test-Path $frameDir) {
$fc = (Get-ChildItem $frameDir -File).Count
Say OK "frames present ($fc files)"
} else {
Say WARN "frames dir missing"
}
}
# --- 7. permission layer config ---
$ownPatch = Join-Path $runDir 'cordis.patch.yml'
$mode = 'unknown'
if (Test-Path $ownPatch) {
$pt = Get-Content $ownPatch -Raw -Encoding UTF8
$hasSandbox = $pt -match 'id:\s*sandbox-policy'
$hasApproval = $pt -match 'id:\s*approval'
$hasPerm = $pt -match 'id:\s*permission'
if ($hasSandbox -and $hasApproval -and $hasPerm) {
$mode = 'full'
Say OK "permission layer config present -> mode: FULL"
if ($pt -match 'danger-full-access') { Say OK "sandbox mode is danger-full-access" }
} elseif ($pt -match 'COMPLEMENT MODE') {
$mode = 'complement'
Say OK "COMPLEMENT mode: permission layer yields to other plugins"
Say INFO " prompt layers + skills still apply; this is intentional, not a fault"
} else {
Say WARN "permission layer config incomplete"
}
} else {
Say FAIL "cordis.patch.yml missing in runtime copy"
$fixable.Add('copy-runtime')
}
# --- 8. approval answerer in index.js ---
$idx = Join-Path $runDir 'index.js'
if (Test-Path $idx) {
$it = Get-Content $idx -Raw -Encoding UTF8
if ($it -match 'installApprovalAnswerer') { Say OK "approval answerer code present" }
else { Say WARN "approval answerer code NOT found (old build?)" }
}
# --- 9. skills landed ---
$skillsDir = Join-Path $DshHome 'skills'
$want = 0
$srcSkills = Join-Path $runDir 'skills'
if (Test-Path $srcSkills) { $want = (Get-ChildItem $srcSkills -Directory).Count }
if (Test-Path $skillsDir) {
$sn = (Get-ChildItem $skillsDir -Directory).Count
Say INFO "skills in DSH_HOME\skills = $sn"
if ($want -gt 0) {
if ($sn -ge $want) { Say OK "skills synced ($sn >= $want)" }
else {
Say WARN "skills not fully synced ($sn of $want)"
$fixable.Add('skills')
}
}
} else {
Say WARN "DSH_HOME\skills not found"
$fixable.Add('skills')
}
# --- 10. user-layer override check ---
if (Test-Path $profPatch) {
$ut = Get-Content $profPatch -Raw -Encoding UTF8
$ovr = @()
foreach ($id in 'sandbox-policy', 'approval', 'permission') {
if ($ut -match ("-\s*id:\s*" + [regex]::Escape($id))) { $ovr += $id }
}
if ($ovr.Count -gt 0) {
Say WARN "user-layer profile/cordis.patch.yml overrides: $($ovr -join ', ')"
Say INFO " -> user layer applies AFTER bundle layer, so it wins."
Say INFO " Delete those blocks there, or run: .\switch-mode.ps1 -Mode complement"
Say INFO " (not auto-fixed: touching a profile's own config can break other plugins)"
} else {
Say OK "no user-layer override of permission ids"
}
} else {
Say INFO "no user-layer cordis.patch.yml (bundle layer wins by default)"
}
# --- 11. conflicting plugins (precise) ---
$CONFLICT_IDS = @('sandbox-policy', 'approval', 'permission', 'spill-policy', 'tool-result-pruner')
if (Test-Path $pkgJson) {
try {
$j = Get-Content $pkgJson -Raw -Encoding UTF8 | ConvertFrom-Json
$hard = @()
$scanned = 0
foreach ($b in @($j.dsh.profile.bundles)) {
if ($b -eq $PkgName) { continue }
$bp = Join-Path $profileDir "node_modules\$b\cordis.patch.yml"
if (-not (Test-Path $bp)) { continue }
$scanned++
$bt = Get-Content $bp -Raw -Encoding UTF8
$ids = @()
foreach ($m in [regex]::Matches($bt, '(?m)^\s*-?\s*id:\s*([A-Za-z0-9_\-]+)')) { $ids += $m.Groups[1].Value }
$hit = @($ids | Where-Object { $CONFLICT_IDS -contains $_ } | Sort-Object -Unique)
if ($hit.Count -gt 0) { $hard += ("$b(" + ($hit -join '/') + ")") }
}
if ($hard.Count -eq 0) {
Say OK "no permission-config conflict (scanned $scanned plugins)"
} else {
Say WARN ("hard conflict: " + ($hard -join ', '))
Say INFO " -> only one contender can own the permission layer; pick one"
if ($mode -eq 'full') { Say INFO " or run: .\switch-mode.ps1 -Mode complement" }
}
} catch {}
}
# ---------- FIX ----------
if ($Fix -and $fixable.Count -gt 0) {
Write-Host ""
Write-Host "=====================" -ForegroundColor Cyan
Write-Host "repairing $($fixable.Count) item(s)" -ForegroundColor Cyan
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
# backup package.json once
if ((Test-Path $pkgJson) -and ($fixable -contains 'dep' -or $fixable -contains 'bundle')) {
Copy-Item $pkgJson "$pkgJson.bak-doctor-$stamp" -Force
Say FIX "backup: package.json.bak-doctor-$stamp"
}
# copy-runtime / copy-source: re-copy from the package source next to this script
foreach ($k in @('copy-runtime', 'copy-source')) {
if ($fixable -contains $k) {
$dst = if ($k -eq 'copy-runtime') { $runDir } else { $plugDir }
if (Test-Path $here) {
if (Test-Path $dst) { Remove-Item $dst -Recurse -Force }
New-Item -ItemType Directory -Force -Path $dst | Out-Null
Copy-Item "$here\*" $dst -Recurse -Force
Say FIX "re-copied package files into $dst"
} else {
Say WARN "cannot re-copy: run this from the package directory"
}
}
}
# exports./client
if ($fixable -contains 'exports') {
try {
$rj = Get-Content $runPkg -Raw -Encoding UTF8 | ConvertFrom-Json
if (-not $rj.exports) {
$rj | Add-Member -NotePropertyName exports -NotePropertyValue ([pscustomobject]@{}) -Force
}
$rj.exports | Add-Member -NotePropertyName './client' -NotePropertyValue './client.js' -Force
[IO.File]::WriteAllText($runPkg, ($rj | ConvertTo-Json -Depth 10), (New-Object Text.UTF8Encoding($false)))
Say FIX "added exports['./client'] to runtime package.json"
} catch { Say WARN "could not patch exports: $($_.Exception.Message)" }
}
# dep / bundle
if ($fixable -contains 'dep' -or $fixable -contains 'bundle') {
$raw = Get-Content $pkgJson -Raw -Encoding UTF8
$out = New-Object System.Collections.Generic.List[string]
$depAdded = $false
foreach ($l in ($raw -split "`n")) {
if (-not $depAdded -and $fixable -contains 'dep' -and $l -match '^\s*"dependencies":\s*\{') {
$out.Add($l)
$out.Add(" `"$PkgName`": `"file:./plugins/$PkgName`",")
$depAdded = $true
continue
}
$out.Add($l)
}
[IO.File]::WriteAllText($pkgJson, ($out -join "`n"), (New-Object Text.UTF8Encoding($false)))
if ($fixable -contains 'dep') { Say FIX "added dependencies entry" }
if ($fixable -contains 'bundle') {
Say WARN "bundles entry must be added by the DSH plugin panel (it rewrites the list on save)"
}
}
# skills
if ($fixable -contains 'skills') {
try {
if (-not (Test-Path $skillsDir)) { New-Item -ItemType Directory -Force -Path $skillsDir | Out-Null }
$copied = 0
foreach ($d in (Get-ChildItem $srcSkills -Directory -ErrorAction SilentlyContinue)) {
$target = Join-Path $skillsDir $d.Name
if (-not (Test-Path $target)) {
Copy-Item $d.FullName $target -Recurse -Force
$copied++
}
}
Say FIX "synced $copied skill directories into DSH_HOME\skills"
} catch { Say WARN "skill sync failed: $($_.Exception.Message)" }
}
Write-Host ""
Say INFO "re-run doctor.ps1 to confirm; then fully quit and reopen DSH."
} elseif ($Fix) {
Write-Host ""
Write-Host "nothing to repair" -ForegroundColor Green
}
# --- summary ---
Write-Host ""
Write-Host "=====================" -ForegroundColor Cyan
Write-Host ("RESULT: OK={0} WARN={1} FAIL={2} MODE={3}" -f $ok, $warn, $fail, $mode) -ForegroundColor Cyan
Write-Host ""
if ($fail -gt 0) {
Write-Host "ACTION: fix the [FAIL] items above, then fully quit DSH and reopen." -ForegroundColor Red
if (-not $Fix) { Write-Host " or try: powershell -File .\doctor.ps1 -Fix" -ForegroundColor Yellow }
exit 2
} elseif ($warn -gt 0) {
Write-Host "ACTION: review [WARN] items. Plugin should still work." -ForegroundColor Yellow
exit 1
} else {
Write-Host "All good. Ask the agent to call moyun_ultimate_profile to confirm." -ForegroundColor Green
exit 0
}