Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

fix(install): a fresh Windows install can boot, and every on-ramp leads to the real stack (#1475)

Beenu Aroraf7c17e4844d3
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json
index fc969bca7..625ec6331 100644
--- a/.devcontainer/devcontainer.json
+++ b/.devcontainer/devcontainer.json
@@ -46,7 +46,13 @@
"onCreateCommand": "pnpm install --frozen-lockfile",
"//postStartCommand": "Starts dockerd. Runs on every container start rather than only at create, so a Codespace stop/resume comes back with a working daemon — `onCreateCommand` would leave the second boot without one.",
"postStartCommand": "bash .devcontainer/start-docker.sh",
- "postAttachCommand": "echo '\\n>>> AiSOC dev container is ready.\\n>>> To run the demo, open a terminal and run:\\n>>> pnpm aisoc:demo --no-open\\n>>> Then click the forwarded port 3000 in the Ports panel.\\n>>> Or, no-Docker: pip install -e packages/aisoc-sandbox && aisoc-sandbox demo\\n'",
+ // `make up`, not `pnpm aisoc:demo`. The demo compose file has no ingest
+ // service, no fusion service and Kafka disabled — its own header says not
+ // to use it to evaluate whether AiSOC works — so pointing a fresh
+ // Codespace at it showed a populated console that had never run the
+ // pipeline. Both installers were rewritten to remove that handoff; this
+ // banner was the last place still sending people to it.
+ "postAttachCommand": "echo '\\n>>> AiSOC dev container is ready.\\n>>> To run the real stack, open a terminal and run:\\n>>> make up # starts it and creates your administrator\\n>>> make smoke # proves the pipeline end to end\\n>>> Then click the forwarded port 3000 in the Ports panel.\\n>>> Or, no-Docker: pip install -e packages/aisoc-sandbox && aisoc-sandbox demo\\n'",
"remoteUser": "node",
"containerEnv": {
"AISOC_DEV_MODE": "1"
diff --git a/.env.example b/.env.example
index d6f855aa3..5040764da 100644
--- a/.env.example
+++ b/.env.example
@@ -4,13 +4,17 @@
# ╔════════════════════════════════════════════════════════════════════════════╗
# ║ YOU DO NOT HAVE TO EDIT THIS FILE TO GET A WORKING STACK. ║
# ║ ║
-# ║ make up creates .env from this template and fills the four ║
-# ║ generated secrets — AISOC_CREDENTIAL_KEY, SECRET_KEY, ║
-# ║ AISOC_SERVICE_TOKEN, AISOC_ACTIONS_SERVICE_TOKEN — with ║
-# ║ real random values. ║
+# ║ make up creates .env from this template and fills the fifteen ║
+# ║ generated secrets with real random values — the ║
+# ║ credential vault key, the session signing key, five ║
+# ║ service-to-service credentials, the realtime and ║
+# ║ metrics tokens, and four datastore passwords. The list ║
+# ║ lives in scripts/ensure_env.py; this comment does not ║
+# ║ repeat it, because a second copy is a second thing to ║
+# ║ go stale. ║
# ║ make env does only that, if you want to look before you start. ║
# ║ ║
-# ║ Those three ship EMPTY here rather than as `replace-me-…` prose. A ║
+# ║ They ship EMPTY here rather than as `replace-me-…` prose. A ║
# ║ placeholder is not a neutral default: a non-empty AISOC_CREDENTIAL_KEY ║
# ║ that is not a valid Fernet key made every connector save answer HTTP 500, ║
# ║ so copying this template used to break the product while skipping the copy ║
@@ -21,8 +25,9 @@
# ║ OPENAI_API_KEY a hosted provider key for better AI triage. CORE ║
# ║ ships a local model, so this is an upgrade, not a ║
# ║ requirement — see "AI / LLM" below. ║
-# ║ POSTGRES_PASSWORD the dev default works out of the box; change it for ║
-# ║ anything shared. ║
+# ║ ║
+# ║ The datastore passwords are generated too, so there is no shared default ║
+# ║ left for you to change. ║
# ╚════════════════════════════════════════════════════════════════════════════╝
# ─── Image Pinning ────────────────────────────────────────────────────────────
diff --git a/.github/ISSUE_TEMPLATE/installer-failure.yml b/.github/ISSUE_TEMPLATE/installer-failure.yml
new file mode 100644
index 000000000..6d9f1e3f8
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/installer-failure.yml
@@ -0,0 +1,114 @@
+name: Installer failure
+description: install.sh or install.ps1 did not get you to a working console
+title: "[Install]: "
+labels: ["bug", "installer", "triage"]
+assignees: []
+
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Both installers link here when they fail, so the fields below are the
+ ones we would otherwise have to ask for. The two that decide almost
+ every case are the **exit code** and the **diagnose output** — the
+ installers document their exit codes, so the number alone usually
+ names the step that failed.
+
+ If you have not run it yet, this changes nothing and takes a minute:
+
+ ```
+ ./install.sh --diagnose # Linux / macOS
+ .\install.ps1 -Diagnose # Windows
+ ```
+
+ - type: dropdown
+ id: platform
+ attributes:
+ label: Platform
+ options:
+ - Windows 11
+ - Windows 10
+ - macOS (Apple silicon)
+ - macOS (Intel)
+ - Linux — Debian / Ubuntu
+ - Linux — Fedora / RHEL / CentOS
+ - Linux — Arch
+ - Linux — other
+ - Other / not sure
+ validations:
+ required: true
+
+ - type: dropdown
+ id: entrypoint
+ attributes:
+ label: How did you start the install?
+ options:
+ - "install.sh (curl | bash one-liner)"
+ - "install.sh (from a clone)"
+ - "install.ps1 (irm | iex one-liner)"
+ - "install.ps1 (from a clone)"
+ - "make up"
+ - "docker compose up -d"
+ - Other
+ validations:
+ required: true
+
+ - type: input
+ id: exit_code
+ attributes:
+ label: Exit code
+ description: >-
+ The number the installer exited with. Both installers document theirs:
+ 2 = a prerequisite could not be installed, 3 = the stack did not come
+ up, 4 = preflight refused, 5 = the clone or the end-to-end pipeline
+ check failed.
+ placeholder: "3"
+ validations:
+ required: false
+
+ - type: textarea
+ id: output
+ attributes:
+ label: Installer output
+ description: >-
+ The last 50 or so lines, including the error. Paste as text rather
+ than a screenshot so it is searchable for the next person.
+ render: shell
+ validations:
+ required: true
+
+ - type: textarea
+ id: diagnose
+ attributes:
+ label: Diagnose output
+ description: "Output of `./install.sh --diagnose` or `.\\install.ps1 -Diagnose`."
+ render: shell
+ validations:
+ required: false
+
+ - type: textarea
+ id: environment
+ attributes:
+ label: Environment
+ description: >-
+ Versions and the resources Docker has. `make doctor` prints all of
+ this if the clone got far enough.
+ placeholder: |
+ docker --version :
+ docker compose version :
+ python3 --version :
+ Docker memory / disk :
+ Anything already listening on 5432, 3000, 8000 or 11434:
+ render: shell
+ validations:
+ required: false
+
+ - type: checkboxes
+ id: checked
+ attributes:
+ label: Before filing
+ options:
+ - label: >-
+ I checked that no secret, token or password is included in the
+ output I pasted above.
+ required: true
diff --git a/.github/workflows/installer-smoke.yml b/.github/workflows/installer-smoke.yml
index a04975d67..113bb125c 100644
--- a/.github/workflows/installer-smoke.yml
+++ b/.github/workflows/installer-smoke.yml
@@ -332,6 +332,93 @@ jobs:
Write-Host "REGRESSION: undocumented exit code $rc from -Diagnose" -ForegroundColor Red
exit 1
+ # The one install step that decides whether the stack can boot at all, run
+ # on the OS it was broken on. install.ps1 plain-copied `.env.example` for
+ # as long as it existed: that ships `ENVIRONMENT=production` with
+ # `SECRET_KEY`, `JWT_SECRET`, `METRICS_TOKEN` and `AISOC_CREDENTIAL_KEY`
+ # empty, and `enforce_secure_defaults` refuses to start the API on exactly
+ # those values — so a fresh Windows install ended at "These services are
+ # not running: api" with nothing pointing back at the copy.
+ #
+ # Nothing here could see it: the Windows jobs above run `-Diagnose` only,
+ # which makes no changes, and a full install needs Docker Desktop. This
+ # job needs neither — it dot-sources the installer's own function and
+ # checks the file it produces, so it exercises the real code path on a
+ # real Windows runner in seconds.
+ env-secrets-windows:
+ name: .env secrets are generated on Windows
+ runs-on: windows-latest
+ timeout-minutes: 10
+ needs: lint-powershell
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ # 3.11, like every other workflow and every service image. The
+ # installer tells a Windows user to install 3.12 — the host
+ # scripts are stdlib-only and support 3.9+ — but CI must exercise
+ # the interpreter the project actually ships.
+ python-version: "3.11"
+
+ - name: Initialize-EnvFile produces a bootable .env
+ shell: pwsh
+ run: |
+ $ErrorActionPreference = 'Stop'
+
+ # Dot-source the installer with only its final `Invoke-Main` call
+ # removed, so every function is defined and nothing runs. Writing
+ # a temp copy rather than Invoke-Expression keeps the param()
+ # block legal — it has to be the first statement of a script.
+ $src = Get-Content -Raw -Encoding UTF8 .\install.ps1
+ $trimmed = $src -replace '(?m)^Invoke-Main\s*\r?$', ''
+ if ($trimmed -eq $src) {
+ Write-Host '::error::install.ps1 no longer ends by calling Invoke-Main; this job needs updating'
+ exit 1
+ }
+ $shim = Join-Path $env:RUNNER_TEMP 'install-functions.ps1'
+ Set-Content -Path $shim -Value $trimmed -Encoding UTF8
+ . $shim
+
+ $script:RepoRoot = (Get-Location).Path
+ if (Test-Path .env) { Remove-Item .env -Force }
+
+ Initialize-EnvFile
+
+ if (-not (Test-Path .env)) {
+ Write-Host '::error::Initialize-EnvFile produced no .env'
+ exit 1
+ }
+
+ # Every name scripts/ensure_env.py generates must come out with a
+ # real value. The names are read from the generator itself rather
+ # than copied into this file, so adding a secret there cannot
+ # leave this check behind.
+ $generatorSrc = Get-Content -Raw -Encoding UTF8 scripts/ensure_env.py
+ $block = [regex]::Match($generatorSrc, 'GENERATED[^=]*=\s*\{(.*?)\n\}', 'Singleline')
+ if (-not $block.Success) {
+ Write-Host '::error::could not find the GENERATED mapping in scripts/ensure_env.py'
+ exit 1
+ }
+ $names = @([regex]::Matches($block.Groups[1].Value, '"([A-Z0-9_]+)"\s*:') | ForEach-Object { $_.Groups[1].Value })
+ if ($names.Count -lt 1) { Write-Host '::error::no generated-secret names found'; exit 1 }
+ Write-Host "checking $($names.Count) generated secrets"
+
+ $envText = Get-Content .env
+ $empty = @()
+ foreach ($name in $names) {
+ $line = $envText | Where-Object { $_ -match "^$name=" } | Select-Object -Last 1
+ $value = if ($line) { ($line -replace "^$name=", '').Trim() } else { '' }
+ if ([string]::IsNullOrWhiteSpace($value)) { $empty += $name }
+ }
+
+ if ($empty.Count -gt 0) {
+ Write-Host "::error::these secrets are empty in the generated .env: $($empty -join ', ')"
+ Write-Host 'The API refuses to start in production on empty secrets, so this install could not boot.'
+ exit 1
+ }
+
+ Write-Host "OK: all $($names.Count) generated secrets carry values."
+
uninstaller-safety:
name: Uninstaller safety refusal exit code
runs-on: ubuntu-latest
diff --git a/.github/workflows/isolation.yml b/.github/workflows/isolation.yml
index f2cfac905..72a81b466 100644
--- a/.github/workflows/isolation.yml
+++ b/.github/workflows/isolation.yml
@@ -39,7 +39,6 @@ on:
- "docker-compose.yml"
- "infra/**"
- ".env.example"
- - "render.yaml"
- ".github/workflows/isolation.yml"
pull_request:
paths:
@@ -64,7 +63,6 @@ on:
- "docker-compose.yml"
- "infra/**"
- ".env.example"
- - "render.yaml"
- ".github/workflows/isolation.yml"
# Matching isolation-live.yml, so a maintainer can run the isolation gate on
# demand rather than only when a path filter happens to match.
diff --git a/.gitleaksignore b/.gitleaksignore
index ca2fd72ee..2d35c4d0e 100644
--- a/.gitleaksignore
+++ b/.gitleaksignore
@@ -62,11 +62,6 @@ scripts/detection_specs_part2.py:jwt:1111
# ── Infrastructure and CI ─────────────────────────────────────────────────
-# Render IaC. The match is the YAML `key:` field of an env-var declaration
-# and the value is the variable's *name* (`AISOC_DISABLE_NEO4J`,
-# `AISOC_DISABLE_QDRANT`), not its value, which is the string "true".
-render.yaml:generic-api-key:78
-render.yaml:generic-api-key:132
# The disaster-recovery job's BACKUP_ENCRYPTION_KEY used to be a committed
# 64-hex constant and needed an entry here. It is generated per run now, so
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 320681130..97a4f996b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,102 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
is empty; a skip while lock-only services exist is still lost coverage,
and a failed or cancelled leg on either matrix still fails.
+### Fixed — a fresh Windows install could not boot, and nothing could see it
+
+- **`install.ps1` now generates `.env`'s secrets instead of copying the
+ template.** `Initialize-EnvFile` was a plain `Copy-Item .env.example .env`;
+ that template ships `ENVIRONMENT=production` with `SECRET_KEY`,
+ `JWT_SECRET`, `METRICS_TOKEN` and `AISOC_CREDENTIAL_KEY` empty, and
+ `enforce_secure_defaults` refuses to start the API in production on exactly
+ those values — so the install ended at "These services are not running:
+ api" with nothing pointing back at the copy. It now runs the same
+ `scripts/ensure_env.py` that `make env` runs, and Python 3 joins Git,
+ Docker, Node and pnpm as a winget-installed prerequisite because three
+ steps of the install are Python programs. `compose-smoke.yml` had already
+ worked around this for itself, with a comment noting that a bare copy "has
+ provisioned an environment no real deployment would boot".
+- **A port already in use no longer stops the install on Windows.**
+ `Test-CorePortsFree` exited 3 and told the operator to edit
+ `docker-compose.yml` by hand, on the two conditions most likely in this
+ audience's environment — an existing Postgres on 5432, an Ollama on 11434 —
+ while `README.md` promised the opposite. It now runs the same
+ `scripts/resolve_port_conflicts.py` that `make up` runs, and every compose
+ call in the installer goes through one helper so a remapped stack is
+ addressed consistently. The closing banner reads the moved console address
+ from `.env` rather than printing a hardcoded `localhost:3000`.
+- `--no-pull` and `--rebuild` in `install.sh` were parsed into an array that
+ nothing read once the demo handoff was removed, so both were accepted and
+ silently ignored while `--help` documented them. They now set
+ `AISOC_PULL_POLICY=never` and `make up UP_FLAGS=--build` respectively, and
+ the script's header describes the flow it actually runs.
+- Both installers linked an issue template that did not exist, under two
+ different names, at the moment a failing install asks for help.
+ `.github/ISSUE_TEMPLATE/installer-failure.yml` now exists and both point
+ at it.
+
+### Changed — one way in, and no on-ramp that cannot prove itself
+
+- **The devcontainer and the sandbox README no longer send people to
+ `pnpm aisoc:demo`.** That compose file has no ingest service, no fusion
+ service and Kafka disabled — its own header says not to use it to evaluate
+ whether AiSOC works — and both installers were rewritten to remove the
+ handoff, but a fresh Codespace's attach banner and the sandbox's "when
+ you're ready for the real stack" line were still pointing at it. Both now
+ say `make up`. A parity-gate check covers all eight on-ramp surfaces at
+ once, exempting blockquotes and `:::caution` admonitions so the warnings
+ that keep evaluators *away* from that stack can stay.
+- **`render.yaml` and `infra/render/` are removed.** The blueprint's header
+ claimed a "Deploy to Render" button in `README.md` that has never existed,
+ and what it deployed was a ~$63/month stack with `AISOC_DISABLE_KAFKA` set
+ on three services and no ingest or fusion at all — a paid one-click path to
+ a populated console that cannot answer whether the pipeline works. Its
+ path filters in `isolation.yml` and its two `.gitleaksignore` exemptions go
+ with it. The Fly, Railway and Coolify recipes are untouched and deploy the
+ same lean shape; they deserve the same scrutiny.
+- The README's quick start now names all four on-ramps — `make up`, the
+ Windows and Unix one-liners, `pip install aisoc-sandbox`, and Codespaces —
+ where previously a Windows reader met only `make up`, a command their OS
+ does not have. Still inside the 250-line cap, paid for by reflowing.
+
+### Fixed — install documentation that described a different product
+
+- `apps/docs/docs/quickstart.md` advertised a machine 1.5 GB smaller than the
+ measured requirement (6.5 GB / ~18 GB / py3.11+ against the measured 8 GB /
+ 20 GB / 3.9+), re-introduced the `cp .env.example .env` step the Makefile
+ eliminated, described `.env.example` as shipping secrets it no longer
+ ships, and attributed the port check to a script that does not perform it.
+- `apps/docs/docs/installation.md` said "fourteen CORE containers" (sixteen)
+ and told Windows users to run PowerShell as Administrator, which
+ `install.ps1`'s own guidance contradicts. `.env.example`'s header said
+ "the four generated secrets" (fifteen).
+- Four surfaces still advertised Swagger at `http://localhost:8000/api/docs`,
+ which the production-class stack `make up` starts answers 404 on:
+ `docs/QUICK_INSTALL.md`, `scripts/lab.sh`'s banner, and the `make up`
+ transcripts in `quickstart.md` and `deployment/walkthrough.mdx`.
+ `apps/docs/docs/api/rest.md` now says plainly that `make up` does not serve
+ them and names `make up-dev`, which does.
+- The sandbox README's badge said "not yet published" and its install section
+ said the upload was blocked on credentials, while PyPI has been serving
+ `aisoc-sandbox` 0.1.0; it also claimed the production stack needs an LLM
+ API key, which has not been true since the bundled local model shipped.
+
+### Added — gates, so none of the above drifts back
+
+- `tests/test_installer_parity_gate.py` asserts that both installers generate
+ the `.env` secrets and that `install.ps1` resolves port conflicts and
+ passes the port overlay to every compose call — the two holes that let the
+ Windows breakers ship for as long as they existed. Three existing
+ assertions were matching the installer's `-NoLaunch` *help text* rather
+ than its invocations, so they now read action lines with the output
+ cmdlets removed.
+- `installer-smoke.yml` gains a `windows-latest` job that dot-sources the
+ installer's own `Initialize-EnvFile` and fails if any generated secret
+ comes out empty. The existing Windows jobs run `-Diagnose` only, which
+ makes no changes, and a full install needs Docker Desktop — this needs
+ neither.
+- `scripts/check_profile_service_counts.py` reads number words as well as
+ digits and registers the installation page's requirements table, which is
+ where "fourteen" survived every digit-based check.
## [20.1.0] - 2026-10-22
### Security
diff --git a/Makefile b/Makefile
index ce161b3a8..cce60ce6d 100644
--- a/Makefile
+++ b/Makefile
@@ -133,7 +133,12 @@ env:
# process holding the port nor what to do about it. Half the stack is running
# by then, so the error also arrives after a minute of unrelated output.
up: env _ports _refresh
- $(COMPOSE) up -d
+ @# UP_FLAGS is the documented way to pass compose's own flags through
+ @# without a second code path for starting the stack. install.sh's
+ @# --rebuild uses it (`make up UP_FLAGS=--build`), which is how that
+ @# flag reaches compose on the Unix side while install.ps1 appends
+ @# --build to its own invocation. Empty by default.
+ $(COMPOSE) up -d $(UP_FLAGS)
@echo ""
@echo "Waiting for services to become healthy…"
@$(MAKE) --no-print-directory _wait
diff --git a/README.md b/README.md
index dd923c68d..9f92475af 100644
--- a/README.md
+++ b/README.md
@@ -45,13 +45,11 @@ git clone https://github.com/beenuar/AiSOC && cd AiSOC
make up
```
-The [Technical Guide](https://raw.githubusercontent.com/beenuar/AiSOC/main/apps/web/public/papers/aisoc-technical-guide.pdf) covers this in depth: server sizing, where the
-model runs, every failure mode with its cause and fix, the REST API, MCP, and every console surface.
+**On Windows**, or on a machine with nothing installed yet, one line does the prerequisites too: `iwr -useb https://raw.githubusercontent.com/beenuar/AiSOC/main/install.ps1 | iex` (`curl -fsSL https://raw.githubusercontent.com/beenuar/AiSOC/main/install.sh | bash` on Linux and macOS). **Without Docker at all**, `pip install aisoc-sandbox && aisoc-sandbox demo` walks one alert through the agent funnel offline in under 30 seconds. **Without your own machine**, open the repo in GitHub Codespaces and run `make up` in its terminal. All four end at the same console; only the first three install anything.
-Needs Docker Compose v2 with **8 GB memory and 20 GB free disk in the Docker VM**, plus `python3`
-(3.9+) and `bash`; `make doctor` checks all of it and
-[Installation](https://beenuar.github.io/AiSOC/docs/installation#requirements) says what each number
-was measured against. The first run downloads a ~2 GB model into a volume only `make clean` clears.
+The [Technical Guide](https://raw.githubusercontent.com/beenuar/AiSOC/main/apps/web/public/papers/aisoc-technical-guide.pdf) covers this in depth: server sizing, where the model runs, every failure mode with its cause and fix, the REST API, MCP, and every console surface.
+
+Needs Docker Compose v2 with **8 GB memory and 20 GB free disk in the Docker VM**, plus `python3` (3.9+) and `bash`; `make doctor` checks all of it and [Installation](https://beenuar.github.io/AiSOC/docs/installation#requirements) says what each number was measured against. The first run downloads a ~2 GB model into a volume only `make clean` clears.
`make up` also creates `.env` and generates the **fifteen** secrets in it — the credential vault, the
session signing key, five service-to-service credentials and four datastore passwords — then creates an
diff --git a/apps/docs/docs/api/rest.md b/apps/docs/docs/api/rest.md
index 477119b19..73c37b6ba 100644
--- a/apps/docs/docs/api/rest.md
+++ b/apps/docs/docs/api/rest.md
@@ -43,13 +43,18 @@ API keys are created via `POST /api/v1/api-keys` and can be scoped to specific p
## Interactive Docs
-When running locally, interactive Swagger UI is available at:
-
-- **Swagger UI**: [http://localhost:8000/api/docs](http://localhost:8000/api/docs)
-- **ReDoc**: [http://localhost:8000/api/redoc](http://localhost:8000/api/redoc)
-- **OpenAPI JSON**: [http://localhost:8000/api/openapi.json](http://localhost:8000/api/openapi.json)
-
-The full spec is also committed at [`docs/openapi.yaml`](https://github.com/beenuar/AiSOC/blob/main/docs/openapi.yaml).
+**`make up` does not serve them, and that is deliberate.** It starts a
+production-class stack with the interactive docs disabled, so
+`/api/docs` there answers 404 — pointing you at it would be pointing you at
+nothing. Read the committed spec instead:
+[`docs/openapi.yaml`](https://github.com/beenuar/AiSOC/blob/main/docs/openapi.yaml).
+
+They are served by the development overlay (`make up-dev`), which is the
+only documented local path that enables them:
+
+- **Swagger UI**: `http://localhost:8000/api/docs`
+- **ReDoc**: `http://localhost:8000/api/redoc`
+- **OpenAPI JSON**: `http://localhost:8000/api/openapi.json`
## Endpoint Groups
diff --git a/apps/docs/docs/architecture/overview.md b/apps/docs/docs/architecture/overview.md
index f5c684649..09fc5b91f 100644
--- a/apps/docs/docs/architecture/overview.md
+++ b/apps/docs/docs/architecture/overview.md
@@ -61,7 +61,6 @@ AiSOC/
│ ├── fly/ # Fly.io machines + deploy script (one recipe among several;
│ │ # no hosted demo is operated from here)
│ ├── railway/ # Railway template (railway.toml)
-│ ├── render/ # Render blueprint (render.yaml at repo root)
│ ├── terraform/ # AWS (VPC, EKS, RDS, ElastiCache, MSK) + GCP + Azure skeletons
│ └── helm/ # Kubernetes Helm chart (HPA, PDB, Ingress per service)
├── docs/
diff --git a/apps/docs/docs/deployment/walkthrough.mdx b/apps/docs/docs/deployment/walkthrough.mdx
index 94f258779..273b23ee0 100644
--- a/apps/docs/docs/deployment/walkthrough.mdx
+++ b/apps/docs/docs/deployment/walkthrough.mdx
@@ -101,7 +101,8 @@ administrator. On a first run it also downloads the bundled
```
Console: http://192.0.2.10:3000
- API: http://localhost:8000/api/docs
+ API: http://localhost:8000 (spec: docs/openapi.yaml; interactive
+ docs are off in this production-class stack)
Prove the pipeline works: make smoke
diff --git a/apps/docs/docs/installation.md b/apps/docs/docs/installation.md
index 2da373907..4bb6b9202 100644
--- a/apps/docs/docs/installation.md
+++ b/apps/docs/docs/installation.md
@@ -22,7 +22,7 @@ deploying to production, see [Deployment options](./deployment/docker).
# Linux + macOS (one-liner):
curl -fsSL https://raw.githubusercontent.com/beenuar/AiSOC/main/install.sh | bash
-# Windows (PowerShell as Administrator):
+# Windows (PowerShell, as your normal user — winget elevates per package):
iwr -useb https://raw.githubusercontent.com/beenuar/AiSOC/main/install.ps1 | iex
```
@@ -38,7 +38,7 @@ against rather than estimated from.
| | CORE | Why |
|---|---|---|
-| Docker memory | **8 GB** | Steady-state RSS across the fourteen CORE containers is well under this. The headroom is for the bundled local model, whose process grows to roughly the model size (~2 GB) while a request is in flight. |
+| Docker memory | **8 GB** | Steady-state RSS across the sixteen CORE containers is well under this. The headroom is for the bundled local model, whose process grows to roughly the model size (~2 GB) while a request is in flight. |
| Docker disk | **20 GB** | Images plus the ~2 GB model plus room for Kafka, Postgres and Qdrant volumes to grow. Below roughly 2 GB free, Kafka corrupts its log directory **and still passes its healthcheck** — `make doctor` fails on this before it can happen. |
| `python3` | **3.9+** | `make up` runs `scripts/ensure_env.py` on the host to create `.env` and generate its secrets, and `make smoke` — the headline proof — is a host-side Python script. CI runs 3.11. |
| `bash` | any | Every script under `scripts/` has a bash shebang. macOS's bundled 3.2 is sufficient. |
diff --git a/apps/docs/docs/quickstart.md b/apps/docs/docs/quickstart.md
index 0586b7592..9b3454c50 100644
--- a/apps/docs/docs/quickstart.md
+++ b/apps/docs/docs/quickstart.md
@@ -9,11 +9,15 @@ processed an event:
```bash
git clone https://github.com/beenuar/AiSOC.git && cd AiSOC
-cp .env.example .env
make up
make smoke
```
+There is deliberately no `cp .env.example .env` step. `make up` creates
+`.env` itself and **generates the fifteen secrets in it** — copying the
+template by hand leaves those empty, and the API refuses to start in
+production on empty secrets.
+
`make up` starts the CORE stack and finishes by creating an administrator.
`make smoke` posts one real event to the ingest API and follows it through
Kafka, detection, correlation and Postgres, then reads the resulting alert
@@ -40,10 +44,10 @@ idempotently on Linux, macOS and Windows and then runs Path A for you.
| Requirement | Minimum | Needed for |
|---|---|---|
| Docker + Compose v2 | v2.x | everything |
-| RAM available to Docker | **6.5 GB** (CORE) · 12 GB (`full`) | `make up` · `make up-full` |
-| Free Docker disk | **~18 GB** | `make up` |
-| `bash` | any | `make up` — its pre-flight port check is a shell script |
-| `python3` | 3.11+ | `make smoke`, `make stats`, the eval harness |
+| RAM available to Docker | **8 GB** (CORE) · 12 GB (`full`) | `make up` · `make up-full` |
+| Free Docker disk | **20 GB** | `make up` |
+| `bash` | any | every script under `scripts/` has a bash shebang |
+| `python3` | 3.9+ | `make up` (`.env` secrets, port resolution), `make smoke`, `make stats`, the eval harness |
| Node.js | 22 LTS | `install.sh` / `install.ps1`, and building the web console |
| pnpm | ≥ 8 | as above |
| Go | 1.25+ | only if you are hacking on the Go services or plugins |
@@ -51,11 +55,17 @@ idempotently on Linux, macOS and Windows and then runs Path A for you.
Three of those are easy to miss, because nothing names them until the command
that needs them fails:
-- **`bash`.** `make up` runs `scripts/doctor.sh --ports-only` before it calls
- compose, so a port conflict is reported against the process holding the
- port rather than as a `Bind for 0.0.0.0:5432 failed` against whichever
- container lost the race. It is a hard gate: no bash, no `make up`.
-- **`python3` on the host**, not just in the containers. `make smoke` runs
+- **`bash`.** Every script `make up` reaches for has a bash shebang. It is a
+ hard gate: no bash, no `make up`.
+- **A port already in use does not stop the install.** `make up` runs
+ `scripts/resolve_port_conflicts.py` before it calls compose, which
+ *republishes* AiSOC's side of any taken port into
+ `docker-compose.ports.yml` and names what held the old one — rather than
+ leaving you a `Bind for 0.0.0.0:5432 failed` against whichever container
+ lost the race. Only the published side moves; traffic inside the compose
+ network is unaffected.
+- **`python3` on the host**, not just in the containers. It creates `.env`
+ and generates its secrets, resolves those ports, and `make smoke` runs
`tests/e2e/golden_pipeline/run_golden_pipeline.py` on your machine, against
the stack's published ports. Without it you can start AiSOC but you cannot
prove it works.
@@ -75,37 +85,43 @@ Windows has no `make`. `install.ps1` runs the same steps natively — see
```bash
git clone https://github.com/beenuar/AiSOC.git
cd AiSOC
-cp .env.example .env
```
-`.env.example` ships a working `POSTGRES_PASSWORD` (`aisoc_dev_secret`), so
-the database comes up without you touching anything.
+That is the whole of it — there is no file to copy and nothing to edit.
+`make up` runs `scripts/ensure_env.py`, which creates `.env` from the
+template and fills its **fifteen** generated secrets with real random
+values: the credential vault key, the session signing key, five
+service-to-service credentials, the realtime and metrics tokens, and four
+datastore passwords. `make env` does only that step, if you want to look
+before you start.
-**It does not ship a usable `AISOC_CREDENTIAL_KEY`.** The line you copy is:
+The history here is the reason the step is gone rather than merely
+optional. `.env.example` used to ship:
```bash
AISOC_CREDENTIAL_KEY=replace-me-with-a-freshly-generated-fernet-key
```
-That placeholder is not a Fernet key, and it is worse than leaving the
+That placeholder was not a Fernet key, and it was worse than leaving the
variable empty: an unset key makes the API generate an ephemeral one and warn,
while a malformed key makes the credential vault raise, so the first request
-that touches a connector secret returns HTTP 500. Generate a real one and
-paste it in before you go near the Connectors page:
+that touches a connector secret returned HTTP 500 — minutes after the copy,
+with nothing connecting the two. The template now ships these **empty** and
+the generator fills them, so following the documented path and skipping it
+both end up with a working vault. If you ever need to mint one by hand:
```bash
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
```
-Nothing in Path A needs it — the pipeline proof below does not touch the
-vault — so you can also come back to this when you connect your first source.
Full threat model and rotation procedure:
[Operations: Credentials](./operations/credentials).
-AI triage additionally needs a provider key (`OPENAI_API_KEY` or
-`ANTHROPIC_API_KEY`). Without one the stack still boots and every alert is
-triaged by the deterministic path, and the console labels it as such —
-nothing pretends the AI ran.
+AI triage needs no key either: the stack ships a local model and runs triage
+with no credentials. Pointing it at a hosted provider (`OPENAI_API_KEY` or
+`ANTHROPIC_API_KEY`) is an upgrade, not a prerequisite — and when no model is
+reachable at all, every alert is triaged by the deterministic path and the
+console labels it as such. Nothing pretends the AI ran.
### 2. Start the stack
@@ -120,9 +136,13 @@ it, so `make up` returning 0 means the services are actually up.
```
Console: http://localhost:3000
- API: http://localhost:8000/api/docs
+ API: http://localhost:8000 (spec: docs/openapi.yaml; interactive
+ docs are off in this production-class stack)
```
+If a port was taken, the console address printed here is the one AiSOC
+moved to — use what the command prints rather than the line above.
+
### 3. Prove the pipeline works
```bash
@@ -426,15 +446,16 @@ The same services as Path A and B, driven through `aisoc <verb>` instead of
```bash
git clone https://github.com/beenuar/AiSOC.git
cd AiSOC
-cp .env.example .env
+make env # creates .env and generates its fifteen secrets
python -m venv .venv && source .venv/bin/activate
pip install -e packages/aisoc-cli
```
-Set `AISOC_CREDENTIAL_KEY` to a generated Fernet key as described in
-[Clone and configure](#1-clone-and-configure), and add at least one AI
-provider key (`OPENAI_API_KEY` or `ANTHROPIC_API_KEY`) if you want AI triage.
+`make env` is the same step `make up` runs, so if you have already started
+the stack there is nothing to do here. Add a hosted provider key
+(`OPENAI_API_KEY` or `ANTHROPIC_API_KEY`) only if you want triage to run
+against one instead of the bundled local model.
Confirm the CLI is on PATH:
diff --git a/docs/QUICK_INSTALL.md b/docs/QUICK_INSTALL.md
index 8403a4299..517c515a6 100644
--- a/docs/QUICK_INSTALL.md
+++ b/docs/QUICK_INSTALL.md
@@ -30,8 +30,10 @@ pipeline end to end — one real event through Kafka, fusion and detection, read
back as an alert from the API. If that check fails the installer exits
non-zero and says so; "the containers started" is not "it works".
-The console is at `http://localhost:3000` and Swagger at
-`http://localhost:8000/api/docs`. Sign in as `[email protected]` with the
+The console is at `http://localhost:3000` and the API at
+`http://localhost:8000`. There is no interactive `/api/docs` page: this is a
+production-class stack and the spec generator is off, which is the posture to
+keep — read `docs/openapi.yaml` instead. Sign in as `[email protected]` with the
generated password. The console starts **empty** — that is correct, because
nothing has been connected yet. `make demo` loads clearly-labelled synthetic
data if you want something to look at.
diff --git a/infra/render/README.md b/infra/render/README.md
deleted file mode 100644
index 722b54056..000000000
--- a/infra/render/README.md
+++ /dev/null
@@ -1,149 +0,0 @@
-# AiSOC on Render
-
-One-click deploy of the full AiSOC demo stack to [Render](https://render.com)
-via Render's [Blueprint](https://render.com/docs/blueprint-spec) feature.
-
-[![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/beenuar/AiSOC)
-
-## What this deploys
-
-The lean demo profile — same shape as the [Fly demo](../fly/), without
-the heavy storage tier:
-
-| Service | Plan | Role |
-|---|---|---|
-| `aisoc-api` | starter ($7/mo) | FastAPI core + investigation ledger |
-| `aisoc-agents` | standard ($25/mo) | LangGraph orchestrator (needs 2GB RAM) |
-| `aisoc-realtime` | starter ($7/mo) | WebSocket fanout |
-| `aisoc-web` | starter ($7/mo) | Next.js console + marketing |
-| `aisoc-postgres` | starter ($7/mo) | Managed Postgres (1GB) |
-| `aisoc-redis` | starter ($10/mo) | Managed Redis (25MB) |
-
-**Total: ~$63/mo** for an always-on, public-facing demo. Significantly
-cheaper than running the full storage tier (Kafka + ClickHouse + OpenSearch
-+ Neo4j + Qdrant) which Render doesn't offer managed versions of.
-
-## What's disabled (and why it's fine)
-
-The Blueprint sets these flags on the api and agents services:
-
-```yaml
-AISOC_DISABLE_KAFKA: "true"
-AISOC_DISABLE_CLICKHOUSE: "true"
-AISOC_DISABLE_NEO4J: "true"
-AISOC_DISABLE_QDRANT: "true"
-```
-
-The demo profile uses **Postgres + Redis** for everything — alerts, cases,
-investigations, the agent ledger, the cache layer. ClickHouse-backed event
-search and Neo4j-backed attack graphs are *hidden in the UI* when the
-backing store is absent, so the demo never shows a broken page.
-
-If you need the full storage tier in production, use:
-
-- **Self-hosted on Render**: not recommended — single-instance Kafka and
- ClickHouse on Render's plans is more expensive than running them on a
- dedicated VM.
-- **Kubernetes / Helm**: see [`infra/helm/`](../helm/) — production-grade,
- brings its own Kafka/ClickHouse/OpenSearch.
-- **Terraform / AWS**: see [`infra/terraform/`](../terraform/) — uses MSK,
- RDS, ElastiCache, OpenSearch Service, ECS for the application tier.
-
-## Deploy walkthrough
-
-### Option A: one-click (recommended)
-
-1. Click the **Deploy to Render** button above.
-2. Render asks for permission to read your fork of `beenuar/AiSOC`. Grant it.
-3. Render parses [`render.yaml`](../../render.yaml) at the repo root, shows
- the service plan, and asks you to confirm.
-4. Click **Apply**. Render provisions Postgres + Redis first (~2 min),
- then deploys the four web services in dependency order (~6-8 min for
- the first build because Docker layers aren't cached yet).
-5. Once `aisoc-web` is green, open `https://aisoc-web-<hash>.onrender.com`.
- The demo banner shows; the deeplink lands on a pre-seeded incident.
-
-### Option B: manual
-
-If you've forked the repo and changed things:
-
-```bash
-# From the repo root, after pushing your fork to GitHub:
-gh repo view --web
-# Then in Render: New + → Blueprint → Connect repo → select fork.
-# Render auto-detects render.yaml at the repo root → Apply.
-```
-
-## Post-deploy: pre-warm the demo
-
-The blueprint wires `preDeployCommand: alembic upgrade head && python -m
-app.scripts.seed_demo` onto the `aisoc-api` service, so every Render deploy
-runs migrations and seeds the demo tenant before the new instance accepts
-traffic. The seeder is idempotent — re-running against an already-seeded
-database is a cheap no-op that refreshes `INC-RT-001` (the in-flight
-LockBit 3.0 ransomware investigation the demo deeplink targets) plus the
-14 other canonical incidents.
-
-If you ever need to re-seed manually (e.g. local recovery, or after a
-database reset), use Render's Shell tab on the `aisoc-api` service and run:
-
-```bash
-python -m app.scripts.seed_demo
-```
-
-## Daily reset (optional)
-
-The Fly demo wipes and re-seeds the demo tenant daily via a scheduled
-machine. Render doesn't have native cron, so the options are:
-
-1. **Render Cron Job service** (~$1/mo) — add a 7th service of type `cron`
- to `render.yaml` that runs the seed script on a schedule. Skipped from
- the Blueprint by default to keep the cost story simple.
-2. **GitHub Actions workflow** — add a scheduled workflow of your own that
- hits the deployed api. Free, but tied to your GH Actions minutes budget.
- There is no such workflow in this repository today.
-3. **Skip it** — for a personal evaluation deploy, the demo data will drift
- over time but won't break.
-
-## Troubleshooting
-
-### "Web service failed health check"
-
-The web service's health check hits `/`, which requires the api to be up
-(it server-side renders the case list). If the api is still booting,
-Render marks web as failed. Wait 60s and retry — Render auto-redeploys
-on failed health checks up to 3 times.
-
-### "Out of memory on aisoc-agents"
-
-The starter plan (512MB) is not enough for LangGraph + the LLM client
-buffers. The Blueprint defaults agents to `standard` (2GB) for this
-reason. If you downgraded it, bump back up.
-
-### Demo banner not showing
-
-Check that `NEXT_PUBLIC_AISOC_DEMO_MODE=true` is set on the `aisoc-web`
-service. The variable is baked into the JS bundle at build time, so
-flipping it requires a redeploy (not just a restart).
-
-### Slow first investigation
-
-First boot does Alembic migrations + creates the ledger schema, which
-can take 20-30s on cold Postgres. Subsequent investigations land in
-&lt;5s once the schema is in place.
-
-## Files
-
-```
-infra/render/
-└── README.md — this file (Render-specific walkthrough + cost notes)
-
-<repo root>/
-└── render.yaml — Render Blueprint manifest (the source of truth).
- Lives at the root because Render's "Deploy to Render"
- button only auto-detects blueprints at the root of
- the repo, not in subdirectories.
-```
-
-For the full deployment philosophy and platform comparison, see the
-[main README](../../README.md#-deploy-in-one-click).
diff --git a/install.ps1 b/install.ps1
index 0338a3bf3..04bbcd2a7 100644
--- a/install.ps1
+++ b/install.ps1
@@ -9,20 +9,28 @@
What this script does, in order:
1. Verifies you're on Windows 10 (build 19041+) or Windows 11.
2. Verifies WSL2 is enabled (required by Docker Desktop).
- 3. Installs (idempotently) the four prerequisites AiSOC needs:
+ 3. Installs (idempotently) the five prerequisites AiSOC needs:
- Git
- Docker Desktop (which bundles Docker Engine + Compose v2)
- Node.js 22 LTS
- pnpm 8+ (via corepack)
+ - Python 3 (runs the same setup scripts the Unix path runs:
+ the .env secret generator, the port resolver, and the
+ end-to-end pipeline check in step 9)
All installs go through winget, the official Windows package
manager. We never download random installers from the internet.
4. Clones the AiSOC repo (if you ran the script as a one-liner) or
reuses it (if you ran .\install.ps1 from inside a clone).
- 5. Creates a .env from .env.example so the first boot has sane
- defaults.
+ 5. Creates a .env and generates its fifteen secrets, by running
+ `scripts/ensure_env.py` — the same generator `make env` runs.
+ A plain copy of .env.example cannot boot: it ships
+ ENVIRONMENT=production with the secrets empty, and the API
+ refuses to start in production on those values.
6. Runs `pnpm install --frozen-lockfile` to fetch the workspace's
Node deps.
- 7. Starts the CORE stack with `docker compose up -d` and waits for
+ 7. Moves AiSOC's published ports off anything already listening
+ (`scripts/resolve_port_conflicts.py`, as `make up` does), then
+ starts the CORE stack with `docker compose up -d` and waits for
every container to report healthy.
8. Creates the first administrator and prints its generated password
once.
@@ -604,6 +612,80 @@ Workaround: install pnpm manually, then re-run this script:
Write-Ok "pnpm installed: $((& pnpm --version))"
}
+# ─── Step 4b: Python 3 ────────────────────────────────────────────────────
+
+# Python is a hard prerequisite on Windows for the same reason it is on the
+# `make up` path: three steps of this install are Python programs that the
+# Unix path runs and this one must not diverge from —
+# `scripts/ensure_env.py` (the fifteen generated secrets),
+# `scripts/resolve_port_conflicts.py` (moving a published port off whatever
+# already holds it) and the golden-pipeline runner that proves the install.
+#
+# It used to be optional, and each of those three silently degraded: the
+# `.env` shipped placeholder secrets that `enforce_secure_defaults` refuses
+# to boot on, a busy port was a hard stop, and the pipeline check was
+# skipped. Installing it is one winget package and removes all three.
+function Install-Python {
+ $found = Resolve-Python
+ if ($null -ne $found) {
+ # Splatting needs a plain variable (`@name`); `@(expression)` in an
+ # argument position passes one array argument instead of several.
+ $probeArgs = @($found.Prefix) + @('--version')
+ $version = (& $found.Exe @probeArgs 2>&1 | Out-String).Trim()
+ Write-Ok "python already installed: $version"
+ return
+ }
+ Install-WingetPackage -Id 'Python.Python.3.12' -DisplayName 'Python 3.12'
+ if ($null -eq (Resolve-Python)) {
+ # winget puts python on PATH through the registry, which this
+ # process has not re-read yet.
+ Update-PathFromRegistry
+ }
+ $resolved = Resolve-Python
+ if ($null -eq $resolved) {
+ Stop-WithError @"
+Python was installed via winget but no working interpreter is on PATH.
+
+Windows ships a Microsoft Store stub named python.exe that prints a
+"not found" notice instead of a version, and it takes precedence on a
+fresh PATH. Open a new PowerShell window and re-run this script; if it
+still fails, disable the stub in:
+ Settings > Apps > Advanced app settings > App execution aliases
+"@
+ }
+ $versionArgs = @($resolved.Prefix) + @('--version')
+ $version = (& $resolved.Exe @versionArgs 2>&1 | Out-String).Trim()
+ Write-Ok "python installed: $version"
+}
+
+# Runs a repository Python script with whichever interpreter spelling this
+# machine has, from the repository root. Returns the exit code rather than
+# throwing: every caller here has its own, more useful, failure message.
+function Invoke-RepoPython {
+ param(
+ [Parameter(Mandatory)][string]$RelativePath,
+ [string[]]$ScriptArgs = @()
+ )
+ $python = Resolve-Python
+ if ($null -eq $python) { return $null }
+ # Built as one variable because splatting is `@name`: `@(expression)` in
+ # an argument position passes a single array argument instead.
+ $invokeArgs = @($python.Prefix) + @((Join-Path $RepoRoot $RelativePath)) + $ScriptArgs
+ Push-Location $RepoRoot
+ try {
+ # `| Out-Host`, not a bare call: a PowerShell function returns
+ # everything it writes to the pipeline, so without this the caller's
+ # `$code` would be an array of the script's printed lines with the
+ # exit code last. The operator still sees the output — these scripts
+ # report which secrets were filled and which ports moved — it just
+ # goes to the host instead of the return value.
+ & $python.Exe @invokeArgs | Out-Host
+ return $LASTEXITCODE
+ } finally {
+ Pop-Location
+ }
+}
+
# ─── Step 5: clone or locate repo ─────────────────────────────────────────
$script:RepoRoot = $null
@@ -699,20 +781,64 @@ Then re-run this installer.
# ─── Step 6: .env bootstrap ───────────────────────────────────────────────
+# Creates `.env` and fills its generated secrets, by running the same
+# `scripts/ensure_env.py` that `make env` runs. It is idempotent, so it runs
+# unconditionally — an existing `.env` keeps every value it already has and
+# only empty-or-placeholder secrets are filled.
+#
+# This used to be `Copy-Item .env.example .env`, and a plain copy cannot
+# produce a bootable deployment: `.env.example` ships `ENVIRONMENT=production`
+# with `SECRET_KEY`, `JWT_SECRET`, `METRICS_TOKEN` and `AISOC_CREDENTIAL_KEY`
+# empty, and `enforce_secure_defaults` (services/api/app/core/config.py)
+# refuses to start the API in production on exactly those values. The symptom
+# was `Wait-StackHealthy` reporting "These services are not running: api" with
+# nothing connecting it back to the copy. `compose-smoke.yml` already runs the
+# generator for this reason, with a comment saying a bare copy "has
+# provisioned an environment no real deployment would boot".
function Initialize-EnvFile {
- $envPath = Join-Path $RepoRoot '.env'
- $exampleEnv = Join-Path $RepoRoot '.env.example'
- if (Test-Path $envPath) {
- Write-Ok ".env already exists at $envPath"
+ $envPath = Join-Path $RepoRoot '.env'
+ $exampleEnv = Join-Path $RepoRoot '.env.example'
+ $generator = Join-Path $RepoRoot 'scripts\ensure_env.py'
+
+ if (-not (Test-Path $generator)) {
+ # Older checkout without the generator: the copy is all there is, and
+ # it is better than no .env at all — but say what it costs.
+ if (-not (Test-Path $envPath) -and (Test-Path $exampleEnv)) {
+ Copy-Item $exampleEnv $envPath
+ Write-Warn "Created $envPath by copying .env.example — scripts/ensure_env.py is not in this checkout,"
+ Write-Warn 'so its secrets are placeholders and the API will refuse to start. Update your clone.'
+ } else {
+ Write-Warn "No scripts/ensure_env.py and no .env.example in repo; skipping .env creation."
+ }
return
}
- if (Test-Path $exampleEnv) {
- Copy-Item $exampleEnv $envPath
- Write-Ok "Created $envPath from .env.example"
- Write-Info " (Optional: edit .env to add your OpenAI/Anthropic API key for richer agent runs.)"
- } else {
- Write-Warn "No .env.example found in repo; skipping .env creation."
+
+ Write-Info 'Creating .env and generating its secrets...'
+ $code = Invoke-RepoPython -RelativePath 'scripts\ensure_env.py'
+ if ($null -eq $code) {
+ Stop-WithError @"
+No Python 3 interpreter is available, so .env secrets cannot be generated.
+
+This is not optional: .env.example ships ENVIRONMENT=production with empty
+SECRET_KEY / JWT_SECRET / METRICS_TOKEN / AISOC_CREDENTIAL_KEY, and the API
+refuses to start in production on those values. Copying the template would
+produce a stack that cannot boot.
+
+Install Python and re-run this installer:
+ winget install --id Python.Python.3.12
+"@ 2
}
+ if ($code -ne 0) {
+ Stop-WithError @"
+scripts/ensure_env.py exited $code, so .env is not usable.
+
+Re-run it directly to see why:
+ cd $RepoRoot
+ python scripts\ensure_env.py
+"@ 2
+ }
+ Write-Ok "Environment ready at $envPath"
+ Write-Info ' (Optional: edit .env to add your OpenAI/Anthropic API key for richer agent runs.)'
}
# ─── Step 7: pnpm install + handoff ───────────────────────────────────────
@@ -766,7 +892,12 @@ function Get-ComposePublishedPort {
$previous = $ErrorActionPreference
try {
$ErrorActionPreference = 'Continue'
- $mapped = & docker compose port $Service $ContainerPort 2>$null | Select-Object -Last 1
+ # Through Get-ComposeArgs so a stack already remapped by a previous
+ # run reports the port it actually publishes. Without the overlay
+ # this asks the base composition and answers 5432 for a postgres
+ # that moved, which reads as a conflict with something else.
+ $portArgs = @(Get-ComposeArgs) + @('port', $Service, "$ContainerPort")
+ $mapped = & docker @portArgs 2>$null | Select-Object -Last 1
} catch {
return $null
} finally {
@@ -842,15 +973,80 @@ function Test-CorePortsFree {
}
if ($conflicts.Count -eq 0) { return }
Write-Host ''
- foreach ($conflict in $conflicts) { Write-Err $conflict }
+ foreach ($conflict in $conflicts) { Write-Warn $conflict }
Write-Host ''
- Write-Err 'Not starting: the ports above are taken by something else.'
- Write-Err 'Stop that process, or edit the host port in docker-compose.yml.'
+
+ # Resolve rather than refuse, exactly as `make up` does on the Unix path.
+ # This used to `exit 3` here and tell the operator to go edit
+ # docker-compose.yml, which is a hard stop at step one of the documented
+ # quick start triggered by the single most likely condition in this
+ # audience's environment: an existing Postgres on 5432, or an Ollama on
+ # 11434. The README promises "a port already in use does not stop the
+ # install"; on Windows that promise was false.
+ #
+ # Only the published side moves — service-to-service traffic inside the
+ # compose network uses container ports and service names.
+ Write-Info 'Moving AiSOC off the ports above (nothing else is touched)...'
+ $code = Invoke-RepoPython -RelativePath 'scripts\resolve_port_conflicts.py'
+ if ($code -eq 0) {
+ Write-Ok 'Ports resolved. The addresses printed at the end are the ones to use.'
+ return
+ }
+
+ # Falling through means resolution itself failed, which is the only case
+ # that still deserves a stop: there is nowhere free to move to, or no
+ # interpreter to do the moving.
+ if ($null -eq $code) {
+ Write-Err 'The ports above are taken, and no Python 3 interpreter is available to move them.'
+ Write-Err ' winget install --id Python.Python.3.12'
+ } else {
+ Write-Err "Could not find free ports to move to (scripts\resolve_port_conflicts.py exited $code)."
+ }
+ Write-Err 'Stop whatever holds the ports above, or edit the host port in docker-compose.yml.'
Write-Err "(A docker-compose.override.yml needs 'ports: !override' — a plain"
Write-Err ' override appends, leaving the conflicting binding in place.)'
exit 3
}
+# The compose invocation for this repository, including the generated port
+# overlay when `scripts/resolve_port_conflicts.py` wrote one. This mirrors the
+# Makefile's `COMPOSE` variable; every compose call in this installer goes
+# through it so a remapped stack is addressed consistently — starting it with
+# the overlay and then running `ps` or `bootstrap_admin` without it would be
+# two different compositions.
+#
+# Deliberately `docker-compose.ports.yml` as a second `-f` rather than
+# `docker-compose.override.yml`: an override *appends* port bindings, leaving
+# the conflicting one published.
+function Get-ComposeArgs {
+ $composeArgs = @('compose')
+ if ($null -ne $script:RepoRoot) {
+ if (Test-Path (Join-Path $script:RepoRoot 'docker-compose.ports.yml')) {
+ $composeArgs += @('-f', 'docker-compose.yml', '-f', 'docker-compose.ports.yml')
+ }
+ }
+ return $composeArgs
+}
+
+# The address the console actually answers on. `AISOC_CONSOLE_URL` is written
+# into `.env` by scripts/resolve_port_conflicts.py whenever the console moves
+# off 3000, which is the same source the Makefile's `console_url` reads.
+# Printing a hardcoded localhost:3000 after moving the console hands the
+# operator a URL that answers nothing — worse than the conflict itself.
+function Get-ConsoleUrl {
+ $default = 'http://localhost:3000'
+ if ($null -eq $script:RepoRoot) { return $default }
+ $envPath = Join-Path $script:RepoRoot '.env'
+ if (-not (Test-Path $envPath)) { return $default }
+ $line = Get-Content $envPath -ErrorAction SilentlyContinue |
+ Where-Object { $_ -match '^AISOC_CONSOLE_URL=' } |
+ Select-Object -Last 1
+ if ([string]::IsNullOrWhiteSpace($line)) { return $default }
+ $value = ($line -replace '^AISOC_CONSOLE_URL=', '').Trim().Trim('"').Trim("'")
+ if ([string]::IsNullOrWhiteSpace($value)) { return $default }
+ return $value
+}
+
# Waits on the services that declare a healthcheck, and refuses to call a
# stack up while any container is dead.
#
@@ -864,7 +1060,8 @@ function Wait-StackHealthy {
Write-Info 'Waiting for services to become healthy...'
$pending = @()
for ($attempt = 0; $attempt -lt 60; $attempt++) {
- $lines = @(& docker compose ps -a --format '{{.Service}} {{.State}} {{.Health}}' 2>$null)
+ $psArgs = @(Get-ComposeArgs) + @('ps', '-a', '--format', '{{.Service}} {{.State}} {{.Health}}')
+ $lines = @(& docker @psArgs 2>$null)
$broken = @()
$pending = @()
foreach ($line in $lines) {
@@ -927,7 +1124,9 @@ function Start-Stack {
try {
Test-CorePortsFree
- $composeArgs = @('compose', 'up', '-d')
+ # Get-ComposeArgs is evaluated after Test-CorePortsFree so it picks up
+ # a port overlay written moments ago.
+ $composeArgs = @(Get-ComposeArgs) + @('up', '-d')
if ($Rebuild) { $composeArgs += '--build' }
& docker @composeArgs
if ($LASTEXITCODE -ne 0) {
@@ -957,7 +1156,8 @@ function New-AdminAccount {
try {
# Output is deliberately neither captured nor suppressed: the
# generated password is printed here, once, and stored nowhere.
- & docker compose run --rm -T api python -m app.scripts.bootstrap_admin
+ $bootstrapArgs = @(Get-ComposeArgs) + @('run', '--rm', '-T', 'api', 'python', '-m', 'app.scripts.bootstrap_admin')
+ & docker @bootstrapArgs
if ($LASTEXITCODE -ne 0) {
Write-Host ''
Write-Warn 'Could not create the administrator — the stack is up, but you cannot sign in yet.'
@@ -1127,8 +1327,13 @@ function Write-SuccessBanner {
Write-Host 'The end-to-end pipeline check did not run — see the note above.' -ForegroundColor Yellow
}
Write-Host ''
- Write-Host ' Web console: http://localhost:3000'
- Write-Host ' API + Swagger: http://localhost:8000/api/docs'
+ Write-Host " Web console: $(Get-ConsoleUrl)"
+ Write-Host ' API: http://localhost:8000'
+ # Not /api/docs: interactive docs are deliberately off in this
+ # production-class stack, so advertising them hands the reader a 404.
+ # install.sh's banner says the same thing.
+ Write-Host ' API spec: docs/openapi.yaml (interactive docs are off in'
+ Write-Host ' this production-class stack, which is the posture to keep)'
Write-Host ' Realtime WS: ws://localhost:8086'
Write-Host ''
Write-Host " Sign in as: $adminEmail"
@@ -1180,7 +1385,7 @@ function Invoke-Main {
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 ' https://github.com/beenuar/AiSOC/issues/new?template=installer-failure.yml'
Write-Host ''
Write-Host ' System info:' -ForegroundColor DarkGray
try {
@@ -1234,6 +1439,7 @@ function Invoke-Main {
Install-Docker
Install-Node
Install-Pnpm
+ Install-Python
} else {
Write-Info "-NoInstall: skipping prerequisite install. Verifying what's on PATH..."
if (-not (Test-CommandExists git)) { Stop-WithError "git missing (and -NoInstall was given)" }
@@ -1242,6 +1448,9 @@ function Invoke-Main {
if ($LASTEXITCODE -ne 0) { Stop-WithError "docker compose v2 missing (and -NoInstall was given)" }
if (-not (Test-CommandExists node)) { Stop-WithError "node missing (and -NoInstall was given)" }
if (-not (Test-CommandExists pnpm)) { Stop-WithError "pnpm missing (and -NoInstall was given)" }
+ # Checked by running it, not by name: Windows ships a Store stub
+ # called python.exe that is on PATH and is not an interpreter.
+ if ($null -eq (Resolve-Python)) { Stop-WithError "python 3 missing (and -NoInstall was given) — .env secrets and port resolution both need it" }
Test-DockerDaemon
}
diff --git a/install.sh b/install.sh
index e2724852e..c6f6c7176 100755
--- a/install.sh
+++ b/install.sh
@@ -14,11 +14,18 @@
# - pnpm 8+ (via corepack)
# 3. Clones the AiSOC repo (if you ran the script as a one-liner) or
# reuses it (if you ran ./install.sh from inside a clone).
-# 4. Creates a .env from .env.example so the first boot has sane defaults.
+# 4. Creates a .env and generates its secrets with scripts/ensure_env.py
+# (what `make env` runs). A plain copy of .env.example cannot boot:
+# it ships ENVIRONMENT=production with the secrets empty, and the API
+# refuses to start in production on those values.
# 5. Runs `pnpm install` to fetch the orchestrator's Node deps.
-# 6. Hands off to `pnpm aisoc:demo`, which pulls prebuilt images, brings
-# up the slim demo profile, seeds the showcase ransomware case, and
-# opens your browser at the case ledger view.
+# 6. Starts the CORE stack with `make up` — the real deployment defined
+# by the root docker-compose.yml, which moves any published port that
+# is already taken, then creates the first administrator and prints
+# its generated password once.
+# 7. Pushes one real event through the pipeline and verifies it comes
+# back out of the API as an alert. A failure here fails the install:
+# "the containers started" is not "the application works".
#
# Usage:
# One-liner (no clone needed):
@@ -29,9 +36,12 @@
#
# 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.
+# --no-launch Set everything up but don't start the stack, create the
+# administrator or run the pipeline check.
+# --no-pull Use the images already on this machine; don't refresh
+# them from the registry (AISOC_PULL_POLICY=never).
+# --rebuild Build the service images from source instead of using
+# the published ones.
# --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.
@@ -47,16 +57,17 @@
# --help Show this text and exit.
#
# Exit codes:
-# 0 success — demo stack is up and your browser opened
+# 0 success — the stack is up and one real event came back out as an alert
# 1 prerequisite install failed
# 2 Docker daemon refused to come up
-# 3 pnpm aisoc:demo failed (stack didn't boot or seed)
+# 3 the stack did not come up
# 4 preflight failed (use --skip-preflight to override at your own risk)
+# 5 the clone failed, or the end-to-end pipeline check did
#
# 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
-# repo is cloned, a re-run completes in roughly the time `pnpm aisoc:demo`
-# itself takes (≈ 3.5 minutes on a warm Docker daemon).
+# right version?" before doing anything. On a warm Docker daemon with the
+# images already pulled, a re-run is a few minutes — most of it the stack
+# coming up and the pipeline check.
#
# Tested on:
# - Ubuntu 22.04 / 24.04
@@ -157,7 +168,8 @@ DIAGNOSE_ONLY=0
NON_INTERACTIVE=0
CLONE_DIR="${HOME}/aisoc"
BRANCH="main"
-DEMO_FLAGS=()
+NO_PULL=0
+REBUILD=0
# If stdin isn't a TTY (curl|bash, CI, log redirects), default to
# non-interactive. Users who *want* prompts in those environments can pass
@@ -170,8 +182,8 @@ while [ $# -gt 0 ]; do
case "$1" in
--no-install) NO_INSTALL=1 ;;
--no-launch) NO_LAUNCH=1 ;;
- --no-pull) DEMO_FLAGS+=("--no-pull") ;;
- --rebuild) DEMO_FLAGS+=("--rebuild") ;;
+ --no-pull) NO_PULL=1 ;;
+ --rebuild) REBUILD=1 ;;
--skip-preflight) SKIP_PREFLIGHT=1 ;;
--diagnose) DIAGNOSE_ONLY=1 ;;
--non-interactive) NON_INTERACTIVE=1 ;;
@@ -761,7 +773,7 @@ ensure_env_file() {
fi
}
-# ─── Step 7: pnpm install + handoff to aisoc:demo ────────────────────────────
+# ─── Step 7: pnpm install, then start the stack ──────────────────────────────
run_pnpm_install() {
info "Installing JS workspace deps (pnpm install)..."
@@ -776,8 +788,10 @@ package.json and pnpm-lock.yaml disagree — re-clone or 'git checkout pnpm-lock
run_demo() {
if [ "$NO_LAUNCH" = "1" ]; then
- info "--no-launch: skipping pnpm aisoc:demo. To start the stack later:"
- info " cd $REPO_ROOT && pnpm aisoc:demo"
+ info "--no-launch: not starting the stack. To start it later:"
+ info " cd $REPO_ROOT"
+ info " make up # starts the stack and creates the administrator"
+ info " make smoke # proves the pipeline end to end"
return 0
fi
section "Starting AiSOC (CORE profile)"
@@ -804,10 +818,27 @@ run_demo() {
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.
+ # --no-pull and --rebuild, honoured rather than collected and dropped.
+ # They used to be parsed into a DEMO_FLAGS array that nothing read once
+ # the demo handoff was removed, so both were accepted and silently
+ # ignored — the installer's own --help documented behaviour it no longer
+ # had. --no-pull sets AISOC_PULL_POLICY=never, which `make up`'s refresh
+ # step and compose's own `pull_policy` both already understand; --rebuild
+ # goes through the Makefile's UP_FLAGS passthrough so there is still one
+ # code path that starts the stack.
+ local -a make_args=(up)
+ if [ "$REBUILD" = "1" ]; then
+ info "--rebuild: building the service images from source."
+ make_args+=("UP_FLAGS=--build")
+ fi
+ if [ "$NO_PULL" = "1" ]; then
+ info "--no-pull: using the images already on this machine."
+ export AISOC_PULL_POLICY=never
+ fi
+
+ # Run docker via `sg docker` if the user was just added to the group and
+ # hasn't logged out — otherwise the first `docker compose` call explodes.
+ #
# One architecture, one command. This used to hand off to
# `pnpm aisoc:demo`, which started a *different* nine-service compose file
# with no ingest service, no fusion service and Kafka disabled — its only
@@ -818,10 +849,16 @@ run_demo() {
# `make up` is now the only path, so what the installer starts, what the
# README documents and what CI tests are the same stack.
if [ "$DOCKER_NEEDS_NEWGRP" = "1" ] && have sg; then
- sg docker -c "cd '$REPO_ROOT' && make up" \
+ # `sg` takes one command string, so the arguments are quoted into it.
+ local quoted_args=""
+ local arg
+ for arg in "${make_args[@]}"; do
+ quoted_args+=" $(printf '%q' "$arg")"
+ done
+ sg docker -c "cd '$REPO_ROOT' && make${quoted_args}" \
|| { err "'make up' exited non-zero."; exit 3; }
else
- ( cd "$REPO_ROOT" && make up ) \
+ ( cd "$REPO_ROOT" && make "${make_args[@]}" ) \
|| { err "'make up' exited non-zero."; exit 3; }
fi
}
diff --git a/packages/aisoc-sandbox/README.md b/packages/aisoc-sandbox/README.md
index cf3669b74..f6a713d18 100644
--- a/packages/aisoc-sandbox/README.md
+++ b/packages/aisoc-sandbox/README.md
@@ -3,29 +3,30 @@
> Run an AiSOC agent investigation **offline in under 30 seconds**. No Docker, no API key, no network.
[![License: MIT](https://img.shields.io/badge/License-MIT-22c55e.svg)](https://github.com/beenuar/AiSOC/blob/main/LICENSE)
-[![PyPI release](https://img.shields.io/badge/pypi-not%20yet%20published-f59e0b)](https://github.com/beenuar/AiSOC/blob/main/CHANGELOG.md)
+[![PyPI release](https://img.shields.io/pypi/v/aisoc-sandbox?color=22c55e)](https://pypi.org/project/aisoc-sandbox/)
`aisoc-sandbox` is the quickest possible on-ramp to [AiSOC](https://github.com/beenuar/AiSOC). It walks one alert fixture through a four-stage agent funnel — **Detect → Triage → Hunt → Respond** — using a deterministic offline reasoner in place of a real LLM, and prints the resulting Investigation Ledger to your terminal.
-It is the simulator-equivalent of the production [`services/agents/`](https://github.com/beenuar/AiSOC/tree/main/services/agents) graph, collapsed into a single zero-dependency Python package. **When you're ready to run the real stack: `pnpm aisoc:demo` from a fresh clone of [AiSOC](https://github.com/beenuar/AiSOC).**
+It is the simulator-equivalent of the production [`services/agents/`](https://github.com/beenuar/AiSOC/tree/main/services/agents) graph, collapsed into a single zero-dependency Python package. **When you're ready to run the real stack: `git clone https://github.com/beenuar/AiSOC && cd AiSOC && make up`.**
## Why this exists
-The production AiSOC stack needs Postgres, Kafka, Redis, an LLM API key, and ~5 minutes to boot. That's the right cost for a buyer evaluating against their own alert data — but it's the wrong cost for a developer who just wants to see how the agent reasons before they commit their evening.
+The production AiSOC stack needs Postgres, Kafka, Redis and a few minutes to boot. That's the right cost for a buyer evaluating against their own alert data — but it's the wrong cost for a developer who just wants to see how the agent reasons before they commit their evening. (It does **not** need an API key: the stack ships a local model and runs triage with no credentials.)
This package collapses the boot time to **< 5 seconds** and the disk footprint to **< 50 KB**. The trade-off is that the reasoning is deterministic and the tools are simulated (not executed); see "Differences from the production stack" below.
## Install
```bash
-# Today (from this monorepo):
+pip install aisoc-sandbox
+aisoc-sandbox demo
+
+# Or without installing anything permanently:
+pipx run aisoc-sandbox demo
+
+# Or from a clone of the monorepo, to run it against your own changes:
git clone https://github.com/beenuar/AiSOC.git
cd AiSOC && pip install -e packages/aisoc-sandbox
-
-# Once published to PyPI (ready, unpublished — the upload is blocked on
-# registry credentials, which is an account action, not a code change):
-# pip install aisoc-sandbox
-# pipx run aisoc-sandbox demo
```
Python 3.10+ on Linux / macOS / Windows. Zero runtime dependencies.
@@ -118,9 +119,9 @@ print(ledger.to_json())
| Persistence | In-memory; one CLI invocation | Postgres `investigation_events` table |
| Latency | Synthetic per-stage numbers | Real LLM + tool latency |
| Boot time | < 5 s | ~5 min cold, ~3.5 min warm |
-| Dependencies | None | Postgres + Kafka + Redis + LLM API key |
+| Dependencies | None | Postgres + Kafka + Redis (a local model ships with the stack; no API key needed) |
-This is on purpose. The sandbox is the **on-ramp**, not a replacement: it gives you 30-second visibility into how the funnel hangs together so you can decide whether the full demo is worth the 5-minute boot.
+This is on purpose. The sandbox is the **on-ramp**, not a replacement: it gives you 30-second visibility into how the funnel hangs together so you can decide whether the full stack is worth the boot.
## License
diff --git a/render.yaml b/render.yaml
deleted file mode 100644
index f8245ccb8..000000000
--- a/render.yaml
+++ /dev/null
@@ -1,255 +0,0 @@
-# AiSOC on Render — Blueprint manifest
-#
-# Why this exists:
-# The "Deploy to Render" button in README.md points GitHub at this file.
-# Render reads it as a Blueprint and provisions the entire AiSOC stack —
-# 4 web services + Postgres + Redis — in a single click, no manual setup.
-#
-# What it deploys (the *lean demo profile* — same shape as Fly):
-# - api (FastAPI core)
-# - agents (LangGraph orchestrator)
-# - web (Next.js console + marketing)
-# - realtime (WebSocket fanout)
-# - aisoc-postgres (managed Render Postgres)
-# - aisoc-redis (managed Render Redis)
-#
-# What it skips (and why):
-# - Kafka, ClickHouse, OpenSearch, Neo4j, Qdrant — Render does not offer
-# managed versions, and self-hosting them on Render's instance plans is
-# wasteful. The lean profile uses the AISOC_DISABLE_* flags (defined in
-# services/api/app/core/config.py) so the API and agents degrade
-# gracefully: alerts work, cases work, the agent investigates. Heavy
-# analytics (ClickHouse-backed event search, Neo4j attack graphs) are
-# hidden in the UI when the backing store is absent.
-#
-# For a production install with the full storage tier, use Helm
-# (infra/helm/) or Terraform (infra/terraform/) — those targets assume
-# you have your own Kafka, ClickHouse, etc.
-#
-# Plan choice (`starter` vs `free`):
-# We default to `starter` ($7/svc/mo) because the `free` plan sleeps after
-# 15 min of inactivity — the agent's WebSocket connection breaks, and
-# cold starts blow the sub-60s time-to-first-investigation budget the
-# demo promises. Override `plan: free` per-service if you're truly just
-# kicking the tires.
-#
-# Re-deploys:
-# Render auto-redeploys on every push to the branch tracked by the
-# service. The `buildCommand` rebuilds the relevant Docker image; the
-# `startCommand` is the same one used in the service's Dockerfile.
-
-services:
- # ─── api ──────────────────────────────────────────────────────────────
- # Core FastAPI app. Mirrors the Fly demo's api service.
- - type: web
- name: aisoc-api
- runtime: docker
- dockerfilePath: ./services/api/Dockerfile
- dockerContext: ./services/api
- plan: starter
- healthCheckPath: /health
- autoDeploy: true
- # Render runs preDeployCommand once after a successful image build but
- # before the new instance accepts traffic. We use it to (a) apply
- # alembic migrations on every deploy and (b) idempotently re-seed the
- # 15-incident demo dataset including the in-flight INC-RT-001 ransomware
- # investigation that the web app's "Try the demo" CTA links to. The
- # seeder is safe to run on every deploy — it short-circuits if the
- # canonical case_numbers already exist. Without this hook the demo
- # would land on an empty dashboard and break the < 5 min clone-to-
- # investigation acceptance criterion.
- preDeployCommand: alembic upgrade head && python -m app.scripts.seed_demo
- envVars:
- - key: ENVIRONMENT
- value: demo
- - key: PORT
- value: "8000"
- # Demo gates: write actions return 403, mutating endpoints become
- # read-only. Flip these to `false` for a production deploy.
- - key: AISOC_DEMO_MODE
- value: "true"
- - key: AISOC_DEMO_TENANT
- value: demo
- # Disable optional integrations — Render doesn't offer Kafka/CH/etc.
- - key: AISOC_DISABLE_KAFKA
- value: "true"
- - key: AISOC_DISABLE_CLICKHOUSE
- value: "true"
- - key: AISOC_DISABLE_NEO4J
- value: "true"
- - key: AISOC_DISABLE_QDRANT
- value: "true"
- # Database wiring: Render injects the connection string via
- # `fromDatabase` when the resource is in the same Blueprint.
- - key: DATABASE_URL
- fromDatabase:
- name: aisoc-postgres
- property: connectionString
- - key: REDIS_URL
- fromService:
- type: redis
- name: aisoc-redis
- property: connectionString
- # Cross-service URLs — used by the api when it needs to call agents
- # (e.g. /investigate kickoff). Render assigns each service a
- # `<name>.onrender.com` hostname which we resolve via fromService.
- - key: AGENTS_API_URL
- fromService:
- type: web
- name: aisoc-agents
- property: hostport
- # Auto-generated JWT secret — rotated only if the user destroys it.
- - key: JWT_SECRET
- generateValue: true
-
- # ─── agents ───────────────────────────────────────────────────────────
- # LangGraph orchestrator + investigator. Talks to api over Render's
- # internal network (same hostport mechanism the api uses to reach it).
- - type: web
- name: aisoc-agents
- runtime: docker
- dockerfilePath: ./services/agents/Dockerfile
- dockerContext: ./services/agents
- # Agents need more memory for the LangGraph runtime + LLM client
- # buffers — Render's `standard` plan ships 2GB vs starter's 512MB.
- plan: standard
- healthCheckPath: /health
- autoDeploy: true
- envVars:
- - key: ENVIRONMENT
- value: demo
- - key: PORT
- value: "8084"
- # Deterministic mode means the agent runs the canonical investigation
- # without hitting OpenAI/Anthropic — keeps the demo cheap and
- # offline-reproducible. Users with their own API keys can flip this.
- - key: AISOC_AGENT_MODE
- value: deterministic
- - key: AISOC_DISABLE_KAFKA
- value: "true"
- - key: AISOC_DISABLE_QDRANT
- value: "true"
- - key: AISOC_DISABLE_NEO4J
- value: "true"
- - key: DATABASE_URL
- fromDatabase:
- name: aisoc-postgres
- property: connectionString
- - key: REDIS_URL
- fromService:
- type: redis
- name: aisoc-redis
- property: connectionString
- - key: CORE_API_URL
- fromService:
- type: web
- name: aisoc-api
- property: hostport
- # Optional — users wire these via the Render dashboard if they want
- # the agent to call out to OpenAI/Anthropic. Defaults to deterministic
- # offline mode.
- - key: OPENAI_API_KEY
- sync: false
- - key: ANTHROPIC_API_KEY
- sync: false
-
- # ─── realtime ─────────────────────────────────────────────────────────
- # Node.js WebSocket fanout. Has to keep the connection open for live
- # ledger streaming, so we explicitly keep it on starter (no sleep).
- - type: web
- name: aisoc-realtime
- runtime: docker
- dockerfilePath: ./services/realtime/Dockerfile
- dockerContext: ./services/realtime
- plan: starter
- healthCheckPath: /health
- autoDeploy: true
- envVars:
- - key: NODE_ENV
- value: production
- - key: PORT
- value: "8086"
- - key: REDIS_URL
- fromService:
- type: redis
- name: aisoc-redis
- property: connectionString
- # No Kafka — realtime falls back to Redis pub/sub for fanout when
- # AISOC_DISABLE_KAFKA is set. See services/realtime/src/index.ts.
- - key: AISOC_DISABLE_KAFKA
- value: "true"
-
- # ─── web ──────────────────────────────────────────────────────────────
- # Next.js console + marketing landing. Served last — depends on api +
- # realtime URLs being known so it can bake them into NEXT_PUBLIC_*.
- - type: web
- name: aisoc-web
- runtime: docker
- # The web Dockerfile needs the monorepo root as context (it copies
- # pnpm-workspace.yaml + packages/). This is the same gotcha we hit on
- # Fly, hence the explicit `.` context.
- dockerfilePath: ./apps/web/Dockerfile
- dockerContext: .
- plan: starter
- healthCheckPath: /
- autoDeploy: true
- envVars:
- - key: NODE_ENV
- value: production
- - key: PORT
- value: "3000"
- # Public-facing URLs — consumed by the browser, so they must be the
- # internet-reachable hostnames Render assigns each service.
- - key: NEXT_PUBLIC_API_URL
- fromService:
- type: web
- name: aisoc-api
- property: host
- - key: NEXT_PUBLIC_WS_URL
- fromService:
- type: web
- name: aisoc-realtime
- property: host
- # Demo banner — same flags the Fly demo uses, surfaced via
- # apps/web/src/lib/demoMode.ts. The variable names here MUST match
- # the ones that module reads (NEXT_PUBLIC_DEMO_*, no AISOC infix);
- # the previous NEXT_PUBLIC_AISOC_DEMO_* form was a typo that left
- # demo mode silently disabled on Render.
- - key: NEXT_PUBLIC_DEMO_MODE
- value: "true"
- # Land "Try the demo" visitors on the in-flight LockBit 3.0 ransomware
- # investigation seeded by services/api/app/scripts/seed_demo.py.
- # INC-RT-001 is the showcase scenario — encryption is already in
- # progress and the agent is streaming live decisions to the ledger.
- - key: NEXT_PUBLIC_DEMO_DEEPLINK
- value: /cases/INC-RT-001?tab=ledger
- - key: NEXT_PUBLIC_DEMO_BANNER
- value: "Demo data resets daily at 00:00 UTC. All write actions are disabled."
- # One-click auto-login for the read-only demo analyst account. The
- # seeder creates this user as part of the demo tenant; values must
- # stay in sync with services/api/app/scripts/seed_demo.py (which
- # sources DEMO_USER_EMAIL from app/api/v1/dev_auth.py and sets the
- # password to "aisoc-demo" via get_password_hash).
- - key: NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL
- - key: NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD
- value: aisoc-demo
-
- # ─── redis ────────────────────────────────────────────────────────────
- # Render's managed Redis. Used as cache + pub/sub spine when Kafka is
- # disabled. The free `starter` plan caps at 25MB which is more than
- # enough for the demo profile.
- - type: redis
- name: aisoc-redis
- plan: starter
- ipAllowList: [] # private — only siblings in this Blueprint reach it.
-
-databases:
- # ─── postgres ─────────────────────────────────────────────────────────
- # Render's managed Postgres. Demo profile fits comfortably in the
- # `starter` plan (1GB storage). Production deploys should resize via
- # the Render dashboard or use an external managed Postgres (RDS, etc.).
- - name: aisoc-postgres
- plan: starter
- databaseName: aisoc
- user: aisoc
diff --git a/scripts/check_profile_service_counts.py b/scripts/check_profile_service_counts.py
index 350c87053..831b968af 100644
--- a/scripts/check_profile_service_counts.py
+++ b/scripts/check_profile_service_counts.py
@@ -67,6 +67,39 @@ ONE_SHOT: frozenset[str] = frozenset({"ollama-pull"})
#: number. Deliberately a list of exact sites rather than a search for any
#: integer near the word "services": a gate that guesses which numbers are
#: claims would either miss the one that matters or flag prose forever.
+# Prose in this repository writes small counts as words as often as digits
+# ("the sixteen CORE containers"), and a gate that could only read digits
+# could not watch those sentences at all — which is how
+# `apps/docs/docs/installation.md` sat at "fourteen" while every registered
+# digit site was correct. The range covers the profile counts plus headroom;
+# anything outside it is reported rather than silently skipped.
+_NUMBER_WORDS: dict[str, int] = {
+ "ten": 10,
+ "eleven": 11,
+ "twelve": 12,
+ "thirteen": 13,
+ "fourteen": 14,
+ "fifteen": 15,
+ "sixteen": 16,
+ "seventeen": 17,
+ "eighteen": 18,
+ "nineteen": 19,
+ "twenty": 20,
+ "twenty-one": 21,
+ "twenty-two": 22,
+ "twenty-three": 23,
+ "twenty-four": 24,
+}
+
+
+def _as_count(raw: str) -> int | None:
+ """A captured claim as an integer, whether written in digits or words."""
+ text = raw.strip().lower()
+ if text.isdigit():
+ return int(text)
+ return _NUMBER_WORDS.get(text)
+
+
CLAIM_SITES: tuple[tuple[str, str, str], ...] = (
# Three figures that had drifted to 10, fifteen and fifteen against a
# compose file supporting neither. Registered rather than merely
@@ -78,6 +111,17 @@ CLAIM_SITES: tuple[tuple[str, str, str], ...] = (
("AGENTS.md", "core", r"CORE profile: (\d+) long-running services"),
("AGENTS.md", "prod:full", r"adds the rest \((\d+) services"),
("install.sh", "core", r"Starting the (\d+)-service CORE stack"),
+ # The installation page's Requirements table, where the memory figure is
+ # justified *by* the container count ("steady-state RSS across the N CORE
+ # containers"). It read "fourteen" for as long as connectors and actions
+ # had been in CORE: written as a word, so neither the digit-based claim
+ # sites nor the unregistered-figure sweep below could see it. This is the
+ # entry that makes the word form watchable.
+ (
+ "apps/docs/docs/installation.md",
+ "core",
+ r"Steady-state RSS across the ([a-z-]+|\d+) CORE containers",
+ ),
("apps/docs/docs/deployment/walkthrough.mdx", "core", r"starts the (\d+) CORE services"),
("Makefile", "core", r"`missing` on all (\d+) first-party services"),
# The production deployment page. `prod:full` is a separate figure from
@@ -399,7 +443,12 @@ def scan() -> tuple[dict[str, int], dict[str, set[str]], list[str]]:
f"CLAIM_SITES, or it was deleted and the entry is stale."
)
continue
- published = int(found.group(1))
+ published = _as_count(found.group(1))
+ if published is None:
+ errors.append(
+ f"{rel}: matched {found.group(1)!r} for the {profile!r} count, which is neither a number nor a number word this gate knows"
+ )
+ continue
if published != counts[profile]:
errors.append(
f"{rel}: publishes {published} services for the {profile!r} profile; "
diff --git a/scripts/lab.sh b/scripts/lab.sh
index 38aadf4a1..61d3e822d 100755
--- a/scripts/lab.sh
+++ b/scripts/lab.sh
@@ -145,7 +145,7 @@ banner "AiSOC Demo Lab is ready"
echo ""
echo -e " ${BOLD}Service URLs${NC}"
echo -e " ${CYAN}Web App ${NC} http://localhost:3000"
-echo -e " ${CYAN}API (REST) ${NC} http://localhost:8000/api/docs"
+echo -e " ${CYAN}API (REST) ${NC} http://localhost:8000 (spec: docs/openapi.yaml)"
echo -e " ${CYAN}API (GraphQL) ${NC} http://localhost:8000/graphql"
echo -e " ${CYAN}Agent Orchestrator${NC} http://localhost:8001/docs"
echo -e " ${CYAN}Jaeger Tracing ${NC} http://localhost:16686"
diff --git a/scripts/resolve_port_conflicts.py b/scripts/resolve_port_conflicts.py
index 8e6311894..c3fd0315f 100755
--- a/scripts/resolve_port_conflicts.py
+++ b/scripts/resolve_port_conflicts.py
@@ -219,6 +219,41 @@ def _our_containers() -> set[str]:
return set()
+def _published_by_service() -> dict[str, list[tuple[int, int]]]:
+ """`{service: [(host_port, container_port), …]}` from the inventory."""
+ out: dict[str, list[tuple[int, int]]] = {}
+ for host, service, container in inventory():
+ out.setdefault(service, []).append((host, container))
+ return out
+
+
+def _parses_as_yaml(text: str) -> bool:
+ """Whether compose could read this overlay at all.
+
+ A duplicate mapping key is valid-looking text that the YAML parser
+ rejects outright, which is how an unusable overlay shipped looking
+ correct. PyYAML permits duplicates, so the keys are counted directly
+ rather than trusting a successful parse.
+ """
+ try:
+ import yaml # noqa: PLC0415 — optional, and only the self-test needs it
+ except ImportError:
+ # No PyYAML here; the key-count assertion beside this still holds.
+ return True
+ try:
+ yaml.safe_load(text.replace("!override", ""))
+ except yaml.YAMLError:
+ return False
+ seen: set[str] = set()
+ for line in text.splitlines():
+ if line.startswith(" ") and line.endswith(":") and not line.startswith(" ") and not line.strip().startswith("#"):
+ key = line.strip()
+ if key in seen:
+ return False
+ seen.add(key)
+ return True
+
+
def render(moves: list[tuple[int, str, int, int]]) -> str:
lines = [
"# Generated by scripts/resolve_port_conflicts.py — do not edit by hand.",
@@ -235,11 +270,36 @@ def render(moves: list[tuple[int, str, int, int]]) -> str:
"",
"services:",
]
- for old, service, container, new in moves:
- lines.append(f" # {service}: {old} was in use, published on {new} instead")
+ # Grouped by service, and emitting that service's *whole* published port
+ # list, for two reasons that both produced a broken stack:
+ #
+ # One block per move meant a service publishing two conflicting ports got
+ # its key written twice — `ingest-worker` publishes 8081 and 9090, and on
+ # a host where both were taken the overlay was unparseable YAML
+ # ("mapping key already defined"), so `make up` failed with the file in
+ # place and looking correct.
+ #
+ # And because `ports: !override` *replaces* the list rather than merging
+ # into it, naming only the moved port silently unpublishes every other
+ # port that service exposes. A service with one conflicting and one clean
+ # port would have come up missing the clean one.
+ moved: dict[str, dict[int, int]] = {}
+ for _old, service, container, new in moves:
+ moved.setdefault(service, {})[container] = new
+
+ published: dict[str, list[tuple[int, int]]] = {}
+ for host, service, container in inventory():
+ published.setdefault(service, []).append((host, container))
+
+ for service, by_container in moved.items():
+ notes = ", ".join(f"{old} → {new}" for old, _s, container, new in moves if _s == service for new in (by_container[container],))
+ lines.append(f" # {service}: {notes} (the ports not listed here were free and are unchanged)")
lines.append(f" {service}:")
lines.append(" ports: !override")
- lines.append(f' - "{new}:{container}"')
+ # Every port this service publishes, in the order the inventory
+ # lists them, with the moved ones substituted.
+ for host, container in published.get(service, []):
+ lines.append(f' - "{by_container.get(container, host)}:{container}"')
return "\n".join(lines) + "\n"
@@ -273,6 +333,30 @@ def _self_test() -> int:
results.append(("the overlay publishes the new port", '"15432:5432"' in rendered))
results.append(("the inventory parses out of doctor.sh", len(inventory()) >= 16))
+ # A service publishing two ports with both taken. One block per move
+ # wrote its key twice, and compose refuses the whole file with
+ # "mapping key already defined" — so `make up` failed on a host with
+ # this conflict shape, with the overlay in place and looking right.
+ multi = [service for service, ports in _published_by_service().items() if len(ports) > 1]
+ if multi:
+ service = multi[0]
+ ports = _published_by_service()[service]
+ both = [(host, service, container, 15000 + i) for i, (host, container) in enumerate(ports)]
+ text = render(both)
+ results.append(
+ (f"a service with {len(ports)} moved ports gets one YAML key ({service})", text.count(f"\n {service}:\n") == 1),
+ )
+ results.append(("...and that overlay parses", _parses_as_yaml(text)))
+
+ # `ports: !override` replaces the list, so naming only the moved
+ # port unpublishes the rest. Move one; the other must survive.
+ host_kept, container_kept = ports[1]
+ one = [(ports[0][0], service, ports[0][1], 15999)]
+ text_one = render(one)
+ results.append(
+ ("a port that did not move is still published", f'"{host_kept}:{container_kept}"' in text_one),
+ )
+
for label, ok in results:
print(f" {'PASS' if ok else 'FAIL'} {label}")
failed = [label for label, ok in results if not ok]
diff --git a/tests/test_installer_parity_gate.py b/tests/test_installer_parity_gate.py
index 68a31353c..86c40af67 100644
--- a/tests/test_installer_parity_gate.py
+++ b/tests/test_installer_parity_gate.py
@@ -76,6 +76,20 @@ def _code_lines(text: str) -> list[str]:
return out
+# Lines that *print* rather than *do*. A banner telling the operator what to
+# run later contains the same command text as the invocation that runs it,
+# and that near-miss is not hypothetical here: the installer's `-NoLaunch`
+# help prints `docker compose up -d`, `docker compose ps -a` and
+# `docker compose run --rm -T api …` verbatim, so three assertions below
+# would have passed on a script that only ever *mentioned* those commands.
+_OUTPUT_CMDLET = re.compile(r"^\s*Write-(Host|Info|Ok|Warn|Err|Log|Section)\b", re.IGNORECASE)
+
+
+def _action_lines(text: str) -> str:
+ """Code lines with the output cmdlets removed — what the script executes."""
+ return "\n".join(line for line in _code_lines(text) if not _OUTPUT_CMDLET.match(line))
+
+
# ── What the installer starts ───────────────────────────────────────────────
@@ -95,22 +109,97 @@ def test_windows_installer_does_not_hand_off_to_the_demo_stack() -> None:
def test_windows_installer_starts_the_real_stack() -> None:
- code = "\n".join(_code_lines(_read(INSTALL_PS1)))
- assert "'compose', 'up', '-d'" in code or "docker compose up -d" in code, (
+ actions = _action_lines(_read(INSTALL_PS1))
+ assert ("'up', '-d'" in actions) or ("'compose', 'up', '-d'" in actions) or ("docker compose up -d" in actions), (
"install.ps1 must start the deployment defined by the root docker-compose.yml, the same one `make up` starts."
)
def test_windows_installer_waits_for_containers_to_be_healthy() -> None:
"""`docker compose up -d` returning 0 is not the stack being up."""
- code = "\n".join(_code_lines(_read(INSTALL_PS1)))
- assert "docker compose ps -a" in code, (
+ actions = _action_lines(_read(INSTALL_PS1))
+ assert ("'ps', '-a'" in actions) or ("docker compose ps -a" in actions), (
"install.ps1 must poll `docker compose ps -a` before declaring the "
"stack up. Without `-a` an exited container is absent from the "
"listing entirely and a crash-looping service reads as success."
)
for state in ("exited", "restarting", "unhealthy"):
- assert state in code, f"install.ps1's wait loop does not treat {state!r} as a failure"
+ assert state in actions, f"install.ps1's wait loop does not treat {state!r} as a failure"
+
+
+# ── No on-ramp may point an evaluator at the demo stack ────────────────────
+
+#: Surfaces a first-time user meets. Each one has, at some point, told
+#: somebody to run `pnpm aisoc:demo` as their way into the product:
+#: install.sh and install.ps1 by handing off to it, the devcontainer in its
+#: attach banner, and the sandbox README in its "when you're ready for the
+#: real stack" line. The compose file behind that command has no ingest
+#: service, no fusion service and Kafka disabled — its own header says it
+#: "does NOT run the AiSOC pipeline" and must not be used to evaluate
+#: whether AiSOC works — so each of those sent an evaluator to a populated
+#: console that had never run the product.
+#:
+#: Fixing the installers did not fix the class; the other two were found
+#: still doing it afterwards. This checks all of them at once.
+ONRAMP_SURFACES = (
+ "install.sh",
+ "install.ps1",
+ ".devcontainer/devcontainer.json",
+ "packages/aisoc-sandbox/README.md",
+ "apps/docs/docs/quickstart.md",
+ "apps/docs/docs/installation.md",
+ "docs/QUICK_INSTALL.md",
+ "README.md",
+)
+
+
+def _instructional_lines(path: Path, text: str) -> list[str]:
+ """Lines that tell a reader to do something, minus the ones explaining
+ what we deliberately do *not* do.
+
+ Every one of these files is entitled to name the demo stack while
+ warning readers off it — several now do, at length, and a gate that
+ could not tell a warning from an instruction would force those
+ warnings to be deleted. That would be the wrong direction: the warning
+ is the thing keeping an evaluator out of a console that proves nothing.
+
+ So the exemptions are the three shapes commentary actually takes here:
+ a source-code comment, a Markdown blockquote, and a Docusaurus
+ admonition (`:::caution` … `:::`). Everything else counts.
+ """
+ if path.suffix == ".ps1":
+ return _code_lines(text)
+ if path.suffix in {".sh", ".json"}:
+ return [line for line in text.splitlines() if not line.strip().startswith(("#", "//"))]
+
+ out: list[str] = []
+ in_admonition = False
+ for line in text.splitlines():
+ stripped = line.strip()
+ if stripped.startswith(":::"):
+ # `:::caution Title` opens, a bare `:::` closes.
+ in_admonition = len(stripped) > 3
+ continue
+ if in_admonition or stripped.startswith(">"):
+ continue
+ out.append(line)
+ return out
+
+
[email protected]("rel", ONRAMP_SURFACES)
+def test_no_onramp_offers_the_demo_stack_as_a_way_in(rel: str) -> None:
+ path = REPO / rel
+ if not path.is_file():
+ pytest.skip(f"{rel} is not in this checkout")
+ offenders = [line.strip() for line in _instructional_lines(path, _read(path)) if DEMO_HANDOFF in line]
+ assert not offenders, (
+ f"{rel} points a first-time user at the demo stack:\n "
+ + "\n ".join(offenders)
+ + f"\n`{DEMO_HANDOFF}` starts a compose file with no ingest and no fusion service. "
+ "It cannot answer whether AiSOC works, so it must not be anybody's way in — "
+ "use `make up`. Explaining in a comment why it is not used is fine; telling "
+ "somebody to run it is not."
+ )
# ── Parity with the Makefile targets install.sh reaches through `make` ──────
@@ -132,9 +221,9 @@ def test_windows_installer_creates_the_first_administrator() -> None:
"""
module = "app.scripts.bootstrap_admin"
assert module in _makefile_recipe("bootstrap"), f"`make bootstrap` no longer runs {module}; update this gate and install.ps1 together"
- code = "\n".join(_code_lines(_read(INSTALL_PS1)))
- assert module in code, f"install.ps1 never runs {module}, so no administrator is created"
- assert "docker compose run --rm -T api" in code, (
+ actions = _action_lines(_read(INSTALL_PS1))
+ assert module in actions, f"install.ps1 never runs {module}, so no administrator is created"
+ assert ("'run', '--rm', '-T', 'api'" in actions) or ("docker compose run --rm -T api" in actions), (
"install.ps1 must create the administrator the same way `make bootstrap` does — a one-shot `docker compose run --rm -T api`"
)
@@ -151,6 +240,73 @@ def test_windows_installer_runs_the_golden_pipeline() -> None:
)
+# ── Setup steps that are Python programs on both paths ─────────────────────
+#
+# Both of these shipped broken on Windows, and this gate is why they could.
+# It asserted compose/bootstrap/smoke/lockfile parity and said nothing about
+# how `.env` is produced or what happens when a port is taken — so
+# install.ps1 plain-copied `.env.example` (ENVIRONMENT=production with the
+# secrets empty, which `enforce_secure_defaults` refuses to boot on) and
+# exited 3 on a busy port, for as long as both existed.
+
+
+def test_both_installers_generate_the_env_secrets() -> None:
+ """A copied `.env.example` is not a usable environment.
+
+ `.env.example` ships `ENVIRONMENT=production` with `SECRET_KEY`,
+ `JWT_SECRET`, `METRICS_TOKEN` and `AISOC_CREDENTIAL_KEY` empty.
+ `scripts/ensure_env.py` is what fills them, `make env` runs it, and an
+ installer that only copies the template hands the operator a stack whose
+ API crash-loops on its first boot with nothing pointing back at the copy.
+ """
+ generator = "ensure_env.py"
+ assert generator in _makefile_recipe("env"), f"`make env` no longer runs {generator}; update this gate and both installers together"
+ for path in (INSTALL_SH, INSTALL_PS1):
+ text = _read(path)
+ body = _action_lines(text) if path is INSTALL_PS1 else text
+ assert generator in body, (
+ f"{path.name} never runs scripts/{generator}, so the `.env` it writes carries "
+ "empty secrets and the API refuses to start in production."
+ )
+
+
+def test_windows_installer_resolves_port_conflicts_rather_than_refusing() -> None:
+ """A busy port must move the publication, not stop the install.
+
+ `make up` runs `scripts/resolve_port_conflicts.py`, which republishes the
+ conflicting port and writes `docker-compose.ports.yml`. install.ps1 used
+ to `exit 3` and tell the operator to edit `docker-compose.yml` by hand —
+ on the two conditions most likely in this audience's environment, an
+ existing Postgres on 5432 or an Ollama on 11434 — while README.md
+ promises "a port already in use does not stop the install".
+ """
+ resolver = "resolve_port_conflicts.py"
+ assert resolver in _makefile_recipe("_ports"), f"`make up` no longer runs {resolver}; update this gate and install.ps1 together"
+ actions = _action_lines(_read(INSTALL_PS1))
+ assert resolver in actions, (
+ f"install.ps1 never runs scripts/{resolver}, so a port already in use is a hard stop on Windows "
+ "while the same condition is resolved automatically on the `make up` path."
+ )
+
+
+def test_windows_installer_passes_the_port_overlay_to_every_compose_call() -> None:
+ """Starting a remapped stack and then addressing the base composition is
+ two different stacks: `ps` reports nothing to wait for and
+ `bootstrap_admin` runs against a project the operator is not using. The
+ Makefile funnels every call through its `COMPOSE` variable for this
+ reason; install.ps1 funnels them through `Get-ComposeArgs`."""
+ overlay = "docker-compose.ports.yml"
+ assert overlay in _read(MAKEFILE), f"the Makefile no longer builds {overlay}; update this gate and install.ps1 together"
+ actions = _action_lines(_read(INSTALL_PS1))
+ assert overlay in actions, f"install.ps1 never references {overlay}, so a remapped stack is addressed inconsistently"
+
+ # Every `& docker` invocation that speaks to the project must go through
+ # the helper. A raw `docker compose …` would silently target the base
+ # composition.
+ raw = [line.strip() for line in actions.splitlines() if re.search(r"&\s*docker\s+compose\b", line) and "version" not in line]
+ assert not raw, "install.ps1 calls compose without the port overlay:\n " + "\n ".join(raw)
+
+
def test_both_installers_use_a_frozen_lockfile() -> None:
"""A self-hoster must not silently resolve a dependency set nobody tested."""
for path in (INSTALL_SH, INSTALL_PS1):