Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions docs/2026-09-26-defect-closure/handoffs/ACCEPTANCE-RUN-5.md
Original file line number Diff line number Diff line change
@@ -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.
53 changes: 47 additions & 6 deletions src-tauri/src/arch_engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
});
Expand All @@ -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 (<html lang=\"en\"><body>{{children}}</body></html>);\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 (<main className=\"flex min-h-screen items-center justify-center\"><h1 className=\"text-4xl font-bold\">Welcome to {name}</h1></main>);\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(())
Expand Down Expand Up @@ -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();
Expand Down
21 changes: 19 additions & 2 deletions src-tauri/src/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1037,6 +1037,18 @@ fn install_project_dependencies(project_path: &str) -> Result<String, String> {
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");
Expand All @@ -1046,8 +1058,13 @@ fn install_project_dependencies(project_path: &str) -> Result<String, String> {
};
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
Expand Down
Loading
Loading