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.

feat(demo,infra): WS-A3 — canonical INC-RT-001 deeplink + bake demo flags into web image

Beenu Arorac20c22559989
diff --git a/.github/workflows/publish-images.yml b/.github/workflows/publish-images.yml
index c24e9a6bb..f941890d0 100644
--- a/.github/workflows/publish-images.yml
+++ b/.github/workflows/publish-images.yml
@@ -72,6 +72,27 @@ jobs:
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
type=sha,prefix=sha-,format=short
+ # Web image needs NEXT_PUBLIC_DEMO_* flags baked in at build time so
+ # the published ghcr.io/beenuar/aisoc-web image used by `pnpm aisoc:demo`
+ # ships a bundle that knows it's a demo (banner, auto-login, deeplink).
+ # Without these the bundle has empty strings → demo affordances no-op
+ # and visitors get bounced to /login on first navigation. Other images
+ # (api/agents/realtime) gate demo behavior at runtime via AISOC_DEMO_MODE
+ # so they don't need build args. The Dockerfile already defaults these
+ # to demo values; setting them here is explicit-is-better-than-implicit.
+ - id: web-build-args
+ if: matrix.service == 'web'
+ run: |
+ {
+ echo 'build_args<<EOF'
+ echo 'NEXT_PUBLIC_DEMO_MODE=true'
+ echo 'NEXT_PUBLIC_DEMO_DEEPLINK=/cases/INC-RT-001?tab=ledger'
+ echo 'NEXT_PUBLIC_DEMO_BANNER=Demo data resets daily at 00:00 UTC. All write actions are disabled.'
+ echo 'NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD=aisoc-demo'
+ echo 'EOF'
+ } >> "$GITHUB_OUTPUT"
+
- uses: docker/build-push-action@v7
with:
context: ${{ matrix.context }}
@@ -79,6 +100,7 @@ jobs:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+ build-args: ${{ steps.web-build-args.outputs.build_args }}
cache-from: type=gha,scope=${{ matrix.service }}
cache-to: type=gha,mode=max,scope=${{ matrix.service }}
platforms: linux/amd64
diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile
index d31d66c9b..150d47e5c 100644
--- a/apps/web/Dockerfile
+++ b/apps/web/Dockerfile
@@ -49,6 +49,30 @@ ARG NEXT_PUBLIC_WS_URL=""
ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}
ENV NEXT_PUBLIC_WS_URL=${NEXT_PUBLIC_WS_URL}
+# ─── Build-time demo-mode flags (client-side bundle) ────────────────────────
+# These drive the in-bundle demo experience read by `apps/web/src/lib/demoMode.ts`:
+# - NEXT_PUBLIC_DEMO_MODE: gates the banner, auto-login, and read-only UI
+# - NEXT_PUBLIC_DEMO_DEEPLINK: the case URL the onboarding "Try Demo" CTA targets
+# - NEXT_PUBLIC_DEMO_BANNER: top-of-page banner copy
+# - NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL/_PASSWORD: credentials DemoAutoLogin uses on
+# first paint so visitors land already authenticated and can roam
+#
+# Defaults match the canonical hosted demo so a no-arg `docker build` of the web
+# image (e.g. CI's publish-images.yml) ships a demo-ready bundle. Production
+# customers override NEXT_PUBLIC_DEMO_MODE="" at build time to suppress all
+# demo affordances. The api/agents/realtime images are unaffected — demo gating
+# in those services is runtime via AISOC_DEMO_MODE, not build-time.
+ARG NEXT_PUBLIC_DEMO_MODE="true"
+ARG NEXT_PUBLIC_DEMO_DEEPLINK="/cases/INC-RT-001?tab=ledger"
+ARG NEXT_PUBLIC_DEMO_BANNER="Demo data resets daily at 00:00 UTC. All write actions are disabled."
+ARG NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL="[email protected]"
+ARG NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD="aisoc-demo"
+ENV NEXT_PUBLIC_DEMO_MODE=${NEXT_PUBLIC_DEMO_MODE}
+ENV NEXT_PUBLIC_DEMO_DEEPLINK=${NEXT_PUBLIC_DEMO_DEEPLINK}
+ENV NEXT_PUBLIC_DEMO_BANNER=${NEXT_PUBLIC_DEMO_BANNER}
+ENV NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL=${NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL}
+ENV NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD=${NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD}
+
# Use pnpm's default symlinked node_modules — same layout as local dev,
# so tsup/tsc bin shims resolve correctly inside each workspace package.
RUN pnpm install --no-frozen-lockfile
diff --git a/apps/web/src/app/why-open-source/page.tsx b/apps/web/src/app/why-open-source/page.tsx
index 05f393140..8a64f2d64 100644
--- a/apps/web/src/app/why-open-source/page.tsx
+++ b/apps/web/src/app/why-open-source/page.tsx
@@ -420,7 +420,7 @@ export default function WhyOpenSourcePage() {
</p>
<div className="mt-6 flex flex-wrap justify-center gap-3">
<a
- href="https://tryaisoc.com/cases/INC-001?tab=ledger"
+ href="https://tryaisoc.com/cases/INC-RT-001?tab=ledger"
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-2 rounded-md bg-brand-500 px-4 py-2 text-sm font-semibold text-white transition hover:bg-brand-400"
diff --git a/apps/web/src/components/cases/CaseWorkspace.tsx b/apps/web/src/components/cases/CaseWorkspace.tsx
index dca8372fb..43a745b02 100644
--- a/apps/web/src/components/cases/CaseWorkspace.tsx
+++ b/apps/web/src/components/cases/CaseWorkspace.tsx
@@ -302,9 +302,10 @@ function TaskRow({ task, onChangeStatus }: TaskRowProps) {
export function CaseWorkspace({ caseId }: { caseId: string }) {
const [demoMode, setDemoMode] = useState(false);
- // Honor `?tab=…` so the hosted demo deeplink (`/cases/INC-001?tab=ledger`)
- // lands visitors directly on the live agent decision feed. Falls back to
- // the overview when the param is missing or unrecognized.
+ // Honor `?tab=…` so the hosted demo deeplink
+ // (`/cases/INC-RT-001?tab=ledger`) lands visitors directly on the live
+ // agent decision feed for the LockBit 3.0 ransomware showcase. Falls back
+ // to the overview when the param is missing or unrecognized.
const searchParams = useSearchParams();
const initialTab: WorkspaceTab = useMemo(() => {
const t = searchParams?.get('tab') ?? null;
diff --git a/apps/web/src/components/landing/Hero.test.tsx b/apps/web/src/components/landing/Hero.test.tsx
index febc421ae..711e37c1e 100644
--- a/apps/web/src/components/landing/Hero.test.tsx
+++ b/apps/web/src/components/landing/Hero.test.tsx
@@ -39,7 +39,7 @@ describe('Hero', () => {
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(/auditable AI SOC/i);
expect(screen.getByRole('link', { name: /open the demo/i })).toHaveAttribute(
'href',
- 'https://tryaisoc.com/cases/INC-001?tab=ledger',
+ 'https://tryaisoc.com/cases/INC-RT-001?tab=ledger',
);
expect(screen.getByRole('link', { name: /open console/i })).toHaveAttribute('href', '/dashboard');
});
diff --git a/apps/web/src/components/landing/Hero.tsx b/apps/web/src/components/landing/Hero.tsx
index df0c1322a..bc8f47476 100644
--- a/apps/web/src/components/landing/Hero.tsx
+++ b/apps/web/src/components/landing/Hero.tsx
@@ -41,7 +41,7 @@ export function Hero() {
<div className="mt-8 flex flex-wrap items-center gap-3">
<a
- href="https://tryaisoc.com/cases/INC-001?tab=ledger"
+ href="https://tryaisoc.com/cases/INC-RT-001?tab=ledger"
target="_blank"
rel="noreferrer"
className="group inline-flex items-center gap-2 rounded-lg bg-brand-500 px-5 py-3 text-sm font-semibold text-white transition hover:bg-brand-400"
diff --git a/apps/web/src/lib/demoMode.ts b/apps/web/src/lib/demoMode.ts
index f2d1c3893..df87fb139 100644
--- a/apps/web/src/lib/demoMode.ts
+++ b/apps/web/src/lib/demoMode.ts
@@ -6,7 +6,7 @@
*
* - `isDemoMode()` → true when the deployment is the hosted demo
* - `demoBannerMessage()` → the banner copy to render at the top of every page
- * - `demoDeeplink()` → the `/cases/INC-001?tab=ledger` deeplink the
+ * - `demoDeeplink()` → the `/cases/INC-RT-001?tab=ledger` deeplink the
* README "Live Demo" button targets, so we land
* visitors on a hot, mid-investigation view
*
diff --git a/docker-compose.demo.yml b/docker-compose.demo.yml
index 442070dbe..41d894ee3 100644
--- a/docker-compose.demo.yml
+++ b/docker-compose.demo.yml
@@ -260,6 +260,20 @@ services:
API_URL: http://api:8000
AGENTS_URL: http://agents:8084
REALTIME_URL: http://realtime:4000
+ # NEXT_PUBLIC_* values are inlined as string literals into the client
+ # bundle at `next build` time, so the local demo experience (banner,
+ # auto-login, deeplink routing) requires baking them in here. Without
+ # these the bundle ships with empty strings and `isDemoMode()` returns
+ # false → no banner, no auto-login, visitor gets bounced to /login on
+ # first navigation. Mirrors the prod hosted defaults in
+ # apps/web/Dockerfile so `pnpm aisoc:demo --rebuild` produces an image
+ # behaviourally identical to the published ghcr.io/beenuar/aisoc-web
+ # image used by the no-flag default flow.
+ NEXT_PUBLIC_DEMO_MODE: "true"
+ NEXT_PUBLIC_DEMO_DEEPLINK: "/cases/INC-RT-001?tab=ledger"
+ NEXT_PUBLIC_DEMO_BANNER: "Demo data resets daily at 00:00 UTC. All write actions are disabled."
+ NEXT_PUBLIC_DEMO_AUTOLOGIN_EMAIL: "[email protected]"
+ NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD: "aisoc-demo"
container_name: aisoc-demo-web
pull_policy: missing
depends_on:
diff --git a/infra/coolify/README.md b/infra/coolify/README.md
index fee6aea8d..778cba3d3 100644
--- a/infra/coolify/README.md
+++ b/infra/coolify/README.md
@@ -75,8 +75,11 @@ POSTGRES_PASSWORD=<click Generate>
# Public URLs — replace with your domain
NEXT_PUBLIC_API_URL=https://api.aisoc.example.com
NEXT_PUBLIC_WS_URL=wss://realtime.aisoc.example.com
-NEXT_PUBLIC_AISOC_DEMO_MODE=true
-NEXT_PUBLIC_AISOC_DEMO_DEEPLINK=/cases/INC-001?tab=ledger
+NEXT_PUBLIC_DEMO_MODE=true
+NEXT_PUBLIC_DEMO_DEEPLINK=/cases/INC-RT-001?tab=ledger
+NEXT_PUBLIC_DEMO_BANNER=Demo data resets daily. All write actions are disabled.
+NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD=aisoc-demo
```
Optional (only if you want LLM-backed agents instead of the
@@ -116,15 +119,23 @@ First deploy takes ~10-15 minutes (Docker image pulls + first build).
### Step 6: Pre-warm the demo
-SSH into the VPS and run the seed inside the api container:
+The api container's entrypoint runs `alembic upgrade head && python -m
+app.scripts.seed_demo` on every start, so the demo tenant — including
+the in-flight LockBit 3.0 ransomware investigation `INC-RT-001` — is
+present before the service accepts traffic. The seeder is idempotent:
+re-running against an already-seeded database is a cheap no-op that
+refreshes the canonical 15 incidents.
+
+If you ever need to re-seed manually, SSH into the VPS and run:
```bash
docker exec -it $(docker ps -qf "name=aisoc-api") \
- python scripts/demo_seed.py --reset --kickoff-investigation
+ python -m app.scripts.seed_demo
```
-Open `https://web.aisoc.example.com` — demo banner shows, deeplink
-lands on a pre-seeded incident.
+Open `https://web.aisoc.example.com` — the onboarding hero loads with
+the demo banner primed, and the **Try Demo** CTA deep-links to
+`/cases/INC-RT-001?tab=ledger`.
## Disabling optional services
@@ -152,7 +163,7 @@ disabled storage tier.
Coolify has scheduled tasks built in. To rotate the demo daily:
1. Project → **+ New Resource** → **Service** → **Schedule**.
-2. **Command**: `docker exec aisoc-api python scripts/demo_seed.py --reset --kickoff-investigation`
+2. **Command**: `docker exec aisoc-api python -m app.scripts.seed_demo`
3. **Cron**: `0 0 * * *` (daily at 00:00 UTC).
4. **Save**.
@@ -214,7 +225,7 @@ settings → **Network**.
### Web service shows "demo banner" but deeplink doesn't work
-Run the seed (Step 6 above) — if it never executed, INC-001 doesn't
+Run the seed (Step 6 above) — if it never executed, `INC-RT-001` doesn't
exist in Postgres yet, so the deeplink 404s. The seed is *not*
auto-triggered on Coolify the way it is on the Fly demo.
diff --git a/infra/fly/api/fly.toml b/infra/fly/api/fly.toml
index 8ab16c90d..a40201aa7 100644
--- a/infra/fly/api/fly.toml
+++ b/infra/fly/api/fly.toml
@@ -44,7 +44,7 @@ kill_timeout = "5s"
PORT = "8000"
# Demo gates: write actions return 403, mutating endpoints become read-only
AISOC_DEMO_MODE = "true"
- # Tenant rotation runs daily; the seeder writes the canonical INC-001 case
+ # Tenant rotation runs daily; the seeder writes the canonical INC-RT-001 case
AISOC_DEMO_TENANT = "demo"
# Disable optional integrations (no Kafka/ClickHouse/OpenSearch on demo)
AISOC_DISABLE_KAFKA = "true"
diff --git a/infra/railway/README.md b/infra/railway/README.md
index ece7dd4ec..4c32a65dc 100644
--- a/infra/railway/README.md
+++ b/infra/railway/README.md
@@ -126,9 +126,11 @@ NODE_ENV=production
PORT=3000
NEXT_PUBLIC_API_URL=https://${{ api.RAILWAY_PUBLIC_DOMAIN }}
NEXT_PUBLIC_WS_URL=wss://${{ realtime.RAILWAY_PUBLIC_DOMAIN }}
-NEXT_PUBLIC_AISOC_DEMO_MODE=true
-NEXT_PUBLIC_AISOC_DEMO_DEEPLINK=/cases/INC-001?tab=ledger
-NEXT_PUBLIC_AISOC_DEMO_BANNER=Demo data resets daily. All write actions are disabled.
+NEXT_PUBLIC_DEMO_MODE=true
+NEXT_PUBLIC_DEMO_DEEPLINK=/cases/INC-RT-001?tab=ledger
+NEXT_PUBLIC_DEMO_BANNER=Demo data resets daily. All write actions are disabled.
+NEXT_PUBLIC_DEMO_AUTOLOGIN_PASSWORD=aisoc-demo
```
5. **Settings** → **Networking** → **Generate Domain**.
@@ -137,15 +139,23 @@ NEXT_PUBLIC_AISOC_DEMO_BANNER=Demo data resets daily. All write actions are disa
### Step 6: Pre-warm the demo
+The api service runs `alembic upgrade head && python -m
+app.scripts.seed_demo` on every deploy via Railway's `releaseCommand`,
+so the canonical 15 incidents (including the in-flight LockBit 3.0
+ransomware investigation `INC-RT-001`) are present before the new
+instance accepts traffic. The seeder is idempotent — re-running against
+an already-seeded database is a cheap no-op.
+
+If you ever need to re-seed manually, open the api service's shell in
+Railway and run:
+
```bash
-# From your local machine:
-CORE_API_URL=https://api-<hash>.up.railway.app \
-AGENTS_API_URL=https://agents-<hash>.up.railway.app \
- python scripts/demo_seed.py --reset --kickoff-investigation
+python -m app.scripts.seed_demo
```
-Open the web service's URL — you should land on the demo banner with the
-INC-001 deeplink primed.
+Open the web service's URL — you should land on the onboarding hero with
+the demo banner primed and the **Try Demo** CTA deep-linking to
+`/cases/INC-RT-001?tab=ledger`.
## Why this isn't a one-click experience
@@ -171,7 +181,7 @@ the demo daily, add a 5th service running the seed script:
# In a copy of railway.toml under a new service "demo-seed":
[deploy]
cronSchedule = "0 0 * * *" # daily at 00:00 UTC
-startCommand = "python scripts/demo_seed.py --reset --kickoff-investigation"
+startCommand = "python -m app.scripts.seed_demo"
```
Or skip it for personal evaluation deploys.
diff --git a/infra/railway/railway.toml b/infra/railway/railway.toml
index d243ee95e..b5c9ee961 100644
--- a/infra/railway/railway.toml
+++ b/infra/railway/railway.toml
@@ -48,6 +48,25 @@ healthcheckTimeout = 60
restartPolicyType = "ON_FAILURE"
restartPolicyMaxRetries = 10
+# Run migrations + idempotent demo seed in a temporary VM before the new
+# release is promoted. This is what makes the Railway "Deploy" button a
+# real one-click experience: by the time the api goes healthy and the
+# user opens the web service, the canonical 15-incident demo (with the
+# in-flight LockBit 3.0 ransomware investigation INC-RT-001 already
+# streaming agent decisions) is sitting in Postgres waiting to be seen.
+#
+# Why preDeployCommand vs startCommand:
+# - preDeployCommand runs once per deploy in an isolated VM with all
+# env vars wired up. Failures abort the release before traffic is
+# swung over — exactly the gate we want for migrations.
+# - startCommand would re-run migrations + seed on *every* container
+# restart, which is wasteful and racy under multiple replicas.
+#
+# Idempotency: services/api/app/scripts/seed_demo.py short-circuits when
+# the demo tenant already exists, so re-running on every deploy (which
+# is what Railway does) is cheap.
+preDeployCommand = "alembic upgrade head && python -m app.scripts.seed_demo"
+
# Service-level env. The actual secrets (DATABASE_URL, REDIS_URL) are
# auto-injected by Railway when you attach the Postgres + Redis plugins
# — we do NOT set them here, because hardcoding `${{ Postgres.DATABASE_URL }}`
diff --git a/infra/render/README.md b/infra/render/README.md
index 6279251a5..335c455f5 100644
--- a/infra/render/README.md
+++ b/infra/render/README.md
@@ -77,16 +77,19 @@ gh repo view --web
## Post-deploy: pre-warm the demo
-Render doesn't have an equivalent of Fly's `flyctl ssh console -C` for
-running one-shot commands, but the demo seeds itself the first time a
-visitor lands on the api (`scripts/demo_seed.py` runs on startup if the
-demo tenant is empty). For a faster cold start:
+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
-# From your local machine, point the seed script at the deployed api:
-CORE_API_URL=https://aisoc-api-<hash>.onrender.com \
-AGENTS_API_URL=https://aisoc-agents-<hash>.onrender.com \
- python scripts/demo_seed.py --reset --kickoff-investigation
+python -m app.scripts.seed_demo
```
## Daily reset (optional)
diff --git a/scripts/aisoc-demo.ts b/scripts/aisoc-demo.ts
index 0c044f69b..f5d8f400f 100644
--- a/scripts/aisoc-demo.ts
+++ b/scripts/aisoc-demo.ts
@@ -17,23 +17,30 @@
*
* On a warm Docker daemon the full path is roughly 3.5 minutes:
* about 90s pull + 60s startup + 30s seed + 30s investigation. The
- * v1.0 acceptance gate is clone-to-investigation in ≤ 5 minutes on a
- * clean Mac with a cold Docker daemon.
+ * v1.0 acceptance gate (the WS-A acceptance to-do in the buyer-value
+ * plan) is clone-to-investigation in ≤ 5 minutes on a clean Mac with
+ * a cold Docker daemon. The `--budget-ms` flag enforces this gate
+ * automatically and `--results-file` writes a phase-by-phase JSON
+ * timing report so CI / nightly runs can spot regressions.
*
* Usage: pnpm aisoc:demo
*
* Flags:
- * --no-pull skip the `docker compose pull` step (use cached images)
- * --no-open skip launching the browser (CI / headless usage)
- * --rebuild docker compose up --build instead of using prebuilt images
- * --tag <tag> override AISOC_TAG (default: latest)
+ * --no-pull skip the `docker compose pull` step (use cached images)
+ * --no-open skip launching the browser (CI / headless usage)
+ * --rebuild docker compose up --build instead of using prebuilt images
+ * --tag <tag> override AISOC_TAG (default: latest)
+ * --budget-ms <number> fail with exit 3 if total elapsed exceeds this many ms
+ * --results-file <p> write per-phase timing JSON to <p> (used by acceptance)
*
* Exit codes:
* 0 = success, browser opened
* 1 = failed to start the stack
* 2 = stack started but data could not be seeded or investigated
+ * 3 = success but exceeded --budget-ms (acceptance regression)
*/
import { execSync, spawnSync } from "node:child_process";
+import { writeFileSync } from "node:fs";
import { createConnection } from "node:net";
import { join } from "node:path";
import { platform } from "node:os";
@@ -42,6 +49,32 @@ const ROOT = join(__dirname, "..");
const COMPOSE_FILE = join(ROOT, "docker-compose.demo.yml");
const STARTED_AT = Date.now();
+// Per-phase timing for the v1.0 ≤5-min acceptance gate. Each step()
+// call closes the previous phase and opens a new one, so the final
+// summary shows where the wall-clock minute went (pull, boot, seed,
+// kickoff). Without this the buyer just sees a single "3m42s"
+// number with no way to diagnose what regressed if a future change
+// pushes us over budget.
+interface Phase {
+ name: string;
+ startedAtMs: number;
+ endedAtMs?: number;
+}
+const phases: Phase[] = [];
+function startPhase(name: string): void {
+ const now = Date.now();
+ if (phases.length > 0) {
+ const prev = phases[phases.length - 1];
+ if (prev.endedAtMs === undefined) prev.endedAtMs = now;
+ }
+ phases.push({ name, startedAtMs: now });
+}
+function closeLastPhase(): void {
+ if (phases.length === 0) return;
+ const prev = phases[phases.length - 1];
+ if (prev.endedAtMs === undefined) prev.endedAtMs = Date.now();
+}
+
const c = {
green: (s: string) => `\x1b[32m${s}\x1b[0m`,
yellow: (s: string) => `\x1b[33m${s}\x1b[0m`,
@@ -56,6 +89,13 @@ interface Flags {
noOpen: boolean;
rebuild: boolean;
tag: string;
+ // Acceptance-gate plumbing. `budgetMs` is the v1.0 ≤5-min target;
+ // when set the script exits 3 (success-but-over-budget) so CI can
+ // distinguish a regression from a hard failure. `resultsFile` writes
+ // a structured JSON timing report that scripts/aisoc-acceptance.ts
+ // consumes for nightly regression tracking.
+ budgetMs: number | null;
+ resultsFile: string | null;
}
function parseFlags(argv: string[]): Flags {
@@ -64,6 +104,8 @@ function parseFlags(argv: string[]): Flags {
noOpen: false,
rebuild: false,
tag: "latest",
+ budgetMs: null,
+ resultsFile: null,
};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
@@ -71,6 +113,13 @@ function parseFlags(argv: string[]): Flags {
else if (a === "--no-open") flags.noOpen = true;
else if (a === "--rebuild") flags.rebuild = true;
else if (a === "--tag") flags.tag = argv[++i] ?? "latest";
+ else if (a === "--budget-ms") {
+ const raw = argv[++i];
+ const n = raw ? Number.parseInt(raw, 10) : Number.NaN;
+ flags.budgetMs = Number.isFinite(n) && n > 0 ? n : null;
+ } else if (a === "--results-file") {
+ flags.resultsFile = argv[++i] ?? null;
+ }
}
return flags;
}
@@ -86,6 +135,16 @@ function log(msg: string) {
}
function step(n: number, total: number, msg: string) {
+ // Every visible step doubles as a phase boundary for the timing
+ // report. The label uses the step msg (without the [n/total] prefix)
+ // so the JSON report reads naturally — "Pulling prebuilt images…"
+ // instead of "[2/7] Pulling…". We strip the parenthesized suffix
+ // some msgs include ("Skipping image pull (--rebuild)") so the
+ // canonical phase names stay stable between runs even when flags
+ // differ — the acceptance harness compares phase durations across
+ // runs and a label drift would break trend comparisons.
+ const cleanLabel = msg.replace(/\s*\([^)]*\)\s*$/, "").trim();
+ startPhase(cleanLabel);
console.log(`\n${c.bold(c.blue(`[${n}/${total}] ${msg}`))} ${c.dim(`(${elapsed()})`)}`);
}
@@ -460,6 +519,109 @@ ${c.bold("Total elapsed:")} ${c.green(elapsed())}
`);
}
+// ---------- Acceptance-gate reporting ----------
+
+function formatMs(ms: number): string {
+ const total = Math.round(ms / 1000);
+ const m = Math.floor(total / 60);
+ const s = total % 60;
+ return m > 0 ? `${m}m${String(s).padStart(2, "0")}s` : `${s}s`;
+}
+
+interface RunReport {
+ // ISO-8601 wall-clock so nightly runs stay sortable in a JSON ledger.
+ finishedAt: string;
+ totalMs: number;
+ totalLabel: string;
+ budgetMs: number | null;
+ withinBudget: boolean | null;
+ showcaseCaseFound: boolean;
+ investigationKickedOff: boolean;
+ flags: {
+ rebuild: boolean;
+ noPull: boolean;
+ noOpen: boolean;
+ tag: string;
+ };
+ phases: Array<{ name: string; durationMs: number; label: string }>;
+}
+
+function buildReport(
+ flags: Flags,
+ showcaseCaseFound: boolean,
+ investigationKickedOff: boolean,
+): RunReport {
+ closeLastPhase();
+ const totalMs = Date.now() - STARTED_AT;
+ return {
+ finishedAt: new Date().toISOString(),
+ totalMs,
+ totalLabel: formatMs(totalMs),
+ budgetMs: flags.budgetMs,
+ withinBudget: flags.budgetMs === null ? null : totalMs <= flags.budgetMs,
+ showcaseCaseFound,
+ investigationKickedOff,
+ flags: {
+ rebuild: flags.rebuild,
+ noPull: flags.noPull,
+ noOpen: flags.noOpen,
+ tag: flags.tag,
+ },
+ phases: phases.map((p) => {
+ const end = p.endedAtMs ?? Date.now();
+ const dur = end - p.startedAtMs;
+ return { name: p.name, durationMs: dur, label: formatMs(dur) };
+ }),
+ };
+}
+
+function printPhaseTable(report: RunReport): void {
+ // ASCII table — readable by humans in CI logs and screenshot-friendly
+ // for "yes, the demo really did boot in 3m20s" buyer-facing benchmarks.
+ // Plain spaces (no Unicode box drawing) to stay terminal-portable.
+ console.log(c.bold("Phase breakdown"));
+ const rows = report.phases.map((p) => [p.name, p.label, `${p.durationMs}ms`]);
+ const headers = ["Phase", "Duration", "ms"];
+ const all = [headers, ...rows];
+ const widths = headers.map((_, i) =>
+ Math.max(...all.map((row) => row[i].length)),
+ );
+ const fmt = (row: string[]) =>
+ " " + row.map((cell, i) => cell.padEnd(widths[i])).join(" ");
+ console.log(c.dim(fmt(headers)));
+ console.log(c.dim(" " + widths.map((w) => "-".repeat(w)).join(" ")));
+ for (const row of rows) console.log(fmt(row));
+ console.log(
+ `\n ${c.bold("Total:")} ${c.green(report.totalLabel)} (${report.totalMs}ms)`,
+ );
+ if (report.budgetMs !== null) {
+ const budgetLabel = formatMs(report.budgetMs);
+ if (report.withinBudget) {
+ console.log(
+ ` ${c.bold("Budget:")} ${c.green(`PASS — under ${budgetLabel}`)} ` +
+ c.dim(`(${report.budgetMs - report.totalMs}ms headroom)`),
+ );
+ } else {
+ console.log(
+ ` ${c.bold("Budget:")} ${c.red(`FAIL — exceeded ${budgetLabel} by ${formatMs(report.totalMs - report.budgetMs)}`)} ` +
+ c.dim("(WS-A acceptance regression)"),
+ );
+ }
+ }
+}
+
+function emitReport(flags: Flags, report: RunReport): void {
+ if (!flags.resultsFile) return;
+ try {
+ writeFileSync(flags.resultsFile, JSON.stringify(report, null, 2) + "\n");
+ console.log(c.dim(` results JSON written to ${flags.resultsFile}`));
+ } catch (e: any) {
+ console.error(
+ c.yellow(` failed to write results to ${flags.resultsFile}: ${e?.message ?? e}`),
+ );
+ }
+}
+
// ---------- Main ----------
async function main() {
@@ -467,7 +629,10 @@ async function main() {
console.log(
c.bold("AiSOC Demo") +
- c.dim(` — tag=${flags.tag}${flags.rebuild ? " · rebuild" : ""}`),
+ c.dim(
+ ` — tag=${flags.tag}${flags.rebuild ? " · rebuild" : ""}` +
+ (flags.budgetMs ? ` · budget=${formatMs(flags.budgetMs)}` : ""),
+ ),
);
if (!checkDocker()) process.exit(1);
@@ -481,10 +646,31 @@ async function main() {
console.error(c.yellow("seed step had issues; continuing"));
}
const seededCase = await findSeededCase();
+ // We track these for the run report so the acceptance harness can
+ // distinguish "stack came up but no case showed" (a seed regression)
+ // from "everything booted but the LLM call failed" (a flaky live LLM).
+ let investigationKickedOff = false;
if (seededCase) {
- await kickoffInvestigation(seededCase.id);
+ investigationKickedOff = await kickoffInvestigation(seededCase.id);
}
await openInBrowser(seededCase, flags);
+
+ // Reporting runs after openInBrowser so the cheerful "demo is up"
+ // banner stays at the top of the user's eyeline. The phase table
+ // and budget verdict come immediately after — for a `pnpm aisoc:demo`
+ // user without --budget-ms it's just a nice-to-have timing breakdown;
+ // for the acceptance harness it's the gate.
+ console.log("");
+ const report = buildReport(flags, seededCase !== null, investigationKickedOff);
+ printPhaseTable(report);
+ emitReport(flags, report);
+
+ if (flags.budgetMs !== null && !report.withinBudget) {
+ // Exit 3 (distinct from 1=hard-fail and 2=crash) so CI can label
+ // the run "regression" rather than "broken". The stack is left
+ // running so the human can poke at the slow step.
+ process.exit(3);
+ }
process.exit(0);
}
diff --git a/services/api/app/middleware/demo_mode.py b/services/api/app/middleware/demo_mode.py
index 24509dbb7..0e6803e47 100644
--- a/services/api/app/middleware/demo_mode.py
+++ b/services/api/app/middleware/demo_mode.py
@@ -49,8 +49,10 @@ _ALWAYS_ALLOWED_PREFIXES: tuple[str, ...] = (
# In demo mode these *write* endpoints still work — needed for the canned
# "click → see investigation" experience to function.
_DEMO_WRITE_ALLOWLIST: tuple[re.Pattern[str], ...] = (
- # The seed pre-warms a run, but visitors can still kick off their own.
- re.compile(r"^/api/v1/cases/INC-001/investigate$"),
+ # The seed pre-warms a run on INC-RT-001 (the canonical LockBit 3.0
+ # showcase) and seeds the stock catalogue INC-001…INC-014. Visitors can
+ # kick off investigations against any of them — match the seeded ID shape.
+ re.compile(r"^/api/v1/cases/INC(?:-RT)?-\d{3}/investigate$"),
re.compile(r"^/api/v1/investigations/[^/]+/cancel$"),
# Acknowledgement is local-state-only on the visitor's view.
re.compile(r"^/api/v1/alerts/[^/]+/ack$"),
diff --git a/services/api/app/scripts/demo_seed.py b/services/api/app/scripts/demo_seed.py
index d9164af57..2ed063c1d 100644
--- a/services/api/app/scripts/demo_seed.py
+++ b/services/api/app/scripts/demo_seed.py
@@ -1,9 +1,9 @@
"""demo_seed — Reset and warm up the hosted demo at tryaisoc.com.
-This is the canonical entrypoint for the hosted-demo refresh job. It runs
-inside the api image (so it gets DATABASE_URL via Fly Postgres attach,
-REDIS_URL via Upstash attach, and access to the rest of the API package),
-and is invoked one of three ways:
+This is the kickoff wrapper around the canonical ``seed_demo`` entrypoint.
+It runs inside the api image (so it gets DATABASE_URL via Fly Postgres
+attach, REDIS_URL via Upstash attach, and access to the rest of the API
+package), and is invoked one of three ways:
* **Post-deploy** — `infra/fly/fly-demo-deploy.sh` runs it via
`flyctl ssh console -a aisoc-demo-api -C "python -m app.scripts.demo_seed
@@ -17,12 +17,21 @@ and is invoked one of three ways:
shim, which just re-execs this module.)
Why three responsibilities in one entrypoint?
-1. Drop demo-tenant data so each visitor sees the same canonical INC-001.
+1. Drop demo-tenant data so each visitor sees the same canonical
+ ``INC-RT-001`` LockBit 3.0 in-flight ransomware investigation.
2. Re-seed canonical demo data via the existing ``seed_demo`` module —
same data self-hosters get with ``pnpm seed:demo``.
-3. Pre-warm an investigation so the deeplink ``/cases/INC-001?tab=ledger``
- already has agent events streaming when the browser arrives. This is
- the keystone of the sub-60s time-to-first-investigation target.
+3. Pre-warm an investigation so the deeplink
+ ``/cases/INC-RT-001?tab=ledger`` already has agent events streaming
+ when the browser arrives. This is the keystone of the sub-5min
+ clone-to-investigation target.
+
+For most platforms (Render, Railway, Coolify, docker-compose), the
+release/preDeploy command runs ``python -m app.scripts.seed_demo``
+directly — no kickoff is needed because the seed already populates the
+in-flight investigation artifacts. This wrapper is only required when
+you want a *live agent run* streaming on top of seeded state, which is
+the Fly hosted-demo experience.
Idempotent. Safe to re-run. ``--dry-run`` prints actions without touching
any state.
@@ -53,7 +62,7 @@ log = logging.getLogger("demo-seed")
CORE_API_URL = os.getenv("CORE_API_URL", "http://localhost:8000")
AGENTS_API_URL = os.getenv("AGENTS_API_URL", "http://aisoc-demo-agents.internal:8084")
DEMO_TENANT = os.getenv("AISOC_DEMO_TENANT", "demo")
-DEMO_CASE_ID = os.getenv("AISOC_DEMO_CASE_ID", "INC-001")
+DEMO_CASE_ID = os.getenv("AISOC_DEMO_CASE_ID", "INC-RT-001")
HTTP_TIMEOUT = float(os.getenv("AISOC_DEMO_HTTP_TIMEOUT", "30"))
@@ -112,7 +121,7 @@ def _run_local_seeder() -> None:
async def _kickoff_investigation(client: httpx.AsyncClient) -> str | None:
- """Start an agent run against ``INC-001`` so the demo lands hot.
+ """Start an agent run against ``INC-RT-001`` so the demo lands hot.
Returns the run_id on success, or None if the agent declined (e.g.,
no model key + deterministic mode disabled). We never fail the deploy
@@ -198,7 +207,7 @@ def main() -> int:
p.add_argument(
"--kickoff-investigation",
action="store_true",
- help="Start an agent run against INC-001 so the deeplink lands hot.",
+ help="Start an agent run against INC-RT-001 so the deeplink lands hot.",
)
p.add_argument(
"--wait-for-api",
diff --git a/services/api/app/scripts/seed_demo.py b/services/api/app/scripts/seed_demo.py
index 3638ff8ab..d5f47a36f 100644
--- a/services/api/app/scripts/seed_demo.py
+++ b/services/api/app/scripts/seed_demo.py
@@ -1273,8 +1273,9 @@ def _make_case(tenant_id: uuid.UUID, idx: int, when: datetime, alert_ids: list[u
weights=[30, 35, 10, 15, 10],
)[0]
techniques = _pick_techniques(2)
- # Human-readable identifier — keep in sync with the demo deeplinks the
- # marketing site and product walkthroughs use (e.g. /cases/INC-001).
+ # Human-readable identifier for the stock catalogue (INC-001, INC-002, …).
+ # The hot showcase deeplink (/cases/INC-RT-001?tab=ledger) targets the
+ # in-flight LockBit 3.0 ransomware investigation seeded separately above.
return Case(
tenant_id=tenant_id,
case_number=f"INC-{idx + 1:03d}",
diff --git a/services/api/migrations/028_aisoc_cases_case_number.sql b/services/api/migrations/028_aisoc_cases_case_number.sql
index f16993d11..9e7b64238 100644
--- a/services/api/migrations/028_aisoc_cases_case_number.sql
+++ b/services/api/migrations/028_aisoc_cases_case_number.sql
@@ -1,11 +1,12 @@
-- Migration 028: Human-readable case identifiers on aisoc_cases
--
--- The web console (and a number of demo deeplinks like /cases/INC-001) needs to
--- look up a case by a stable, short, human-readable identifier — not a UUID.
--- The ORM `cases` table already has a `case_number` column (e.g. CASE-1042),
--- but the canonical demo table `aisoc_cases` does not. Adding it here lets
--- the API resolve `/api/v1/cases/INC-001` against `case_number` while still
--- accepting raw UUIDs, without breaking any existing rows.
+-- The web console (and demo deeplinks like /cases/INC-RT-001 or /cases/INC-007)
+-- need to look up a case by a stable, short, human-readable identifier — not a
+-- UUID. The ORM `cases` table already has a `case_number` column (e.g.
+-- CASE-1042), but the canonical demo table `aisoc_cases` does not. Adding it
+-- here lets the API resolve `/api/v1/cases/INC-RT-001` (or any `INC-NNN` from
+-- the seeded catalogue) against `case_number` while still accepting raw UUIDs,
+-- without breaking any existing rows.
ALTER TABLE aisoc_cases
ADD COLUMN IF NOT EXISTS case_number TEXT;
diff --git a/services/api/tests/test_demo_mode.py b/services/api/tests/test_demo_mode.py
index 7542f306f..8e1d99f16 100644
--- a/services/api/tests/test_demo_mode.py
+++ b/services/api/tests/test_demo_mode.py
@@ -5,9 +5,10 @@ These verify the gate behaves correctly in both modes:
- When `AISOC_DEMO_MODE=False`, the middleware is transparent — every request
flows through and responses do **not** carry demo headers.
- When `AISOC_DEMO_MODE=True`, GET requests succeed and pick up the banner
- headers, allowlisted writes (kickoff against `INC-001`, alert ack) succeed,
- and arbitrary mutating writes return 403 with the `demo_mode_read_only`
- error code.
+ headers, allowlisted writes (kickoff against the showcase `INC-RT-001`
+ ransomware case or any stock `INC-NNN` catalogue case, plus alert ack)
+ succeed, and arbitrary mutating writes return 403 with the
+ `demo_mode_read_only` error code.
The middleware is the *only* thing under test; we mount it on a stub Starlette
app so the test doesn't pull in the real DB / auth stack.
@@ -49,9 +50,9 @@ def app(monkeypatch: pytest.MonkeyPatch) -> FastAPI:
def delete_case(case_id: str) -> dict[str, Any]:
return {"deleted": case_id}
- @app.post("/api/v1/cases/INC-001/investigate")
- def investigate() -> dict[str, Any]:
- return {"run_id": "demo-run-123"}
+ @app.post("/api/v1/cases/{case_number}/investigate")
+ def investigate(case_number: str) -> dict[str, Any]:
+ return {"run_id": "demo-run-123", "case_number": case_number}
@app.post("/api/v1/alerts/{alert_id}/ack")
def ack(alert_id: str) -> dict[str, Any]:
@@ -118,14 +119,42 @@ def test_arbitrary_delete_is_blocked_with_403(app: FastAPI) -> None:
def test_canonical_investigation_kickoff_is_allowed(app: FastAPI) -> None:
- """The canned demo flow must work end-to-end."""
+ """The canned demo flow must work end-to-end against the showcase case.
+
+ The README "Try Demo" CTA deeplinks to ``/cases/INC-RT-001?tab=ledger`` —
+ the in-flight LockBit 3.0 ransomware investigation — so kicking off a
+ fresh agent run there must succeed under the demo-mode gate.
+ """
client = TestClient(app)
- r = client.post("/api/v1/cases/INC-001/investigate")
+ r = client.post("/api/v1/cases/INC-RT-001/investigate")
assert r.status_code == 200
- assert r.json() == {"run_id": "demo-run-123"}
+ body = r.json()
+ assert body["run_id"] == "demo-run-123"
+ assert body["case_number"] == "INC-RT-001"
assert r.headers["X-AiSOC-Demo"] == "true"
+def test_stock_catalogue_investigation_kickoff_is_allowed(app: FastAPI) -> None:
+ """Stock catalogue cases (INC-001 … INC-014) must also be investigatable.
+
+ Visitors who navigate the case list will click into other seeded
+ incidents; the demo-mode gate must let them kick off agent runs there
+ without a 403.
+ """
+ client = TestClient(app)
+ r = client.post("/api/v1/cases/INC-007/investigate")
+ assert r.status_code == 200
+ assert r.json()["case_number"] == "INC-007"
+
+
+def test_unseeded_case_kickoff_is_blocked(app: FastAPI) -> None:
+ """A made-up case ID must NOT bypass the gate — only seeded shapes do."""
+ client = TestClient(app)
+ r = client.post("/api/v1/cases/EVIL-CASE/investigate")
+ assert r.status_code == 403
+ assert r.json()["error"] == "demo_mode_read_only"
+
+
def test_alert_acknowledge_is_allowed(app: FastAPI) -> None:
client = TestClient(app)
r = client.post("/api/v1/alerts/abc-123/ack")