From df9234daba4670a51bacb43c7e2d6c58b6db86e4 Mon Sep 17 00:00:00 2001 From: Robin Coe Date: Sat, 17 Oct 2026 00:01:17 -0400 Subject: [PATCH] #4: move xpq-claude-setup.sh and the xpq-wsl-network skill into the repo Both lived on OneDrive under xpq-project/config/. Code-related content belongs in the repos. The skill follows the repo layout: skills/xpq-wsl-network.md, with its PowerShell helper at scripts/wsl-net.ps1, run from the .xpq-org-main clone like the other skills. README documents the script, the skill and the symlink step. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 23 +++++- scripts/wsl-net.ps1 | 96 ++++++++++++++++++++++++ scripts/xpq-claude-setup.sh | 141 ++++++++++++++++++++++++++++++++++++ skills/xpq-wsl-network.md | 71 ++++++++++++++++++ 4 files changed, 330 insertions(+), 1 deletion(-) create mode 100644 scripts/wsl-net.ps1 create mode 100755 scripts/xpq-claude-setup.sh create mode 100644 skills/xpq-wsl-network.md diff --git a/README.md b/README.md index 5cf9493..d2e3743 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,8 @@ xpq-org/ │ ├── prune-local-branches.sh Delete local branches already on origin/dev or origin/main │ ├── xpq-branch-guard.sh PreToolUse hook: blocks edits when not on issue branch │ ├── xpq-pr-merge-guard.sh PreToolUse hook: blocks PR merges and pushes to main/master/dev +│ ├── xpq-claude-setup.sh Per-machine Claude Code setup: user-level guard hooks, deny rules +│ ├── wsl-net.ps1 Windows-side WSL networking switch, run by /xpq-wsl-network │ ├── pr-unresolved-threads.sh Lists a PR's unresolved review threads; exit 1 if any │ ├── install-hooks.sh Install the commit-msg hook into any git repo │ ├── hooks/ @@ -148,7 +150,8 @@ xpq-org/ │ ├── skills/ │ ├── xpquest-daily-log.md Claude Code skill: /xpquest-daily-log [DATE] -│ └── xpq-pr-review-cycle.md Claude Code skill: /xpq-pr-review-cycle [REPO N] +│ ├── xpq-pr-review-cycle.md Claude Code skill: /xpq-pr-review-cycle [REPO N] +│ └── xpq-wsl-network.md Claude Code skill: /xpq-wsl-network [status|mirrored|tailscale|nat] │ ├── SR_ED_CONVENTIONS.md Full conventions: issue types, labels, commit rules, SR&ED guidance └── README.md This file @@ -259,6 +262,12 @@ started inside a repo, such as `~/xpquest/xpq-api`, has neither guard. Launch fr or pass `--settings ~/xpquest/.claude/settings.json`. The `xpq-pr-review-cycle` skill probes for this before it does anything. +`scripts/xpq-claude-setup.sh` is the per-machine setup for these guards. Run it once on each +machine (`--dry-run` previews). It installs both guards as user-level hooks in +`~/.claude/settings.json`, adds deny rules for PR merges and local native builds, strips +allow rules that defeat the guards from every `settings.local.json` in the workspace, and +disables the synced plugins that are not used here. It needs `jq`. + The merge guard is a backstop against accidents and injected text, not a security boundary: it matches command text and does not see through variables, scripts or `--input` files. Text that merely mentions a blocked command (a commit message, a comment body) trips it too; pass @@ -335,6 +344,7 @@ Invoke from within a Claude Code session: | `/xpquest-daily-log [DATE]` | One date (default: yesterday). Always writes/overwrites. | | `/xpquest-daily-log --from DATE [--to DATE]` | Date range. Always writes/overwrites. | | `/xpq-pr-review-cycle [REPO N]` | Takes one open PR to "ready for you to merge" (below). | +| `/xpq-wsl-network [MODE]` | Sets WSL2 networking (mirrored, tailscale or nat) so the dev machines can reach each other. `status` changes nothing. | The skill reads the bash-generated `github_summary` as structured input, augments it with `gh issue view` body content (the PM/architecture "why"), reads Claude Code session JSONL @@ -357,6 +367,17 @@ mkdir -p ~/.claude/skills/xpq-pr-review-cycle ln -sfn ~/xpquest/.xpq-org-main/skills/xpq-pr-review-cycle.md ~/.claude/skills/xpq-pr-review-cycle/SKILL.md ``` +### `/xpq-wsl-network [MODE]` + +Switches this machine's WSL2 networking between mirrored, Tailscale and NAT. `scripts/wsl-net.ps1` +does the Windows-side work and needs admin, so the skill launches it through a UAC prompt. It +states what will change and waits for a yes, except for `status`. + +```bash +mkdir -p ~/.claude/skills/xpq-wsl-network +ln -sfn ~/xpquest/.xpq-org-main/skills/xpq-wsl-network.md ~/.claude/skills/xpq-wsl-network/SKILL.md +``` + --- ## Setting up a new repo diff --git a/scripts/wsl-net.ps1 b/scripts/wsl-net.ps1 new file mode 100644 index 0000000..1f5f4c1 --- /dev/null +++ b/scripts/wsl-net.ps1 @@ -0,0 +1,96 @@ +# wsl-net.ps1: switch this machine's WSL networking between mirrored, tailscale and nat. +# Run elevated (the skill launches it via UAC). Idempotent; backs up .wslconfig first. +# -Mode status read-only report +# -Mode mirrored .wslconfig networkingMode=mirrored + inbound allow rules for $Ports +# -Mode tailscale remove mirrored + rules (Tailscale runs inside WSL, NAT underneath) +# -Mode nat remove mirrored + rules (plain NAT) +# In every mode except status the legacy portproxy entries and the "WSL Port Forward 8080" +# task are removed; neither is wanted with mirrored, tailscale or a deliberate NAT setup. +param( + [Parameter(Mandatory)][ValidateSet('status','mirrored','tailscale','nat')][string]$Mode, + [int[]]$Ports = @(22), + [string]$LanCidr = '' +) +$ErrorActionPreference = 'Continue' +$cfg = Join-Path $env:USERPROFILE '.wslconfig' +$creator = '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' # WSL's Hyper-V VM creator id +$prefix = 'XPQ WSL inbound' + +function Get-LanCidr { + $route = Get-NetRoute -DestinationPrefix '0.0.0.0/0' | Sort-Object RouteMetric | Select-Object -First 1 + $ip = Get-NetIPAddress -InterfaceIndex $route.InterfaceIndex -AddressFamily IPv4 | Select-Object -First 1 + $b = [Net.IPAddress]::Parse($ip.IPAddress).GetAddressBytes() + $net = for ($i = 0; $i -lt 4; $i++) { + $bits = [math]::Max(0, [math]::Min(8, $ip.PrefixLength - 8 * $i)) + $b[$i] -band ((0xFF -shl (8 - $bits)) -band 0xFF) + } + "$($net -join '.')/$($ip.PrefixLength)" +} + +function Set-WslConfigKey([string]$Key, [string]$Value) { + $lines = if (Test-Path $cfg) { @(Get-Content $cfg) } else { @() } + if ($lines.Count) { Copy-Item $cfg "$cfg.bak-$(Get-Date -Format yyyyMMdd-HHmmss)" } + $out = New-Object System.Collections.Generic.List[string] + $in = $false; $done = $false; $hasSection = $false + foreach ($l in $lines) { + if ($l -match '^\s*\[(.+)\]\s*$') { + if ($in -and -not $done -and $Value) { $out.Add("$Key=$Value"); $done = $true } + $in = ($Matches[1] -eq 'wsl2'); if ($in) { $hasSection = $true } + } + if ($in -and $l -match "^\s*$Key\s*=") { + if ($Value -and -not $done) { $out.Add("$Key=$Value"); $done = $true } + continue + } + $out.Add($l) + } + if ($Value -and -not $done) { + if (-not $hasSection) { $out.Add('[wsl2]') } + $out.Add("$Key=$Value") + } + Set-Content -Path $cfg -Value $out +} + +function Remove-XpqRules { + Get-NetFirewallHyperVRule -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "$prefix*" } | Remove-NetFirewallHyperVRule + Get-NetFirewallRule -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "$prefix*" } | Remove-NetFirewallRule +} + +function Remove-LegacyProxy { + Unregister-ScheduledTask -TaskName 'WSL Port Forward 8080' -Confirm:$false -ErrorAction SilentlyContinue + netsh interface portproxy reset | Out-Null +} + +function Show-Status { + "host: $env:COMPUTERNAME" + "--- .wslconfig"; if (Test-Path $cfg) { Get-Content $cfg } else { '(none)' } + "--- portproxy"; netsh interface portproxy show all + "--- legacy task"; Get-ScheduledTask -TaskName 'WSL Port Forward 8080' -ErrorAction SilentlyContinue | Select-Object TaskName,State | Out-String + "--- hyper-v fw"; Get-NetFirewallHyperVVMSetting -PolicyStore ActiveStore -ErrorAction SilentlyContinue | Format-List Name,Enabled,DefaultInboundAction | Out-String + "--- XPQ hyper-v rules"; Get-NetFirewallHyperVRule -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "$prefix*" } | Format-Table Name,Enabled,Action,LocalPorts,RemoteAddresses -Auto | Out-String + "--- XPQ windows rules"; Get-NetFirewallRule -ErrorAction SilentlyContinue | Where-Object { $_.Name -like "$prefix*" } | Format-Table Name,Enabled,Profile -Auto | Out-String + "--- lan cidr"; Get-LanCidr +} + +if ($Mode -eq 'status') { Show-Status; return } + +Remove-LegacyProxy +Remove-XpqRules + +switch ($Mode) { + 'mirrored' { + if (-not $LanCidr) { $LanCidr = Get-LanCidr } + Set-WslConfigKey 'networkingMode' 'mirrored' + foreach ($p in $Ports) { + New-NetFirewallHyperVRule -Name "$prefix $p" -DisplayName "$prefix $p" -Direction Inbound -VMCreatorId $creator ` + -Protocol TCP -LocalPorts $p -RemoteAddresses $LanCidr -Action Allow | Out-Null + New-NetFirewallRule -Name "$prefix $p" -DisplayName "$prefix $p" -Direction Inbound -Protocol TCP -LocalPort $p ` + -RemoteAddress $LanCidr -Profile Private -Action Allow | Out-Null + } + "mirrored configured; allowed from $LanCidr on ports $($Ports -join ',')" + } + default { + Set-WslConfigKey 'networkingMode' '' + "$Mode configured; networkingMode removed from .wslconfig" + } +} +"Run 'wsl --shutdown' (from Windows) for the change to take effect." diff --git a/scripts/xpq-claude-setup.sh b/scripts/xpq-claude-setup.sh new file mode 100755 index 0000000..037a6d0 --- /dev/null +++ b/scripts/xpq-claude-setup.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash +# xpq-claude-setup.sh: per-machine Claude Code setup for the XP Quest workspace. +# +# Run once on each machine (flash, antman, any new one). Idempotent; every file it changes +# is backed up next to itself as .bak- first. +# +# 1. Installs the two guards as USER-level hooks (~/.claude/settings.json), so they load +# whatever directory a session is launched from. The merge guard is wrapped so it only +# runs for sessions under the workspace; the branch guard already scopes itself. +# 2. Adds built-in permissions.deny rules: gh pr merge, and local Quarkus native builds. +# Deny beats any allow rule and applies in every repo on the machine. +# 3. Removes allow rules that defeat the guards (gh pr *, bash *, python3 *, sh *, native +# builds) from every settings.local.json in the workspace. +# 4. Disables the claude.ai-synced plugins that are not used here. +# +# Usage: xpq-claude-setup.sh [--dry-run] [--keep-plugins] [--drop-workspace-hooks] +# --dry-run print what would change; write nothing +# --keep-plugins skip step 4 +# --drop-workspace-hooks also remove the hooks block from the shared workspace +# settings.json. That file is shared by every machine through +# OneDrive, so pass this only after ALL machines have run this +# script; until then a machine that has not would lose its guards. +# +# Env: XPQ_HOME (default ~/xpquest), XPQ_PLUGINS (space-separated plugin ids to disable). + +set -euo pipefail + +XPQ="${XPQ_HOME:-$HOME/xpquest}" +USER_SETTINGS="$HOME/.claude/settings.json" +WORKSPACE_SETTINGS="$XPQ/.claude/settings.json" +PLUGINS="${XPQ_PLUGINS:-operations@synced productivity@synced product-management@synced}" +STAMP=$(date +%Y%m%d-%H%M%S) + +DRY=0 KEEP_PLUGINS=0 DROP_WS_HOOKS=0 +for arg in "$@"; do + case "$arg" in + --dry-run) DRY=1 ;; + --keep-plugins) KEEP_PLUGINS=1 ;; + --drop-workspace-hooks) DROP_WS_HOOKS=1 ;; + *) echo "Unknown option: $arg" >&2; exit 2 ;; + esac +done + +command -v jq >/dev/null || { echo "jq is required (sudo apt install jq)" >&2; exit 2; } + +BRANCH_GUARD="$XPQ/xpq-org/scripts/xpq-branch-guard.sh" +MERGE_GUARD="$XPQ/xpq-org/scripts/xpq-pr-merge-guard.sh" +for f in "$BRANCH_GUARD" "$MERGE_GUARD"; do + [[ -f "$f" ]] || { echo "Missing guard script: $f (clone xpq-org first)" >&2; exit 2; } +done + +BRANCH_CMD="bash $BRANCH_GUARD" +MERGE_CMD="case \"\$PWD\" in $XPQ|$XPQ/*) exec bash $MERGE_GUARD ;; esac" + +DENY='[ + "Bash(gh pr merge)", + "Bash(gh pr merge *)", + "Bash(*mvn* -Dnative*)", + "Bash(*mvn* -Pnative*)", + "Bash(*quarkus build*--native*)" +]' + +# Applies a jq filter to a JSON file: prints a diff, backs up and writes unless --dry-run. +apply() { + local file=$1; shift + local new + new=$(jq "$@" "$file") + if [[ "$new" == "$(jq . "$file")" ]]; then + echo " unchanged: $file" + return + fi + diff <(jq . "$file") <(printf '%s\n' "$new") | sed 's/^/ /' || true + if (( DRY )); then + echo " would update: $file" + else + cp -p "$file" "$file.bak-$STAMP" + # Write through the path so a symlinked settings file stays a symlink. + printf '%s\n' "$new" > "$file" + echo " updated: $file (backup: $file.bak-$STAMP)" + fi +} + +echo "1+2. User-level hooks and deny rules" +mkdir -p "$(dirname "$USER_SETTINGS")" +[[ -f "$USER_SETTINGS" ]] || { (( DRY )) || echo '{}' > "$USER_SETTINGS"; } +if [[ -f "$USER_SETTINGS" ]]; then + apply "$USER_SETTINGS" \ + --arg branch "$BRANCH_CMD" --arg merge "$MERGE_CMD" --arg mguard "$MERGE_GUARD" \ + --arg bguard "$BRANCH_GUARD" --argjson deny "$DENY" ' + def entry($m; $c): {matcher: $m, hooks: [{type: "command", command: $c}]}; + # Drop any earlier entry for either guard, then add the current ones. + .hooks.PreToolUse = ( + [ (.hooks.PreToolUse // [])[] + | select(any(.hooks[]?; (.command // "") | (contains($mguard) or contains($bguard))) | not) ] + + [ entry("Write|Edit"; $branch), entry("Bash"; $merge) ] ) + | .permissions.deny = (((.permissions.deny // []) + $deny) | unique)' +else + echo " would create: $USER_SETTINGS" +fi + +echo "3. Allow rules that defeat the guards" +shopt -s nullglob +for f in "$XPQ/.claude/settings.local.json" "$XPQ"/*/.claude/settings.local.json \ + "$HOME/.claude/settings.local.json"; do + [[ -f "$f" ]] || continue + apply "$f" ' + if (.permissions.allow | type) == "array" then + .permissions.allow |= map(select( + (test("^Bash\\((gh pr( merge| create --base main)?|bash|sh|python3?)( \\*|:\\*)?\\)$") + or test("^Bash\\(gh pr (merge|create --base main)") + or test("-[DP]native")) | not)) + else . end' +done + +if (( DROP_WS_HOOKS )); then + echo "Workspace hooks (shared by all machines)" + if [[ -f "$WORKSPACE_SETTINGS" ]]; then + apply "$WORKSPACE_SETTINGS" 'del(.hooks)' + else + echo " not found: $WORKSPACE_SETTINGS" + fi +fi + +if (( ! KEEP_PLUGINS )); then + echo "4. Plugins" + if ! command -v claude >/dev/null; then + echo " claude not on PATH; skipped" + else + for p in $PLUGINS; do + if (( DRY )); then + echo " would run: claude plugin disable $p" + elif claude plugin disable "$p" >/dev/null 2>&1; then + echo " disabled: $p" + else + echo " not disabled (already off, not installed, or managed on claude.ai): $p" + fi + done + fi +fi + +echo "Done. Restart any running Claude Code sessions to pick up the changes." diff --git a/skills/xpq-wsl-network.md b/skills/xpq-wsl-network.md new file mode 100644 index 0000000..a53516f --- /dev/null +++ b/skills/xpq-wsl-network.md @@ -0,0 +1,71 @@ +--- +name: xpq-wsl-network +description: Set up WSL2 networking on an XP Quest dev machine (antman, flash) so the machines can reach each other. Modes - mirrored (default), tailscale, nat (revert). Run as /xpq-wsl-network [status|mirrored|tailscale|nat]. +--- + +# xpq-wsl-network + +Runs the same on every machine. Mirrored networking gives WSL the Windows host's LAN IP; +Tailscale runs inside WSL and works across networks. NAT is the vanilla WSL default. + +Argument: `status` (default if none), `mirrored`, `tailscale` or `nat`. Ask which if unclear. +Never change anything for `status`. For other modes, state what will change and wait for a +yes before running. + +## Mechanics + +`scripts/wsl-net.ps1` in the `~/xpquest/.xpq-org-main` clone does all Windows-side work. It needs admin; Claude's +PowerShell is not elevated, so launch it through UAC. The user must click Yes on the prompt. + +```bash +SCRIPT=~/xpquest/.xpq-org-main/scripts/wsl-net.ps1 +cp "$SCRIPT" "$(wslpath "$(cmd.exe /c 'echo %TEMP%' 2>/dev/null | tr -d '\r')")/wsl-net.ps1" +powershell.exe -NoProfile -Command "Start-Process powershell -Verb RunAs -Wait -ArgumentList '-NoProfile -ExecutionPolicy Bypass -Command \"& \$env:TEMP\\wsl-net.ps1 -Mode *> \$env:TEMP\\wsl-net.log\"'" +iconv -f UTF-16 -t UTF-8 "$(wslpath "$(cmd.exe /c 'echo %TEMP%' 2>/dev/null | tr -d '\r')")/wsl-net.log" +``` + +If the UAC prompt is declined, do not retry; give the user the commands to run in an admin +PowerShell instead. `status` needs no elevation: run the script with the same +`powershell.exe -File` form, without `-Verb RunAs`. + +What the script does, per mode: +- `mirrored`: sets `networkingMode=mirrored` in `%USERPROFILE%\.wslconfig` (other keys kept, + backup made), adds inbound-allow rules for TCP 22 scoped to the LAN subnet in BOTH the + Hyper-V firewall (default inbound is Block) and Windows Defender Firewall (Private profile). + Extra ports: `-Ports 22,3000`. Rule names start with `XPQ WSL inbound`. +- `tailscale` / `nat`: removes `networkingMode` and the XPQ rules. +- All modes except `status`: delete the legacy `WSL Port Forward 8080` task and reset + portproxy, since neither belongs with mirrored or tailscale. + +## Steps by mode + +### mirrored +1. Run the script with `-Mode mirrored`. +2. Warn that `wsl --shutdown` kills this session. Tell the user to run `wsl --shutdown` from + Windows, reopen WSL, then continue below. +3. In WSL: `ss -tln | grep ':22 '` must show a listener; if not, + `sudo systemctl enable --now ssh` (the OpenSSH server must be installed). +4. Verify from the other machine: `ping `, `ssh @`. Disconnect NordVPN + during the test; if it fixes things, enable its LAN-discovery setting. +5. If the hostname does not resolve, that is LAN DNS, not WSL: use router DNS reservations or + `/etc/hosts` / `C:\Windows\System32\drivers\etc\hosts` entries. + +### tailscale +1. Run the script with `-Mode tailscale` (leaves NAT networking, removes mirrored and rules). +2. After `wsl --shutdown`, in WSL (systemd must be on: `/etc/wsl.conf` has `[boot] systemd=true`): + `curl -fsSL https://tailscale.com/install.sh | sh`, then + `sudo tailscale up --ssh --hostname=-wsl`. Distinct hostnames avoid clashing with + a Windows-side Tailscale node. The user runs `tailscale up` themselves (`! sudo tailscale up ...`) + because it needs browser login. +3. Verify: `tailscale status`, then `ssh -wsl` from the other machine. +4. Check the choice against security-model.md before leaving it in place: it adds a + third-party control plane. + +### nat +Run the script with `-Mode nat`, then `wsl --shutdown`. Result: vanilla NAT, no XPQ rules. + +## Rules +- Both machines must end in the same mode; after changing one, remind the user to run this + skill on the other. +- Do not edit sshd settings or Windows sshd; this skill only owns WSL networking. +- Report the script log faithfully, including errors.