diff --git a/docs/2026-09-26-defect-closure/handoffs/ACCEPTANCE-RUN-5.md b/docs/2026-09-26-defect-closure/handoffs/ACCEPTANCE-RUN-5.md
new file mode 100644
index 0000000..63df4cb
--- /dev/null
+++ b/docs/2026-09-26-defect-closure/handoffs/ACCEPTANCE-RUN-5.md
@@ -0,0 +1,58 @@
+# Acceptance Run 5 — from an empty repo to a type-checking, building app
+
+**Date:** 2026-09-29 · branch `hardening/production`
+**Command:**
+
+```powershell
+$env:ACC_AGENT_MODEL="opencode-go/gpt-5.6-luna"; $env:ACC_POC_TIMEOUT="300"
+cargo test -p sourceforge --lib -- --ignored --nocapture test_real_poc_from_empty
+```
+
+New test `real_pipeline_test::test_real_poc_from_empty`: the project starts as an
+**empty git repo** (a README and a remote, nothing else) and runs the production
+path with `install_deps: true` (the hard gate) and `deliver: true`.
+
+## Result — the delivery chain works, the last check fails closed
+
+```
+scaffold done scaffolded 15 files npm install + prisma generate ok
+tsc Pass (real typecheck)
+build Pass (real `next build`)
+output Pass (.next/BUILD_ID)
+delivery merged: [1-1.1] conflicts: [] app/about/page.tsx in base project: true
+verification passed=false → deploy skipped (fail-closed)
+only failing check: E2E runtime test — "Server failed to boot within 60 seconds"
+```
+
+So: **empty repo → scaffolded app → real install → real typecheck → real build →
+agent's feature merged into the project**. The run correctly refuses to deploy
+while one check fails.
+
+## Six defects this run found and fixed
+
+| # | Defect | Fix |
+|---|---|---|
+| 1 | **Scaffold emitted invalid TypeScript**: `{{`/`}}` were written literally in three non-`format!` strings (`app/api/health/route.ts`, `lib/prisma.ts`, `lib/supabase.ts`) — every scaffolded app failed `tsc` and `next build` | single braces; regression test scans **every** file in `files_created` for doubled braces |
+| 2 | **Prisma schema had no models** → `prisma generate` exits 1 → `npm install` failed | scaffold ships a `User` model; `postinstall: prisma generate`; test asserts a model exists |
+| 3 | **Scaffold lacked `typecheck`/`test` scripts and the env vars the checks require** | added both scripts, a real `node:test` file, and JWT_SECRET/PORT/CLIENT_URL to `.env.example` |
+| 4 | **`npm`/`npx` invoked directly** — same `.cmd`-shim bug as the agent adapter, so the build/typecheck checks always reported "program not found" on Windows | `npm_command()` routes through `cmd /C` |
+| 5 | **Build artifact check ran before the build** → could never pass on a fresh project | build runs first, then artifact checks; `.next/BUILD_ID` accepted for Next.js |
+| 6 | **Undiagnosable failures**: `tsc` counted errors on the *wrong stream* (reported "0 errors" while failing), build failures discarded their output, server output went to an undrained pipe | diagnostics capture the real errors (this is what exposed defects 1 and 2); server output goes to a log file with its tail in the failure message |
+
+Plus: `install_project_dependencies` bootstraps `.env` from `.env.example` (Prisma's
+postinstall resolves the datasource URL during install).
+
+## Still open
+
+- **`E2E runtime test` fails**: the dev server did not answer within 60 s. It is no
+ longer a mystery box — the boot failure now carries the server log tail, so the
+ next run will say why (Next dev cold start, port, missing env…). Until then the
+ run stays `verification_failed` and deploy stays skipped — correct behaviour.
+- The runtime check's six auth-flow probes only apply to apps with auth routes;
+ apps without them are now judged on serving traffic (a template contract was
+ being imposed on every app).
+- GitHub delivery (private repo, issues, PRs) — unchanged, see `EXTERNAL-VERIFICATION.md`.
+
+## Gates
+
+Rust **218 lib + 42 integration** (2 real-agent tests `ignored`), Web 343, `tsc`/`lint` clean.
diff --git a/src-tauri/src/arch_engine.rs b/src-tauri/src/arch_engine.rs
index f316ae2..a550400 100644
--- a/src-tauri/src/arch_engine.rs
+++ b/src-tauri/src/arch_engine.rs
@@ -70,7 +70,7 @@ fn w(base: &Path, rel: &str, content: &str, r: &mut ScaffoldReport) -> Result<()
fn scaffold_nextjs(base: &Path, name: &str, stack: &StackPreset, r: &mut ScaffoldReport) -> Result<(), String> {
let pkg = serde_json::json!({
"name": name, "version": "0.1.0", "private": true,
- "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" },
+ "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "typecheck": "tsc --noEmit", "test": "node --test tests", "postinstall": "prisma generate" },
"dependencies": { "next": "^14.2.0", "react": "^18.3.0", "react-dom": "^18.3.0", "@prisma/client": "^5.15.0", "@supabase/supabase-js": "^2.43.0", "zod": "^3.23.0" },
"devDependencies": { "typescript": "^5.5.0", "@types/node": "^20.14.0", "@types/react": "^18.3.0", "@types/react-dom": "^18.3.0", "prisma": "^5.15.0", "tailwindcss": "^3.4.0", "postcss": "^8.4.0", "autoprefixer": "^10.4.0" }
});
@@ -81,16 +81,26 @@ fn scaffold_nextjs(base: &Path, name: &str, stack: &StackPreset, r: &mut Scaffol
w(base, "postcss.config.js", "module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };\n", r)?;
let prov = if stack.id.contains("supabase") { "postgresql" } else { "postgresql" };
- w(base, "prisma/schema.prisma", &format!("generator client {{\n provider = \"prisma-client-js\"\n}}\n\ndatasource db {{\n provider = \"{prov}\"\n url = env(\"DATABASE_URL\")\n}}\n"), r)?;
+ // A model is required: `prisma generate` exits 1 on a model-less schema
+ // ("You don't have any models defined"), which broke `npm install`
+ // (postinstall) and therefore the whole build for every scaffolded app.
+ w(base, "prisma/schema.prisma", &format!("generator client {{\n provider = \"prisma-client-js\"\n}}\n\ndatasource db {{\n provider = \"{prov}\"\n url = env(\"DATABASE_URL\")\n}}\n\nmodel User {{\n id String @id @default(cuid())\n email String @unique\n name String?\n createdAt DateTime @default(now())\n}}\n"), r)?;
w(base, "app/layout.tsx", &format!("import type {{ Metadata }} from 'next';\nimport './globals.css';\nexport const metadata: Metadata = {{ title: '{name}' }};\nexport default function RootLayout({{ children }}: {{ children: React.ReactNode }}) {{\n return (
{{children}});\n}}\n"), r)?;
w(base, "app/globals.css", "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n", r)?;
w(base, "app/page.tsx", &format!("export default function Home() {{\n return (Welcome to {name}
);\n}}\n"), r)?;
- w(base, "app/api/health/route.ts", "import {{ NextResponse }} from 'next/server';\nexport async function GET() {{\n return NextResponse.json({{ status: 'ok', timestamp: new Date().toISOString() }});\n}}\n", r)?;
- w(base, "lib/prisma.ts", "import {{ PrismaClient }} from '@prisma/client';\nconst g = globalThis as unknown as {{ prisma: PrismaClient }};\nexport const prisma = g.prisma || new PrismaClient();\nif (process.env.NODE_ENV !== 'production') g.prisma = prisma;\n", r)?;
- w(base, "lib/supabase.ts", "import {{ createClient }} from '@supabase/supabase-js';\nexport const supabase = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!);\n", r)?;
- w(base, ".env.example", "# Database\nDATABASE_URL=\"postgresql://postgres:[PASSWORD]@db.[REF].supabase.co:5432/postgres\"\n# Supabase\nNEXT_PUBLIC_SUPABASE_URL=\"https://[REF].supabase.co\"\nNEXT_PUBLIC_SUPABASE_ANON_KEY=\"your-anon-key\"\n", r)?;
+ w(base, "app/api/health/route.ts", "import { NextResponse } from 'next/server';\nexport async function GET() {\n return NextResponse.json({ status: 'ok', timestamp: new Date().toISOString() });\n}\n", r)?;
+ w(base, "lib/prisma.ts", "import { PrismaClient } from '@prisma/client';\nconst g = globalThis as unknown as { prisma: PrismaClient };\nexport const prisma = g.prisma || new PrismaClient();\nif (process.env.NODE_ENV !== 'production') g.prisma = prisma;\n", r)?;
+ w(base, "lib/supabase.ts", "import { createClient } from '@supabase/supabase-js';\nexport const supabase = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!);\n", r)?;
+ w(base, ".env.example", "# App\nJWT_SECRET=\"change-me\"\nPORT=3000\nCLIENT_URL=\"http://localhost:3000\"\n# Database\nDATABASE_URL=\"postgresql://postgres:[PASSWORD]@db.[REF].supabase.co:5432/postgres\"\n# Supabase\nNEXT_PUBLIC_SUPABASE_URL=\"https://[REF].supabase.co\"\nNEXT_PUBLIC_SUPABASE_ANON_KEY=\"your-anon-key\"\n", r)?;
w(base, ".gitignore", "node_modules/\n.next/\ndist/\n.env\n.env.local\n*.db\n", r)?;
+ w(
+ base,
+ "tests/scaffold.test.mjs",
+ "import test from 'node:test';\nimport assert from 'node:assert/strict';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { fileURLToPath } from 'node:url';\n\nconst read = (rel) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf8');\n\ntest('scaffold defines a build script', () => {\n const pkg = JSON.parse(read('../package.json'));\n assert.ok(pkg.scripts.build, 'package.json must define a build script');\n});\n\ntest('scaffold ships the health route', () => {\n assert.ok(existsSync(fileURLToPath(new URL('../app/api/health/route.ts', import.meta.url))));\n});\n",
+ r,
+ )?;
+
r.next_steps.push("4. Run: npx prisma generate".into());
r.next_steps.push("5. Set DATABASE_URL + Supabase keys in .env".into());
Ok(())
@@ -139,6 +149,37 @@ mod tests {
assert!(Path::new(&p).join("prisma/schema.prisma").exists());
}
+ #[test]
+ fn test_scaffold_output_is_buildable_typescript() {
+ // Two defects found by the from-empty acceptance run, both of which made
+ // every scaffolded Next.js app fail `tsc` and `next build`:
+ // - `{{`/`}}` written literally into plain (non-`format!`) strings;
+ // - a Prisma schema with no models, so `prisma generate` exits 1.
+ let (_d, p) = tp();
+ let report = scaffold_project("nextjs-prisma-vercel", &p, "na").unwrap();
+ assert!(!report.files_created.is_empty());
+ for rel in &report.files_created {
+ if !rel.ends_with(".ts") && !rel.ends_with(".tsx") && !rel.ends_with(".mjs") {
+ continue;
+ }
+ let content = std::fs::read_to_string(Path::new(&p).join(rel)).unwrap();
+ assert!(!content.contains("{{"), "{rel} contains doubled braces");
+ assert!(!content.contains("}}"), "{rel} contains doubled braces");
+ }
+
+ let schema =
+ std::fs::read_to_string(Path::new(&p).join("prisma/schema.prisma")).unwrap();
+ assert!(
+ schema.contains("model "),
+ "prisma generate needs at least one model"
+ );
+
+ let pkg = std::fs::read_to_string(Path::new(&p).join("package.json")).unwrap();
+ for script in ["typecheck", "test", "postinstall"] {
+ assert!(pkg.contains(&format!("\"{script}\"")), "package.json must define {script}");
+ }
+ }
+
#[test]
fn test_nextjs_prisma_uses_postgresql() {
let (_d, p) = tp();
diff --git a/src-tauri/src/pipeline.rs b/src-tauri/src/pipeline.rs
index b16fb84..3135d98 100644
--- a/src-tauri/src/pipeline.rs
+++ b/src-tauri/src/pipeline.rs
@@ -1037,6 +1037,18 @@ fn install_project_dependencies(project_path: &str) -> Result {
vec!["install", "--no-audit", "--no-fund"]
};
+ // Bootstrap `.env` from `.env.example` when missing: toolchains run during
+ // `npm install` (e.g. Prisma's `postinstall: prisma generate`) resolve the
+ // datasource URL and fail hard without it. Never clobber a real `.env`.
+ let mut bootstrapped = false;
+ let env_example = base.join(".env.example");
+ let env_file = base.join(".env");
+ if !env_file.exists() && env_example.exists() {
+ std::fs::copy(&env_example, &env_file)
+ .map_err(|e| format!("cannot bootstrap .env from .env.example: {e}"))?;
+ bootstrapped = true;
+ }
+
let mut cmd = if cfg!(windows) {
let mut c = std::process::Command::new("cmd");
c.arg("/C").arg("npm");
@@ -1046,8 +1058,13 @@ fn install_project_dependencies(project_path: &str) -> Result {
};
cmd.args(&args).current_dir(base);
- run_with_timeout(cmd, DEPENDENCY_INSTALL_TIMEOUT_SECS)
- .map(|_| format!("dependencies installed (npm {})", args.join(" ")))
+ run_with_timeout(cmd, DEPENDENCY_INSTALL_TIMEOUT_SECS).map(|_| {
+ format!(
+ "dependencies installed (npm {}{})",
+ args.join(" "),
+ if bootstrapped { ", .env bootstrapped" } else { "" }
+ )
+ })
}
/// Run a command with a wall-clock timeout, sending its output to a temp log so
diff --git a/src-tauri/src/real_pipeline_test.rs b/src-tauri/src/real_pipeline_test.rs
index 66366e9..3b6a758 100644
--- a/src-tauri/src/real_pipeline_test.rs
+++ b/src-tauri/src/real_pipeline_test.rs
@@ -322,7 +322,7 @@ fn test_real_pipeline_end_to_end() {
// Preserve artifacts for inspection: the worktrees live inside the fixture
// TempDir, which is deleted when it drops.
- let artifacts = Path::new(env!("CARGO_MANIFEST_DIR")).join("target/real-run-artifacts");
+ let artifacts = std::env::temp_dir().join("sourceforge-artifacts").join("real");
let _ = std::fs::remove_dir_all(&artifacts);
if copy_dir_all(project.path(), &artifacts).is_ok() {
println!("artifacts preserved at {}", artifacts.display());
@@ -370,3 +370,218 @@ fn test_real_pipeline_end_to_end() {
"farewell.ts must be in the base project"
);
}
+
+/// An empty repo (only a README + a remote) so the scaffold stage has to build
+/// the app from nothing.
+fn make_empty_repo() -> tempfile::TempDir {
+ let dir = tempfile::TempDir::new().unwrap();
+ let base = dir.path();
+ std::fs::write(
+ base.join("README.md"),
+ "# From-Empty POC\n\n## Setup\n\nInstall dependencies with `npm install`, then run `npm run dev`.\n\
+ Build with `npm run build` and start with `npm start`.\n\n\
+ ## Environment Variables\n\nCopy `.env.example` to `.env` and fill in every required value.\n\
+ Required variables: JWT_SECRET, DATABASE_URL, PORT, CLIENT_URL.\n\n\
+ ## Architecture\n\nThis project was generated by the SourceForge pipeline from an empty \
+ repository. The scaffold stage creates the application skeleton, the agent wave implements \
+ the requested steps in isolated worktrees, delivery merges their branches, and verification \
+ installs the toolchain and runs the real build, typecheck and runtime checks before deploy.\n\n\
+ ## Testing\n\nRun `npm test` for unit tests and `npm run typecheck` for static analysis.\n",
+ )
+ .unwrap();
+ let git = |args: &[&str]| {
+ let out = std::process::Command::new("git")
+ .args(args)
+ .current_dir(base)
+ .output()
+ .expect("git");
+ assert!(
+ out.status.success(),
+ "git {:?} failed: {}",
+ args,
+ String::from_utf8_lossy(&out.stderr)
+ );
+ };
+ git(&["init", "-q", "-b", "main"]);
+ git(&["config", "user.email", "pipeline@test.local"]);
+ git(&["config", "user.name", "Pipeline Test"]);
+ git(&["add", "-A"]);
+ git(&["commit", "-q", "-m", "empty project"]);
+ git(&[
+ "remote",
+ "add",
+ "origin",
+ "https://example.com/from-empty-poc.git",
+ ]);
+ dir
+}
+
+/// One tiny step so the app still builds: adds a page to the scaffolded Next.js
+/// app.
+fn make_poc_spec(dir: &Path) -> String {
+ let path = dir.join("poc-plan.md");
+ std::fs::write(
+ &path,
+ "# Plan\n\n## Phase 1: Feature\n\n\
+ ### Step 1.1: Add an About page\n\
+ **Wave:** A \u{00b7} **Depends on:** \u{2014}\n\
+ Create `app/about/page.tsx` in this repository: a Next.js server component that \
+ default-exports a component rendering an `` with the text `About`. Dependency-free.\n",
+ )
+ .unwrap();
+ path.to_string_lossy().to_string()
+}
+
+/// From-empty milestone: does the pipeline turn an empty repo into a project
+/// whose toolchain is really installed and whose build/test checks really run?
+///
+/// `install_deps: true` enables the hard gate (`VerifyMode::RequireBuild`), so a
+/// build that cannot run fails the run instead of being skipped.
+///
+/// Run: cargo test -p sourceforge --lib -- --ignored --nocapture test_real_poc_from_empty
+#[test]
+#[ignore = "spawns a real agent CLI and runs npm install; run explicitly with --ignored"]
+fn test_real_poc_from_empty() {
+ let timeout_secs: u64 = std::env::var("ACC_POC_TIMEOUT")
+ .ok()
+ .and_then(|v| v.parse().ok())
+ .unwrap_or(420);
+
+ let project = make_empty_repo();
+ let spec_dir = tempfile::TempDir::new().unwrap();
+ let spec = make_poc_spec(spec_dir.path());
+
+ let db_dir = tempfile::TempDir::new().unwrap();
+ let conn: Connection = crate::db::init_db_path(&db_dir.path().join("poc.db")).expect("init db");
+ let db = Mutex::new(conn);
+
+ let run = {
+ let conn = db.lock().unwrap();
+ crate::pipeline_store::create_run(
+ &conn,
+ None,
+ &spec,
+ &project.path().to_string_lossy(),
+ Some(STACK),
+ )
+ .unwrap()
+ };
+
+ let opts = PipelineOptions {
+ run_id: run.id.clone(),
+ project_id: None,
+ spec_path: spec.clone(),
+ project_path: project.path().to_string_lossy().to_string(),
+ stack_id: Some(STACK.to_string()),
+ agent_command: "opencode".to_string(),
+ base_branch: "main".to_string(),
+ allow_deploy_on_failed_verification: false,
+ generate_dockerfile: true,
+ agent_timeout_secs: timeout_secs,
+ };
+
+ let registry = crate::agent_adapters::AdapterRegistry::new();
+ let wave_runner = AdapterWaveRunner {
+ registry,
+ agent_command: "opencode".to_string(),
+ base_branch: "main".to_string(),
+ deadline_secs: None,
+ cost_cap_usd: None,
+ };
+ let deployer = MockDeployer {
+ url: "https://mock-vercel.example.app".to_string(),
+ fail: false,
+ };
+ let llm = crate::compounder_llm::LlmProvider::Static("[]".to_string());
+
+ let adapters = PipelineAdapters {
+ deployer: &deployer,
+ wave_runner: &wave_runner,
+ event_sink: &NoopEventSink,
+ llm: &llm,
+ cli_status: Some(all_clis_installed()),
+ // The whole point: real dependencies in, real build/test gate on.
+ install_deps: true,
+ deliver: true,
+ run_compounder: false,
+ };
+
+ let report = crate::pipeline::run_pipeline(&db, &opts, &adapters).expect("pipeline ran");
+
+ println!("\n===== FROM-EMPTY POC REPORT =====");
+ println!("status: {}", report.status);
+ println!("error : {:?}", report.error);
+ for stage in &report.stages {
+ println!(
+ " stage {:<20} {:<14} {}",
+ stage.name, stage.status, stage.message
+ );
+ }
+ let scaffolded = project.path().join("package.json").exists();
+ let installed = project.path().join("node_modules").exists();
+ println!(
+ "scaffolded={scaffolded} installed={installed} next_build_dir={}",
+ project.path().join(".next").exists()
+ );
+ if let Some(wave) = &report.wave {
+ for agent in &wave.agents {
+ println!(
+ " agent {:<6} status={:<8} cost_usd={:.4}",
+ agent.agent_ref, agent.status, agent.cost_usd
+ );
+ }
+ }
+ println!("merges: {}", report.artifacts["merges"]);
+ println!(
+ "delivered app/about/page.tsx in base project: {}",
+ project.path().join("app/about/page.tsx").exists()
+ );
+ if let Some(verification) = &report.verification {
+ println!("verification passed={}", verification["passed"]);
+ if let Some(checks) = verification["checks"].as_array() {
+ for check in checks {
+ println!(
+ " check {:<42} {}",
+ check["name"].as_str().unwrap_or("?"),
+ check["status"]
+ );
+ }
+ }
+ }
+ let artifacts = std::env::temp_dir().join("sourceforge-artifacts").join("poc");
+ let _ = std::fs::remove_dir_all(&artifacts);
+ if copy_dir_all(project.path(), &artifacts).is_ok() {
+ println!("artifacts preserved at {}", artifacts.display());
+ }
+ println!("=================================\n");
+
+ // 1. The scaffold produced a project from nothing.
+ assert!(scaffolded, "the scaffold stage must create package.json");
+ // 2. The dependencies were really installed (not skipped).
+ assert!(
+ installed,
+ "install_deps=true must install node_modules; status={} error={:?}",
+ report.status, report.error
+ );
+ // 3. The build gate really executed: with node_modules present the build
+ // check can no longer Skip (that is the milestone claim).
+ let verification = report.verification.as_ref().expect("verification ran");
+ let build_check = verification["checks"]
+ .as_array()
+ .expect("checks")
+ .iter()
+ .find(|check| check["name"] == "npm run build passes")
+ .cloned()
+ .expect("build check present");
+ assert!(
+ build_check["status"] != serde_json::json!("Skip"),
+ "the real build gate must run once dependencies are installed: {build_check}"
+ );
+ // 4. Agent work was delivered, not stranded.
+ let merges = &report.artifacts["merges"];
+ assert_eq!(
+ merges["conflicts"].as_array().map(Vec::len),
+ Some(0),
+ "no merge conflicts: {merges}"
+ );
+}
diff --git a/src-tauri/src/verification.rs b/src-tauri/src/verification.rs
index eafc9ec..25247dd 100644
--- a/src-tauri/src/verification.rs
+++ b/src-tauri/src/verification.rs
@@ -286,10 +286,12 @@ fn verify_project_lenient(base: &Path) -> VerificationReport {
check_package_scripts(base, &mut report);
// ── 2. Build output ──────────────────────────────────────────
- check_build_output(base, &mut report);
- check_index_html(base, &mut report);
+ // Run the build first: the artifact checks below inspect its output, so
+ // checking them beforehand can never pass on a fresh project.
check_typescript(base, &mut report);
check_npm_build(base, &mut report);
+ check_build_output(base, &mut report);
+ check_index_html(base, &mut report);
// ── 3. Deployment config ─────────────────────────────────────
check_spa_config(base, &mut report);
@@ -471,8 +473,10 @@ fn check_package_scripts(base: &Path, report: &mut VerificationReport) {
fn check_build_output(base: &Path, report: &mut VerificationReport) {
let has_dist = base.join("dist").is_dir();
let has_build = base.join("build").is_dir();
- if has_dist || has_build {
- let dir = if has_dist { "dist/" } else { "build/" };
+ // Next.js emits .next/ (BUILD_ID appears once the build finished).
+ let has_next = base.join(".next").join("BUILD_ID").exists();
+ if has_dist || has_build || has_next {
+ let dir = if has_dist { "dist/" } else if has_build { "build/" } else { ".next/" };
report.add(BuildCheck {
name: "build output exists".into(),
status: CheckStatus::Pass,
@@ -525,6 +529,20 @@ fn check_index_html(base: &Path, report: &mut VerificationReport) {
}
}
+/// `npm`/`npx` are `.cmd` shims on Windows, which `Command::new` cannot
+/// execute: they must go through `cmd /C` (the same fix the agent adapter
+/// needed). Without this every build/typecheck check reported
+/// "program not found" and could never actually run.
+fn npm_command(program: &str) -> std::process::Command {
+ if cfg!(windows) {
+ let mut cmd = std::process::Command::new("cmd");
+ cmd.arg("/C").arg(program);
+ cmd
+ } else {
+ std::process::Command::new(program)
+ }
+}
+
fn check_typescript(base: &Path, report: &mut VerificationReport) {
if !base.join("tsconfig.json").exists() {
report.add(BuildCheck {
@@ -534,7 +552,7 @@ fn check_typescript(base: &Path, report: &mut VerificationReport) {
});
return;
}
- let output = Command::new("npx")
+ let output = npm_command("npx")
.args(["tsc", "--noEmit"])
.current_dir(base)
.output();
@@ -547,11 +565,31 @@ fn check_typescript(base: &Path, report: &mut VerificationReport) {
});
}
Ok(out) => {
+ // `tsc` writes diagnostics to stdout, not stderr. Counting only
+ // stderr reported "0 errors" for a failing typecheck.
+ let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
- let err_count = stderr.lines().filter(|l| l.contains("error TS")).count();
+ let err_count = stdout
+ .lines()
+ .chain(stderr.lines())
+ .filter(|line| line.contains("error TS"))
+ .count();
+ let mut detail: Vec<&str> = stdout
+ .lines()
+ .chain(stderr.lines())
+ .filter(|line| line.contains("error TS"))
+ .take(3)
+ .collect();
report.add(BuildCheck {
name: "TypeScript compiles".into(),
- status: CheckStatus::Fail(format!("tsc --noEmit: {} errors", err_count)),
+ status: CheckStatus::Fail(format!(
+ "tsc --noEmit: {err_count} errors{}",
+ if detail.is_empty() {
+ String::new()
+ } else {
+ format!(" — {}", detail.drain(..).collect::>().join(" | "))
+ }
+ )),
detail: String::new(),
});
}
@@ -579,7 +617,7 @@ fn check_npm_build(base: &Path, report: &mut VerificationReport) {
});
return;
}
- let output = Command::new("npm")
+ let output = npm_command("npm")
.args(["run", "build"])
.current_dir(base)
.output();
@@ -591,10 +629,18 @@ fn check_npm_build(base: &Path, report: &mut VerificationReport) {
detail: "Build succeeded".into(),
});
}
- Ok(_) => {
+ Ok(out) => {
+ // A failed build with no output tail is undiagnosable.
+ let text = format!(
+ "{}{}",
+ String::from_utf8_lossy(&out.stdout),
+ String::from_utf8_lossy(&out.stderr)
+ );
+ let tail: Vec<&str> = text.lines().rev().take(6).collect();
+ let tail = tail.into_iter().rev().collect::>().join(" | ");
report.add(BuildCheck {
name: "npm run build passes".into(),
- status: CheckStatus::Fail("npm run build failed — check build errors".into()),
+ status: CheckStatus::Fail(format!("npm run build failed: {tail}")),
detail: String::new(),
});
}
@@ -855,6 +901,29 @@ fn check_security(base: &Path, report: &mut VerificationReport) {
}
}
+fn server_log_path() -> std::path::PathBuf {
+ std::env::temp_dir().join(format!("sourceforge-e2e-{}.log", std::process::id()))
+}
+
+/// Server stdout/stderr → log file (never a pipe nobody drains). Falls back to
+/// the null device if the temp file cannot be opened.
+fn server_log_stdio() -> Stdio {
+ std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(server_log_path())
+ .map(Stdio::from)
+ .unwrap_or_else(|_| Stdio::null())
+}
+
+fn server_log_tail() -> String {
+ let Ok(text) = std::fs::read_to_string(server_log_path()) else {
+ return String::new();
+ };
+ let lines: Vec<&str> = text.lines().rev().take(6).collect();
+ lines.into_iter().rev().collect::>().join(" | ")
+}
+
fn check_e2e_runtime(base: &Path, report: &mut VerificationReport) {
let is_nextjs = base.join("next.config.ts").exists() || base.join("next.config.js").exists();
let is_express = base.join("src").join("server.ts").exists();
@@ -902,8 +971,8 @@ fn check_e2e_runtime(base: &Path, report: &mut VerificationReport) {
.env("NEXT_PUBLIC_SUPABASE_URL", "https://placeholder.supabase.co")
.env("NEXT_PUBLIC_SUPABASE_ANON_KEY", "placeholder")
.current_dir(base)
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
+ .stdout(server_log_stdio())
+ .stderr(server_log_stdio())
.spawn()
.ok();
} else if is_express {
@@ -917,7 +986,7 @@ fn check_e2e_runtime(base: &Path, report: &mut VerificationReport) {
.env("DATABASE_URL", "postgresql://none:none@localhost:5432/none")
.env("NODE_ENV", "test")
.current_dir(base)
- .stdout(Stdio::piped()).stderr(Stdio::piped())
+ .stdout(server_log_stdio()).stderr(server_log_stdio())
.spawn().ok();
}
}
@@ -936,12 +1005,11 @@ fn check_e2e_runtime(base: &Path, report: &mut VerificationReport) {
// Wait for boot
let mut booted = false;
- for _ in 0..40 { // Next.js takes longer to boot
+ for _ in 0..120 {
+ // Next dev cold-compiles on first request: allow up to 60s.
std::thread::sleep(Duration::from_millis(500));
- if http_get(port, if is_nextjs { "/api/auth/register" } else { "/api/health" }) == Ok(405) || http_get(port, if is_nextjs { "/api/auth/login" } else { "/api/health" }) == Ok(405) {
- continue; // 405 = server booting but route not ready yet
- }
- if http_get(port, if is_nextjs { "/" } else { "/api/health" }).is_ok() {
+ // Probe a route any app has; `/api/auth/*` is template-specific.
+ if http_get(port, "/api/health").is_ok() || http_get(port, "/").is_ok() {
booted = true;
break;
}
@@ -951,12 +1019,39 @@ fn check_e2e_runtime(base: &Path, report: &mut VerificationReport) {
let _ = server.kill();
report.add(BuildCheck {
name: "E2E runtime test".into(),
- status: CheckStatus::Fail("Server failed to boot within 20 seconds".into()),
+ status: CheckStatus::Fail(format!(
+ "Server failed to boot within 60 seconds: {}",
+ server_log_tail()
+ )),
detail: String::new(),
});
return;
}
+ // The auth-flow probes below belong to the reference template. An app
+ // without auth routes would be failed for endpoints it never had, so the
+ // runtime check verifies what the app does expose: that it serves traffic.
+ let has_auth_routes = base.join("app").join("api").join("auth").exists()
+ || base.join("src").join("routes").join("auth").exists();
+ if !has_auth_routes {
+ let responds = http_get(port, "/api/health").is_ok() || http_get(port, "/").is_ok();
+ let _ = server.kill();
+ report.add(BuildCheck {
+ name: "E2E runtime test".into(),
+ status: if responds {
+ CheckStatus::Pass
+ } else {
+ CheckStatus::Fail("server booted but no route responded".into())
+ },
+ detail: if responds {
+ "Server booted and served a response (no auth routes in this app — auth-flow probes not applicable)".into()
+ } else {
+ String::new()
+ },
+ });
+ return;
+ }
+
let mut passed = 0;
let mut failed = 0;