Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
feat(installer): bulletproof zero-prereq one-click installer (#99)
Beenu Arora0612a2261f81
diff --git a/.github/workflows/installer-smoke.yml b/.github/workflows/installer-smoke.ymlnew file mode 100644index 000000000..d8450925c--- /dev/null+++ b/.github/workflows/installer-smoke.yml@@ -0,0 +1,387 @@+name: Installer Smoke++# Gates regressions in the one-click installer. Three layers, fastest first:+#+# 1. Lint — shellcheck on the bash side, PSScriptAnalyzer on the PowerShell+# side, plus `bash -n`/`pwsh -NoProfile -Command` parse-only checks.+# Catches obvious typos, missing quoting, $args shadowing, etc., in+# under a minute.+#+# 2. Diagnose — runs `./install.sh --diagnose --non-interactive` inside+# clean containers for every distro family the installer claims to+# support (Ubuntu, Debian, Fedora, Alpine, Arch, openSUSE). The+# preflight library is allowed to fail (the runner doesn't have a real+# Docker daemon inside the container) — what we're asserting is that+# the script *parses, loads, runs preflight without crashing, and+# exits with one of the documented codes (0 success, 4 preflight+# failure)*. A 1/2/3 (prereq install / docker daemon / demo phase)+# means the script blew past preflight when it shouldn't have, which+# is the actual regression we care about.+#+# Windows preflight is checked in a 3rd job on a windows-latest runner+# because `pwsh` on linux can't accurately exercise winget/WSL paths.+#+# 3. (Future) Full install — actually run `./install.sh --no-launch` in+# a privileged container with a real dockerd. Slow + flaky to set up+# on hosted runners, so deferred to a nightly workflow rather than a+# PR gate.+#+# This workflow runs on any change to the installer surface AND on a+# weekly schedule, so we catch upstream rot (a new shellcheck release+# flagging a previously-clean construct, a distro removing a package+# we relied on, etc.) before a contributor does.++on:+ pull_request:+ branches: [main, develop]+ paths:+ - 'install.sh'+ - 'install.ps1'+ - 'uninstall.sh'+ - 'uninstall.ps1'+ - 'scripts/install/**'+ - '.github/workflows/installer-smoke.yml'+ push:+ branches:+ - main+ - 'release/**'+ - 'hotfix/**'+ paths:+ - 'install.sh'+ - 'install.ps1'+ - 'uninstall.sh'+ - 'uninstall.ps1'+ - 'scripts/install/**'+ - '.github/workflows/installer-smoke.yml'+ schedule:+ # Mondays 06:00 UTC — catches "it broke on its own" upstream changes.+ - cron: '0 6 * * 1'+ workflow_dispatch: {}++concurrency:+ group: ${{ github.workflow }}-${{ github.ref }}+ cancel-in-progress: true++jobs:+ lint-bash:+ name: Lint bash (shellcheck + parse)+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@v6++ - name: shellcheck+ run: |+ # Pinned to the runner's bundled shellcheck. We don't pull a+ # newer release here on purpose — we want CI to match what a+ # contributor's `apt install shellcheck` gives them on Ubuntu+ # LTS. If a newer release flags something, that's noise to+ # triage in a separate PR, not a surprise gate.+ shellcheck --version+ shellcheck install.sh+ shellcheck uninstall.sh+ shellcheck scripts/install/preflight.sh++ - name: bash -n parse-only check+ run: |+ # Belt-and-braces: shellcheck rarely misses syntax errors but+ # `bash -n` catches the few it does (notably bash 4+ syntax that+ # would explode on macOS bash 3.2).+ bash -n install.sh+ bash -n uninstall.sh+ bash -n scripts/install/preflight.sh++ - name: Bash 3.2 compatibility (macOS-style) parse+ run: |+ # macOS still ships bash 3.2.57 by default and we promise to+ # support it. Easiest way to catch a bash-4-only construct is+ # to disable POSIX-mode extensions and run the parser in+ # compat31 mode. Not bulletproof but cheap insurance.+ bash --version | head -1+ BASH_COMPAT=3.1 bash -n install.sh+ BASH_COMPAT=3.1 bash -n scripts/install/preflight.sh++ lint-powershell:+ name: Lint PowerShell (PSScriptAnalyzer + parse)+ runs-on: windows-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@v6++ - name: PSScriptAnalyzer+ shell: pwsh+ run: |+ # PSScriptAnalyzer ships with the windows-latest runner image.+ # We treat warnings as warnings (Information output) but error+ # on Errors. This stays loose on style and strict on bugs.+ $version = (Get-Module -ListAvailable PSScriptAnalyzer | Sort-Object Version -Descending | Select-Object -First 1).Version+ Write-Host "PSScriptAnalyzer $version"++ $files = @(+ 'install.ps1',+ 'uninstall.ps1',+ 'scripts/install/preflight.ps1'+ )++ # Rules we deliberately disable, with rationale so future-us+ # doesn't re-enable them and wonder why CI exploded:+ #+ # PSAvoidUsingWriteHost — we use Write-Host on purpose for+ # user-facing installer output (goes to the console host,+ # not the success/error/info streams a parent script might+ # be piping). Documented approved pattern for interactive+ # scripts.+ #+ # PSUseShouldProcessForStateChangingFunctions — would force+ # -WhatIf/-Confirm onto every install function. We have+ # explicit Confirm-Action prompts + -NonInteractive parameter+ # handling instead, which is more honest about the granularity+ # of confirmation an installer actually needs.+ #+ # PSUseApprovedVerbs — preflight.ps1 uses the Pf-* prefix as+ # an internal namespace marker (Pf-CheckRam, Pf-Summary, etc.).+ # "Pf" isn't an approved verb, but renaming all of them to+ # Test-PfRam etc. would be a large cosmetic diff and the+ # functions are all script-scoped. install.ps1 and uninstall.ps1+ # use proper approved verbs everywhere.+ $excludeRules = @(+ 'PSAvoidUsingWriteHost',+ 'PSUseShouldProcessForStateChangingFunctions',+ 'PSUseApprovedVerbs'+ )++ $errorCount = 0+ foreach ($f in $files) {+ Write-Host ""+ Write-Host "== $f =="+ $results = Invoke-ScriptAnalyzer -Path $f -Severity @('Error','Warning') -ExcludeRule $excludeRules+ if ($null -ne $results) {+ $results | Format-Table -AutoSize+ $errs = @($results | Where-Object { $_.Severity -eq 'Error' })+ $errorCount += $errs.Count+ } else {+ Write-Host "clean"+ }+ }+ if ($errorCount -gt 0) {+ Write-Host ""+ Write-Host "PSScriptAnalyzer found $errorCount error(s)." -ForegroundColor Red+ exit 1+ }++ - name: Parse-only check (AST)+ shell: pwsh+ run: |+ # Parse via the PowerShell AST. Catches syntax errors the+ # analyzer doesn't surface as Errors (e.g. mismatched braces).+ $files = @(+ 'install.ps1',+ 'uninstall.ps1',+ 'scripts/install/preflight.ps1'+ )+ $bad = 0+ foreach ($f in $files) {+ $tokens = $errors = $null+ [System.Management.Automation.Language.Parser]::ParseFile(+ (Resolve-Path $f).Path, [ref]$tokens, [ref]$errors+ ) | Out-Null+ if ($errors.Count -gt 0) {+ Write-Host "Parse errors in ${f}:" -ForegroundColor Red+ $errors | ForEach-Object {+ Write-Host " Line $($_.Extent.StartLineNumber): $($_.Message)"+ }+ $bad+++ } else {+ Write-Host "$f parses cleanly"+ }+ }+ if ($bad -gt 0) { exit 1 }++ diagnose-linux:+ name: --diagnose in clean ${{ matrix.distro }}+ runs-on: ubuntu-latest+ timeout-minutes: 10+ needs: lint-bash+ strategy:+ fail-fast: false+ matrix:+ # Each entry: a distro family + the package-manager bootstrap+ # the installer's preflight needs (curl + ca-certs + procps for+ # `ps`/port checks; tar/gzip on alpine for the install path it+ # may eventually exercise). We deliberately do NOT pre-install+ # docker/git/node — the script should be tolerant of their+ # absence in --diagnose mode (preflight reports them, doesn't+ # try to install).+ include:+ - distro: ubuntu-24.04+ image: ubuntu:24.04+ bootstrap: 'apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates procps lsof iproute2 file'+ - distro: ubuntu-22.04+ image: ubuntu:22.04+ bootstrap: 'apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates procps lsof iproute2 file'+ - distro: debian-12+ image: debian:12+ bootstrap: 'apt-get update && apt-get install -y --no-install-recommends bash curl ca-certificates procps lsof iproute2 file'+ - distro: fedora-40+ image: fedora:40+ bootstrap: 'dnf install -y bash curl ca-certificates procps-ng lsof iproute file'+ - distro: alpine-3.20+ image: alpine:3.20+ bootstrap: 'apk add --no-cache bash curl ca-certificates procps lsof iproute2 file coreutils'+ - distro: archlinux+ image: archlinux:latest+ bootstrap: 'pacman -Sy --noconfirm bash curl ca-certificates procps-ng lsof iproute2 file'+ - distro: opensuse-leap+ image: opensuse/leap:15.6+ bootstrap: 'zypper --non-interactive install bash curl ca-certificates procps lsof iproute2 file'++ steps:+ - uses: actions/checkout@v6++ - name: Run --diagnose in ${{ matrix.image }}+ run: |+ # Mount the checkout into the container and run preflight only.+ # We accept exit codes 0 (preflight passed) and 4 (preflight+ # found something it doesn't like, which on a stripped-down+ # CI container is *expected* — no docker, no swap, etc.). What+ # we reject is anything that means the script crashed or fell+ # through preflight into the install phase: 1, 2, 3, or any+ # signal-style 13X. Those are the regressions that ship angry+ # users.+ set -e+ # `cleanup` traps so we always print logs even on the unhappy+ # paths, and so the docker rm doesn't leak across matrix legs+ # if the runner's reused.+ cid=""+ cleanup() { [ -n "$cid" ] && docker rm -f "$cid" >/dev/null 2>&1 || true; }+ trap cleanup EXIT++ docker pull --quiet "${{ matrix.image }}"+ # Outer shell is POSIX `sh` (not `bash`) on purpose — the alpine+ # base image doesn't ship bash, so `bash -lc '...'` would fail+ # at container-init *before* the bootstrap step even runs (the+ # whole point of which is to apk-add bash). The wrapper itself+ # only uses POSIX sh constructs (set -e, [ ], ||, if/fi). The+ # actual installer is still invoked via `bash` because by then+ # the bootstrap step has installed it.+ cid=$(docker create \+ --workdir /aisoc \+ -v "$PWD:/aisoc:ro" \+ "${{ matrix.image }}" \+ sh -lc '+ set -e+ echo "--- bootstrap ---"+ ${{ matrix.bootstrap }}+ echo "--- diagnose ---"+ # --non-interactive so the installer never tries to read+ # stdin (which would hang). Capture exit code without+ # tripping `set -e`.+ rc=0+ bash /aisoc/install.sh --diagnose --non-interactive || rc=$?+ echo "--- exit code: $rc ---"+ # 0 = preflight clean; 4 = preflight failed (acceptable in CI+ # where there is no docker daemon, real ports are not in use,+ # etc. — we just want preflight to RUN). Anything else is a+ # script-level regression.+ if [ "$rc" -eq 0 ] || [ "$rc" -eq 4 ]; then+ echo "OK: documented exit code $rc"+ exit 0+ fi+ echo "REGRESSION: undocumented exit code $rc from --diagnose" >&2+ exit 1+ '+ )+ docker start --attach "$cid"++ diagnose-windows:+ name: -Diagnose on windows-latest+ runs-on: windows-latest+ timeout-minutes: 10+ needs: lint-powershell+ steps:+ - uses: actions/checkout@v6++ - name: Run -Diagnose -NonInteractive+ shell: pwsh+ run: |+ # Exit code policy mirrors the linux job: 0 = preflight clean,+ # 4 = preflight failed for environment reasons (CI runners+ # don't always have Docker Desktop / WSL2 in the state our+ # preflight expects). Anything else is a regression.+ $rc = 0+ try {+ & .\install.ps1 -Diagnose -NonInteractive+ $rc = $LASTEXITCODE+ } catch {+ Write-Host "Caught exception:" -ForegroundColor Yellow+ Write-Host $_.Exception.Message+ $rc = 1+ }+ Write-Host ""+ Write-Host "exit code: $rc"+ if ($rc -eq 0 -or $rc -eq 4) {+ Write-Host "OK: documented exit code $rc"+ exit 0+ }+ Write-Host "REGRESSION: undocumented exit code $rc from -Diagnose" -ForegroundColor Red+ exit 1++ uninstaller-safety:+ name: Uninstaller safety refusal exit code+ runs-on: ubuntu-latest+ timeout-minutes: 5+ needs: lint-bash+ steps:+ - uses: actions/checkout@v6++ - name: Refuse to nuke a non-AiSOC directory+ run: |+ # Spin up a clean ubuntu container, set up a fake $HOME/aisoc+ # directory that does NOT look like an AiSOC clone (no compose+ # file, no package.json), then run the uninstaller from a+ # neutral cwd with --repo --yes. The script should:+ # 1. Fail to locate a real clone (no compose marker anywhere).+ # 2. Fall through to the canonical $HOME/aisoc path.+ # 3. See the dir exists but lacks the AiSOC marker.+ # 4. Refuse to delete it and exit with code 3.+ # This is the regression that, if it ever flips back to exit 0,+ # silently turns "I refused to delete this" into "all clean!"+ # for any CI/scripted caller.+ set -e+ docker run --rm \+ -v "$PWD:/aisoc-src:ro" \+ ubuntu:24.04 \+ bash -lc '+ set -e+ apt-get update >/dev/null+ apt-get install -y --no-install-recommends bash curl ca-certificates >/dev/null++ # Copy the uninstaller out of the read-only mount so its+ # BASH_SOURCE-based self-discovery does NOT find the real+ # checkout (which IS a valid AiSOC clone and would be a+ # legitimate delete target).+ cp /aisoc-src/uninstall.sh /tmp/uninstall.sh+ chmod +x /tmp/uninstall.sh++ # Make a fake $HOME/aisoc that is NOT an AiSOC clone.+ export HOME=/root+ mkdir -p "$HOME/aisoc"+ echo "fake content" > "$HOME/aisoc/somefile"++ # Run from /tmp (not from the real checkout) so+ # find_repo() falls through cleanly.+ cd /tmp+ rc=0+ bash /tmp/uninstall.sh --repo --yes || rc=$?+ echo "uninstaller exit code: $rc"++ if [ "$rc" -ne 3 ]; then+ echo "REGRESSION: expected exit 3 (safety refusal), got $rc" >&2+ exit 1+ fi+ if [ ! -f "$HOME/aisoc/somefile" ]; then+ echo "REGRESSION: uninstaller deleted the file even though it refused!" >&2+ exit 1+ fi+ echo "OK: uninstaller correctly refused with exit 3 and left $HOME/aisoc intact"+ 'diff --git a/docs/QUICK_INSTALL.md b/docs/QUICK_INSTALL.mdindex 130ccaa7c..a010ff22b 100644--- a/docs/QUICK_INSTALL.md+++ b/docs/QUICK_INSTALL.md@@ -91,27 +91,89 @@ the `docker` group to take effect.### `install.sh` (Linux + macOS)```text---no-install Skip the dependency-install phase (use what's on PATH).---no-launch Set everything up but don't run pnpm aisoc:demo at the end.---no-pull Forwarded to aisoc:demo to skip image pull.---rebuild Forwarded to aisoc:demo to build images from source.---clone-dir DIR Where to clone the repo when running as a one-liner.- Default: $HOME/aisoc---branch BR Git branch to clone. Default: main.---help Show this text and exit.+--no-install Skip the dependency-install phase (use what's on PATH).+--no-launch Set everything up but don't run pnpm aisoc:demo at the end.+--no-pull Forwarded to aisoc:demo to skip image pull.+--rebuild Forwarded to aisoc:demo to build images from source.+--clone-dir DIR Where to clone the repo when running as a one-liner.+ Default: $HOME/aisoc+--branch BR Git branch to clone. Default: main.+--skip-preflight Skip the up-front environment checks and dive straight in.+ Use only if you know your machine is fine and preflight is+ misdiagnosing it.+--diagnose Run preflight only and exit. No installs, no clone, no+ Docker pulls. For "is this machine going to make it?"+ triage before committing to a full install.+--non-interactive Never prompt the user. Implied when stdin isn't a TTY+ (e.g. CI, curl|bash). Pairs cleanly with --diagnose for+ automated checks.+--help Show this text and exit.```### `install.ps1` (Windows)```text--NoInstall Skip the dependency-install phase.--NoLaunch Set everything up but don't run pnpm aisoc:demo.--NoPull Forwarded to aisoc:demo.--Rebuild Forwarded to aisoc:demo.--CloneDir PATH Where to clone. Default: $env:USERPROFILE\aisoc--Branch NAME Git branch. Default: main.+-NoInstall Skip the dependency-install phase.+-NoLaunch Set everything up but don't run pnpm aisoc:demo.+-NoPull Forwarded to aisoc:demo.+-Rebuild Forwarded to aisoc:demo.+-CloneDir PATH Where to clone. Default: $env:USERPROFILE\aisoc+-Branch NAME Git branch. Default: main.+-SkipPreflight Skip the up-front environment checks.+-Diagnose Run preflight only and exit (no installs, no clone).+-NonInteractive Never prompt. Implied in CI and over remote PowerShell.+ On Windows, fresh Docker Desktop installs require an+ interactive first-run, so -NonInteractive will refuse+ to install Docker and instead instruct you to do it+ manually before re-running.```+### Exit codes++Both installers use these exit codes consistently. Useful if you're wiring+the installer into CI or wrapping it in a deployment script:++| Code | Meaning |+| --- | --- |+| `0` | Success. Stack is up (or, in `--diagnose` mode, preflight passed). |+| `1` | Generic / unhandled error. The friendly error trap should have printed a hint right above the failure. |+| `2` | Bad arguments. Usually a typo'd flag. |+| `3` | Refused for safety. Currently only the uninstaller emits this — it means the script declined to delete a path it didn't trust. |+| `4` | Preflight found a blocking issue. Re-run with `--skip-preflight` to override, or fix the items the preflight banner flagged. |+| `5` | `git clone` failed after retries. Usually network — check your proxy, or pre-clone the repo and re-run from inside it. |++## Preflight: the "will this work?" check++Before either installer touches your machine, it runs a **preflight** pass+that checks the things most likely to make AiSOC unhappy after install:++- **CPU architecture** — must be x86_64 / amd64 / arm64. (32-bit ARM, MIPS,+ RISC-V etc. won't work; the Docker images aren't built for them.)+- **RAM** — at least 4 GB free. AiSOC runs ~10 containers; less than 4 GB+ and Postgres or OpenSearch will OOM mid-investigation.+- **Disk** — at least 10 GB free in the install target.+- **Network** — can resolve and reach `github.com`, `ghcr.io`, and the+ appropriate package registry (`registry.npmjs.org`, `apt`/`dnf`/`brew`+ repos, etc.). Catches corp-proxy / firewall issues before you waste 10+ minutes pulling Docker images.+- **Ports** — checks that the ports AiSOC binds to (`3000`, `5432`, `6379`,+ `8000`, `8001`, `8086`, `9092`) are either free or already owned by an+ AiSOC container. If port 3000 is taken by another `next-server`, you'll+ see it in preflight rather than in a confusing demo crash later.+- **macOS Docker Desktop memory budget** — checks Docker Desktop has at+ least 4 GB allocated, and tells you exactly which menu to open if not.+- **Windows version + WSL2** — checks you're on a build new enough to+ install Docker Desktop, and that Hyper-V / Virtual Machine Platform are+ available.++Run `./install.sh --diagnose` (Linux/macOS) or `.\install.ps1 -Diagnose`+(Windows) to see the report without installing anything. It's safe to run+on a production machine — preflight is read-only.++If preflight reports a problem you've decided to ignore (for example, port+3000 is in use by a dev server you'll kill before launch), use+`--skip-preflight` / `-SkipPreflight` to bypass the gate.+## Common cases**I already have Docker / Node / pnpm.** The installer detects them, prints@@ -186,6 +248,49 @@ winget uninstall Git.Git## Troubleshooting+### Preflight failed — what now?++`./install.sh --diagnose` (or `-Diagnose` on Windows) is the same engine+that runs at the top of every install. The output groups findings into+**FAIL** (will block install) and **WARN** (won't block, but worth knowing).+The lines below the finding tell you exactly what to do — there are no+"see logs for details" cliffhangers.++If you're sure preflight is wrong (e.g. it can't reach `ghcr.io` because+your corporate proxy intercepts TLS), you can pass `--skip-preflight` /+`-SkipPreflight` to bypass the gate. The installer will still try to do+its job; you'll just lose the early warning.++### Port conflicts++[port-conflicts]: # "Anchored from preflight output"++<a id="port-conflicts"></a>++AiSOC binds these host ports by default:++| Port | Container | Override env var |+| --- | --- | --- |+| `3000` | `aisoc-web` (Next.js dashboard) | `AISOC_WEB_PORT` |+| `5432` | `aisoc-postgres` | `AISOC_POSTGRES_PORT` |+| `6379` | `aisoc-redis` | `AISOC_REDIS_PORT` |+| `8000` | `aisoc-api` (FastAPI) | `AISOC_API_PORT` |+| `8001` | `aisoc-realtime` (WebSocket fan-out) | `AISOC_REALTIME_PORT` |+| `8086` | `aisoc-influx` (telemetry sink) | `AISOC_INFLUX_PORT` |+| `9092` | `aisoc-kafka` | `AISOC_KAFKA_PORT` |++If preflight flags one of these as in use:++1. Find what's holding it:+ - Linux/macOS: `lsof -nP -iTCP:3000 -sTCP:LISTEN`+ - Windows: `Get-NetTCPConnection -LocalPort 3000 | Select OwningProcess; Get-Process -Id <pid>`+2. Either stop that process, or set the matching `AISOC_*_PORT` env var+ in `.env` (or in your shell) and re-run `pnpm aisoc:demo`.++Preflight only **warns** if a port is taken by a process that looks like+an existing AiSOC container — re-running the installer on a machine that+already has the demo running won't fail preflight.+### Linux: "permission denied" talking to DockerThe installer adds you to the `docker` group, but the new membership only@@ -208,6 +313,46 @@ Open Docker Desktop manually once. The first launch needs to grant thecan't automate. After that, Docker Desktop autostarts on subsequent bootsand the installer hand-off works.+### macOS: preflight says "Docker Desktop appears installed but the daemon isn't running"++This is the friendly version of the old "Docker Desktop is allocated only+0 MB of RAM" message. It just means Docker Desktop hasn't booted yet.++`install.sh` will launch Docker Desktop for you and wait up to 90 seconds+for the daemon to come up. If you're running `--diagnose`, open Docker+Desktop yourself (or run `open -a Docker`) and re-run.++### Windows: `-NonInteractive` refused to install Docker Desktop++Docker Desktop's first-time setup requires UI clicks (accept the EULA,+grant the WSL update prompt, etc.) that the installer can't drive+automatically. In `-NonInteractive` mode (which is also auto-detected in+CI and remote PowerShell), the installer refuses rather than hanging+forever waiting for a button press.++The fix is to install Docker Desktop manually one time:++```powershell+winget install --id Docker.DockerDesktop --silent --accept-package-agreements --accept-source-agreements+# then open Docker Desktop, click through the first-run prompts,+# wait for the whale icon to go solid, then re-run the installer.+```++After Docker Desktop has been provisioned once, `-NonInteractive` works+fine for everything else.++### Windows: WSL is missing in `-NonInteractive` mode++Same shape as the Docker Desktop case — installing WSL requires a reboot+and elevated UAC, neither of which the installer can do non-interactively.+Open an elevated PowerShell and run:++```powershell+wsl --install+```++Reboot, then re-run the installer.+### Windows: WSL2 was just enabled — why do I have to reboot?Enabling WSL2 changes a Windows Feature, which requires a kernel reboot.@@ -235,12 +380,18 @@ host yourself.Run `pnpm aisoc:doctor` from inside the clone — it pinpoints which containeror port is unhealthy. Common causes:-- Port 3000, 5432, 6379, or 9092 already in use → free them or set- `AISOC_WEB_PORT=3001` in `.env` and re-run `pnpm aisoc:demo`.+- One of the bound ports is already in use → see+ [Port conflicts](#port-conflicts) above for the table of ports and+ the env vars to change them.- Docker daemon out of disk → `docker system prune -a` and retry.- Corporate proxy blocking `ghcr.io` → either configure Docker'sHTTP proxy or run `./install.sh --rebuild` to build from source.+If `aisoc:demo` finishes "successfully" but no browser opens, that's+usually an `AISOC_NO_BROWSER=1` env var leaking from a previous CI run, or+a headless environment (SSH session, no `$DISPLAY`). The URL is printed in+the final banner — open it manually.+## Security notesThese installers run with **the privileges they need to install systemdiff --git a/install.ps1 b/install.ps1index 887dc69fc..9f0ffe7cb 100644--- a/install.ps1+++ b/install.ps1@@ -44,6 +44,20 @@.PARAMETER BranchGit branch to clone. Default: main.+.PARAMETER SkipPreflight+ Skip the preflight checks (RAM, disk, network, ports, WSL2, Docker reach).+ Use only if you know exactly what you're doing — preflight catches >80%+ of "doesn't work for me" reports.++.PARAMETER Diagnose+ Run preflight checks and exit. No installs, no demo. Useful for triaging+ a half-broken machine without committing to a full install.++.PARAMETER NonInteractive+ Don't prompt for anything; refuse to do any step that needs user input+ (e.g. accepting Docker Desktop's EULA on first launch). Auto-enabled+ when stdin is redirected (iwr | iex) or when $env:CI is set.+.EXAMPLE# One-liner from PowerShell (run as your normal user, not Administrator —# winget will elevate per-package as needed):@@ -63,6 +77,8 @@1 prerequisite install failed2 Docker Desktop refused to come up / WSL2 not enabled3 pnpm aisoc:demo failed (stack didn't boot or seed)+ 4 preflight checks failed (machine doesn't meet minimums)+ 5 git clone failed (network / branch / disk)Tested on:- Windows 11 23H2 (x64 + ARM64)@@ -83,6 +99,9 @@ param([switch]$NoLaunch,[switch]$NoPull,[switch]$Rebuild,+ [switch]$SkipPreflight,+ [switch]$Diagnose,+ [switch]$NonInteractive,[string]$CloneDir = (Join-Path $env:USERPROFILE 'aisoc'),[string]$Branch = 'main')@@ -92,12 +111,19 @@ param(Set-StrictMode -Version Latest$ErrorActionPreference = 'Stop'-# ─── Logging helpers ──────────────────────────────────────────────────────-# We deliberately avoid Write-Host's color params for non-interactive runs-# (CI, redirected stdout). Detection: $Host.UI.RawUI is null when there's-# no console (e.g. piped through iex from iwr in a non-interactive context).+# Auto-detect non-interactive contexts. The classic case is `iwr | iex` from+# a CI runner — there's no terminal to prompt at, and any Read-Host or winget+# UAC dialog would silently hang the pipeline.+if (-not $NonInteractive) {+ if ([Console]::IsInputRedirected -or $env:CI -eq 'true' -or $env:CI -eq '1') {+ $NonInteractive = $true+ }+}-$script:UseColor = ($null -ne $Host.UI.RawUI) -and ($null -eq $env:NO_COLOR)+# ─── Logging helpers ──────────────────────────────────────────────────────+# Write-Host with -ForegroundColor is safe even when stdout is redirected —+# PowerShell strips ANSI codes for non-console hosts. So we don't need a+# UseColor flag; the runtime DTRT.function Write-Log { param([string]$Msg) Write-Host "[aisoc] $Msg" -ForegroundColor DarkGray }function Write-Info { param([string]$Msg) Write-Host "[aisoc] $Msg" -ForegroundColor Blue }@@ -146,11 +172,24 @@ function Test-WSL2 {Write-Section 'WSL2 check'$hasWsl = Get-Command wsl.exe -ErrorAction SilentlyContinueif (-not $hasWsl) {- Write-Warn "WSL is not installed. Installing now (this requires a reboot)..."+ if ($NonInteractive) {+ # `wsl --install` needs admin, can't be silenced, and forces a+ # reboot. None of those work in CI / iwr|iex pipelines.+ Stop-WithError @"+WSL is not installed and we're running non-interactively.+WSL installation requires administrator privileges and a reboot.++Please run the following from an elevated PowerShell, reboot, then re-run+this installer interactively:++ wsl --install+"@ 2+ }+ Write-Warn "WSL is not installed. Installing now (this requires admin and a reboot)..."Write-Info "Running: wsl --install --no-launch"& wsl.exe --install --no-launchif ($LASTEXITCODE -ne 0) {- Stop-WithError "wsl --install failed. Run an elevated PowerShell and try: wsl --install" 2+ Stop-WithError "wsl --install failed (exit $LASTEXITCODE). Run an elevated PowerShell and try: wsl --install" 2}Write-Warn "WSL2 was installed but Windows must reboot before Docker Desktop can use it."Write-Warn "Reboot now, then re-run this installer."@@ -161,6 +200,15 @@ function Test-WSL2 {# docker-desktop distro. We only fail if WSL itself is broken.$statusOutput = & wsl.exe --status 2>&1if ($LASTEXITCODE -ne 0 -and $statusOutput -match 'WSL_E_WSL_OPTIONAL_COMPONENT_REQUIRED') {+ if ($NonInteractive) {+ Stop-WithError @"+WSL needs the 'Virtual Machine Platform' Windows feature, which requires+admin + reboot to enable. Run the following from an elevated PowerShell,+reboot, then re-run this installer interactively:++ Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform -All+"@ 2+ }Write-Warn "WSL needs the Virtual Machine Platform Windows feature."Write-Info "Enabling Virtual Machine Platform (you may need to reboot)..."Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform -All -NoRestart -ErrorAction SilentlyContinue | Out-Null@@ -224,7 +272,18 @@ function Install-WingetPackage {)if (-not $DisplayName) { $DisplayName = $Id }Write-Info "Installing $DisplayName via winget (id: $Id)..."- $args = @(++ # Heads-up for the iwr|iex crowd: winget triggers UAC for installers that+ # need elevation. There's no clean way to detect that ahead of time, but+ # we can at least warn so the user knows to look for the prompt.+ if ($NonInteractive) {+ Write-Warn "winget may trigger a UAC elevation prompt for $DisplayName."+ Write-Warn "If running unattended, the script will hang here until UAC is acknowledged."+ }++ # NOTE: don't name this `$args` — that's a PowerShell automatic variable+ # for unbound positional args and shadowing it triggers StrictMode warnings.+ $wingetArgs = @('install','--id', $Id,'--exact', # match Id exactly, no fuzzy suggestions@@ -233,7 +292,7 @@ function Install-WingetPackage {'--accept-source-agreements','--source', 'winget' # pin to the official source, not msstore)- $proc = Start-Process -FilePath 'winget' -ArgumentList $args -Wait -PassThru -NoNewWindow+ $proc = Start-Process -FilePath 'winget' -ArgumentList $wingetArgs -Wait -PassThru -NoNewWindowswitch ($proc.ExitCode) {0 { Write-Ok "$DisplayName installed." }-1978335189 { Write-Ok "$DisplayName already installed (winget said no upgrade needed)." } # APPINSTALLER_CLI_ERROR_NO_APPLICABLE_INSTALLER@@ -258,6 +317,72 @@ function Update-PathFromRegistry {$env:Path = ($machine, $user -join ';') -replace ';;', ';'}+# ─── Preflight integration ────────────────────────────────────────────────+# preflight.ps1 lives at scripts\install\preflight.ps1 in the repo. When+# the user runs install.ps1 from inside a clone, we source it directly.+# When they ran the one-liner (`iwr | iex`), $PSScriptRoot is empty and+# we have no clone yet, so we fetch preflight.ps1 from the same branch+# we're going to clone shortly and dot-source it from a temp file.++function Invoke-Preflight {+ if ($SkipPreflight) {+ Write-Warn "Skipping preflight checks (--SkipPreflight given)."+ return+ }++ Write-Section 'Preflight checks'++ $preflightLocal = $null+ if ($PSScriptRoot) {+ $candidate = Join-Path $PSScriptRoot 'scripts\install\preflight.ps1'+ if (Test-Path $candidate) {+ $preflightLocal = $candidate+ }+ }++ if (-not $preflightLocal) {+ # We're running as a one-liner. Fetch preflight.ps1 from the same+ # branch we're about to clone. We use a temp file rather than+ # `iex (iwr ...)` because dot-sourcing is cleaner and the file+ # has multiple functions we want in scope.+ $url = "https://raw.githubusercontent.com/beenuar/AiSOC/$Branch/scripts/install/preflight.ps1"+ $preflightLocal = Join-Path $env:TEMP "aisoc-preflight-$([guid]::NewGuid().ToString('N')).ps1"+ Write-Info "Fetching preflight.ps1 from $url ..."+ try {+ Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $preflightLocal -ErrorAction Stop+ } catch {+ Write-Warn "Could not fetch preflight.ps1: $($_.Exception.Message)"+ Write-Warn "Continuing without preflight (re-run with -SkipPreflight to suppress this warning)."+ return+ }+ }++ # Dot-source so its functions land in our scope.+ try {+ . $preflightLocal+ } catch {+ Write-Warn "Failed to load preflight library: $($_.Exception.Message)"+ Write-Warn "Continuing without preflight."+ return+ }++ if (-not (Get-Command -Name 'Invoke-AiSOCPreflight' -ErrorAction SilentlyContinue)) {+ Write-Warn "preflight.ps1 loaded but didn't expose Invoke-AiSOCPreflight; skipping."+ return+ }++ try {+ $ok = Invoke-AiSOCPreflight+ } catch {+ Write-Err "Preflight crashed: $($_.Exception.Message)"+ Stop-WithError "Preflight could not complete. Re-run with -SkipPreflight to bypass at your own risk." 4+ }++ if (-not $ok) {+ Stop-WithError "Preflight failed. Fix the issues above and re-run, or pass -SkipPreflight to override." 4+ }+}+# ─── Step 1: Git ──────────────────────────────────────────────────────────function Install-Git {@@ -285,6 +410,24 @@ function Install-Docker {Test-DockerDaemonreturn}++ if ($NonInteractive) {+ # Docker Desktop's first-run flow is interactive (EULA + WSL2 prompt).+ # Refusing to install in non-interactive mode is much safer than+ # silently installing a Docker that the user can't actually start.+ Stop-WithError @"+Docker Desktop is not installed and we're running non-interactively.+Docker Desktop's first run requires accepting an EULA from a UI, which can't+happen in this context.++Please either:+ 1. Install Docker Desktop manually from https://docker.com/products/docker-desktop+ and re-run this installer, OR+ 2. Re-run this installer from an interactive PowerShell window:+ irm https://raw.githubusercontent.com/beenuar/AiSOC/main/install.ps1 | iex+"@ 2+ }+Install-WingetPackage -Id 'Docker.DockerDesktop' -DisplayName 'Docker Desktop'# Docker Desktop install puts docker.exe at:@@ -307,20 +450,31 @@ function Install-Docker {Write-Ok "docker installed: $((& docker --version))"# Try to start Docker Desktop. The shortcut path is consistent across- # versions. Start-Process with -PassThru lets us check the spawn- # succeeded; the actual daemon takes 10-30 s more to come up.+ # versions. Start-Process is fire-and-forget; the actual daemon takes+ # 30-90 s more to come up on the first run because the WSL2 distro+ # has to be created.$dockerDesktop = "$env:ProgramFiles\Docker\Docker\Docker Desktop.exe"if (Test-Path $dockerDesktop) {Write-Info "Launching Docker Desktop..."Start-Process -FilePath $dockerDesktop -ErrorAction SilentlyContinue | Out-Null+ } else {+ Write-Warn "Docker Desktop executable not found at expected path:"+ Write-Warn " $dockerDesktop"+ Write-Warn "Please launch Docker Desktop manually from the Start Menu."}Test-DockerDaemon}function Test-DockerDaemon {- Write-Info "Waiting for Docker daemon (up to 90 s)..."- $deadline = (Get-Date).AddSeconds(90)+ # First-run Docker Desktop on Windows can take 2-3 minutes because it+ # provisions a WSL2 distro and installs the Linux kernel. We poll for+ # up to 3 minutes, with progress messages every 30 s so the user+ # doesn't think we're hung.+ $timeoutSeconds = 180+ Write-Info "Waiting for Docker daemon (up to $timeoutSeconds s — first run can be slow)..."+ $deadline = (Get-Date).AddSeconds($timeoutSeconds)+ $lastNotice = Get-Datewhile ((Get-Date) -lt $deadline) {try {& docker info *>&1 | Out-Null@@ -329,15 +483,22 @@ function Test-DockerDaemon {return}} catch { }++ if (((Get-Date) - $lastNotice).TotalSeconds -gt 30) {+ $remaining = [int](($deadline - (Get-Date)).TotalSeconds)+ Write-Info " ... still waiting (${remaining}s remaining). If this is your first run, accept any prompts from Docker Desktop."+ $lastNotice = Get-Date+ }Start-Sleep -Seconds 3}- Write-Err "Docker daemon is not responding after 90 s."+ Write-Err "Docker daemon is not responding after $timeoutSeconds s."Write-Err ""Write-Err "First-time Docker Desktop setup is interactive:"Write-Err " 1. Find 'Docker Desktop' in the Start Menu and launch it."Write-Err " 2. Accept the licence agreement."- Write-Err " 3. Wait for the whale icon in the system tray to stop animating."- Write-Err " 4. Re-run this installer."+ Write-Err " 3. If asked, install the WSL2 kernel update."+ Write-Err " 4. Wait for the whale icon in the system tray to stop animating."+ Write-Err " 5. Re-run this installer."exit 2}@@ -345,7 +506,10 @@ function Test-DockerDaemon {function Install-Node {$major = Get-CommandMajorVersion -Name 'node'- if ($major -ne $null -and $major -ge 20) {+ # $null on the LHS is the PowerShell idiom — putting $null on the right+ # unboxes the LHS if it's an array, which Get-CommandMajorVersion can+ # technically return if Select-Object -First 1 misbehaves.+ if (($null -ne $major) -and ($major -ge 20)) {Write-Ok "node already installed: $((& node --version))"return}@@ -360,21 +524,44 @@ function Install-Node {function Install-Pnpm {$major = Get-CommandMajorVersion -Name 'pnpm'- if ($major -ne $null -and $major -ge 8) {+ if ($null -ne $major -and $major -ge 8) {Write-Ok "pnpm already installed: $((& pnpm --version))"return}++ # Try corepack first (the modern Node-bundled package-manager manager).+ # Fall back to a global npm install if corepack misbehaves — older Node+ # bundles, locked-down corporate networks, or registry hiccups all+ # break corepack in different ways.Write-Info "Enabling corepack and activating pnpm 8.15.1..."+ $corepackOk = $true& corepack enable 2>&1 | Out-Null- if ($LASTEXITCODE -ne 0) {- Stop-WithError "corepack enable failed. Make sure node was installed correctly."+ if ($LASTEXITCODE -ne 0) { $corepackOk = $false }+ if ($corepackOk) {+ & corepack prepare [email protected] --activate 2>&1 | Out-Null+ if ($LASTEXITCODE -ne 0) { $corepackOk = $false }}- & corepack prepare [email protected] --activate 2>&1 | Out-Null- if ($LASTEXITCODE -ne 0) {- Stop-WithError "corepack prepare pnpm failed."++ if (-not $corepackOk -or -not (Test-CommandExists pnpm)) {+ Write-Warn "corepack route failed; falling back to: npm install -g [email protected]"+ & npm install -g [email protected] 2>&1 | Out-Null+ if ($LASTEXITCODE -ne 0) {+ Stop-WithError @"+Could not install pnpm via corepack OR npm.++Workaround: install pnpm manually, then re-run this script:+ npm install -g [email protected]+ irm https://raw.githubusercontent.com/beenuar/AiSOC/main/install.ps1 | iex+"@+ }}+if (-not (Test-CommandExists pnpm)) {- Stop-WithError "pnpm was activated but isn't on PATH. Open a new PowerShell window and re-run this script."+ # PATH refresh hasn't picked up the new global bin yet.+ Update-PathFromRegistry+ }+ if (-not (Test-CommandExists pnpm)) {+ Stop-WithError "pnpm was installed but isn't on PATH. Open a new PowerShell window and re-run this script."}Write-Ok "pnpm installed: $((& pnpm --version))"}@@ -403,11 +590,24 @@ function Resolve-Repo {Write-Info "Updating existing clone at $CloneDir..."Push-Location $CloneDirtry {- & git fetch --quiet origin- & git checkout --quiet $Branch- & git pull --ff-only --quiet- } catch {- Write-Warn "git pull failed; using whatever is on disk."+ # PowerShell try/catch doesn't catch non-zero native exit+ # codes, so check $LASTEXITCODE explicitly. We don't fail+ # hard on update failure — the user might have local edits+ # or be offline; we'd rather use what's on disk than abort.+ & git fetch --quiet origin 2>&1 | Out-Null+ if ($LASTEXITCODE -ne 0) {+ Write-Warn "git fetch failed; using local state."+ } else {+ & git checkout --quiet $Branch 2>&1 | Out-Null+ if ($LASTEXITCODE -ne 0) {+ Write-Warn "git checkout $Branch failed; staying on current branch."+ } else {+ & git pull --ff-only --quiet 2>&1 | Out-Null+ if ($LASTEXITCODE -ne 0) {+ Write-Warn "git pull failed (likely local commits); using local state."+ }+ }+ }} finally {Pop-Location}@@ -419,12 +619,44 @@ function Resolve-Repo {}Write-Info "Cloning AiSOC into $CloneDir (branch: $Branch)..."- & git clone --branch $Branch --depth 50 https://github.com/beenuar/AiSOC.git $CloneDir- if ($LASTEXITCODE -ne 0) {- Stop-WithError "git clone failed."++ # Retry up to 3 times with backoff. The most common failure on Windows+ # is corporate-proxy-related (407, SSL handshake failures) on the first+ # attempt but fine after a retry once the proxy creds are cached.+ $maxAttempts = 3+ $attempt = 0+ while ($attempt -lt $maxAttempts) {+ $attempt+++ & git clone --branch $Branch --depth 50 https://github.com/beenuar/AiSOC.git $CloneDir+ if ($LASTEXITCODE -eq 0) {+ $script:RepoRoot = $CloneDir+ Write-Ok "Cloned AiSOC to $RepoRoot"+ return+ }++ if ($attempt -lt $maxAttempts) {+ Write-Warn "git clone failed (attempt $attempt/$maxAttempts). Retrying in 3 s..."+ # Clean up partial clone so the retry doesn't trip over an+ # existing dir.+ if (Test-Path $CloneDir) {+ try { Remove-Item -Recurse -Force $CloneDir -ErrorAction Stop } catch { }+ }+ Start-Sleep -Seconds 3+ }}- $script:RepoRoot = $CloneDir- Write-Ok "Cloned AiSOC to $RepoRoot"++ Stop-WithError @"+git clone failed after $maxAttempts attempts.++Common causes:+ * No internet (try: Test-NetConnection github.com -Port 443)+ * Corporate proxy not configured for git+ (try: git config --global http.proxy http://proxy:port)+ * Branch '$Branch' doesn't exist on the remote+ (try: git ls-remote --heads https://github.com/beenuar/AiSOC.git)++Then re-run this installer.+"@ 5}# ─── Step 6: .env bootstrap ───────────────────────────────────────────────@@ -513,10 +745,64 @@ function Write-SuccessBanner {# ─── Main ─────────────────────────────────────────────────────────────────function Invoke-Main {+ # Friendly error handler. Without this, an unhandled exception dumps a+ # gnarly red PowerShell stack trace at the user with no context. We catch+ # it, surface the most useful info, and link them to where to file an+ # issue with that info pre-filled.+ trap {+ $err = $_+ Write-Host ''+ Write-Host '┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓' -ForegroundColor Red+ Write-Host '┃ AiSOC installer hit an unexpected error. ┃' -ForegroundColor Red+ Write-Host '┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛' -ForegroundColor Red+ Write-Host ''+ Write-Host " Error: $($err.Exception.Message)" -ForegroundColor Yellow+ if ($err.InvocationInfo) {+ Write-Host " At: $($err.InvocationInfo.ScriptName):$($err.InvocationInfo.ScriptLineNumber)" -ForegroundColor DarkGray+ Write-Host " $($err.InvocationInfo.Line.Trim())" -ForegroundColor DarkGray+ }+ Write-Host ''+ Write-Host ' What to try:' -ForegroundColor Cyan+ Write-Host ' 1. Re-run with: .\install.ps1 -Diagnose'+ Write-Host ' (preflight only — no installs)'+ Write-Host ' 2. Read the troubleshooting guide:'+ Write-Host ' https://github.com/beenuar/AiSOC/blob/main/docs/QUICK_INSTALL.md#troubleshooting'+ Write-Host ' 3. File an issue with the system info below:'+ Write-Host ' https://github.com/beenuar/AiSOC/issues/new?template=installer-bug.md'+ Write-Host ''+ Write-Host ' System info:' -ForegroundColor DarkGray+ try {+ $os = Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction SilentlyContinue+ if ($os) {+ Write-Host " OS: $($os.Caption) build $($os.BuildNumber) ($env:PROCESSOR_ARCHITECTURE)" -ForegroundColor DarkGray+ }+ } catch { }+ Write-Host " PSVer: $($PSVersionTable.PSVersion)" -ForegroundColor DarkGray+ if (Test-CommandExists docker) {+ try { Write-Host " Docker: $((& docker --version) 2>$null)" -ForegroundColor DarkGray } catch { }+ }+ if (Test-CommandExists node) {+ try { Write-Host " Node: $((& node --version) 2>$null)" -ForegroundColor DarkGray } catch { }+ }+ Write-Host ''+ exit 1+ }+Write-Section 'AiSOC One-Click Installer (Windows)'Test-WindowsVersion+ # Preflight before we touch anything. In Diagnose mode this is also+ # the only thing we run.+ Invoke-Preflight++ if ($Diagnose) {+ Write-Host ''+ Write-Ok "Diagnose complete. No changes were made."+ Write-Info "Drop -Diagnose to continue with the full install."+ exit 0+ }+if (-not $NoInstall) {Test-WSL2if (-not (Test-Winget)) { exit 1 }diff --git a/install.sh b/install.shindex 12a62c2f6..d5399fbf6 100755--- a/install.sh+++ b/install.sh@@ -28,20 +28,30 @@# ./install.sh## Flags:-# --no-install Skip the dependency-install phase (use what's on PATH).-# --no-launch Set everything up but don't run pnpm aisoc:demo at the end.-# --no-pull Forwarded to aisoc:demo to skip image pull.-# --rebuild Forwarded to aisoc:demo to build images from source.-# --clone-dir DIR Where to clone the repo when running as a one-liner.-# Default: $HOME/aisoc-# --branch BR Git branch to clone. Default: main.-# --help Show this text and exit.+# --no-install Skip the dependency-install phase (use what's on PATH).+# --no-launch Set everything up but don't run pnpm aisoc:demo at the end.+# --no-pull Forwarded to aisoc:demo to skip image pull.+# --rebuild Forwarded to aisoc:demo to build images from source.+# --skip-preflight Skip the early environment checks (RAM, disk, ports, …).+# Use this if preflight is wrong about your machine and+# you know what you're doing.+# --diagnose Run preflight checks only, then exit. No installs, no+# changes. Useful for "is my machine ready?" before you+# commit to the full install.+# --non-interactive Don't open prompts or browsers. Combine with --no-launch+# for fully unattended provisioning. Implied when stdin+# isn't a TTY (CI, log redirects).+# --clone-dir DIR Where to clone the repo when running as a one-liner.+# Default: $HOME/aisoc+# --branch BR Git branch to clone. Default: main.+# --help Show this text and exit.## Exit codes:# 0 success — demo stack is up and your browser opened# 1 prerequisite install failed# 2 Docker daemon refused to come up# 3 pnpm aisoc:demo failed (stack didn't boot or seed)+# 4 preflight failed (use --skip-preflight to override at your own risk)## Safe to re-run. Each install step checks "is this already present and the# right version?" before doing anything. If everything's installed and the@@ -91,6 +101,46 @@ section() {die() { err "$*"; exit 1; }+# ─── Friendly error trap ─────────────────────────────────────────────────────+# When `set -e` fires, the default behaviour is a silent exit with the failing+# command's status code. That's awful UX for a one-click installer aimed at+# people who just want a working dashboard. We replace it with a banner that+# tells them which step failed, where to find the troubleshooting docs, and+# how to file a useful bug report.++INSTALLER_VERSION="2026.05"+TROUBLESHOOT_URL="https://github.com/beenuar/AiSOC/blob/main/docs/QUICK_INSTALL.md#troubleshooting"+ISSUES_URL="https://github.com/beenuar/AiSOC/issues/new?template=installer-failure.yml"++on_error() {+ local exit_code=$?+ local line="${1:-?}"+ # Don't fire for our own clean exits (die, exit N from preflight, etc.) — those+ # already printed a clear message. We only want to catch *unexpected* failures+ # that bubble up through `set -e`.+ if [ $exit_code -eq 0 ]; then return; fi+ printf '\n%s%s━━━ Installer failed (exit %d at line %s) ━━━%s\n\n' \+ "$C_BOLD" "$C_RED" "$exit_code" "$line" "$C_RESET" >&2+ cat >&2 <<EOF+${C_BOLD}This shouldn't have happened.${C_RESET} The installer hit an error it didn't+know how to recover from. Two things help most:++ 1. ${C_BOLD}Common fixes:${C_RESET} ${TROUBLESHOOT_URL}+ 2. ${C_BOLD}If that didn't help:${C_RESET} open an issue with the lines above and:+ - your OS: ${OS_FAMILY:-unknown} (${DISTRO_ID:-?} ${DISTRO_VERSION:-?})+ - architecture: ${ARCH:-unknown}+ - package mgr: ${PKG_MGR:-unknown}+ - installer ver: ${INSTALLER_VERSION}+ Issue template: ${ISSUES_URL}++You can also run the installer in diagnose-only mode to see what's missing:+ bash $0 --diagnose++EOF+ exit "$exit_code"+}+trap 'on_error $LINENO' ERR+usage() {# Echo the leading comment block (everything between line 2 and the first# blank line after the shebang) so --help and the source stay in sync.@@ -102,19 +152,32 @@ usage() {NO_INSTALL=0NO_LAUNCH=0+SKIP_PREFLIGHT=0+DIAGNOSE_ONLY=0+NON_INTERACTIVE=0CLONE_DIR="${HOME}/aisoc"BRANCH="main"DEMO_FLAGS=()+# If stdin isn't a TTY (curl|bash, CI, log redirects), default to+# non-interactive. Users who *want* prompts in those environments can pass+# --interactive (we don't expose that flag explicitly — yet).+if [ ! -t 0 ]; then+ NON_INTERACTIVE=1+fi+while [ $# -gt 0 ]; docase "$1" in- --no-install) NO_INSTALL=1 ;;- --no-launch) NO_LAUNCH=1 ;;- --no-pull) DEMO_FLAGS+=("--no-pull") ;;- --rebuild) DEMO_FLAGS+=("--rebuild") ;;- --clone-dir) CLONE_DIR="${2:?}"; shift ;;- --branch) BRANCH="${2:?}"; shift ;;- --help|-h) usage ;;+ --no-install) NO_INSTALL=1 ;;+ --no-launch) NO_LAUNCH=1 ;;+ --no-pull) DEMO_FLAGS+=("--no-pull") ;;+ --rebuild) DEMO_FLAGS+=("--rebuild") ;;+ --skip-preflight) SKIP_PREFLIGHT=1 ;;+ --diagnose) DIAGNOSE_ONLY=1 ;;+ --non-interactive) NON_INTERACTIVE=1 ;;+ --clone-dir) CLONE_DIR="${2:?}"; shift ;;+ --branch) BRANCH="${2:?}"; shift ;;+ --help|-h) usage ;;*) die "unknown flag: $1 (try --help)" ;;esacshift@@ -237,11 +300,92 @@ version_at_least() {[ -n "$major" ] && [ "$major" -ge "$want_major" ]}+# ─── Preflight ───────────────────────────────────────────────────────────────+# We catch the "your machine isn't going to make it" cases up-front, before we+# spend ten minutes downloading Docker images and ask for your sudo password.+# Source preflight.sh from the on-disk clone if we have one, otherwise fetch+# it from the same branch we'd clone. Either way we set AISOC_PREFLIGHT_SOFT+# so the library returns rather than exits — we want to print our own banner+# with the --skip-preflight escape hatch.++PREFLIGHT_TMP=""+cleanup_preflight_tmp() {+ if [ -n "$PREFLIGHT_TMP" ] && [ -f "$PREFLIGHT_TMP" ]; then+ rm -f "$PREFLIGHT_TMP"+ fi+}++run_preflight() {+ if [ "$SKIP_PREFLIGHT" = "1" ]; then+ warn "--skip-preflight: skipping environment checks. Hope you know what you're doing."+ return 0+ fi++ local pf_script=""+ # Mode A: we're running from a clone — preflight.sh sits next to us.+ if [ -n "${BASH_SOURCE[0]:-}" ] && [ "${BASH_SOURCE[0]}" != "bash" ]; then+ local self_dir+ self_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)" || self_dir=""+ if [ -n "$self_dir" ] && [ -f "$self_dir/scripts/install/preflight.sh" ]; then+ pf_script="$self_dir/scripts/install/preflight.sh"+ fi+ fi+ # Mode B: streamed via curl|bash. Fetch preflight from the same branch.+ if [ -z "$pf_script" ]; then+ if ! have curl; then+ warn "curl missing — skipping preflight (we can't fetch it without curl)."+ return 0+ fi+ PREFLIGHT_TMP="$(mktemp 2>/dev/null || mktemp -t aisoc-preflight)"+ trap cleanup_preflight_tmp EXIT+ local pf_url="https://raw.githubusercontent.com/beenuar/AiSOC/${BRANCH}/scripts/install/preflight.sh"+ info "Fetching preflight checks from ${pf_url}..."+ if ! curl -fsSL "$pf_url" -o "$PREFLIGHT_TMP"; then+ warn "Couldn't fetch preflight.sh from $pf_url. Continuing without preflight."+ warn "(Pass --skip-preflight to silence this warning.)"+ return 0+ fi+ pf_script="$PREFLIGHT_TMP"+ fi++ # Tell preflight where we'll install to so disk-space checks land on the+ # right filesystem. If we're in a clone, that's REPO_ROOT; otherwise it's+ # the directory we plan to clone into.+ if [ -d "$CLONE_DIR" ]; then+ export AISOC_REPO_ROOT="$CLONE_DIR"+ elif [ -n "${BASH_SOURCE[0]:-}" ] && [ "${BASH_SOURCE[0]}" != "bash" ]; then+ AISOC_REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)" || AISOC_REPO_ROOT=""+ [ -n "$AISOC_REPO_ROOT" ] && export AISOC_REPO_ROOT+ fi+ export AISOC_PREFLIGHT_SOFT=1++ # Source rather than exec so we inherit the function and can call it; the+ # library is careful to save/restore errexit on its own.+ # shellcheck disable=SC1090+ . "$pf_script"+ local pf_rc=0+ run_aisoc_preflight || pf_rc=$?+ if [ $pf_rc -ne 0 ]; then+ err ""+ err "Preflight found at least one blocking issue (see above)."+ err "Fix the items marked FAIL and re-run, OR pass --skip-preflight to override."+ err "Common fixes: ${TROUBLESHOOT_URL}"+ exit 4+ fi+ ok "Preflight passed."+}+# ─── Homebrew bootstrap (macOS only) ─────────────────────────────────────────ensure_brew() {if [ "$PKG_MGR" != "brew-missing" ]; then return 0; fiwarn "Homebrew is required on macOS but isn't installed."+ if [ "$NON_INTERACTIVE" = "1" ]; then+ err "Homebrew installer needs an interactive TTY (sudo + license prompts)."+ err "Install Homebrew first: /bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""+ err "Then re-run this installer."+ die "Cannot bootstrap Homebrew non-interactively."+ fiinfo "Installing Homebrew (you'll be prompted for your password)..."/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" \|| die "Homebrew install failed. See https://brew.sh and re-run this script."@@ -304,19 +448,47 @@ ensure_docker() {fiif [ "$OS_FAMILY" = "macos" ]; then+ # Cask name history: Homebrew renamed `docker` → `docker-desktop` in 2024+ # because the bare `docker` cask now installs only the CLI. Try the new+ # name first, then fall back to the old one for older brew installs.info "Installing Docker Desktop via Homebrew..."- brew install --cask docker || die "brew install --cask docker failed."- cat <<EOF--${C_BOLD}${C_YELLOW}Docker Desktop installed but not running.${C_RESET}+ if ! brew install --cask docker-desktop 2>/dev/null; then+ brew install --cask docker || die "brew install --cask docker(-desktop) failed."+ fi-Please:- 1. Open Docker Desktop from Applications (or Spotlight: 'Docker').- 2. Accept the licence agreement on first launch.- 3. Wait for the whale icon in the menu bar to stop animating.- 4. Re-run this installer.+ # Auto-launch Docker Desktop and wait for the daemon. The user still has+ # to accept the licence on first run — we detect that case by polling for+ # up to 3 minutes and printing a clear hint if it never comes up.+ if [ -d "/Applications/Docker.app" ]; then+ info "Launching Docker Desktop..."+ open -a Docker >/dev/null 2>&1 || warn "couldn't auto-launch Docker Desktop; open it manually."+ else+ warn "Docker.app not found in /Applications — you may need to launch Docker Desktop manually."+ fi-EOF+ info "Waiting up to 3 min for Docker Desktop to start (first launch can be slow)..."+ local mac_i=0+ while [ $mac_i -lt 90 ]; do+ if docker info >/dev/null 2>&1; then+ ok "Docker Desktop is up."+ ok "docker installed: $(docker --version)"+ return 0+ fi+ sleep 2+ mac_i=$((mac_i+1))+ # Print a heartbeat every 30 s so the user knows we're not hung.+ if [ $((mac_i % 15)) -eq 0 ]; then+ info "...still waiting for Docker Desktop ($((mac_i*2))s elapsed)"+ fi+ done++ err "Docker Desktop didn't become responsive within 3 minutes."+ err ""+ err "Most likely cause: you need to accept the Docker Desktop licence on first launch."+ err " 1. Open Docker Desktop from Applications (or Spotlight: 'Docker')."+ err " 2. Click through the licence + onboarding."+ err " 3. Wait for the whale icon in the menu bar to stop animating."+ err " 4. Re-run this installer."exit 2fi@@ -354,13 +526,13 @@ EOF# Wrapper that runs `docker ...` either directly or via `sg docker -c` so# the current shell sees the new group membership without requiring logout.# Both branches take a single shell expression (possibly with redirects), which-# is why we eval rather than exec the array.+# is why we eval rather than exec the array. We use "$*" (join with space) not+# "$@" (separate args) because eval needs one composite string to parse.docker_cmd() {if [ "$DOCKER_NEEDS_NEWGRP" = "1" ] && have sg; thensg docker -c "$*"else- # shellcheck disable=SC2294 # intentional: callers pass shell expressions- eval "$@"+ eval "$*"fi}@@ -438,11 +610,32 @@ ensure_pnpm() {# corepack ships with Node 16.13+. It manages pnpm/yarn versions per project# so we don't have to mess with global npm installs (which always end in# tears on multi-version setups).- $SUDO corepack enable 2>/dev/null || corepack enable || die "corepack enable failed."- # Pin to the version package.json declares ([email protected]). corepack reads- # the workspace's "packageManager" field on first invocation.- corepack prepare [email protected] --activate || die "corepack prepare pnpm failed."- have pnpm || die "pnpm install reported success but pnpm is still not on PATH."+ local corepack_ok=0+ if have corepack; then+ if $SUDO corepack enable 2>/dev/null || corepack enable 2>/dev/null; then+ # Pin to the version package.json declares ([email protected]). corepack reads+ # the workspace's "packageManager" field on first invocation.+ if corepack prepare [email protected] --activate 2>/dev/null; then+ corepack_ok=1+ fi+ fi+ fi++ # Fallback: corepack got rejected by Node's signature checks (a common+ # bug in older Node 20 minor versions) or isn't present. Use npm directly.+ if [ "$corepack_ok" = "0" ]; then+ warn "corepack didn't activate pnpm cleanly. Falling back to 'npm install -g [email protected]'."+ if have npm; then+ $SUDO npm install -g [email protected] 2>/dev/null \+ || npm install -g [email protected] \+ || die "npm install -g pnpm failed. Try: sudo npm install -g [email protected]"+ else+ die "Neither corepack nor npm is available to install pnpm. Re-install Node.js."+ fi+ fi++ have pnpm || die "pnpm install reported success but pnpm is still not on PATH. \+Open a new shell and re-run this installer."ok "pnpm installed: $(pnpm --version)"}@@ -458,22 +651,38 @@ ensure_pnpm() {REPO_ROOT=""ensure_repo() {- local self_dir+ local candidate=""++ # Strategy A: BASH_SOURCE[0] points at install.sh on disk.# When piped through bash, $0 is "bash" (or "/usr/bin/bash"), not a path# to this script. BASH_SOURCE[0] is empty in that case.if [ -n "${BASH_SOURCE[0]:-}" ] && [ "${BASH_SOURCE[0]}" != "bash" ]; then- self_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"- if [ -d "$self_dir/.git" ] && [ -f "$self_dir/package.json" ]; then- # Sanity-check it's actually AiSOC and not some other repo that- # happened to ship an install.sh.- if grep -q '"name": "aisoc"' "$self_dir/package.json" 2>/dev/null; then- REPO_ROOT="$self_dir"- ok "Using existing AiSOC clone at $REPO_ROOT"- return 0- fi+ local self_dir+ self_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd)" || self_dir=""+ if [ -n "$self_dir" ] && [ -d "$self_dir/.git" ] && [ -f "$self_dir/package.json" ]; then+ candidate="$self_dir"+ fi+ fi++ # Strategy B: CWD is inside an AiSOC clone (user ran `bash install.sh`+ # from a subdirectory, or saved install.sh elsewhere).+ if [ -z "$candidate" ] && have git; then+ local toplevel+ toplevel="$(git rev-parse --show-toplevel 2>/dev/null || true)"+ if [ -n "$toplevel" ] && [ -f "$toplevel/package.json" ]; then+ candidate="$toplevel"fifi+ # Verify candidate is actually AiSOC and not some other repo that+ # happened to ship an install.sh.+ if [ -n "$candidate" ] \+ && grep -q '"name": "aisoc"' "$candidate/package.json" 2>/dev/null; then+ REPO_ROOT="$candidate"+ ok "Using existing AiSOC clone at $REPO_ROOT"+ return 0+ fi+# Mode B: clone fresh.if [ -d "$CLONE_DIR" ]; thenif [ -d "$CLONE_DIR/.git" ] && grep -q '"name": "aisoc"' "$CLONE_DIR/package.json" 2>/dev/null; then@@ -487,10 +696,32 @@ ensure_repo() {die "$CLONE_DIR exists but isn't an AiSOC clone. Pass --clone-dir to choose a different location, or remove it first."fiinfo "Cloning AiSOC into $CLONE_DIR (branch: $BRANCH)..."- git clone --branch "$BRANCH" --depth 50 https://github.com/beenuar/AiSOC.git "$CLONE_DIR" \- || die "git clone failed."- REPO_ROOT="$CLONE_DIR"- ok "Cloned AiSOC to $REPO_ROOT"+ # Retry up to 3 times — transient DNS or partial-fetch failures are common+ # on flaky networks and we don't want to dump the user back to a bare prompt+ # after a single hiccup.+ local clone_attempts=0+ while [ $clone_attempts -lt 3 ]; do+ if git clone --branch "$BRANCH" --depth 50 \+ https://github.com/beenuar/AiSOC.git "$CLONE_DIR" 2>&1; then+ REPO_ROOT="$CLONE_DIR"+ ok "Cloned AiSOC to $REPO_ROOT"+ return 0+ fi+ clone_attempts=$((clone_attempts + 1))+ if [ $clone_attempts -lt 3 ]; then+ warn "git clone failed (attempt $clone_attempts/3). Retrying in 3s..."+ rm -rf "$CLONE_DIR" 2>/dev/null || true+ sleep 3+ fi+ done+ err "git clone failed after 3 attempts."+ err " Repo: https://github.com/beenuar/AiSOC.git (branch: $BRANCH)"+ err " Target: $CLONE_DIR"+ err "Possible causes:"+ err " - Network firewall blocking github.com"+ err " - Branch '$BRANCH' doesn't exist (try --branch main)"+ err " - $CLONE_DIR isn't writable by your user"+ exit 5}# ─── Step 6: .env bootstrap ──────────────────────────────────────────────────@@ -532,12 +763,30 @@ run_demo() {info "Handing off to 'pnpm aisoc:demo' — this will pull images, start the"info "stack, seed the showcase ransomware case, and open your browser."echo++ # In non-interactive / headless contexts (CI, ssh without DISPLAY, --non-interactive),+ # don't try to pop a browser. The demo script honours AISOC_NO_BROWSER=1.+ local need_no_browser=0+ if [ "$NON_INTERACTIVE" = "1" ]; then+ need_no_browser=1+ elif [ "$OS_FAMILY" != "macos" ] && [ -z "${DISPLAY:-}" ] && [ -z "${WAYLAND_DISPLAY:-}" ]; then+ need_no_browser=1+ fi+ if [ "$need_no_browser" = "1" ]; then+ info "(headless or non-interactive — skipping browser auto-open)"+ export AISOC_NO_BROWSER=1+ fi+# We forward the user's --no-pull / --rebuild flags through to the demo# script. Run docker via `sg docker` if the user was just added to the# group and hasn't logged out — otherwise pnpm aisoc:demo will explode on# its very first `docker compose` call.if [ "$DOCKER_NEEDS_NEWGRP" = "1" ] && have sg; then- sg docker -c "cd '$REPO_ROOT' && pnpm aisoc:demo ${DEMO_FLAGS[*]:-}" \+ # `sg` spawns a fresh shell that wipes our env, so re-export AISOC_NO_BROWSER+ # inline if we set it.+ local pre=""+ [ "$need_no_browser" = "1" ] && pre="AISOC_NO_BROWSER=1 "+ sg docker -c "cd '$REPO_ROOT' && ${pre}pnpm aisoc:demo ${DEMO_FLAGS[*]:-}" \|| { err "pnpm aisoc:demo exited non-zero."; exit 3; }else( cd "$REPO_ROOT" && pnpm aisoc:demo "${DEMO_FLAGS[@]}" ) \@@ -578,6 +827,13 @@ EOFmain() {section "AiSOC One-Click Installer"detect_os+ run_preflight++ if [ "$DIAGNOSE_ONLY" = "1" ]; then+ ok "Diagnose-only mode: preflight passed, exiting before installing anything."+ info "Re-run without --diagnose to actually install."+ exit 0+ fiif [ "$NO_INSTALL" = "0" ]; thensection "Installing prerequisites"diff --git a/scripts/aisoc-demo.ts b/scripts/aisoc-demo.tsindex f5d8f400f..cff47cb6b 100644--- a/scripts/aisoc-demo.ts+++ b/scripts/aisoc-demo.ts@@ -240,17 +240,52 @@ async function waitFor(return false;}+// Returns true if we're sure there's no display the browser could land on.+// On Linux this is the usual "headless server" check (no DISPLAY/WAYLAND+// and no xdg-open). On macOS and Windows the OS always has a session, so+// we only honor the explicit AISOC_NO_BROWSER opt-out.+function isHeadless(): boolean {+ if (process.env.AISOC_NO_BROWSER === "1") return true;+ if (process.env.CI) return true;+ const p = platform();+ if (p === "linux") {+ if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return true;+ }+ return false;+}+function openBrowser(url: string) {const p = platform();- const cmd =- p === "darwin" ? "open" : p === "win32" ? "start" : "xdg-open";try {if (p === "win32") {- // `start` is a cmd.exe builtin — needs `cmd /c`+ // `start` is a cmd.exe builtin, not an exe — must go through cmd.+ // The empty "" arg is cmd's title slot; without it `start` swallows+ // the URL as a window title when the URL starts with a quote.spawnSync("cmd", ["/c", "start", "", url], { stdio: "ignore", detached: true });- } else {- spawnSync(cmd, [url], { stdio: "ignore", detached: true });+ return;+ }+ if (p === "darwin") {+ spawnSync("open", [url], { stdio: "ignore", detached: true });+ return;}+ // Linux: xdg-open is present on most desktops but not on minimal+ // server installs (Debian-slim, Alpine, GitHub Actions ubuntu-latest+ // when no desktop env). Probe for it first; if missing, just log.+ const probe = spawnSync("which", ["xdg-open"], { stdio: "ignore" });+ if (probe.status === 0) {+ spawnSync("xdg-open", [url], { stdio: "ignore", detached: true });+ return;+ }+ // Fall back to common alternatives that some distros ship.+ for (const alt of ["sensible-browser", "x-www-browser", "gnome-open"]) {+ const altProbe = spawnSync("which", [alt], { stdio: "ignore" });+ if (altProbe.status === 0) {+ spawnSync(alt, [url], { stdio: "ignore", detached: true });+ return;+ }+ }+ // No opener available; URL is already in the success banner above.+ log(c.dim("(no browser opener found — open the URL manually)"));} catch {// Best-effort. The URL is logged anyway.}@@ -276,9 +311,23 @@ function checkDocker(): boolean {}log(c.green("ok") + ` ${compose}`);- const info = tryRun("docker info --format '{{.ServerVersion}}'");+ // Cross-platform note: single-quote --format works on POSIX shells but+ // not on Windows cmd, where {{ gets interpreted by Go's template parser+ // through cmd's mangled quoting. Use spawnSync directly with shell:false+ // so the args are passed verbatim to docker.exe and the quoting layer+ // is removed entirely.+ const infoResult = spawnSync(+ "docker",+ ["info", "--format", "{{.ServerVersion}}"],+ { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] },+ );+ const info = infoResult.status === 0 ? infoResult.stdout.trim() : "";if (!info) {- console.error(c.red("docker daemon is not running. Start Docker Desktop and retry."));+ console.error(+ c.red(+ "docker daemon is not running. Start Docker Desktop (or `sudo systemctl start docker` on Linux) and retry.",+ ),+ );return false;}log(c.green("ok") + ` docker daemon up (server ${info})`);@@ -500,6 +549,10 @@ async function openInBrowser(step(7, 7, `Opening browser at ${url}`);if (flags.noOpen) {log(c.dim("--no-open: not launching browser"));+ } else if (isHeadless()) {+ // CI, headless server, or AISOC_NO_BROWSER=1. Don't try to spawn a+ // GUI process the user can't see — just leave the URL in the banner.+ log(c.dim("headless environment detected — not launching browser (set AISOC_NO_BROWSER=0 to override)"));} else {openBrowser(url);}diff --git a/scripts/install/preflight.ps1 b/scripts/install/preflight.ps1new file mode 100644index 000000000..b8063a4f2--- /dev/null+++ b/scripts/install/preflight.ps1@@ -0,0 +1,408 @@+<#+.SYNOPSIS+ AiSOC preflight checks for Windows.++.DESCRIPTION+ Mirror of scripts/install/preflight.sh, but for the Windows + WSL2+ + Docker Desktop world. Designed to be dot-sourced by install.ps1+ *before* any prerequisite work, but can also be run standalone:++ powershell -ExecutionPolicy Bypass -File scripts\install\preflight.ps1++ The goal is to catch the failures that would happen 4 minutes from+ now — no disk, can't talk to ghcr.io, port 3000 is held by IIS, WSL2+ isn't installed, Docker Desktop is using Hyper-V instead of WSL2 —+ *before* we ask the user to download a gigabyte of images.++ Checks performed (in order):++ 1. Windows version (build 19041 / 20H1+ for WSL2)+ 2. CPU architecture (amd64 / arm64 only)+ 3. RAM (>= 4 GB hard, >= 8 GB recommended)+ 4. Free disk on the install drive (>= 10 GB hard, >= 20 GB rec)+ 5. Internet reachability (api.github.com, ghcr.io, npmjs.org)+ 6. WSL2 is installed and has a default distro+ 7. Docker Desktop service / engine is reachable (best effort)+ 8. Required ports (3000/5432/6379/8000/8001/8086/9092) are free+ OR held by an existing AiSOC container we can reuse+ 9. No leftover/conflicting AiSOC containers from a prior run+ 10. Hyper-V vs WSL2 sanity check (warn if both seem half-on)++ Each check produces one of three states:++ PASS - silent, just increments the success counter+ WARN - yellow line, doesn't block install+ FAIL - red line, increments fail counter++.PARAMETER Soft+ If set, the script writes the summary and exits 0 even with+ failures. install.ps1 uses this on its second pass after auto-fix.++.PARAMETER SkipNetwork+ Skip the connectivity probes (for air-gapped install testing).+ Failures become warnings.++.PARAMETER InstallRoot+ Root path used for the disk space check. Defaults to the parent of+ this script (so the repo root) when dot-sourced, or the current+ working directory when run standalone.++.OUTPUTS+ Exit code 0 = all checks passed (or only warnings)+ Exit code 1 = at least one hard failure+ Exit code 2 = preflight itself failed to gather data++.NOTES+ This script intentionally does NOT modify anything on the system.+ It only reads. install.ps1 is responsible for any fixes.+#>+[CmdletBinding()]+param(+ [switch]$Soft,+ [switch]$SkipNetwork,+ [string]$InstallRoot+)++# We rely on $PSScriptRoot when dot-sourced.+if (-not $InstallRoot) {+ if ($PSScriptRoot) {+ $InstallRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path+ } else {+ $InstallRoot = (Get-Location).Path+ }+}++# These ports must match docker-compose.demo.yml. If you change ports+# there, change them here, otherwise users get false negatives.+$script:PfRequiredPorts = @(+ @{ Port = 3000; Name = "web console" },+ @{ Port = 5432; Name = "postgres" },+ @{ Port = 6379; Name = "redis" },+ @{ Port = 8000; Name = "api" },+ @{ Port = 8001; Name = "agents" },+ @{ Port = 8086; Name = "realtime ws" },+ @{ Port = 9092; Name = "kafka" }+)++# Hosts and specific endpoints we know return a valid 2xx/3xx/401.+# (See preflight.sh for the rationale on /v2/ vs root.)+$script:PfNetHosts = @(+ "https://api.github.com/zen",+ "https://ghcr.io/v2/",+ "https://registry.npmjs.org/"+)++$script:PfPass = 0+$script:PfWarn = 0+$script:PfFail = 0++#region Output helpers — keep these terse, the user is staring at it+function script:Pf-Pass($msg) {+ $script:PfPass+++ Write-Host " " -NoNewline+ Write-Host "PASS " -ForegroundColor Green -NoNewline+ Write-Host $msg+}++function script:Pf-Warn($msg, $hint) {+ $script:PfWarn+++ Write-Host " " -NoNewline+ Write-Host "WARN " -ForegroundColor Yellow -NoNewline+ Write-Host $msg+ if ($hint) {+ Write-Host " hint: " -ForegroundColor DarkYellow -NoNewline+ Write-Host $hint+ }+}++function script:Pf-Fail($msg, $hint) {+ $script:PfFail+++ Write-Host " " -NoNewline+ Write-Host "FAIL " -ForegroundColor Red -NoNewline+ Write-Host $msg+ if ($hint) {+ Write-Host " fix: " -ForegroundColor DarkRed -NoNewline+ Write-Host $hint+ }+}+#endregion++function script:Pf-CheckWindowsVersion {+ try {+ $os = Get-CimInstance Win32_OperatingSystem -ErrorAction Stop+ $build = [int]($os.BuildNumber)+ if ($build -lt 19041) {+ Pf-Fail "Windows build $build is too old for WSL2 (need 19041+)." `+ "Run Windows Update until you reach Windows 10 21H2 or newer."+ } else {+ Pf-Pass "Windows build $build supports WSL2"+ }+ } catch {+ Pf-Warn "Couldn't query Windows version via CIM." `+ "If install.ps1 fails, check your PowerShell + WMI repo."+ }+}++function script:Pf-CheckArch {+ $arch = $env:PROCESSOR_ARCHITECTURE+ switch ($arch) {+ "AMD64" { Pf-Pass "CPU architecture: amd64"; return }+ "ARM64" { Pf-Pass "CPU architecture: arm64"; return }+ default {+ Pf-Fail "CPU architecture '$arch' is not supported." `+ "AiSOC requires amd64 or arm64. ARM32/x86 won't work — Docker Desktop doesn't even run there."+ }+ }+}++function script:Pf-CheckRam {+ try {+ $cs = Get-CimInstance Win32_ComputerSystem -ErrorAction Stop+ $ramMb = [int]($cs.TotalPhysicalMemory / 1MB)+ if ($ramMb -lt 4096) {+ Pf-Fail "Only ${ramMb} MB of RAM detected (need >= 4096 MB)." `+ "AiSOC won't fit. Close apps, reboot, or run on a bigger machine."+ } elseif ($ramMb -lt 8192) {+ Pf-Warn "Only ${ramMb} MB of RAM detected (recommend 8 GB+)." `+ "The demo will run but may be slow. Close other heavy apps before launching."+ } else {+ Pf-Pass "RAM: ${ramMb} MB total"+ }+ } catch {+ Pf-Warn "Couldn't measure system RAM." `+ "If install fails OOM, you have less than 8 GB free."+ }+}++function script:Pf-CheckDisk {+ try {+ $drive = (Get-Item $InstallRoot).PSDrive.Name+ $info = Get-PSDrive -Name $drive -ErrorAction Stop+ $freeGb = [math]::Round($info.Free / 1GB, 1)+ if ($freeGb -lt 10) {+ Pf-Fail "Only ${freeGb} GB free on ${drive}: (need >= 10 GB)." `+ "Free up disk space or pick a different install drive with -InstallRoot."+ } elseif ($freeGb -lt 20) {+ Pf-Warn "Only ${freeGb} GB free on ${drive}: (recommend 20 GB+)." `+ "Docker images alone are ~5 GB; add data + logs + builds and you'll fill up fast."+ } else {+ Pf-Pass "Disk: ${freeGb} GB free on ${drive}:"+ }+ } catch {+ Pf-Warn "Couldn't check free disk space at $InstallRoot." `+ "Make sure that path exists and is on an NTFS volume."+ }+}++function script:Pf-CheckNetwork {+ if ($SkipNetwork) {+ Pf-Warn "Network checks skipped (-SkipNetwork)." `+ "If image pulls fail, the cause is probably a corporate proxy."+ return+ }+ $failed = 0+ foreach ($url in $script:PfNetHosts) {+ try {+ # Invoke-WebRequest has no equivalent of curl --max-time; use+ # a HttpClient with a 6 s timeout. We only care about *some*+ # response — any 2xx/3xx/401/403 means the host is reachable.+ $req = [System.Net.WebRequest]::Create($url)+ $req.Timeout = 6000+ $req.Method = "HEAD"+ $resp = $null+ try {+ $resp = $req.GetResponse()+ $code = [int]$resp.StatusCode+ } catch [System.Net.WebException] {+ if ($_.Exception.Response) {+ $code = [int]$_.Exception.Response.StatusCode+ } else {+ $code = 0+ }+ } finally {+ if ($resp) { $resp.Close() }+ }+ if ($code -ge 200 -and $code -lt 400) { continue }+ if ($code -eq 401 -or $code -eq 403) { continue }+ Pf-Warn "Couldn't reach $url (HTTP $code)." `+ "If you're behind a corporate proxy, set HTTP_PROXY + HTTPS_PROXY before continuing."+ $failed+++ } catch {+ Pf-Warn "Couldn't reach $url ($($_.Exception.Message.Split([Environment]::NewLine)[0]))." `+ "If you're behind a corporate proxy, set HTTP_PROXY + HTTPS_PROXY before continuing."+ $failed+++ }+ }+ if ($failed -eq 0) {+ Pf-Pass "Network: github.com, ghcr.io, npmjs.org all reachable"+ }+}++function script:Pf-CheckWsl2 {+ $wslExe = Get-Command wsl.exe -ErrorAction SilentlyContinue+ if (-not $wslExe) {+ Pf-Fail "WSL2 isn't installed (wsl.exe not found)." `+ "Run 'wsl --install' from an elevated PowerShell, then reboot."+ return+ }+ try {+ # 'wsl --status' returns useful text on success, nothing on+ # missing-distro. We just check exit code + non-empty output.+ $statusOutput = & wsl.exe --status 2>&1+ if ($LASTEXITCODE -ne 0) {+ Pf-Fail "WSL is installed but 'wsl --status' failed (exit $LASTEXITCODE)." `+ "Try 'wsl --update' from an elevated PowerShell, then re-run preflight."+ return+ }+ $hasDistro = (& wsl.exe --list --quiet 2>&1) -match '\S'+ if (-not $hasDistro) {+ Pf-Warn "WSL2 has no default distro installed." `+ "Docker Desktop will set this up, but it'll add ~2 minutes to first launch."+ } else {+ Pf-Pass "WSL2 is installed with at least one distro"+ }+ } catch {+ Pf-Warn "Couldn't query 'wsl --status'." `+ "If Docker Desktop fails to start, run 'wsl --update' first."+ }+}++function script:Pf-CheckDockerDesktop {+ # We don't require Docker to be *running* during preflight (install.ps1+ # may install it), but if it IS installed, sanity-check it.+ $dockerExe = Get-Command docker.exe -ErrorAction SilentlyContinue+ if (-not $dockerExe) {+ return # install.ps1 will install it; nothing to check here+ }+ try {+ $out = & docker info --format '{{.ServerVersion}}' 2>&1+ if ($LASTEXITCODE -eq 0 -and $out) {+ Pf-Pass "Docker daemon is reachable (server $out)"+ } else {+ Pf-Warn "Docker is installed but the daemon isn't responding." `+ "Open Docker Desktop and wait for the whale icon to go solid before re-running."+ }+ } catch {+ Pf-Warn "Docker is installed but 'docker info' threw." `+ "Open Docker Desktop and wait for it to finish provisioning."+ }+}++function script:Pf-CheckPorts {+ $conflicts = 0+ $reused = 0+ foreach ($spec in $script:PfRequiredPorts) {+ $port = $spec.Port+ $name = $spec.Name+ $listener = Get-NetTCPConnection -State Listen -LocalPort $port -ErrorAction SilentlyContinue |+ Select-Object -First 1+ if (-not $listener) { continue }++ $owner = "an unknown process"+ try {+ $proc = Get-Process -Id $listener.OwningProcess -ErrorAction SilentlyContinue+ if ($proc) { $owner = "$($proc.ProcessName) (pid $($proc.Id))" }+ } catch { }++ if ($owner -match 'docker|com\.docker|aisoc') {+ Pf-Warn "Port $port ($name) is held by an existing AiSOC/Docker container ($owner)." `+ "We'll reuse it — but if a previous demo crashed, run 'pnpm aisoc:demo:down' first."+ $reused+++ } else {+ Pf-Fail "Port $port ($name) is in use by $owner." `+ "Stop that process, or set the corresponding *_PORT env var. See docs/QUICK_INSTALL.md#port-conflicts."+ $conflicts+++ }+ }+ if ($conflicts -eq 0 -and $reused -eq 0) {+ $portList = ($script:PfRequiredPorts | ForEach-Object { $_.Port }) -join ', '+ Pf-Pass "All required ports ($portList) are free"+ }+}++function script:Pf-CheckStaleContainers {+ $dockerExe = Get-Command docker.exe -ErrorAction SilentlyContinue+ if (-not $dockerExe) { return }+ try {+ # Containers in 'created' or 'exited' state from a previous run+ # will block 'docker compose up' with a name conflict. Detect+ # them so install.ps1 can offer to clean up.+ $stale = & docker ps -a --filter "name=aisoc-" --filter "status=exited" --filter "status=created" --format "{{.Names}}" 2>$null+ if ($LASTEXITCODE -eq 0 -and $stale) {+ $count = ($stale -split "`n" | Where-Object { $_ -ne '' }).Count+ Pf-Warn "Found $count stopped AiSOC container(s) from a previous run." `+ "Run 'docker rm -f `$(docker ps -aq --filter name=aisoc-)' or 'pnpm aisoc:demo:down' to clean up."+ }+ } catch {+ # Don't fail preflight just because docker query was flaky+ }+}++function script:Pf-CheckHyperVConflict {+ # This is a soft check. WSL2 backend is the recommended Docker+ # Desktop setup. If Hyper-V is enabled but WSL2 isn't, Docker+ # Desktop can still work but is much slower and uses more RAM.+ # We only warn — never fail — because some users have legit reasons.+ try {+ $hyperv = Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All -ErrorAction SilentlyContinue+ $wslExe = Get-Command wsl.exe -ErrorAction SilentlyContinue+ if ($hyperv -and $hyperv.State -eq 'Enabled' -and -not $wslExe) {+ Pf-Warn "Hyper-V is enabled but WSL2 isn't." `+ "Docker Desktop will run on the Hyper-V backend (slower, more RAM). Install WSL2 with 'wsl --install' for best perf."+ }+ } catch {+ # Get-WindowsOptionalFeature requires elevation on some systems+ }+}++# Returns $true if preflight passed (or only warnings), $false if any+# hard failures. install.ps1 treats this as a boolean — we deliberately+# don't return exit codes here because PowerShell makes 0 falsy, which+# would invert the meaning at the call site (a hilarious source of bugs).+function script:Pf-Summary {+ Write-Host ""+ Write-Host " Summary: $script:PfPass passed, $script:PfWarn warnings, $script:PfFail failures"+ Write-Host ""+ if ($script:PfFail -gt 0) {+ if ($Soft) {+ Write-Host "Preflight reported failures (continuing because -Soft was set)." -ForegroundColor Yellow+ Write-Host "Full troubleshooting: docs/QUICK_INSTALL.md#troubleshooting"+ return $true+ }+ Write-Host "Preflight FAILED. Address the items above and re-run." -ForegroundColor Red+ Write-Host "Full troubleshooting: docs/QUICK_INSTALL.md#troubleshooting"+ return $false+ }+ if ($script:PfWarn -gt 0) {+ Write-Host "Preflight passed with warnings — installer will continue." -ForegroundColor Yellow+ return $true+ }+ Write-Host "Preflight passed cleanly. Ready to install." -ForegroundColor Green+ return $true+}++# Note the casing — install.ps1 calls this as Invoke-AiSOCPreflight to+# match the project name. PowerShell function names are case-insensitive,+# but matching the project casing makes greps useful.+function Invoke-AiSOCPreflight {+ Write-Host ""+ Write-Host "Preflight checks" -ForegroundColor Cyan+ Pf-CheckWindowsVersion+ Pf-CheckArch+ Pf-CheckRam+ Pf-CheckDisk+ Pf-CheckNetwork+ Pf-CheckWsl2+ Pf-CheckDockerDesktop+ Pf-CheckPorts+ Pf-CheckStaleContainers+ Pf-CheckHyperVConflict+ return (Pf-Summary)+}++# When run standalone (not dot-sourced), execute and exit with a+# conventional shell exit code. When dot-sourced, install.ps1 calls+# Invoke-AiSOCPreflight itself and inspects the boolean return value.+if ($MyInvocation.InvocationName -ne '.') {+ if (Invoke-AiSOCPreflight) { exit 0 } else { exit 1 }+}diff --git a/scripts/install/preflight.sh b/scripts/install/preflight.shnew file mode 100755index 000000000..e62776bbc--- /dev/null+++ b/scripts/install/preflight.sh@@ -0,0 +1,446 @@+#!/usr/bin/env bash+###############################################################################+# AiSOC — Preflight checks (Linux + macOS).+#+# This is a sourced library, not a standalone script. It's loaded by+# install.sh before any prerequisite work begins, and is also runnable on+# its own via:+#+# bash scripts/install/preflight.sh+#+# Goal: catch the things that will make `pnpm aisoc:demo` fail four minutes+# from now — *before* we download a gigabyte of Docker images and ask the+# user to type their sudo password.+#+# We check, in order:+#+# 1. CPU architecture (must be amd64 or arm64)+# 2. Total RAM (≥ 4 GB hard fail, ≥ 8 GB recommended)+# 3. Free disk space at the install root and at $HOME/.docker+# (≥ 10 GB hard fail, ≥ 20 GB recommended)+# 4. Internet reachability (DNS resolves + HTTPS to ghcr.io / github.com)+# 5. Required ports are free, OR already used by an AiSOC container we can+# reuse — anything else is a conflict the user has to resolve+# 6. No leftover/conflicting AiSOC containers from a previous run that+# would refuse to start cleanly+# 7. macOS-specific: Docker Desktop is installed *and* has at least 4 GB+# RAM allocated to the VM (smaller and the api crashes mid-boot)+#+# Each check produces one line of output and one of three states:+#+# PASS — silently records ok=$ok+1+# WARN — prints a yellow line, increments warn count, but doesn't fail+# FAIL — prints a red line, increments fail count+#+# At the end we print a summary. If any FAILs were recorded we exit 1+# *unless* the caller passed AISOC_PREFLIGHT_SOFT=1 (which install.sh sets+# when re-running preflight after a fix, so we don't bail twice).+#+# Exit codes (when run standalone):+# 0 all checks passed+# 1 at least one hard FAIL — installer would not succeed+# 2 preflight itself failed (couldn't gather data)+#+# Reads (no writes):+# AISOC_PREFLIGHT_SOFT if set to 1, return non-zero count instead of exit+# AISOC_REPO_ROOT if set, used as the install location for disk-space+# checks. Otherwise we use $PWD when sourced or+# $HOME/aisoc when run standalone.+# AISOC_SKIP_NETWORK if 1, skip the connectivity probes (for air-gapped+# testing — preflight will WARN, not FAIL).+###############################################################################++# Don't `set -e` because we need to inspect the exit code of each check and+# keep going. The caller (install.sh) sets it; we explicitly disable it on+# entry and restore it at the end so we don't surprise sourced callers.+_AISOC_PREFLIGHT_PREV_E="$(set +o | grep errexit)"+set +e++# ─── Config ──────────────────────────────────────────────────────────────────++# Hard floor / recommended floor for resources. Anything below the hard floor+# is a FAIL; anything between hard and recommended is a WARN. These numbers+# come from running the demo stack repeatedly and watching what actually+# breaks first when the system is starved (api OOM-kills around 3 GB total+# RAM, postgres + opensearch trash the disk below 8 GB free).+readonly _PF_RAM_MIN_MB=4096+readonly _PF_RAM_REC_MB=8192+readonly _PF_DISK_MIN_GB=10+readonly _PF_DISK_REC_GB=20++# Ports the demo stack exposes on the host. We probe each one and (a)+# tolerate it being free, (b) tolerate it being held by an aisoc-* container+# from a previous run, but (c) fail if it's held by anything else. The list+# is kept in lockstep with docker-compose.demo.yml — when a port is added+# there, add it here too.+#+# Using parallel arrays instead of an associative array because macOS still+# ships Bash 3.2 by default and `declare -A` only works in 4+.+readonly _PF_PORT_NUMS=(3000 5432 6379 8000 8001 8086 9092)+readonly _PF_PORT_NAMES=("web console" "postgres" "redis" "api" "agents" "realtime ws" "kafka")++# Hosts we curl during the connectivity probe. We hit specific endpoints+# that we know will return 200 (not just any path on the host), because+# ghcr.io's root replies 404 and would generate false negatives.+#+# - api.github.com/zen: a stable lightweight 200 endpoint, also confirms+# github.com cert chain+# - ghcr.io/v2/: Docker Registry API root, returns 200 (or 401 with -f off)+# - registry.npmjs.org/: returns the registry status JSON, a 200+readonly _PF_NET_HOSTS=(+ "https://api.github.com/zen"+ "https://ghcr.io/v2/"+ "https://registry.npmjs.org/"+)++# ─── Logging (terminal-aware, mirrors install.sh) ────────────────────────────++if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then+ _PF_RED=$'\033[31m'+ _PF_GREEN=$'\033[32m'+ _PF_YELLOW=$'\033[33m'+ _PF_BLUE=$'\033[34m'+ _PF_DIM=$'\033[2m'+ _PF_BOLD=$'\033[1m'+ _PF_RESET=$'\033[0m'+else+ _PF_RED=""; _PF_GREEN=""; _PF_YELLOW=""; _PF_BLUE=""; _PF_DIM=""; _PF_BOLD=""; _PF_RESET=""+fi++_PF_OK=0+_PF_WARN=0+_PF_FAIL=0+_PF_FAIL_HINTS=()++_pf_pass() {+ printf ' %s✓%s %s\n' "$_PF_GREEN" "$_PF_RESET" "$1"+ _PF_OK=$((_PF_OK + 1))+}++_pf_warn() {+ printf ' %s!%s %s\n' "$_PF_YELLOW" "$_PF_RESET" "$1"+ if [ -n "${2:-}" ]; then+ printf ' %shint:%s %s\n' "$_PF_DIM" "$_PF_RESET" "$2"+ fi+ _PF_WARN=$((_PF_WARN + 1))+}++_pf_fail() {+ printf ' %s✗%s %s\n' "$_PF_RED" "$_PF_RESET" "$1"+ if [ -n "${2:-}" ]; then+ printf ' %sfix:%s %s\n' "$_PF_DIM" "$_PF_RESET" "$2"+ _PF_FAIL_HINTS+=("$2")+ fi+ _PF_FAIL=$((_PF_FAIL + 1))+}++# ─── Helpers ─────────────────────────────────────────────────────────────────++_pf_have() { command -v "$1" >/dev/null 2>&1; }++# Print integer MB of RAM. Linux: parse /proc/meminfo. macOS: hw.memsize.+# Falls back to "0" if neither path works (treat as unknown — we'll WARN).+_pf_total_ram_mb() {+ if [ -r /proc/meminfo ]; then+ awk '/^MemTotal:/ { printf "%d\n", $2/1024; exit }' /proc/meminfo+ elif _pf_have sysctl; then+ # hw.memsize is bytes. Divide by 1024^2 for MB.+ sysctl -n hw.memsize 2>/dev/null | awk '{ printf "%d\n", $1/1024/1024 }'+ else+ echo 0+ fi+}++# Print integer GB of free space at the given path (rounded down). Uses+# `df -P -k` because BSD-df and GNU-df disagree on column order without -P.+_pf_free_disk_gb() {+ local path="$1"+ if [ ! -d "$path" ]; then+ # Walk up to the nearest existing parent — `df` won't report on a path+ # that doesn't exist yet, and we frequently pre-check dirs we're about+ # to create.+ while [ -n "$path" ] && [ "$path" != "/" ] && [ ! -d "$path" ]; do+ path="$(dirname "$path")"+ done+ fi+ df -P -k "$path" 2>/dev/null | awk 'NR==2 { printf "%d\n", $4/1024/1024 }'+}++# Returns 0 if a TCP listener is already bound to localhost:$1, else 1.+# We try `lsof` first (universal), `ss` second (modern Linux), then a raw+# /dev/tcp probe as a last-resort. /dev/tcp is bash-only and may be disabled+# on hardened distros, hence the cascade.+_pf_port_listener() {+ local port="$1"+ if _pf_have lsof; then+ lsof -nP -iTCP:"$port" -sTCP:LISTEN >/dev/null 2>&1 && return 0+ return 1+ fi+ if _pf_have ss; then+ ss -lnt "sport = :$port" 2>/dev/null | grep -q "LISTEN" && return 0+ return 1+ fi+ if (echo > "/dev/tcp/127.0.0.1/$port") >/dev/null 2>&1; then+ return 0+ fi+ return 1+}++# Print the friendly label of whatever process is holding $1, or "" if we+# can't tell. Examples: "docker (aisoc-api-1)", "postgres (system)", "node".+_pf_port_owner() {+ local port="$1" pid cmd container+ if _pf_have lsof; then+ pid="$(lsof -nP -iTCP:"$port" -sTCP:LISTEN -t 2>/dev/null | head -n1)"+ if [ -n "$pid" ]; then+ cmd="$(ps -p "$pid" -o comm= 2>/dev/null | tr -d '[:space:]')"+ if [ "$cmd" = "com.docker.backend" ] || [ "$cmd" = "com.docker.vmnetd" ] || [ "$cmd" = "docker-pr" ] || [ "$cmd" = "docker-proxy" ]; then+ # Try to find the container that opened this published port.+ if _pf_have docker; then+ container="$(docker ps --filter "publish=$port" --format '{{.Names}}' 2>/dev/null | head -n1)"+ if [ -n "$container" ]; then+ echo "docker container: $container"+ return 0+ fi+ fi+ echo "docker (unknown container)"+ return 0+ fi+ echo "${cmd:-pid $pid}"+ return 0+ fi+ fi+ echo ""+}++# Returns 0 if the given port-owner string indicates an AiSOC container —+# i.e. a previous demo run we can safely reuse / restart. The names come+# from docker-compose.demo.yml + the project's compose project name+# (defaults to the directory name, usually "aisoc").+#+# We can't use ${var,,} (bash 4+) here because macOS still ships bash 3.2+# by default. Pipe through tr instead — works everywhere.+_pf_owner_is_aisoc() {+ local lc+ lc="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"+ case "$lc" in+ *aisoc*) return 0 ;;+ *) return 1 ;;+ esac+}++# ─── Checks ──────────────────────────────────────────────────────────────────++_pf_check_arch() {+ case "$(uname -m)" in+ x86_64|amd64|aarch64|arm64)+ _pf_pass "CPU architecture: $(uname -m)"+ ;;+ armv7*|armv6*|i?86)+ _pf_fail "CPU architecture $(uname -m) is not supported." \+ "AiSOC images are amd64 + arm64 only. 32-bit ARM and i386 won't work."+ ;;+ *)+ _pf_warn "CPU architecture $(uname -m) is unrecognised — proceed at your own risk."+ ;;+ esac+}++_pf_check_ram() {+ local mb+ mb="$(_pf_total_ram_mb)"+ if [ "$mb" = "0" ] || [ -z "$mb" ]; then+ _pf_warn "Couldn't read total system RAM."+ return+ fi+ if [ "$mb" -lt "$_PF_RAM_MIN_MB" ]; then+ _pf_fail "RAM: ${mb} MB total (need ≥ ${_PF_RAM_MIN_MB} MB)." \+ "Add memory or run on a larger machine. The demo stack needs ~3 GB resident."+ elif [ "$mb" -lt "$_PF_RAM_REC_MB" ]; then+ _pf_warn "RAM: ${mb} MB total (recommended ≥ ${_PF_RAM_REC_MB} MB)." \+ "Demo will run but may swap. 8 GB is the sweet spot."+ else+ _pf_pass "RAM: ${mb} MB total"+ fi+}++_pf_check_disk() {+ local install_root="${AISOC_REPO_ROOT:-${PWD:-/}}"+ local install_gb+ install_gb="$(_pf_free_disk_gb "$install_root")"+ if [ -z "$install_gb" ]; then install_gb=0; fi++ if [ "$install_gb" -lt "$_PF_DISK_MIN_GB" ]; then+ _pf_fail "Disk: only ${install_gb} GB free at $install_root (need ≥ ${_PF_DISK_MIN_GB} GB)." \+ "Free up space or pass --clone-dir to point install.sh at a roomier disk."+ elif [ "$install_gb" -lt "$_PF_DISK_REC_GB" ]; then+ _pf_warn "Disk: ${install_gb} GB free at $install_root (recommended ≥ ${_PF_DISK_REC_GB} GB)."+ else+ _pf_pass "Disk: ${install_gb} GB free at $install_root"+ fi++ # Docker writes its image cache to /var/lib/docker on Linux and to+ # ~/Library/Containers/com.docker.docker on macOS. Probe whichever one+ # exists. We need this because /home and /var are often separate+ # filesystems and a "20 GB free in $HOME" check tells us nothing about+ # whether a 4 GB image pull will succeed.+ local docker_root=""+ if [ -d /var/lib/docker ]; then+ docker_root=/var/lib/docker+ elif [ -d "$HOME/Library/Containers/com.docker.docker" ]; then+ docker_root="$HOME/Library/Containers/com.docker.docker"+ fi+ if [ -n "$docker_root" ]; then+ local d_gb+ d_gb="$(_pf_free_disk_gb "$docker_root")"+ if [ -n "$d_gb" ] && [ "$d_gb" -lt "$_PF_DISK_MIN_GB" ]; then+ _pf_fail "Disk: only ${d_gb} GB free at Docker root ($docker_root)." \+ "Run 'docker system prune -af' to reclaim space, or move the Docker root."+ fi+ fi+}++_pf_check_network() {+ if [ "${AISOC_SKIP_NETWORK:-0}" = "1" ]; then+ _pf_warn "Skipping network checks (AISOC_SKIP_NETWORK=1)."+ return+ fi+ if ! _pf_have curl; then+ _pf_warn "curl not installed — skipping connectivity probe (will install in step 1)."+ return+ fi+ local host failed=0 http_code+ for host in "${_PF_NET_HOSTS[@]}"; do+ # -m 6: hard 6 s timeout per host. -s: silent. -L: follow redirects.+ # -o /dev/null: discard body. -w '%{http_code}': print just the status.+ # We treat anything in 2xx/3xx/401 as "host is up" — 401 is GHCR's+ # legitimate "auth required" response, not a connectivity failure.+ http_code="$(curl -s -L -m 6 -o /dev/null -w '%{http_code}' "$host" 2>/dev/null || echo "000")"+ case "$http_code" in+ 2*|3*|401|403) continue ;;+ *)+ _pf_warn "Couldn't reach $host (HTTP ${http_code:-no-response})." \+ "If you're behind a corporate proxy, set https_proxy + http_proxy before continuing."+ failed=$((failed + 1))+ ;;+ esac+ done+ if [ "$failed" -eq 0 ]; then+ _pf_pass "Network: github.com, ghcr.io, npmjs.org all reachable"+ fi+}++_pf_check_ports() {+ local i port name owner conflicts=0 reused=0+ for i in "${!_PF_PORT_NUMS[@]}"; do+ port="${_PF_PORT_NUMS[$i]}"+ name="${_PF_PORT_NAMES[$i]}"+ if ! _pf_port_listener "$port"; then+ continue+ fi+ owner="$(_pf_port_owner "$port")"+ if _pf_owner_is_aisoc "$owner"; then+ _pf_warn "Port $port ($name) is held by an existing AiSOC container ($owner)." \+ "We'll reuse it — but if a previous demo crashed, run 'pnpm aisoc:demo:down' first."+ reused=$((reused + 1))+ else+ _pf_fail "Port $port ($name) is in use by ${owner:-an unknown process}." \+ "Stop that process, or set the corresponding *_PORT env var to remap. See docs/QUICK_INSTALL.md#port-conflicts."+ conflicts=$((conflicts + 1))+ fi+ done+ if [ "$conflicts" -eq 0 ] && [ "$reused" -eq 0 ]; then+ _pf_pass "All required ports (${_PF_PORT_NUMS[*]}) are free"+ fi+}++_pf_check_stale_containers() {+ if ! _pf_have docker; then+ return+ fi+ if ! docker info >/dev/null 2>&1; then+ return+ fi+ # Look for stopped/exited aisoc-* containers from a previous failed run.+ # `docker compose up` will sometimes refuse to recreate these depending on+ # the volume state, so we surface them up-front.+ local stale+ stale="$(docker ps -a --filter "name=aisoc-" --filter "status=exited" --format '{{.Names}}' 2>/dev/null | head -5)"+ if [ -n "$stale" ]; then+ _pf_warn "Stale AiSOC containers from a previous run:" \+ "Run 'pnpm aisoc:demo:down' (in the AiSOC clone) to clear them. Listed: $(echo "$stale" | tr '\n' ' ')"+ fi+}++_pf_check_macos_docker() {+ if [ "$(uname -s)" != "Darwin" ]; then return; fi+ if ! _pf_have docker; then return; fi+ # If docker CLI is installed but the daemon isn't reachable, say so+ # *clearly* — we previously printed "Docker Desktop is allocated 0 MB"+ # which sounded like a config problem when actually Docker Desktop just+ # wasn't running. install.sh will boot it on macOS, but the user needs+ # to know that's what's happening.+ if ! docker info >/dev/null 2>&1; then+ _pf_warn "Docker Desktop appears installed but the daemon isn't running." \+ "install.sh will launch it; or open Docker.app yourself and re-run."+ return+ fi+ # Daemon is up — verify it has enough RAM allocated.+ local raw mb+ raw="$(docker info --format '{{json .MemTotal}}' 2>/dev/null)"+ if [ -z "$raw" ] || [ "$raw" = "null" ] || [ "$raw" = "0" ]; then+ # Daemon answered but couldn't tell us its memory budget — odd, skip.+ return+ fi+ # MemTotal is bytes.+ mb=$((raw / 1024 / 1024))+ if [ "$mb" -lt 4000 ]; then+ _pf_fail "Docker Desktop is allocated only ${mb} MB of RAM (need ≥ 4096 MB)." \+ "Open Docker Desktop → Settings → Resources → Memory and bump to at least 4 GB."+ fi+}++# ─── Driver ──────────────────────────────────────────────────────────────────++run_aisoc_preflight() {+ printf '\n%s%sPreflight checks%s\n' "$_PF_BOLD" "$_PF_BLUE" "$_PF_RESET"++ _pf_check_arch+ _pf_check_ram+ _pf_check_disk+ _pf_check_network+ _pf_check_ports+ _pf_check_stale_containers+ _pf_check_macos_docker++ printf '\n %sSummary:%s %s%d passed%s, %s%d warnings%s, %s%d failures%s\n\n' \+ "$_PF_BOLD" "$_PF_RESET" \+ "$_PF_GREEN" "$_PF_OK" "$_PF_RESET" \+ "$_PF_YELLOW" "$_PF_WARN" "$_PF_RESET" \+ "$_PF_RED" "$_PF_FAIL" "$_PF_RESET"++ if [ "$_PF_FAIL" -gt 0 ]; then+ printf '%s%sPreflight FAILED.%s Address the items above and re-run.\n' \+ "$_PF_BOLD" "$_PF_RED" "$_PF_RESET"+ printf '%sFull troubleshooting:%s docs/QUICK_INSTALL.md#troubleshooting\n\n' \+ "$_PF_DIM" "$_PF_RESET"+ if [ "${AISOC_PREFLIGHT_SOFT:-0}" = "1" ]; then+ return 1+ fi+ exit 1+ fi+ return 0+}++# Run automatically only when invoked as a script, not when sourced.+# BASH_SOURCE[0] == $0 means "called directly".+if [ "${BASH_SOURCE[0]}" = "${0}" ]; then+ run_aisoc_preflight+ rc=$?+ # Restore the caller's errexit setting before returning.+ eval "$_AISOC_PREFLIGHT_PREV_E"+ exit $rc+fi++# Sourced — restore errexit and let the caller decide when to run.+eval "$_AISOC_PREFLIGHT_PREV_E"diff --git a/uninstall.ps1 b/uninstall.ps1index 43dfd04c8..4c234fa5f 100644--- a/uninstall.ps1+++ b/uninstall.ps1@@ -51,8 +51,11 @@.NOTESExit codes:0 success- 1 invalid arguments+ 1 invalid arguments / unexpected error2 not run from inside an AiSOC clone (and -RemoveRepo wasn't given)+ 3 refused to delete a path for safety reasons (system dir, not an+ AiSOC clone, etc.) — visible separately so CI scripts don't+ silently treat a refusal as "all done"#>[CmdletBinding()]@@ -72,6 +75,11 @@ if ($All) {$RemoveRepo = $true}+# Tracks whether we refused a delete for safety reasons. We don't fail-fast+# on refusals (the user might still want to clean up volumes / images), but+# we do exit non-zero at the end so CI scripts notice.+$script:SafetyRefused = $false+# ─── Logging helpers (match install.ps1 style) ──────────────────────────────function Write-Log { param([string]$m) Write-Host "[aisoc] $m" -ForegroundColor DarkGray }@@ -140,13 +148,21 @@ if (-not $RepoRoot) {# ─── Step 1: stop the demo stack ────────────────────────────────────────────-function Stop-DemoStack {+function Test-DockerReachable {+ # PowerShell native commands don't throw on non-zero exit, so try/catch+ # around `docker info` is a no-op. Check $LASTEXITCODE explicitly.$docker = Get-Command docker -ErrorAction SilentlyContinue- if (-not $docker) {+ if (-not $docker) { return $false }+ & docker info *> $null+ return ($LASTEXITCODE -eq 0)+}++function Stop-DemoStack {+ if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {Write-Warn "docker not on PATH; skipping compose down."return}- try { docker info 2>$null | Out-Null } catch {+ if (-not (Test-DockerReachable)) {Write-Warn "docker daemon not reachable; skipping compose down."return}@@ -172,12 +188,11 @@ function Stop-DemoStack {function Remove-AiSOCImages {if (-not $RemoveImages) { return }- $docker = Get-Command docker -ErrorAction SilentlyContinue- if (-not $docker) {+ if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {Write-Warn "docker unreachable; skipping image removal."return}- try { docker info 2>$null | Out-Null } catch {+ if (-not (Test-DockerReachable)) {Write-Warn "docker daemon not reachable; skipping image removal."return}@@ -223,6 +238,41 @@ function Remove-NodeModulesTrees {# ─── Step 4: blow away the repo clone ───────────────────────────────────────+function Test-DangerousPath {+ # Refuse rm -rf on system or home-root directories. The "Steam deleted+ # my home" defense — better paranoid than apologetic.+ param([string]$Path)+ if ([string]::IsNullOrWhiteSpace($Path)) { return $true }+ $abs = $Path+ try { $abs = (Resolve-Path -LiteralPath $Path -ErrorAction Stop).ProviderPath } catch {}+ # Normalise: strip trailing slash and lower-case for matching.+ $norm = $abs.TrimEnd('\', '/').ToLowerInvariant()++ # Bare drive roots (C:, D:\, etc.) — refuse before doing anything else.+ if ($norm -match '^[a-z]:$' -or $norm -match '^[a-z]:\\?$') { return $true }++ # Build the blocklist defensively — any of these env vars could in theory+ # be empty on a weird system, and calling .ToLowerInvariant() on $null+ # throws. We collect candidates as nullable strings, then filter empties.+ $candidates = New-Object System.Collections.Generic.List[string]+ $candidates.Add($env:SystemDrive)+ $candidates.Add($env:windir)+ $candidates.Add($env:ProgramFiles)+ $candidates.Add(${env:ProgramFiles(x86)})+ $candidates.Add($env:USERPROFILE)+ if (-not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {+ $candidates.Add((Join-Path $env:USERPROFILE 'Desktop'))+ $candidates.Add((Join-Path $env:USERPROFILE 'Documents'))+ $candidates.Add((Join-Path $env:USERPROFILE 'Downloads'))+ }+ foreach ($c in $candidates) {+ if ([string]::IsNullOrWhiteSpace($c)) { continue }+ $b = $c.TrimEnd('\', '/').ToLowerInvariant()+ if ($norm -eq $b) { return $true }+ }+ return $false+}+function Remove-RepoClone {if (-not $RemoveRepo) { return }$target = if ($RepoRoot) { $RepoRoot } else { Join-Path $env:USERPROFILE 'aisoc' }@@ -230,9 +280,36 @@ function Remove-RepoClone {Write-Warn "No repo found at $target; nothing to remove."return}+ # Final sanity check: target must look like an AiSOC clone. Stops us+ # from rm -rf'ing some unrelated dir the user happened to put in+ # %USERPROFILE%\aisoc.+ $composeFile = Join-Path $target 'docker-compose.demo.yml'+ $pkgFile = Join-Path $target 'package.json'+ $looksLikeAiSOC = $false+ if ((Test-Path $composeFile) -and (Test-Path $pkgFile)) {+ $pkgContent = Get-Content $pkgFile -Raw -ErrorAction SilentlyContinue+ if ($pkgContent -and $pkgContent -match '"name"\s*:\s*"aisoc"') {+ $looksLikeAiSOC = $true+ }+ }+ if (-not $looksLikeAiSOC) {+ Write-Warn "$target doesn't look like an AiSOC clone (missing compose file or package.json marker)."+ Write-Warn "Refusing to delete it — clean it up manually if you really want to."+ $script:SafetyRefused = $true+ return+ }+ if (Test-DangerousPath -Path $target) {+ Write-Err "Refusing to delete $target — looks like a system or profile root directory."+ Write-Err "If you really meant to delete this path, do it by hand."+ $script:SafetyRefused = $true+ return+ }Write-Section "Removing AiSOC repo"Write-Warn "About to recursively delete: $target"if (Confirm-Action "Are you absolutely sure?") {+ # cd somewhere safe before deleting — PowerShell holds a lock on+ # the cwd, so deleting it can fail or leave orphan handles.+ try { Set-Location $env:TEMP } catch { try { Set-Location $env:SystemDrive } catch {} }try {Remove-Item -Recurse -Force -LiteralPath $target -ErrorAction StopWrite-Ok "Repo deleted."@@ -251,7 +328,12 @@ Remove-NodeModulesTreesRemove-RepoCloneWrite-Host ""-Write-Host "AiSOC uninstall complete." -ForegroundColor Green+if ($script:SafetyRefused) {+ Write-Host "AiSOC uninstall finished — but at least one delete was refused for safety." -ForegroundColor Yellow+ Write-Host "See messages above. Exiting with code 3 so CI/scripts notice." -ForegroundColor Yellow+} else {+ Write-Host "AiSOC uninstall complete." -ForegroundColor Green+}Write-Host ""Write-Host "Things this script intentionally did NOT remove:" -ForegroundColor DarkGrayWrite-Host " - Docker Desktop, Node, pnpm, git (shared dev tools)"@@ -262,3 +344,5 @@ Write-Host ""Write-Host "To remove the leftover infrastructure images too:" -ForegroundColor DarkGrayWrite-Host " docker image prune -a # removes ALL dangling+unused images, not just AiSOC's"Write-Host ""++if ($script:SafetyRefused) { exit 3 }diff --git a/uninstall.sh b/uninstall.shindex b249896ae..c0bb76d14 100755--- a/uninstall.sh+++ b/uninstall.sh@@ -33,8 +33,11 @@## Exit codes:# 0 success-# 1 invalid arguments+# 1 invalid arguments / unexpected error# 2 not run from inside an AiSOC clone (and --repo wasn't given)+# 3 refused to delete a path for safety reasons (system dir, not an AiSOC+# clone, etc.) — visible separately so CI scripts don't silently treat+# a refusal as "all done"###############################################################################set -euo pipefail@@ -68,6 +71,11 @@ REMOVE_NODE_MODULES=0REMOVE_REPO=0YES=0 # skip confirmation prompts (for CI / scripted use)+# Tracks whether we refused a delete for safety reasons. We don't fail-fast+# on refusals (the user might still want volumes/images cleaned), but we exit+# non-zero at the end so CI scripts notice.+SAFETY_REFUSED=0+while [ $# -gt 0 ]; docase "$1" in--images) REMOVE_IMAGES=1 ;;@@ -196,6 +204,35 @@ remove_node_modules() {# ─── Step 4: blow away the repo clone ────────────────────────────────────────+is_dangerous_path() {+ # Refuse rm -rf on anything that looks like a system directory or the+ # user's home root. This is the "did Steam delete my home directory"+ # safety check — better paranoid than apologetic. We canonicalise via+ # realpath when available so symlinks can't dodge the blacklist.+ local p="$1"+ case "$p" in+ ""|/|/.|/..) return 0 ;;+ esac+ # Block the user's home root, common system dirs, and the FS root.+ local abs="$p"+ if command -v realpath >/dev/null 2>&1; then+ abs="$(realpath "$p" 2>/dev/null || printf '%s' "$p")"+ fi+ case "$abs" in+ /|/bin|/sbin|/usr|/usr/*|/etc|/etc/*|/var|/var/*|/opt|/opt/*) return 0 ;;+ /lib|/lib/*|/lib64|/lib64/*|/boot|/boot/*|/dev|/dev/*|/proc|/proc/*|/sys|/sys/*) return 0 ;;+ /tmp|/private/tmp|"$HOME"|"$HOME/") return 0 ;;+ /Users|/Users/*|/home|/home/*)+ # Allow /home/<user>/something but not /home or /home/<user> itself.+ # Same for /Users.+ local depth+ depth=$(printf '%s' "$abs" | tr -cd '/' | wc -c | tr -d ' ')+ [ "$depth" -le 2 ] && return 0+ ;;+ esac+ return 1+}+remove_repo_clone() {if [ "$REMOVE_REPO" = "0" ]; then return 0; fi# Two candidate locations: $REPO_ROOT (whatever we found) and the canonical@@ -206,9 +243,29 @@ remove_repo_clone() {warn "No repo found at $target; nothing to remove."return 0fi+ # Final sanity check: the path must look like an AiSOC clone (has the+ # compose file AND a package.json claiming the project name). This stops+ # us from rm -rf'ing some unrelated directory the user happened to put+ # in $HOME/aisoc.+ if [ ! -f "$target/docker-compose.demo.yml" ] || ! grep -q '"name": "aisoc"' "$target/package.json" 2>/dev/null; then+ warn "$target doesn't look like an AiSOC clone (missing compose file or package.json marker)."+ warn "Refusing to delete it — clean it up manually if you really want to."+ SAFETY_REFUSED=1+ return 0+ fi+ if is_dangerous_path "$target"; then+ err "Refusing to delete $target — looks like a system or home root directory."+ err "If you really meant to delete this path, do it by hand."+ SAFETY_REFUSED=1+ return 0+ fisection "Removing AiSOC repo"warn "About to recursively delete: $target"if confirm "Are you absolutely sure?"; then+ # cd somewhere safe before rm -rf'ing — if $REPO_ROOT is the cwd of+ # this shell, deleting it can confuse macOS's filesystem and leave+ # the script unable to print the final banner.+ cd /tmp 2>/dev/null || cd / || truerm -rf "$target"ok "Repo deleted."fi@@ -223,10 +280,22 @@ main() {remove_node_modulesremove_repo_clone- cat <<EOF+ if [ "$SAFETY_REFUSED" = "1" ]; then+ cat <<EOF++${C_YELLOW}AiSOC uninstall finished — but at least one delete was refused for safety.${C_RESET}+${C_YELLOW}See messages above. Exiting with code 3 so CI/scripts notice.${C_RESET}++EOF+ else+ cat <<EOF${C_GREEN}AiSOC uninstall complete.${C_RESET}+EOF+ fi++ cat <<EOF${C_DIM}Things this script intentionally did NOT remove:${C_RESET}- Docker, Node, pnpm, git (shared dev tools)- Your membership in the 'docker' group@@ -237,6 +306,10 @@ ${C_DIM}To remove the leftover infrastructure images too:${C_RESET}docker image prune -a # removes ALL dangling+unused images, not just AiSOC'sEOF++ if [ "$SAFETY_REFUSED" = "1" ]; then+ exit 3+ fi}main "$@"