AI Engineering Workspace
PartialChat, files, terminal and preview in one place. Chat sessions run on a durable Postgres-backed queue (chat only: no tools or shell). Live models need an API key; the terminal is unavailable.
Project files
read-only- ..
- _clean.mjs
- acceptance.mjs
- ai-adapters.mjs
- ai-enqueue.mjs
- central.mjs
- deploy-flow.mjs
- external-vps.mjs
- fake-opencode.mjs
- gates.mjs
- immersive.mjs
- nexus.mjs
- oidc-core.mjs
- oidc-flow.mjs
- opencode-engine.mjs
- owner-auth.mjs
- proxy.mjs
- retake-landing.mjs
- rls.mjs
- run.mjs
- shot-central.mjs
- tenant-isolation.mjs
- trusted-https.mjs
- web-shots.mjs
- with-derived.mjs
app/qa/opencode-engine.mjs
1// Engine tests against a test-double CLI: parsing, deny-by-default policy, project lock, worktree isolation, guarded merge, cancel, recovery.2import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import pg from "pg";3const here = path.dirname(fileURLToPath(import.meta.url)); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "zcs-engtest-"));4process.env.ZCS_OPENCODE_HOME = path.join(tmp, "home"); process.env.ZCS_OPENCODE_BIN = path.join(here, "fake-opencode.mjs");5const E = await import("../scripts/opencode-engine.mjs");6const results = []; const rec = (n, ok, d = "") => { results.push(ok); console.log(`${ok ? "PASS" : "FAIL"} ${n}${d ? " — " + d : ""}`); };7const pw = fs.readFileSync(path.join(os.homedir(), ".config/zoo-cloud-studio/pg-password"), "utf8").trim();8const pool = new pg.Pool({ connectionString: `postgres://studio:${encodeURIComponent(pw)}@127.0.0.1:5432/studio`, max: 4 });9await E.ensureSchema(pool);10const now = () => new Date().toISOString(); const sfx = Date.now();1112// parser (shapes captured from a real opencode 2.4.2 run)13const real = ['{"type":"text","sessionID":"ses_x","part":{"type":"text","text":"OK"}}', '{"type":"step_finish","sessionID":"ses_x","part":{"type":"step-finish","cost":0,"tokens":{"input":5303,"output":3,"reasoning":31}}}', '{"type":"tool_use","part":{"type":"tool","tool":"write","state":{"status":"error","error":"Permission denied: external_directory"}}}', "not json"];14const ev = real.flatMap(E.parseEvent);15rec("parser: text, session id, usage (incl. reasoning), tool error, garbage ignored", ev.some(e => e.text === "OK") && ev.some(e => e.engineSession === "ses_x") && ev.some(e => e.usage?.in === 5303 && e.usage?.out === 34) && ev.some(e => /Permission denied/.test(e.note ?? "")));16rec("free-model allowlist", E.FREE_MODEL("opencode/big-pickle") && E.FREE_MODEL("opencode/beam-free") && !E.FREE_MODEL("opencode/gpt-5") && !E.FREE_MODEL("anthropic/claude") && !E.FREE_MODEL("opencode/x;rm"));17const chat = E.writePolicy("chat"), edit = E.writePolicy("edit");18rec("policy chat: deny-all only", chat.length === 1 && chat[0].effect === "deny" && chat[0].action === "*");19rec("policy edit: no shell/webfetch/external allow; .env reads denied", !edit.some(r => r.effect === "allow" && ["shell", "webfetch", "websearch", "external_directory", "*"].includes(r.action)) && edit.some(r => r.resource === "*.env*" && r.effect === "deny"));20rec("policy file is written outside the workspace (isolated XDG config)", fs.existsSync(path.join(tmp, "home/c/opencode/opencode.jsonc")));21const drain = async g => { const o = { text: "", notes: [], sess: null, usage: null }; for await (const e of g) { if (e.text) o.text += e.text; if (e.note) o.notes.push(e.note); if (e.engineSession) o.sess = e.engineSession; if (e.usage) o.usage = e.usage; } return o; };22const c1 = await drain(E.runCli({ prompt: "hello", model: "opencode/big-pickle", cwd: tmp }));23rec("runCli: streams text, session id and usage from the CLI", /done \(new\)/.test(c1.text) && c1.sess === "ses_fake1" && c1.usage.in === 10);24const c2 = await drain(E.runCli({ prompt: "hello", model: "opencode/big-pickle", cwd: tmp, engineRef: "ses_fake1" }));25rec("runCli: session recovery passes --session", /continued/.test(c2.text));26try { await drain(E.runCli({ prompt: "[fail]", model: "opencode/big-pickle", cwd: tmp })); rec("runCli: non-zero exit raises", false); } catch (e) { rec("runCli: non-zero exit raises a retryable error with stderr", e.retryable === true && /boom/.test(e.message)); }27const ac = new AbortController(); const t0 = Date.now(); setTimeout(() => ac.abort(), 1000); await drain(E.runCli({ prompt: "[slow]", model: "opencode/big-pickle", cwd: tmp, signal: ac.signal }));28rec("runCli: abort kills the process group promptly", Date.now() - t0 < 6000, `${Date.now() - t0}ms`);2930// project/session/run rows31const pid = "p_eng" + sfx; await pool.query("INSERT INTO projects(id,slug,name,created_at,updated_at,org_id) VALUES($1,$1,$1,$2,$2,'org_owner')", [pid, now()]);32const sid = "ses_eng" + sfx; await pool.query("INSERT INTO ai_sessions(id,project_id,title,provider,model,created_at,updated_at,org_id) VALUES($1,$2,'t','opencode','opencode/big-pickle',$3,$3,'org_owner')", [sid, pid, now()]);33const mkRun = async id => { await pool.query("INSERT INTO ai_runs(id,session_id,created_at,updated_at) VALUES($1,$2,$3,$3)", [id, sid, now()]); return { id, session_id: sid, partial: "" }; };34const cp = async (r, k, d) => pool.query("INSERT INTO ai_checkpoints(run_id,seq,kind,detail,created_at) VALUES($1,(SELECT COALESCE(MAX(seq),0)+1 FROM ai_checkpoints WHERE run_id=$1),$2,$3,$4)", [r, k, d, now()]);35const dataDir = path.join(tmp, "data"); const ws = path.join(dataDir, "workspaces", pid); fs.mkdirSync(ws, { recursive: true });36const ses = (await pool.query("SELECT * FROM ai_sessions WHERE id=$1", [sid])).rows[0];37const run = prompt => async id => E.runOpenCode({ ses, run: await mkRun(id), pool, checkpoint: cp, prompt, mode: "edit", workspaceRoot: ws, dataDir });38const r1 = await mkRun("run_a" + sfx); const out1 = await drain(E.runOpenCode({ ses, run: r1, pool, checkpoint: cp, prompt: "[write] make a file", mode: "edit", workspaceRoot: ws, dataDir }));39rec("edit: agent change merged into the project workspace", fs.existsSync(path.join(ws, "agent.txt")) && out1.notes.some(n => /merged agent\//.test(n)));40rec("edit: worktree removed, branch deleted, lock released after merge", !fs.existsSync(path.join(dataDir, "worktrees", r1.id)) && !(await E.gitx(ws, ["branch", "--list", "agent/*"])).trim() && (await pool.query("SELECT 1 FROM workspace_locks WHERE project_id=$1", [pid])).rowCount === 0);41rec("edit: merge commit recorded in project history", /Merge agent run/.test(await E.gitx(ws, ["log", "--pretty=%s", "-5"])));42// concurrency: two agents, same project -> second must wait43const r2 = await mkRun("run_b" + sfx), r3 = await mkRun("run_c" + sfx);44const first = drain(E.runOpenCode({ ses, run: r2, pool, checkpoint: cp, prompt: "[slow] [write]", mode: "edit", workspaceRoot: ws, dataDir })); await new Promise(r => setTimeout(r, 1500));45let waited = null; try { await drain(E.runOpenCode({ ses, run: r3, pool, checkpoint: cp, prompt: "[write]", mode: "edit", workspaceRoot: ws, dataDir })); } catch (e) { waited = e; }46rec("lock: concurrent agent on the same project is refused (waitOnly, retry later)", !!waited && waited.waitOnly === true && /workspace busy/.test(waited.message));47await first;48rec("lock: released after the first agent completes", (await pool.query("SELECT 1 FROM workspace_locks WHERE project_id=$1", [pid])).rowCount === 0);49// stale lock takeover50await pool.query("INSERT INTO workspace_locks(project_id,run_id,locked_at) VALUES($1,'run_dead',$2)", [pid, Date.now() - 600_000]);51const r4 = await mkRun("run_d" + sfx); const out4 = await drain(E.runOpenCode({ ses, run: r4, pool, checkpoint: cp, prompt: "[write]", mode: "edit", workspaceRoot: ws, dataDir }));52rec("lock: stale lock from a dead run is taken over", out4.text.includes("done") || out4.notes.length > 0);53// dirty workspace refused54fs.writeFileSync(path.join(ws, "human-edit.txt"), "uncommitted\n"); const r5 = await mkRun("run_e" + sfx); let dirty = null;55try { await drain(E.runOpenCode({ ses, run: r5, pool, checkpoint: cp, prompt: "[write]", mode: "edit", workspaceRoot: ws, dataDir })); } catch (e) { dirty = e; }56rec("merge safety: uncommitted human edits block agent runs", !!dirty && /uncommitted/.test(dirty.message) && dirty.retryable === false);57await E.gitx(ws, ["add", "-A"]); await E.gitx(ws, ["commit", "-q", "-m", "human"]);58// cancel mid-run -> no merge, cleaned up59const r6 = await mkRun("run_f" + sfx); const ac2 = new AbortController(); setTimeout(() => ac2.abort(), 1500); const before = fs.readdirSync(ws).length;60await drain(E.runOpenCode({ ses, run: r6, pool, checkpoint: cp, prompt: "[slow] [write]", mode: "edit", workspaceRoot: ws, dataDir, signal: ac2.signal }));61rec("cancel: no partial merge, worktree and lock cleaned", fs.readdirSync(ws).length === before && !fs.existsSync(path.join(dataDir, "worktrees", r6.id)) && (await pool.query("SELECT 1 FROM workspace_locks WHERE project_id=$1", [pid])).rowCount === 0);62// recovery: a run that already merged is not executed again (no duplicate non-idempotent work)63const r7 = await mkRun("run_g" + sfx); await cp(r7.id, "merged", "merged agent/x"); const out7 = await drain(E.runOpenCode({ ses, run: r7, pool, checkpoint: cp, prompt: "[write]", mode: "edit", workspaceRoot: ws, dataDir }));64rec("recovery: re-claimed run with a 'merged' checkpoint is not re-executed", out7.notes.some(n => /already merged/.test(n)) && out7.text === "");65// chat mode: scratch dir only, workspace untouched66const filesBefore = fs.readdirSync(ws).join(); const r8 = await mkRun("run_h" + sfx); await drain(E.runOpenCode({ ses, run: r8, pool, checkpoint: cp, prompt: "[write]", mode: "chat", workspaceRoot: ws, dataDir }));67rec("chat mode: runs in a scratch dir; project workspace untouched", fs.readdirSync(ws).join() === filesBefore);68await pool.query("DELETE FROM projects WHERE id=$1", [pid]); await pool.end(); fs.rmSync(tmp, { recursive: true, force: true });69const f = results.filter(x => !x).length; console.log(`${results.length - f}/${results.length} engine checks passed`); process.exit(f ? 1 : 0);70
Conversation
PartialSign in to start AI sessions.
Task checklist
- Application shell deployed
- Persistent projects
- Agent runtime
- Sandboxed terminal
Execution activity
No agent sessions. Git HEAD 1c27633 on master.
Approval requests
None pending.